method2testcases
stringlengths
118
3.08k
### Question: HeapOOM { void createWeakMap() { testMap(new WeakHashMap<>()); } void otherThreadWithOOM(); }### Answer: @Test public void testCreateWeakMap() { heapOOM.createWeakMap(); }
### Question: HeapOOM { public void otherThreadWithOOM() throws Exception { Thread allocateMemory = new Thread(() -> { List<byte[]> data = new ArrayList<>(); while (true) { data.add(new byte[1024 * 10]); try { TimeUnit.MILLISECONDS.sleep(4); } catch (InterruptedException e) { log.error(e.getMessage(), e); } } }); Thread timer = new Thread(() -> { while (true) { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { log.error(e.getMessage(), e); } log.info("timer"); } }); allocateMemory.setName("allocateMemory"); timer.setName("timer"); allocateMemory.start(); timer.start(); allocateMemory.join(); timer.join(); } void otherThreadWithOOM(); }### Answer: @Test public void testOtherThreadWithOOM() throws Exception { heapOOM.otherThreadWithOOM(); }
### Question: Main { void transferAllKey() throws InterruptedException { boolean init = initRedisPool(); if (!init) { return; } JedisPool originPool = origin.getJedisPool(); JedisPool targetPool = target.getJedisPool(); try (final Jedis resource = originPool.getResource()) { if (!RedisPools.isAvailable(resource)) { log.error("conn has invalid "); return; } } try (final Jedis resource = targetPool.getResource()) { if (!RedisPools.isAvailable(resource)) { log.error("conn has invalid "); return; } } Set<String> keys = getKeys(origin, originDatabase); ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); final CountDownLatch latch = new CountDownLatch(keys.size()); Map<Integer, List<String>> collect = keys.stream().collect(groupingBy(String::length)); for (List<String> value : collect.values()) { for (String k : value) { pool.submit(() -> { transferOneKey(k, originPool, targetPool); latch.countDown(); }); } } latch.await(); } Main(RedisPoolProperty originProperty, RedisPoolProperty targetProperty, Integer originDatabase, Integer targetDatabase); }### Answer: @Test public void testTransferAllKey() throws InterruptedException { RedisPoolProperty origin = new RedisPoolProperty(); origin.setHost("127.0.0.1"); origin.setPort(6667); origin.setTimeout(100); RedisPoolProperty target = new RedisPoolProperty(); target.setHost("127.0.0.1"); target.setPort(6667); target.setTimeout(100); Main main = new Main(origin, target, 4, 2); main.transferAllKey(); }
### Question: CopyFile { void copyFileByChar(String from, String dest) { FileReader fileReader = null; FileWriter fileWriter = null; try { fileReader = new FileReader(from); fileWriter = new FileWriter(dest); char[] p = new char[512]; int n; while ((n = fileReader.read(p)) != -1) { fileWriter.write(p, 0, n); String cacheContent = new String(p, 0, n); System.out.println(cacheContent); } } catch (Exception e) { e.printStackTrace(); } finally { try { ResourceTool.close(fileReader, fileWriter); } catch (Exception e) { log.error(e.getMessage(), e); } } } }### Answer: @Test public void testCopyByChar() throws IOException { file.copyFileByChar(from, dest); validateResultFile(); }
### Question: Veterinarian extends Thread { @Override public void run() { while (!shutdown) { seePatient(); try { sleep(restTime); } catch (InterruptedException e) { shutdown(); log.error(e.getMessage(), e); } } } Veterinarian(BlockingQueue<Appointment<Pet>> pets, int pause); @Override void run(); }### Answer: @Test public void testRun() throws Exception { BlockingQueue<Appointment<Pet>> lists = new LinkedBlockingQueue<>(); lists.add(new Appointment<>(new Cat("1"))); lists.add(new Appointment<>(new Cat("2"))); lists.add(new Appointment<>(new Dog("1"))); lists.add(new Appointment<>(new Dog("2"))); Veterinarian veterinarian = new Veterinarian(lists, 2000); veterinarian.text = "Veterinarian 1"; Veterinarian veterinarian2 = new Veterinarian(lists, 1000); veterinarian2.text = "Veterinarian 2"; veterinarian.start(); veterinarian2.start(); veterinarian.join(); veterinarian2.join(); }
### Question: NeverStopThread { void neverStop() { while (!stop) { } log.info("exit neverStop"); } }### Answer: @Test public void testNeverStop() throws Exception { NeverStopThread demo = new NeverStopThread(); Thread thread = new Thread(demo::neverStop); thread.start(); log.info("prepare to stop"); demo.stop(); thread.join(); }
### Question: NeverStopThread { void stopWithVolatile() { this.stopWithVolatile = true; } }### Answer: @Test public void testVolatile() throws InterruptedException { NeverStopThread demo = new NeverStopThread(); Thread thread = new Thread(demo::normalStopWithVolatile); thread.start(); log.info("prepare to stop"); demo.stopWithVolatile(); thread.join(); }
### Question: NeverStopThread { void stopWithSleep() { this.stopWithSleep = true; } }### Answer: @Test public void testSleep() throws InterruptedException { NeverStopThread demo = new NeverStopThread(); Thread thread = new Thread(demo::normalStopWithSleep); thread.start(); log.info("prepare to stop"); demo.stopWithSleep(); thread.join(); }
### Question: FactoryProducer { static Optional<AbstractFactory> getFactory(String choice) { if (choice.equalsIgnoreCase("SHAPE")) { return Optional.of(new ShapeFactory()); } else if (choice.equalsIgnoreCase("COLOR")) { return Optional.of(new ColorFactory()); } return Optional.empty(); } }### Answer: @Test public void testMain() { Optional<AbstractFactory> shapeFactoryOpt = FactoryProducer.getFactory("SHAPE"); Preconditions.checkArgument(shapeFactoryOpt.isPresent()); Optional<Shape> shapeOpt = shapeFactoryOpt.get().getShape("RECTANGLE"); Preconditions.checkArgument(shapeOpt.isPresent()); shapeOpt.get().draw(); Optional<AbstractFactory> colorFactoryOpt = FactoryProducer.getFactory("COLOR"); Preconditions.checkArgument(colorFactoryOpt.isPresent()); Optional<Color> colorOpt = colorFactoryOpt.get().getColor("RED"); Preconditions.checkArgument(colorOpt.isPresent()); colorOpt.get().fill(); }
### Question: Decorator extends Invoice { public void printInvoice() { if (ticket != null) { ticket.printInvoice(); } } Decorator(Invoice t); void printInvoice(); }### Answer: @Test public void test() { Invoice invoice = new Invoice(); Invoice ticket = new FootDecorator(new HeadDecorator(invoice)); ticket.printInvoice(); System.out.println("----------------"); ticket = new FootDecorator(new HeadDecorator(null)); ticket.printInvoice(); }
### Question: MythArrayStack implements MythBaseStack<T> { @Override public void push(T data) { if (isFull()) { return; } top++; this.elementData[top] = data; } MythArrayStack(); MythArrayStack(int maxSize); @Override void push(T data); @Override @SuppressWarnings("unchecked") T pop(); @Override @SuppressWarnings("unchecked") T peek(); @Override int size(); @Override boolean isEmpty(); boolean isFull(); @Override void clear(); }### Answer: @Test public void testPush() { stack.push(1212); assertThat(stack.size(), equalTo(1)); }
### Question: MythArrayStack implements MythBaseStack<T> { @Override @SuppressWarnings("unchecked") public T pop() { if (isEmpty()) { throw new IndexOutOfBoundsException(outOfBoundsMsg(0)); } return (T) elementData[top]; } MythArrayStack(); MythArrayStack(int maxSize); @Override void push(T data); @Override @SuppressWarnings("unchecked") T pop(); @Override @SuppressWarnings("unchecked") T peek(); @Override int size(); @Override boolean isEmpty(); boolean isFull(); @Override void clear(); }### Answer: @Test(expected = IndexOutOfBoundsException.class) public void testPop() { int result = stack.pop(); assertThat(result, equalTo(null)); } @Test public void testPop2() { testPush(); int result = stack.pop(); assertThat(result, equalTo(1212)); }
### Question: MythArrayStack implements MythBaseStack<T> { @Override @SuppressWarnings("unchecked") public T peek() { if (isEmpty()) { throw new IndexOutOfBoundsException(outOfBoundsMsg(0)); } return (T) elementData[top]; } MythArrayStack(); MythArrayStack(int maxSize); @Override void push(T data); @Override @SuppressWarnings("unchecked") T pop(); @Override @SuppressWarnings("unchecked") T peek(); @Override int size(); @Override boolean isEmpty(); boolean isFull(); @Override void clear(); }### Answer: @Test(expected = IndexOutOfBoundsException.class) public void testPeek() { int result = stack.peek(); Assert.assertEquals(1, result); } @Test public void testPeek2() { testPush(); Integer result = stack.peek(); assertThat(result, equalTo(result)); }
### Question: CopyFile { void copyFileByByte(String from, String dest) { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(from); outputStream = new FileOutputStream(dest); byte[] buffer = new byte[1024]; while (inputStream.read(buffer) != -1) { outputStream.write(buffer); } } catch (Exception e) { e.printStackTrace(); } finally { try { ResourceTool.close(inputStream, outputStream); } catch (IOException e) { log.error(e.getMessage(), e); } } } }### Answer: @Test public void testCopyByByte() throws IOException { file.copyFileByByte(from, dest); validateResultFile(); }
### Question: MythArrayStack implements MythBaseStack<T> { @Override public boolean isEmpty() { return top == -1; } MythArrayStack(); MythArrayStack(int maxSize); @Override void push(T data); @Override @SuppressWarnings("unchecked") T pop(); @Override @SuppressWarnings("unchecked") T peek(); @Override int size(); @Override boolean isEmpty(); boolean isFull(); @Override void clear(); }### Answer: @Test public void testIsEmpty() { boolean result = stack.isEmpty(); Assert.assertTrue(result); testPush(); assertThat(stack.isEmpty(), equalTo(false)); }
### Question: MythArrayStack implements MythBaseStack<T> { public boolean isFull() { return top == maxSize - 1; } MythArrayStack(); MythArrayStack(int maxSize); @Override void push(T data); @Override @SuppressWarnings("unchecked") T pop(); @Override @SuppressWarnings("unchecked") T peek(); @Override int size(); @Override boolean isEmpty(); boolean isFull(); @Override void clear(); }### Answer: @Test public void testIsFull() { boolean result = stack.isFull(); assertThat(result, equalTo(false)); for (int i = 0; i < 10; i++) { stack.push(i); } result = stack.isFull(); assertThat(result, equalTo(true)); }
### Question: MythArrayStack implements MythBaseStack<T> { @Override public void clear() { top = -1; elementData = new Object[DEFAULT_CAPACITY]; } MythArrayStack(); MythArrayStack(int maxSize); @Override void push(T data); @Override @SuppressWarnings("unchecked") T pop(); @Override @SuppressWarnings("unchecked") T peek(); @Override int size(); @Override boolean isEmpty(); boolean isFull(); @Override void clear(); }### Answer: @Test public void testClear() { testIsFull(); assertThat(stack.isFull(), equalTo(true)); stack.clear(); assertThat(stack.isEmpty(), equalTo(true)); }
### Question: MythLinkedStack implements MythBaseStack<T> { @Override public void push(T data) { Node newNode = new Node(data); if (!Objects.isNull(top)) { newNode.next = top; } top = newNode; } @Override void push(T data); @Override T pop(); @Override T peek(); @Override int size(); @Override boolean isEmpty(); @Override void clear(); }### Answer: @Test public void testPush() { stack.push(1212); assertThat(stack.size(), equalTo(1)); }
### Question: MythLinkedStack implements MythBaseStack<T> { @Override public T pop() { if (isEmpty()) { return null; } T temp = top.getData(); top = top.next; return temp; } @Override void push(T data); @Override T pop(); @Override T peek(); @Override int size(); @Override boolean isEmpty(); @Override void clear(); }### Answer: @Test public void testPop() throws Exception { testPush(); Integer pop = stack.pop(); assertThat(pop, equalTo(1212)); }
### Question: MythLinkedStack implements MythBaseStack<T> { @Override public T peek() { if (Objects.isNull(top)) { return null; } return top.getData(); } @Override void push(T data); @Override T pop(); @Override T peek(); @Override int size(); @Override boolean isEmpty(); @Override void clear(); }### Answer: @Test public void testPeek() throws Exception { testPush(); assertThat(stack.peek(), equalTo(1212)); }
### Question: MythLinkedStack implements MythBaseStack<T> { @Override public int size() { Node temp = top; if (Objects.isNull(temp)) { return 0; } int count = 0; while (!Objects.isNull(temp)) { count++; temp = top.next; } return count; } @Override void push(T data); @Override T pop(); @Override T peek(); @Override int size(); @Override boolean isEmpty(); @Override void clear(); }### Answer: @Test public void testLength() throws Exception { int result = stack.size(); Assert.assertEquals(0, result); testPush(); assertThat(stack.size(), equalTo(1)); }
### Question: MythLinkedStack implements MythBaseStack<T> { @Override public boolean isEmpty() { return Objects.isNull(top); } @Override void push(T data); @Override T pop(); @Override T peek(); @Override int size(); @Override boolean isEmpty(); @Override void clear(); }### Answer: @Test public void testIsEmpty() { boolean result = stack.isEmpty(); Assert.assertTrue(result); testPush(); assertThat(stack.isEmpty(), equalTo(false)); }
### Question: MythLinkedStack implements MythBaseStack<T> { @Override public void clear() { top = null; } @Override void push(T data); @Override T pop(); @Override T peek(); @Override int size(); @Override boolean isEmpty(); @Override void clear(); }### Answer: @Test public void testClear() { testIsEmpty(); stack.clear(); assertThat(stack.size(), equalTo(0)); }
### Question: CopyFile { void copyFileByCharBuffer(String from, String dest) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(from)); writer = new BufferedWriter(new FileWriter(dest)); String s; while ((s = reader.readLine()) != null) { log.info("line: {}", s); writer.write(s + "\r\n"); } log.info("成功读取并写入"); } catch (Exception e) { log.error(e.getMessage(), e); } finally { try { ResourceTool.close(reader, writer); } catch (Exception e) { log.error(e.getMessage(), e); } } } }### Answer: @Test public void testCopyByCharBuffer() throws IOException { file.copyFileByCharBuffer(from, dest); validateResultFile(); }
### Question: AddTwoBigInteger { MythBaseStack<Integer> add(String one, String other) { boolean oneResult = initBigInteger(one, oneStack); boolean otherResult = initBigInteger(other, otherStack); if (!oneResult || !otherResult) { return null; } int flag = 0; while (!oneStack.isEmpty() && !otherStack.isEmpty()) { int sum; sum = oneStack.pop() + otherStack.pop() + flag - 96; flag = 0; if (sum >= 10) { sum -= 10; flag = 1; } resultStack.push(sum); } if (!oneStack.isEmpty() && otherStack.isEmpty()) { flag = pushResult(flag, oneStack); } else if (oneStack.isEmpty() && !otherStack.isEmpty()) { flag = pushResult(flag, otherStack); } if (flag == 1) { resultStack.push(flag); } return resultStack; } }### Answer: @Test public void testAdd() { AddTwoBigInteger addTwoBigInteger = new AddTwoBigInteger(); MythBaseStack<Integer> result = addTwoBigInteger.add("112233", "332211"); String actual = stackToString(result); log.info(": actual={}", actual); assertThat(actual, equalTo("444444")); addTwoBigInteger.clear(); result = addTwoBigInteger.add("5367868436215345", "743558532109789079793128"); actual = stackToString(result); log.info(": actual={}", actual); assertThat(actual, equalTo("743558537477657516008473")); addTwoBigInteger.clear(); result = addTwoBigInteger.add("0000001", "1"); actual = stackToString(result); log.info(": actual={}", actual); assertThat(actual, equalTo("2")); }
### Question: MatchBracket { public void match(String origin) { log.info("input string={}", origin); initBrackets(); MythBaseStack<Integer> stack = new MythLinkedStack<>(); for (int i = 0; i < origin.length(); i++) { char charAt = origin.charAt(i); if (leftBrackets.contains(charAt)) { stack.push((int) charAt); continue; } if (rightBrackets.contains(charAt)) { int pop = stack.pop(); if (charAt == ')') { if (pop != '(') { stack.push((int) charAt); } } if (charAt == ']') { if (pop != '[') { stack.push((int) charAt); } } if (charAt == '}') { if (pop != '{') { stack.push((int) charAt); } } } } while (!stack.isEmpty()) { log.error("char={}", stack.pop()); } } void match(String origin); }### Answer: @Test public void testMatch() { new MatchBracket().match("[[[}]]]"); }
### Question: TimeWheel { public boolean add(String id, Callable<?> func, Duration delay) { if (Objects.isNull(delay)) { log.warn("delay is null: id={}", id); return false; } if (Objects.isNull(func)) { log.warn("func is null: id={}", id); return false; } if (cacheTasks.containsKey(id)) { log.warn("task has already exist"); return false; } boolean result = insertWheel(id, delay); if (result) { cacheTasks.put(id, func); } return result; } TimeWheel(); TimeWheel(long maxTimeout, boolean needExitVM, boolean debugMode); void start(); void shutdown(); boolean add(String id, Callable<?> func, Duration delay); void printWheel(); }### Answer: @Test public void testAdd() throws Exception { boolean result = timeWheel.add("id", () -> null, Duration.ofMillis(10000)); Assert.assertTrue(result); }
### Question: MT19937Random { public synchronized int next() { return next(32); } MT19937Random(long seed); final synchronized void setSeed(long seed); final synchronized void setSeed(int[] buf); synchronized int next(); synchronized int next(int bits); }### Answer: @Test public void testRandom() { int maxSize = 100000; Set<Integer> pool = new HashSet<>(); for (int i = 0; i < maxSize; i++) { MT19937Random random = new MT19937Random(System.nanoTime()); pool.add(random.next()); } assertThat(pool.size(), equalTo(maxSize)); }
### Question: BinarySearch { public int find(int[] arr, int data) { found(arr, 0, arr.length, data); return index + 1; } int find(int[] arr, int data); }### Answer: @Test public void testFind() { BinarySearch s = new BinarySearch(); int[] dat = new int[dataScale]; for (int i = 0; i < dat.length; i++) { dat[i] = (int) (Math.random() * dataRange + dataBaseValue); } Insert.INSTANCE.sort(dat); for (int i = 0; i < dat.length; i++) { System.out.print(dat[i] + " "); if ((i + 1) % 10 == 0) { System.out.println(); } } int randomValue = (int) (Math.random() * dataRange + dataBaseValue); int result = s.find(dat, randomValue); if (result != -1) { log.debug("你要找的数据是第 {} 个数字 {}", result, randomValue); } else { log.debug("该数据不存在,查找失败!value={}", randomValue); } }
### Question: Fibonacci { static int recursiveOne(int num) { if (num < 0) { return 0; } if (num == 1) { return 1; } return recursiveOne(num - 1) + recursiveOne(num - 2); } }### Answer: @Test public void testRecursiveOne() throws Exception { general(Fibonacci::recursiveOne, 100); }
### Question: Fibonacci { static int loopOne(int num) { if (num <= 0) { return 0; } if (num == 1) { return 1; } int pre = 1; int cur = 1; for (int i = 0; i < num - 2; i++) { int temp = pre; pre = cur; cur = temp + cur; } return cur; } }### Answer: @Test public void testLoopOne() { general(Fibonacci::loopOne, 10); }
### Question: Fibonacci { static int generalTermFormula(int num) { double temp = Math.sqrt(5); return (int) (1 / temp * (Math.pow((1 + temp) / 2, num) - Math.pow((1 - temp) / 2, num))); } }### Answer: @Test public void testGeneralTermFormula() { general(Fibonacci::generalTermFormula, 10); }
### Question: SimpleGenericMethod { public static <T> T getMiddle(T[] list) { return list[list.length / 2]; } static T getMiddle(T[] list); static T getMax(T[] list); }### Answer: @Test public void testGetMiddle() { Float[] arrays = {2.1f, 4.2f, 3.5f}; Float result = SimpleGenericMethod.getMiddle(arrays); assert result == 4.2f; }
### Question: SimpleGenericMethod { public static <T extends Comparable<T> & Serializable> T getMax(T[] list) { T target = list[list.length - 1]; for (int i = list.length - 2; i > -1; i--) { if (target.compareTo(list[i]) < 0) { target = list[i]; } } return target; } static T getMiddle(T[] list); static T getMax(T[] list); }### Answer: @Test public void testGetMax() { Score[] scores = { new Score(80f, 50f), new Score(70f, 80f), new Score(100f, 70f) }; Score result = SimpleGenericMethod.getMax(scores); assert result.getNormal() == 100; }
### Question: CopyFile { void copyByFiles(Path from, Path dest) throws IOException { Files.copy(from, dest); } }### Answer: @Test public void testCopyByFiles() throws IOException { file.copyByFiles(fromPath, destPath); validateResultFile(); }
### Question: HumanLoader extends AbstractLoader<String, HumanVO> { @Override Map<String, HumanVO> getMap() { return map; } }### Answer: @Test public void testLoad(){ HumanLoader humanLoader = new HumanLoader(); humanLoader.load("xx"); Map<String, HumanVO> data = humanLoader.getMap(); }
### Question: ArrayUtils { static <T> T[] create(Class<T> target, int size) { return (T[]) Array.newInstance(target, size); } }### Answer: @Test public void testCreateArray() { String[] stringArray = ArrayUtils.create(String.class, 9); System.out.println(Arrays.toString(stringArray)); assert Arrays.stream(stringArray).allMatch(Objects::isNull); }
### Question: ArrayUtils { static <T extends Comparable<T>> List<T> sort(List<T> list) { return Arrays.asList(list.toArray((T[]) new Comparable[list.size()])); } }### Answer: @Test public void testSort() { List<Integer> list = Arrays.asList(3, 2, 5); List<Integer> result = ArrayUtils.sort(list); log.info("result={}", result); }
### Question: ArrayUtils { static <T extends Comparable<T>> T[] sortToArray(List<T> list) { return list.toArray((T[]) new Comparable[list.size()]); } }### Answer: @Test public void testSortToArray() { List<Integer> list = Arrays.asList(3, 2, 5); Integer[] result = ArrayUtils.sortToArray(list); log.info("result={}", Arrays.toString(result)); }
### Question: GeneralFileActionDemo { public static boolean createDirectory(String url) throws IOException { FileSystem fileSystem = FileSystem.get(getConfig(url)); boolean result = fileSystem.mkdirs(new Path(url)); log.info("result={}", result); return result; } static boolean createDirectory(String url); static void createNewFile(String url, String content); static List<String> listFiles(String url); static boolean deleteByURL(String url); static void writeFileToHDFS(); static void readHDFSFile(String url); }### Answer: @Test public void testCreateDirectory() throws Exception { boolean result = GeneralFileActionDemo.createDirectory(HDFS_HOST + "/flink-batch/test"); assertThat(result, equalTo(true)); }
### Question: ConsumerDemo { static void receiveHi() { SimpleMessageExecutor executor = new SimpleMessageExecutor() { @Override public void execute(String message) { log.info("message={}", message); } @Override public String getTopic() { return HI_TOPIC; } }; KafkaConsumerUtil.consumerPlainText(Duration.ofMillis(1000), Collections.singletonList(executor)); } }### Answer: @Test public void testReceiveHi() { ConsumerDemo.receiveHi(); }
### Question: GeneralFileActionDemo { public static void createNewFile(String url, String content) throws IOException, InterruptedException { FileSystem fs = FileSystem.get(getConfig(url)); FSDataOutputStream os = fs.create(new Path(URI.create(url).getPath())); os.write(content.getBytes(StandardCharsets.UTF_8)); os.flush(); TimeUnit.SECONDS.sleep(4); os.close(); fs.close(); } static boolean createDirectory(String url); static void createNewFile(String url, String content); static List<String> listFiles(String url); static boolean deleteByURL(String url); static void writeFileToHDFS(); static void readHDFSFile(String url); }### Answer: @Test public void testCreateFile() throws IOException, InterruptedException { GeneralFileActionDemo.createNewFile(HDFS_HOST + "/input/b.md", "fdasfasdfasd"); }
### Question: GeneralFileActionDemo { public static boolean deleteByURL(String url) throws IOException { FileSystem fs = FileSystem.get(getConfig(url)); Path path = new Path(url); boolean isDeleted = fs.deleteOnExit(path); fs.close(); return isDeleted; } static boolean createDirectory(String url); static void createNewFile(String url, String content); static List<String> listFiles(String url); static boolean deleteByURL(String url); static void writeFileToHDFS(); static void readHDFSFile(String url); }### Answer: @Test public void testDelete() throws IOException { boolean result = GeneralFileActionDemo .deleteByURL(HDFS_HOST + "/flink-batch/1559008370602_MONTH_2019-03-01_2019-03-27_SPU.csv"); System.out.println(result); }
### Question: GeneralFileActionDemo { public static void readHDFSFile(String url) throws Exception { FileSystem fs = FileSystem.get(getConfig(url)); Path path = new Path(url); if (!fs.exists(path)) { throw new Exception("the file is not found ."); } FSDataInputStream is = fs.open(path); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(is, StandardCharsets.UTF_8)); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } is.close(); fs.close(); } static boolean createDirectory(String url); static void createNewFile(String url, String content); static List<String> listFiles(String url); static boolean deleteByURL(String url); static void writeFileToHDFS(); static void readHDFSFile(String url); }### Answer: @Test public void testRead() throws Exception { String url = "/flink-batch/1559008370602_MONTH_2019-03-01_2019-03-27_SPU.csv"; GeneralFileActionDemo.readHDFSFile(HDFS_HOST + url); }
### Question: Martingale { long martingale(long principal, int count) { if (count < 0) { return principal; } long origin = principal; long start = 1L; for (int i = 0; i < count; i++) { if (principal < start) { log.warn("本金不足: principal={} except={}", principal, start); return principal; } principal -= start; int temp = ThreadLocalRandom.current().nextInt(0, 100); if (temp > 50) { log.info("亏损:{} 当前变动:{}", start, (principal - origin)); start *= 2; } else { log.info("盈利:{} 当前变动:{}", start, (principal - origin)); principal += start * 2; } } return principal; } }### Answer: @Test public void testMartingale() { long result = martingale.martingale(99999999L, 2000); log.info("result={}", result); }
### Question: ConsumerDemo { static void receiveCommand() throws IOException { KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties); kafkaConsumer.subscribe(Collections.singletonList(Constants.COMMAND_TOPIC)); while (true) { ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(100)); for (ConsumerRecord<String, String> record : records) { log.info("offset = {}, value = {}", record.offset(), record.value()); ProductStatisticJobCommand command = mapper .readValue(record.value(), ProductStatisticJobCommand.class); System.out.println(command); } } } }### Answer: @Test public void testReceiveCommand() throws IOException { ConsumerDemo.receiveCommand(); }
### Question: ProducerDemo { static void sendCommand() { Producer<String, String> producer = null; HashSet<ProductStatisticSpan> spans = new HashSet<>(); spans.add(ProductStatisticSpan.MONTH); try { producer = new KafkaProducer<>(properties); for (int i = 0; i < 2; i++) { ProductStatisticJobCommand msg = ProductStatisticJobCommand.builder() .id(UUID.randomUUID().toString() + "_test_" + i) .startTime(toDate(LocalDateTime.now().withMonth(1))) .endTime(toDate(LocalDateTime.now().withMonth(3))) .productStatisticSpan(spans) .build(); ProducerRecord<String, String> record = new ProducerRecord<>(Constants.COMMAND_TOPIC, mapper.writeValueAsString(msg)); long time = System.currentTimeMillis(); producer.send(record, (metadata, e) -> { long elapsedTime = System.currentTimeMillis() - time; if (metadata != null) { log.info("sent record(key={} value={}) meta(partition={}, offset={}) time={}", record.key(), record.value(), metadata.partition(), metadata.offset(), elapsedTime); } else { log.error(e.getMessage(), e); } }); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { try { ResourceTool.close(producer); } catch (IOException e) { log.error(e.getMessage(), e); } } } static Date toDate(LocalDateTime dateTime); }### Answer: @Test public void testSendCommand() { ProducerDemo.sendCommand(); }
### Question: ProducerDemo { static void sendStart() { Producer<String, String> producer = null; try { producer = new KafkaProducer<>(properties); for (int i = 0; i < 20; i++) { StartCommand msg = StartCommand.builder().place("There").scale(i).startTime(new Date()) .build(); producer.send(new ProducerRecord<>(START_TOPIC, mapper.writeValueAsString(msg))); log.info("Sent: {}", msg); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { try { ResourceTool.close(producer); } catch (IOException e) { log.error(e.getMessage(), e); } } } static Date toDate(LocalDateTime dateTime); }### Answer: @Test public void testSendStart() { ProducerDemo.sendStart(); }
### Question: ProducerDemo { static void sendHi() { Producer<String, String> producer = null; try { producer = new KafkaProducer<>(properties); for (int i = 0; i < 100; i++) { String msg = "Message " + i; producer.send(new ProducerRecord<>(HI_TOPIC, msg)); log.info("Sent: {}", msg); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { try { ResourceTool.close(producer); } catch (IOException e) { log.error(e.getMessage(), e); } } } static Date toDate(LocalDateTime dateTime); }### Answer: @Test public void testSendHi() { ProducerDemo.sendHi(); }
### Question: Assembler implements com.fatwire.cs.core.uri.Assembler { @Override public Definition disassemble(URI uri, ContainerType type) throws URISyntaxException { Definition result = null; String path = uri.getPath(); if (log.trace()) log.debug("dissassembling %s", path); Matcher match = sitePattern.matcher(path); if (match.find()) { String site = match.group(2); String subpath = match.group(4); if (siteName.containsKey(site) && sitePrefix.containsKey(site)) { site = siteName.get(site); if (log.debug()) log.debug("site=%s subpath=%s", site, subpath); result = disassembleBlob(uri, site, subpath); if (result == null) { if (log.debug()) log.debug("**** asset found"); return assetDef(uri, site, subpath, getDeviceParam(uri)); } else { if (log.debug()) log.debug("*** blob found"); return result; } } else { log.warn("no prefix for site " + site); } } return qa.disassemble(uri, type); } static URI buildUri(String prefix, String suffix); @Override void setProperties(Properties prp); @Override Definition disassemble(URI uri, ContainerType type); @Override URI assemble(Definition def); }### Answer: @Test public void disassemble() throws URISyntaxException { Definition d = as.disassemble(uri(""), ContainerType.SERVLET); out.println(d.getParameterNames()); out.println("site="+d.getParameter("site")); d = as.disassemble(uri("/About"), ContainerType.SERVLET); out.println(d.getParameterNames()); d = as.disassemble(uri("/1234.gif"), ContainerType.SERVLET); out.println(d.getParameterNames()); d = as.disassemble(uri("/test.js"), ContainerType.SERVLET); out.println(d.getParameterNames()); }
### Question: ClassService { @Transactional public boolean createClass(Class c) { classMapper.insert(c); return true; } @Transactional boolean createClass(Class c); }### Answer: @Test public void createClass() throws Exception { Class c = new Class(); c.setClassName("test"); classService.createClass(c); }
### Question: CityServiceImpl implements CityService { public Page<City> findAll(Pageable pageable) { return null; } City findById(Long id); City findByCountryEquals(String country); Page<City> findAll(Pageable pageable); Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); @TargetDataSource(dataSource = "writeDruidDataSource") @Transactional(value = "writeTransactionManager") City createCity(City city); }### Answer: @Test public void findAll() throws Exception { }
### Question: CityServiceImpl implements CityService { public Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, String country, Pageable pageable) { return null; } City findById(Long id); City findByCountryEquals(String country); Page<City> findAll(Pageable pageable); Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); @TargetDataSource(dataSource = "writeDruidDataSource") @Transactional(value = "writeTransactionManager") City createCity(City city); }### Answer: @Test public void findByNameContainingAndCountryContainingAllIgnoringCase() throws Exception { }
### Question: CityServiceImpl implements CityService { public City findByNameAndCountryAllIgnoringCase(String name, String country) { return null; } City findById(Long id); City findByCountryEquals(String country); Page<City> findAll(Pageable pageable); Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); @TargetDataSource(dataSource = "writeDruidDataSource") @Transactional(value = "writeTransactionManager") City createCity(City city); }### Answer: @Test public void findByNameAndCountryAllIgnoringCase() throws Exception { }
### Question: CityServiceImpl implements CityService { @TargetDataSource(dataSource = "writeDruidDataSource") @Transactional(value = "writeTransactionManager") public City createCity(City city) { return cityRepository.save(city); } City findById(Long id); City findByCountryEquals(String country); Page<City> findAll(Pageable pageable); Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); @TargetDataSource(dataSource = "writeDruidDataSource") @Transactional(value = "writeTransactionManager") City createCity(City city); }### Answer: @Test public void createCity() throws Exception { City city = new City(); city.setCountry("china"); city.setMap("map"); city.setName("beijing"); city.setState("state"); cityService.createCity(city); }
### Question: TeacherService { @Transactional public boolean createTeacher(Teacher teacher) { teacherMapper.insert(teacher); return true; } @Transactional boolean createTeacher(Teacher teacher); }### Answer: @Test public void createTeacher() throws Exception { Teacher teacher = new Teacher(); teacher.setName("test"); teacherService.createTeacher(teacher); }
### Question: StudentService { @Transactional @TargetDataSource(dataSource = "writeDataSource") public boolean createUser(Student student) { studentMapper.insert(student); return true; } @Transactional @TargetDataSource(dataSource = "writeDataSource") boolean createUser(Student student); @TargetDataSource(dataSource = "read1DataSource") List<Student> getByPage(int page, int rows); }### Answer: @Test public void createUser() throws Exception { Student student = new Student(); student.setName("test1"); student.setAge(1); student.setBirthday(new Date()); student.setEmail("[email protected]"); studentService.createUser(student); }
### Question: StudentService { @TargetDataSource(dataSource = "read1DataSource") public List<Student> getByPage(int page, int rows) { Page<Student> studentPage = PageHelper.startPage(page, rows, true); List<Student> students = studentMapper.getBypage(); System.out.println("-------------------" + studentPage.toString() + "-----------"); return students; } @Transactional @TargetDataSource(dataSource = "writeDataSource") boolean createUser(Student student); @TargetDataSource(dataSource = "read1DataSource") List<Student> getByPage(int page, int rows); }### Answer: @Test public void getByPage() throws Exception { studentService.getByPage(1, 2); }
### Question: UserService { @Transactional public boolean createUser(User user) { userMapper.insert(user); return true; } @Transactional boolean createUser(User user); List<User> getByPage(int page, int rows); }### Answer: @Test public void createUser() throws Exception { User user = new User(); user.setName("test1"); user.setAge(1); user.setBirthday(new Date()); user.setEmail("[email protected]"); userService.createUser(user); }
### Question: UserService { public List<User> getByPage(int page, int rows) { Page<User> userPage = PageHelper.startPage(page, rows, true); List<User> users = userMapper.getBypage(); System.out.println("-------------------" + userPage.toString() + "-----------"); return users; } @Transactional boolean createUser(User user); List<User> getByPage(int page, int rows); }### Answer: @Test public void getByPage() throws Exception { userService.getByPage(1, 2); }
### Question: UserServiceImpl implements UserService { @Override public User getUser(Integer id) { User user = userDao.getUser(id); return user; } @Override void createUser(User user); @Override User getUser(Integer id); }### Answer: @Test public void getUser() throws Exception { System.out.println(userService.getUser(1)); }
### Question: UserServiceImpl implements UserService { @Override public void createUser(User user) { userDao.insertUser(user); } @Override void createUser(User user); @Override User getUser(Integer id); }### Answer: @Test public void createUser() throws Exception { User user = new User(); user.setId(1); user.setName("test1"); user.setEmail("[email protected]"); userService.createUser(user); }
### Question: CityServiceImpl implements CityService { public City findById(Long id) { return null; } City findById(Long id); City findByCountryEquals(String country); Page<City> findAll(Pageable pageable); Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); @TargetDataSource(dataSource = "writeDruidDataSource") @Transactional(value = "writeTransactionManager") City createCity(City city); }### Answer: @Test public void findById() throws Exception { }
### Question: CityServiceImpl implements CityService { public City findByCountryEquals(String country) { return null; } City findById(Long id); City findByCountryEquals(String country); Page<City> findAll(Pageable pageable); Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); @TargetDataSource(dataSource = "writeDruidDataSource") @Transactional(value = "writeTransactionManager") City createCity(City city); }### Answer: @Test public void findByCountryEquals() throws Exception { }
### Question: SpeakerController { @DeleteMapping("/{id}") public ResponseEntity deleteSpeaker(@PathVariable long id) { speakerRepository.delete(id); return ResponseEntity.noContent().build(); } @GetMapping(path = "/{id}") ResponseEntity<SpeakerResource> getSpeaker(@PathVariable long id); @GetMapping Resources<SpeakerResource> getAllSpeakers(); @GetMapping("/{id}/topics") Resources<TopicResource> getSpeakerTopics(@PathVariable long id); @PostMapping ResponseEntity<SpeakerResource> createSpeaker(@Validated @RequestBody SpeakerDto speakerDto); @DeleteMapping("/{id}") ResponseEntity deleteSpeaker(@PathVariable long id); @ExceptionHandler(value = {DuplicateEntityException.class}) @ResponseStatus(HttpStatus.CONFLICT) Resource handleDuplicateEntityException(DuplicateEntityException ex); @ExceptionHandler(value = {MethodArgumentNotValidException.class}) @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY) Resources<ValidationErrorResource> handleMethodArgumentNotValid(MethodArgumentNotValidException ex); }### Answer: @Test public void testDeleteSpeaker() throws Exception { Speaker speakerToDelete = given.speaker("TO_DELETE").company("COMPANY").save(); ResultActions actions = mockMvc.perform(RestDocumentationRequestBuilders.delete("/speakers/{id}", speakerToDelete.getId())) .andDo(print()); actions.andExpect(status().isNoContent()); actions.andDo(document("{class-name}/{method-name}")); assertEquals(0, speakerRepository.count()); }
### Question: TopicController { @GetMapping(value = "/topics/{id}") public ResponseEntity<TopicResource> getTopic(@PathVariable long id) { return topicRepository.findOne(id) .map(topic -> ResponseEntity.ok(new TopicResource(topic))) .orElse(new ResponseEntity(HttpStatus.NOT_FOUND)); } @GetMapping(value = "/topics/{id}") ResponseEntity<TopicResource> getTopic(@PathVariable long id); }### Answer: @Test public void testGetTopic() throws Exception { Topic topic = given.topic("SpringRestDocs").description("Test driven documentation").save(); ResultActions actions = mockMvc.perform(get("/topics/{id}", topic.getId())) .andDo(print()); actions.andExpect(status().isOk()) .andExpect(jsonPath("$.name", is(topic.getName()))) .andExpect(jsonPath("$.description", is(topic.getDescription()))) .andDo(document("{class-name}/{method-name}", responseFields( fieldWithPath("name").description("The name of the Topic."), fieldWithPath("description").description("Desc."), subsectionWithPath("_links").description("HATEOAS links")), links(halLinks(), linkWithRel("self").description("The link to self resource")))); }
### Question: SpeakerController { @RequestMapping(value = "/speakers", method = RequestMethod.GET) public List<Speaker> allSpeakers() { return Arrays.asList(new Speaker("Name", "", "company")); } @RequestMapping(value = "/speakers/{id}", method = RequestMethod.GET) @ApiOperation( value = "Find speaker by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Speaker.class) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Speaker not found")}) ResponseEntity<Speaker> speaker( @ApiParam(value = "ID of speaker that needs to be fetched", allowableValues = "range[1,5]", required = true) @PathVariable long id); @RequestMapping(value = "/speakers", method = RequestMethod.GET) List<Speaker> allSpeakers(); }### Answer: @Test public void testAllSpeakers() throws Exception { ResultActions actions = mockMvc.perform(get("/speakers/{id}", 1L)) .andDo(print()); actions.andExpect(jsonPath("$.name", CoreMatchers.is("Name1"))) .andExpect(jsonPath("$.age", CoreMatchers.is("1"))) .andExpect(jsonPath("$.company", CoreMatchers.is("company"))); actions.andDo(document("{class-name}/{method-name}", responseFields(fieldWithPath("name").description("Speakers name"), fieldWithPath("age").description("Age"), fieldWithPath("company").description("The company that speaker is working on.")))); }
### Question: MultiXmlDocumentReader implements DocumentProducer { @Override public Iterator<Document> iterator() { if (inputStream != null) { throw new IllegalStateException("already fetched inputStream!"); } return new MultiXmlDocumentIterator(); } @Override void init(); @Override void close(); @Override void fail(); @Override Iterator<Document> iterator(); void setInput(Resource input); void setElemMatch(QName elemMatch); }### Answer: @Test public void testIterator() throws Exception { reader.setElemMatch(QName.valueOf("{mynamespace}state")); reader.setInput(new ClassPathResource("/dummyXml.xml")); int count = 0; for (Document document : reader) { count++; assertNotNull(((DomRawData)document.getRawData()).getDom()); } assertEquals(2,count); }
### Question: Tag { public String getWord() { return mWord; } private Tag(final Builder builder); String getWord(); int getStartIndex(); int getEndIndex(); }### Answer: @Test public void should_create_tag_with_given_word() { assertEquals(TEST_WORD, mTag.getWord()); }
### Question: Tag { public int getStartIndex() { return mStartIndex; } private Tag(final Builder builder); String getWord(); int getStartIndex(); int getEndIndex(); }### Answer: @Test public void should_create_tag_with_given_start_index() { assertEquals(TEST_START_INDEX, mTag.getStartIndex()); }
### Question: Tag { public int getEndIndex() { return mEndIndex; } private Tag(final Builder builder); String getWord(); int getStartIndex(); int getEndIndex(); }### Answer: @Test public void should_create_tag_with_given_end_index() { assertEquals(TEST_END_INDEX, mTag.getEndIndex()); }
### Question: FileTools { public static boolean createDirectoryStructure(String path, String projectName) { boolean result = true; result &= createDirectory(path + File.separator + projectName); for (String directory : CoreProperties.getDirectories()) { result &= createDirectory(path + File.separator + projectName + File.separator + directory); } return result; } static String getExecutionPath(Class clazz); static boolean createDirectoryStructure(String path, String projectName); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); }### Answer: @Test public void testCreateDirectoryStructure() { System.out.println("createDirectoryStructure"); String path = System.getProperty("user.home"); String project = "Test"; boolean expResult = true; boolean result = FileTools.createDirectoryStructure(path, project); assertEquals(expResult, result); }
### Question: FileTools { public static File doChoosePath() { JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getCurrentDirectory(); } return null; } static String getExecutionPath(Class clazz); static boolean createDirectoryStructure(String path, String projectName); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); }### Answer: @Test @Ignore public void testDoChoosePath() { System.out.println("doChoosePath"); File expResult = null; File result = FileTools.doChoosePath(); assertEquals(expResult, result); fail("The test case is a prototype."); }
### Question: FileTools { public static File doChooseFile(String extension, String directory, String type) { if (MainWindow.getInstance().getActiveProject() != null) { File projectPath = new File( System.getProperty("project.path") + File.separator + directory); if (projectPath.exists()) { JFileChooser fileChooser = new JFileChooser(new SingleRootFileSystemView(projectPath)); fileChooser.setAcceptAllFileFilterUsed(false); FileNameExtensionFilter filter = new FileNameExtensionFilter(type, extension); fileChooser.setFileFilter(filter); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getSelectedFile(); } } } return null; } static String getExecutionPath(Class clazz); static boolean createDirectoryStructure(String path, String projectName); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); }### Answer: @Test @Ignore public void testDoChooseFile() { System.out.println("doChooseFile"); String extension = ""; String directory = ""; String type = ""; File expResult = null; File result = FileTools.doChooseFile(extension, directory, type); assertEquals(expResult, result); fail("The test case is a prototype."); }
### Question: QueryReader { public List<String> readQueries() throws IOException { List<String> queries = new ArrayList<>(); String query; while (!(query = readQuery()).isEmpty()) { queries.add(query.trim()); } return queries; } QueryReader(Reader reader, char delimiter); List<String> readQueries(); }### Answer: @Test void readQueriesReadsAllQueries() throws IOException { QueryReader reader = new QueryReader( new StringReader(SQL_INPUT), ';' ); assertThat(reader.readQueries(), is(QUERIES)); } @Test void readQueriesUsesDelimiter() throws IOException { QueryReader reader = new QueryReader( new StringReader(SQL_INPUT_PIPE_DELIM), '|' ); List<String> queries = new ArrayList<>(QueryReaderTest.QUERIES); queries.replaceAll(s -> s.replace(';', '|')); assertThat(reader.readQueries(), is(queries)); }
### Question: SqlTaskSubmitter { protected final <R> void submitSqlPreparedStatementTask( String query, CheckedSqlFunction<? super PreparedStatement, ? extends R> function, BiConsumer<? super R, ? super Throwable> callback ) { submit(new SqlPreparedStatementTask<>(query, function, wrapCallback(callback))); } }### Answer: @Test void submitSqlPreparedStatementTaskSubmitsTask2() { submitter.submitSqlPreparedStatementTask( "", preparedStatement -> {}, (throwable) -> {} ); assertGotIncremented(); } @Test void submitSqlPreparedStatementTaskSubmitsTask() { submitter.submitSqlPreparedStatementTask( "", preparedStatement -> "", (s, throwable) -> {} ); assertGotIncremented(); } @Test void submitSqlPreparedStatementTaskCompletesCompletableFuture() { addStages(submitter.submitSqlPreparedStatementTask("", statement -> callCounter.addAndGet(1))); assertThat(callCounter.get(), is(3)); } @Test void submitSqlPreparedStatementTaskCompletesCompletableFutureExceptionally() { addStages(submitter.submitSqlPreparedStatementTask("", statement -> { throw new RuntimeException(); })); assertThat(callCounter.get(), is(4)); }
### Question: SqlTaskSubmitter { protected final <R> void submitSqlCallableStatementTask( String query, CheckedSqlFunction<? super CallableStatement, ? extends R> function, BiConsumer<? super R, ? super Throwable> callback ) { submit(new SqlCallableStatementTask<>(query, function, wrapCallback(callback))); } }### Answer: @Test void submitSqlCallableStatementTaskSubmitsTask2() { submitter.submitSqlCallableStatementTask( "", callableStatement -> {}, (throwable) -> {} ); assertGotIncremented(); } @Test void submitSqlCallableStatementTaskSubmitsTask() { submitter.submitSqlCallableStatementTask( "", callableStatement -> "", (s, throwable) -> {} ); assertGotIncremented(); } @Test void submitSqlCallableStatementTaskCompletesCompletableFuture() { addStages(submitter.submitSqlCallableStatementTask("", statement -> callCounter.addAndGet(1))); assertThat(callCounter.get(), is(3)); } @Test void submitSqlCallableStatementTaskCompletesCompletableFutureExceptionally() { addStages(submitter.submitSqlCallableStatementTask("", statement -> { throw new RuntimeException(); })); assertThat(callCounter.get(), is(4)); }
### Question: SqlTaskSubmitter { <R> BiConsumer<? super R, ? super Throwable> wrapCompletableFuture( CompletableFuture<R> completableFuture ) { Objects.requireNonNull(completableFuture); return wrapCallback((result, throwable) -> { if (throwable != null) { completableFuture.completeExceptionally(throwable); } else { completableFuture.complete(result); } }); } }### Answer: @Test void wrapCompletableFutureRequiresNonNullArgument() { assertThrows( NullPointerException.class, () -> submitter.wrapCompletableFuture(null) ); } @Test void wrappedCompletableFutureCompletes() throws Exception { CompletableFuture<Integer> cf = new CompletableFuture<>(); BiConsumer<? super Integer, ? super Throwable> biConsumer = submitter.wrapCompletableFuture(cf); biConsumer.accept(1, null); assertThat(cf.isDone() && !cf.isCancelled() && !cf.isCompletedExceptionally(), is(true)); assertThat(cf.get(), is(1)); } @Test void wrappedCompletableFutureCompletesExceptionally() { CompletableFuture<Integer> cf = new CompletableFuture<>(); BiConsumer<? super Integer, ? super Throwable> biConsumer = submitter.wrapCompletableFuture(cf); biConsumer.accept(1, new Exception()); assertThat(cf.isDone() && !cf.isCancelled() && cf.isCompletedExceptionally(), is(true)); assertThrows(ExecutionException.class, cf::get); } @Test void wrappedCompletableFutureIsWrappedByCallbackWrapper() { CompletableFuture<Integer> cf = new CompletableFuture<>(); BiConsumer<? super Integer, ? super Throwable> biConsumer = submitter.wrapCompletableFuture(cf); biConsumer.accept(null, null); assertThat(submitter.getInteger(), is(1)); }
### Question: SqlTaskSubmitter { protected final <R> void submitSqlConnectionTask( CheckedSqlFunction<? super Connection, ? extends R> function, BiConsumer<? super R, ? super Throwable> callback ) { submit(new SqlConnectionTask<>(function, wrapCallback(callback))); } }### Answer: @Test void submitSqlConnectionTaskCompletesCompletableFuture() { addStages(submitter.submitSqlConnectionTask(connection -> callCounter.addAndGet(1))); assertThat(callCounter.get(), is(3)); } @Test void submitSqlConnectionTaskCompletesCompletableFutureExceptionally() { addStages(submitter.submitSqlConnectionTask(connection -> { throw new RuntimeException(); })); assertThat(callCounter.get(), is(4)); } @Test void submitSqlConnectionTaskSubmitsTask() { submitter.submitSqlConnectionTask( connection -> "", (s, throwable) -> {} ); assertGotIncremented(); } @Test void submitSqlConnectionTaskSubmitsTask2() { submitter.submitSqlConnectionTask( connection -> {}, (throwable) -> {} ); assertGotIncremented(); }
### Question: SqlTaskSubmitter { protected final <R> void submitSqlStatementTask( CheckedSqlFunction<? super Statement, ? extends R> function, BiConsumer<? super R, ? super Throwable> callback ) { submit(new SqlStatementTask<>(function, wrapCallback(callback))); } }### Answer: @Test void submitSqlStatementTaskCompletesCompletableFuture() { addStages(submitter.submitSqlStatementTask(statement -> callCounter.addAndGet(1))); assertThat(callCounter.get(), is(3)); } @Test void submitSqlStatementTaskCompletesCompletableFutureExceptionally() { addStages(submitter.submitSqlStatementTask(statement -> { throw new RuntimeException(); })); assertThat(callCounter.get(), is(4)); } @Test void submitSqlStatementTaskSubmitsTask2() { submitter.submitSqlStatementTask( statement -> {}, (throwable) -> {} ); assertGotIncremented(); } @Test void submitSqlStatementTaskSubmitsTask() { submitter.submitSqlStatementTask( statement -> "", (s, throwable) -> {} ); assertGotIncremented(); }
### Question: AsyncSqlTaskSubmitter extends SqlTaskSubmitter { @Override final <R> BiConsumer<? super R, ? super Throwable> wrapCallback( BiConsumer<? super R, ? super Throwable> callback ) { Objects.requireNonNull(callback); return (r, t) -> syncExecutor.execute(() -> callback.accept(r, t)); } AsyncSqlTaskSubmitter( SqlConnectionPool connectionPool, Executor syncExecutor, Executor asyncExecutor ); @Override final Connection getConnection(); }### Answer: @Test void wrapCallbackWrapsCallbackWithSyncExecutor() { AtomicInteger integer = new AtomicInteger(); AsyncSqlTaskSubmitter submitter = newSubmitter( c -> integer.set(20), Runnable::run ); SqlStatementTask<Void> task = new SqlStatementTask<>( statement -> null, (aVoid, throwable) -> {} ); BiConsumer<? super Void, ? super Throwable> wrapped = submitter.wrapCallback(task.callback); wrapped.accept(null, null); assertThat(integer.get(), is(20)); }
### Question: AbstractSqlStatementTask extends SqlTask<T, R> { @Override final void execute(Connection connection) { try (T statement = statementFactory().apply(connection)) { R result = function.apply(statement); callback.accept(result, null); } catch (Throwable e) { callback.accept(null, e); } } AbstractSqlStatementTask( CheckedSqlFunction<? super T, ? extends R> function, BiConsumer<? super R, ? super Throwable> callback ); }### Answer: @Test void executeAppliesFunction() { AtomicInteger integer = new AtomicInteger(); AbstractSqlStatementTaskImpl task = new AbstractSqlStatementTaskImpl( statement -> { integer.incrementAndGet(); return "Hello"; }, (s, throwable) -> {} ); task.execute(new DummyConnection()); assertThat(integer.get(), is(1)); } @Test void executeCallsCallbackOnSuccess() { AtomicInteger integer = new AtomicInteger(); AbstractSqlStatementTaskImpl task = new AbstractSqlStatementTaskImpl( connection -> "Hello", (s, e) -> { integer.incrementAndGet(); assertThat(s, is("Hello")); assertThat(e, nullValue()); } ); task.execute(new DummyConnection()); assertThat(integer.get(), is(1)); } @Test void executeCallsCallbackOnFailure() { AtomicInteger integer = new AtomicInteger(); AbstractSqlStatementTaskImpl task = new AbstractSqlStatementTaskImpl( connection -> {throw new RuntimeException("Hello");}, (s, e) -> { integer.incrementAndGet(); assertThat(e.getMessage(), is("Hello")); assertThat(s, nullValue()); } ); task.execute(new DummyConnection()); assertThat(integer.get(), is(1)); task = new AbstractSqlStatementTaskImpl( connection -> {throw new Error("World");}, (s, e) -> { integer.incrementAndGet(); assertThat(e.getMessage(), is("World")); assertThat(s, nullValue()); } ); task.execute(new DummyConnection()); assertThat(integer.get(), is(2)); }
### Question: ScriptRunner { public ScriptRunner setReplacements(Map<String, ?> replacements) { for (String key : replacements.keySet()) { Objects.requireNonNull(key, "Map must not contain null keys."); } this.replacements = replacements; return this; } ScriptRunner(Reader reader, Connection connection); void runScript(); ScriptRunner setReplacements(Map<String, ?> replacements); ScriptRunner setLogQueries(boolean logQueries); }### Answer: @Test void setReplacementsRequiresNonNullKeys() { assertThrows(NullPointerException.class, () -> runner.setReplacements(null) ); String msg = assertThrows(NullPointerException.class, () -> runner.setReplacements(mapOf(null, "")) ).getMessage(); assertThat(msg, is("Map must not contain null keys.")); runner.setReplacements(mapOf("", "")); }
### Question: SqlTask { abstract void execute(Connection connection); SqlTask( CheckedSqlFunction<? super T, ? extends R> function, BiConsumer<? super R, ? super Throwable> callback ); }### Answer: @Test void constructorRequiresNonNullFunction() { assertThrows( NullPointerException.class, () -> new SqlTaskImpl(null, (s, e) -> {}) ); SqlTaskImpl sqlTask = new SqlTaskImpl(s -> "", (s, e) -> {}); sqlTask.execute(null); }
### Question: SqlConnectionTask extends SqlTask<Connection, R> { @Override void execute(Connection connection) { try { R result = function.apply(connection); callback.accept(result, null); } catch (Throwable e) { callback.accept(null, e); } } SqlConnectionTask( CheckedSqlFunction<? super Connection, ? extends R> function, BiConsumer<? super R, ? super Throwable> callback ); }### Answer: @Test void executeAppliesFunction() { AtomicInteger integer = new AtomicInteger(); SqlConnectionTask<String> task = new SqlConnectionTask<>( connection -> { integer.incrementAndGet(); return "Hello"; }, (s, throwable) -> {} ); task.execute(new DummyConnection()); assertThat(integer.get(), is(1)); } @Test void executeCallsCallbackOnSuccess() { AtomicInteger integer = new AtomicInteger(); SqlConnectionTask<String> task = new SqlConnectionTask<>( connection -> "Hello", (s, throwable) -> { integer.incrementAndGet(); assertThat(s, is("Hello")); assertThat(throwable, nullValue()); } ); task.execute(new DummyConnection()); assertThat(integer.get(), is(1)); } @Test void executeCallsCallbackOnFailure() { AtomicInteger integer = new AtomicInteger(); SqlConnectionTask<String> task = new SqlConnectionTask<>( connection -> {throw new RuntimeException("Hello");}, (s, throwable) -> { integer.incrementAndGet(); assertThat(throwable.getMessage(), is("Hello")); assertThat(s, nullValue()); } ); task.execute(new DummyConnection()); assertThat(integer.get(), is(1)); task = new SqlConnectionTask<>( connection -> {throw new Error("World");}, (s, throwable) -> { integer.incrementAndGet(); assertThat(throwable.getMessage(), is("World")); assertThat(s, nullValue()); } ); task.execute(new DummyConnection()); assertThat(integer.get(), is(2)); }
### Question: ScriptRunner { public void runScript() throws IOException, SQLException { List<String> queries = queryReader.readQueries(); try (Statement stmt = connection.createStatement()) { for (String query : queries) { executeQuery(stmt, query); } } } ScriptRunner(Reader reader, Connection connection); void runScript(); ScriptRunner setReplacements(Map<String, ?> replacements); ScriptRunner setLogQueries(boolean logQueries); }### Answer: @Test void runScriptExecutesQueries() throws Exception { runner.runScript(); List<String> executedQueries = connection.getLastStatement() .getExecutedQueries(); assertThat(executedQueries, is(QueryReaderTest.QUERIES)); }
### Question: SqlTaskSubmitter { static BiConsumer<? super Void, ? super Throwable> toBiConsumer( Consumer<? super Throwable> consumer ) { Objects.requireNonNull(consumer); return (o, throwable) -> consumer.accept(throwable); } }### Answer: @Test void toBiConsumerRequiresNonNullConsumer() { assertThrows( NullPointerException.class, () -> SqlTaskSubmitter.toBiConsumer(null) ); } @Test void toBiConsumerWrapsConsumer() { AtomicInteger integer = new AtomicInteger(); Consumer<Throwable> consumer = t -> { integer.incrementAndGet(); assertThat(t.getMessage(), is("HI")); }; BiConsumer<?, ? super Throwable> biConsumer = SqlTaskSubmitter.toBiConsumer(consumer); biConsumer.accept(null, new RuntimeException("HI")); assertThat(integer.get(), is(1)); }
### Question: RaftLeaderElection { public String leaderId() { return currentLeader.get(); } RaftLeaderElection(Class api, Config config); String leaderId(); LogicalTimestamp currentTerm(); Mono<Leader> leader(); Mono<HeartbeatResponse> onHeartbeat(HeartbeatRequest request); Mono<VoteResponse> onRequestVote(VoteRequest request); abstract void onBecomeLeader(); abstract void onBecomeCandidate(); abstract void onBecomeFollower(); void on(State state, Consumer func); }### Answer: @Test public void test() throws InterruptedException { Microservices seed = Microservices.builder().startAwait(); GreetingServiceImpl leaderElection1 = new GreetingServiceImpl(new Config()); GreetingServiceImpl leaderElection2 = new GreetingServiceImpl(new Config()); GreetingServiceImpl leaderElection3 = new GreetingServiceImpl(new Config()); Microservices node1 = Microservices.builder().seeds(seed.cluster().address()).services(leaderElection1).startAwait(); Microservices node2 = Microservices.builder().seeds(seed.cluster().address()).services(leaderElection2).startAwait(); Microservices node3 = Microservices.builder().seeds(seed.cluster().address()).services(leaderElection3).startAwait(); Thread.sleep(20000); System.out.println("leaderElection1 leader:" + leaderElection1.leaderId()); System.out.println("leaderElection2 leader:" + leaderElection2.leaderId()); System.out.println("leaderElection3 leader:" + leaderElection3.leaderId()); System.out.println("DONE"); Thread.currentThread().join(); }
### Question: Form extends LinearLayout { public boolean isValid() { validate(); return mIsValid; } Form(Context context); Form(Context context, AttributeSet attrs); boolean isValid(); void setShowErrors(boolean mShowErrors); void addInputValidator(InputValidator inputValidator); void setInputValidatorList(List<InputValidator> mInputValidatorList); void setActivity(Activity mActivity); void setViewGroupRoot(ViewGroup mViewGroupRoot); static Form newInstance(Builder builder); }### Answer: @Test public void validateEmptyForm() { mForm = new Form(mContext); assertTrue(mForm.isValid()); }
### Question: Form extends LinearLayout { public void addInputValidator(InputValidator inputValidator) { mInputValidatorList.add(inputValidator); } Form(Context context); Form(Context context, AttributeSet attrs); boolean isValid(); void setShowErrors(boolean mShowErrors); void addInputValidator(InputValidator inputValidator); void setInputValidatorList(List<InputValidator> mInputValidatorList); void setActivity(Activity mActivity); void setViewGroupRoot(ViewGroup mViewGroupRoot); static Form newInstance(Builder builder); }### Answer: @Test public void showErrorsJava() { mForm = new Form(mContext); InputValidator emailInputValidator = new InputValidator(mContext); emailInputValidator.setRequired(true); emailInputValidator.setEditText(mEmailEditText); mForm.addInputValidator(emailInputValidator); showErrors(); } @Test public void showErrorsBuilder() { mForm = new Form.Builder(mContext) .build(); InputValidator emailValidator = new InputValidator.Builder(mContext) .on(mEmailEditText) .required(true) .build(); mForm.addInputValidator(emailValidator); showErrors(); }
### Question: OptimisticAlexandriaMarkupClient { public AppInfo getAbout() { return unwrap(delegate.getAbout()); } OptimisticAlexandriaMarkupClient(final URI alexandriaURI); OptimisticAlexandriaMarkupClient(final String alexandriaURI); OptimisticAlexandriaMarkupClient(final URI alexandriaURI, SSLContext sslContext); OptimisticAlexandriaMarkupClient(final String alexandriaURI, SSLContext sslContext); WebTarget getRootTarget(); void close(); void setProperty(String jerseyClientProperty, Object value); AppInfo getAbout(); String getTAGML(UUID uuid); String getMarkupDepthLaTex(UUID uuid); String getDocumentLaTeX(UUID uuid); String getMatrixLaTex(UUID uuid); String getKdTreeLaTex(UUID uuid); JsonNode postTAGQLQuery(UUID uuid, String string); UUID addDocumentFromTexMECS(String string); void setDocumentFromTexMECS(UUID uuid, String string); UUID addDocumentFromTAGML(String string); void setDocumentFromTAGML(UUID uuid, String string); }### Answer: @Ignore @Test public void testAbout() { AppInfo about = client.getAbout(); assertThat(about.getVersion()).isNotEmpty(); }
### Question: Fn { public static boolean inList(String obj, String... list) { for (Object e : list) { if (obj.equals(e)) { return true; } } return false; } private Fn(); static boolean inList(String obj, String... list); static boolean inList(Integer obj, int... list); static T iif(Boolean condition, T value1, T value2); static Integer findInMatrix(Object[] matrix, Object search); static Integer findInMatrix(String[] matrix, String search, Boolean caseSensitive); static Boolean toLogical(Object value); static T nvl(T value, T alternateValue); static String bytesToHex(byte[] bytes); static byte[] hexToByte(String hexText); static byte[] base64ToBytes(String encrypted64); static String bytesToBase64(byte[] text); static String bytesToBase64Url(byte[] text); static Map<String, Object> queryParams(Object... params); static String numberToString(Object value, String mask); }### Answer: @Test public void testInList_String_StringArr() { System.out.println("inList"); String obj = "existe"; String[] list = {"EXISTE","exist","exist2","existe"}; boolean expResult = true; boolean result = Fn.inList(obj, list); assertEquals(expResult, result); result = Fn.inList(obj,"EXISTE","exist","exist2","existe"); assertEquals(expResult, result); } @Test public void testInList_Integer_intArr() { System.out.println("inList"); Integer obj = 1; int[] list = {1,2,4,5,1}; boolean expResult = true; boolean result = Fn.inList(obj, list); assertEquals(expResult, result); }
### Question: Fn { public static Integer findInMatrix(Object[] matrix, Object search) { int posicion = -1; for (int i = 0; i < matrix.length; i++) { if (matrix[i] == search) { posicion = i; break; } } return posicion; } private Fn(); static boolean inList(String obj, String... list); static boolean inList(Integer obj, int... list); static T iif(Boolean condition, T value1, T value2); static Integer findInMatrix(Object[] matrix, Object search); static Integer findInMatrix(String[] matrix, String search, Boolean caseSensitive); static Boolean toLogical(Object value); static T nvl(T value, T alternateValue); static String bytesToHex(byte[] bytes); static byte[] hexToByte(String hexText); static byte[] base64ToBytes(String encrypted64); static String bytesToBase64(byte[] text); static String bytesToBase64Url(byte[] text); static Map<String, Object> queryParams(Object... params); static String numberToString(Object value, String mask); }### Answer: @Test public void testFindInMatrix_ObjectArr_Object() { System.out.println("findInMatrix"); Object[] matrix = {3,2,3,4,1}; Object search = 1; Integer expResult = 4; Integer result = Fn.findInMatrix(matrix, search); assertEquals(expResult, result); } @Test public void testFindInMatrix_3args() { System.out.println("findInMatrix"); String[] matrix = {"EXISTE","existe"}; String search = "existe"; Boolean caseSensitive = false; Integer expResult = 0; Integer result = Fn.findInMatrix(matrix, search, caseSensitive); assertEquals(expResult, result); caseSensitive = true; expResult = 1; result = Fn.findInMatrix(matrix, search, caseSensitive); assertEquals(expResult, result); }
### Question: Fn { public static Boolean toLogical(Object value) { if (value == null) { return false; } else if (value instanceof Boolean) { return (Boolean) value; } else if ("1".equals(value.toString())) { return true; } else if ("true".equalsIgnoreCase(value.toString())) { return true; } else if ("0".equals(value.toString())) { return false; } else if ("false".equalsIgnoreCase(value.toString())) { return false; } else if ("".equals(value.toString())) { return false; } return false; } private Fn(); static boolean inList(String obj, String... list); static boolean inList(Integer obj, int... list); static T iif(Boolean condition, T value1, T value2); static Integer findInMatrix(Object[] matrix, Object search); static Integer findInMatrix(String[] matrix, String search, Boolean caseSensitive); static Boolean toLogical(Object value); static T nvl(T value, T alternateValue); static String bytesToHex(byte[] bytes); static byte[] hexToByte(String hexText); static byte[] base64ToBytes(String encrypted64); static String bytesToBase64(byte[] text); static String bytesToBase64Url(byte[] text); static Map<String, Object> queryParams(Object... params); static String numberToString(Object value, String mask); }### Answer: @Test public void testToLogical() { System.out.println("toLogical"); Object value = "1"; Boolean expResult = true; Boolean result = Fn.toLogical(value); assertEquals(expResult, result); value = 1; expResult = true; result = Fn.toLogical(value); assertEquals(expResult, result); value = "0"; expResult = false; result = Fn.toLogical(value); assertEquals(expResult, result); value = 0; expResult = false; result = Fn.toLogical(value); assertEquals(expResult, result); }
### Question: Fn { public static <T> T iif(Boolean condition, T value1, T value2) { if (condition) { return value1; } return value2; } private Fn(); static boolean inList(String obj, String... list); static boolean inList(Integer obj, int... list); static T iif(Boolean condition, T value1, T value2); static Integer findInMatrix(Object[] matrix, Object search); static Integer findInMatrix(String[] matrix, String search, Boolean caseSensitive); static Boolean toLogical(Object value); static T nvl(T value, T alternateValue); static String bytesToHex(byte[] bytes); static byte[] hexToByte(String hexText); static byte[] base64ToBytes(String encrypted64); static String bytesToBase64(byte[] text); static String bytesToBase64Url(byte[] text); static Map<String, Object> queryParams(Object... params); static String numberToString(Object value, String mask); }### Answer: @Test public void testIif() { System.out.println("iif"); boolean condition = (1 == 1); Object value1 = 1; Object value2 = 2; Object expResult = 1; Object result = Fn.iif(condition, value1, value2); assertEquals(expResult, result); }
### Question: Fn { public static <T> T nvl(T value, T alternateValue) { if (value == null) { return alternateValue; } return value; } private Fn(); static boolean inList(String obj, String... list); static boolean inList(Integer obj, int... list); static T iif(Boolean condition, T value1, T value2); static Integer findInMatrix(Object[] matrix, Object search); static Integer findInMatrix(String[] matrix, String search, Boolean caseSensitive); static Boolean toLogical(Object value); static T nvl(T value, T alternateValue); static String bytesToHex(byte[] bytes); static byte[] hexToByte(String hexText); static byte[] base64ToBytes(String encrypted64); static String bytesToBase64(byte[] text); static String bytesToBase64Url(byte[] text); static Map<String, Object> queryParams(Object... params); static String numberToString(Object value, String mask); }### Answer: @Test public void testNvl() { System.out.println("nvl"); Object value = null; Object alternateValue = "es nulo"; Object expResult = "es nulo"; Object result = Fn.nvl(value, alternateValue); assertEquals(expResult, result); }
### Question: Fn { public static String bytesToHex(byte[] bytes) { StringBuilder result = new StringBuilder(); for (byte byt : bytes) { result.append(Integer.toString((byt & 0xff) + 0x100, 16).substring(1)); } return result.toString(); } private Fn(); static boolean inList(String obj, String... list); static boolean inList(Integer obj, int... list); static T iif(Boolean condition, T value1, T value2); static Integer findInMatrix(Object[] matrix, Object search); static Integer findInMatrix(String[] matrix, String search, Boolean caseSensitive); static Boolean toLogical(Object value); static T nvl(T value, T alternateValue); static String bytesToHex(byte[] bytes); static byte[] hexToByte(String hexText); static byte[] base64ToBytes(String encrypted64); static String bytesToBase64(byte[] text); static String bytesToBase64Url(byte[] text); static Map<String, Object> queryParams(Object... params); static String numberToString(Object value, String mask); }### Answer: @Test public void testBytesToHex() throws UnsupportedEncodingException, NoSuchAlgorithmException { System.out.println("bytesToHex"); String expResult = "5ad6f23da25b3a54cd5ae716c401732d"; String msg = "abcdefghijklmnñopqrstuvwxyzáéíóú"; MessageDigest digest = MessageDigest.getInstance("MD5"); byte[] bytes = digest.digest(msg.getBytes("UTF-8")); String result = Fn.bytesToHex(bytes); assertEquals(expResult, result); }
### Question: Fn { public static byte[] hexToByte(String hexText) { int len = hexText.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(hexText.charAt(i), 16) << 4) + Character.digit(hexText.charAt(i+1), 16)); } return data; } private Fn(); static boolean inList(String obj, String... list); static boolean inList(Integer obj, int... list); static T iif(Boolean condition, T value1, T value2); static Integer findInMatrix(Object[] matrix, Object search); static Integer findInMatrix(String[] matrix, String search, Boolean caseSensitive); static Boolean toLogical(Object value); static T nvl(T value, T alternateValue); static String bytesToHex(byte[] bytes); static byte[] hexToByte(String hexText); static byte[] base64ToBytes(String encrypted64); static String bytesToBase64(byte[] text); static String bytesToBase64Url(byte[] text); static Map<String, Object> queryParams(Object... params); static String numberToString(Object value, String mask); }### Answer: @Test public void testHexToByte() throws NoSuchAlgorithmException, UnsupportedEncodingException { System.out.println("hexToByte"); String hexText = "5ad6f23da25b3a54cd5ae716c401732d"; String msg = "abcdefghijklmnñopqrstuvwxyzáéíóú"; MessageDigest digest = MessageDigest.getInstance("MD5"); byte[] expResult = digest.digest(msg.getBytes("UTF-8")); byte[] result = Fn.hexToByte(hexText); assertArrayEquals(expResult, result); }
### Question: Fn { public static byte[] base64ToBytes(String encrypted64){ return Base64.getDecoder().decode(encrypted64); } private Fn(); static boolean inList(String obj, String... list); static boolean inList(Integer obj, int... list); static T iif(Boolean condition, T value1, T value2); static Integer findInMatrix(Object[] matrix, Object search); static Integer findInMatrix(String[] matrix, String search, Boolean caseSensitive); static Boolean toLogical(Object value); static T nvl(T value, T alternateValue); static String bytesToHex(byte[] bytes); static byte[] hexToByte(String hexText); static byte[] base64ToBytes(String encrypted64); static String bytesToBase64(byte[] text); static String bytesToBase64Url(byte[] text); static Map<String, Object> queryParams(Object... params); static String numberToString(Object value, String mask); }### Answer: @Test public void testBase64ToBytes() throws Exception { System.out.println("base64ToBytes"); String clearText = "abcdefghijklmnñopqrstuvwxyzáéíóú"; String key = "123456á"; SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), CipherUtil.BLOWFISH); Cipher cipher = Cipher.getInstance(CipherUtil.BLOWFISH); cipher.init(Cipher.ENCRYPT_MODE, keyspec); byte[] expResult = cipher.doFinal(clearText.getBytes()); String encrypted64 = CipherUtil.encryptBlowfishToBase64(clearText, key); byte[] result = Fn.base64ToBytes(encrypted64); assertArrayEquals(expResult, result); }
### Question: Fn { public static String bytesToBase64(byte[] text){ return Base64.getEncoder().encodeToString(text); } private Fn(); static boolean inList(String obj, String... list); static boolean inList(Integer obj, int... list); static T iif(Boolean condition, T value1, T value2); static Integer findInMatrix(Object[] matrix, Object search); static Integer findInMatrix(String[] matrix, String search, Boolean caseSensitive); static Boolean toLogical(Object value); static T nvl(T value, T alternateValue); static String bytesToHex(byte[] bytes); static byte[] hexToByte(String hexText); static byte[] base64ToBytes(String encrypted64); static String bytesToBase64(byte[] text); static String bytesToBase64Url(byte[] text); static Map<String, Object> queryParams(Object... params); static String numberToString(Object value, String mask); }### Answer: @Test public void testBytesToBase64() throws Exception { System.out.println("bytesToBase64"); String clearText = "abcdefghijklmnñopqrstuvwxyzáéíóú"; String key = "123456á"; SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), CipherUtil.BLOWFISH); Cipher cipher = Cipher.getInstance(CipherUtil.BLOWFISH); cipher.init(Cipher.ENCRYPT_MODE, keyspec); byte[] bytes = cipher.doFinal(clearText.getBytes()); String expResult = CipherUtil.encryptBlowfishToBase64(clearText, key); String result = Fn.bytesToBase64(bytes); assertEquals(expResult, result); }