src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
MavenPOMAnalyzer extends Analyzer { public MavenPOMAnalyzer(Version matchVersion) { this(matchVersion, MAVEN_XML_TAG_SET); } MavenPOMAnalyzer(Version matchVersion); MavenPOMAnalyzer(Version matchVersion, String[] stopWords); static final String[] MAVEN_XML_TAG_SET; } | @Test public void testMavenPOMAnalyzer() throws IOException { String input = "<project xmlns=\"http: + "xmlns:xsi=\"http: + "xsi:schemaLocation=\"http: + "http: + "<modelVersion>4.0.0</modelVersion>" + "<parent>\n" + "<groupId>name.abhijitsarkar.lucene</groupId>\n" + "<artifactId>lucene-learning</artifactId>\n" + "<version>1.0-SNAPSHOT</version>\n" + "</parent>\n" + "<artifactId>maven-repo-mgr</artifactId>\n" + "<packaging>jar</packaging>\n" + "<name>hadoop-examples</name>\n"; String[] output = new String[] { "name.abhijitsarkar.lucene", "lucene-learning" }; TokenStream stream = analyzer.tokenStream("field", new StringReader( input)); CharTermAttribute termAttr = stream .addAttribute(CharTermAttribute.class); OffsetAttribute offsetAtt = stream.addAttribute(OffsetAttribute.class); stream.reset(); Assert.assertTrue("There should be more tokens", stream.incrementToken()); Assert.assertEquals("Wrong token", output[0], termAttr.toString()); Assert.assertEquals("Wrong start offset", 0, offsetAtt.startOffset()); Assert.assertEquals("Wrong end offset", 34, offsetAtt.endOffset()); Assert.assertTrue("There should be more tokens", stream.incrementToken()); Assert.assertEquals("Wrong token", output[1], termAttr.toString()); Assert.assertEquals("Wrong start offset", 35, offsetAtt.startOffset()); Assert.assertEquals("Wrong end offset", 50, offsetAtt.endOffset()); Assert.assertFalse(stream.incrementToken()); stream.close(); } |
LinkedList { public E remove() { return remove(0); } LinkedList(); LinkedList(Collection<E> elements); boolean add(E e); boolean add(int index, E e); boolean addAll(Collection<E> elements); E remove(); E remove(int index); E peek(); int size(); boolean isEmpty(); void reverse(); LinkedListNode<E> head(); LinkedListNode<E> tail(); E get(int index); void set(int index, E element); int indexOf(E element); int lastIndexOf(E element); @Override String toString(); } | @Test public void testRemove() { Assert.assertEquals(3, linkedList.size()); Assert.assertEquals(Integer.valueOf(1), linkedList.remove()); Assert.assertEquals(2, linkedList.size()); Assert.assertEquals(Integer.valueOf(2), linkedList.remove(0)); Assert.assertEquals(1, linkedList.size()); Assert.assertEquals(Integer.valueOf(1), linkedList.remove()); Assert.assertEquals(0, linkedList.size()); } |
LinkedList { public void reverse() { if (size <= 1) { return; } LinkedListNode<E> predecessor = head; LinkedListNode<E> current = head.successor(); LinkedListNode<E> successor = null; while (current != this.tail) { successor = current.successor(); current.setSuccessor(predecessor); predecessor = current; current = successor; } tail = head; tail.setSuccessor(null); head = current; head.setSuccessor(predecessor); } LinkedList(); LinkedList(Collection<E> elements); boolean add(E e); boolean add(int index, E e); boolean addAll(Collection<E> elements); E remove(); E remove(int index); E peek(); int size(); boolean isEmpty(); void reverse(); LinkedListNode<E> head(); LinkedListNode<E> tail(); E get(int index); void set(int index, E element); int indexOf(E element); int lastIndexOf(E element); @Override String toString(); } | @Test public void testReverse() { linkedList.reverse(); Assert.assertEquals(3, linkedList.size()); Assert.assertEquals(Integer.valueOf(1), linkedList.remove()); Assert.assertEquals(2, linkedList.size()); Assert.assertEquals(Integer.valueOf(2), linkedList.remove()); Assert.assertEquals(1, linkedList.size()); Assert.assertEquals(Integer.valueOf(1), linkedList.remove()); Assert.assertEquals(0, linkedList.size()); } |
Hashtable { @SuppressWarnings("unchecked") public Hashtable() { buckets = new LinkedList[capacity]; } @SuppressWarnings("unchecked") Hashtable(); V put(K key, V value); V get(K key); final int size(); final float loadFactor(); static final Logger LOGGER; } | @Test public void testHashtable() { Assert.assertEquals(2, hashtable.size()); Assert.assertEquals(Integer.valueOf(3), hashtable.get(2)); Assert.assertEquals(Integer.valueOf(2), hashtable.get(1)); hashtable.put(2, 5); Assert.assertEquals(Integer.valueOf(5), hashtable.get(2)); Assert.assertEquals(null, hashtable.get(10)); } |
Sorter { public static int[] mergeSort(int[] arr) { return recursiveMergeSort(arr, 0, arr.length - 1); } static int[] mergeSort(int[] arr); static int[] quickSort(int[] arr); static int[] bucketSort(int[] arr); static Integer[] countingSort(final int[] arr); } | @Test public void testMergeSort() { int[] arr = new int[] { 17, 3, 99, 51 }; int[] expected = new int[] { 3, 17, 51, 99 }; int[] actual = Sorter.mergeSort(arr); Assert.assertArrayEquals(expected, actual); } |
IOUtils { public static Writable findInMapFile(final Text key, URI dirURI, final Configuration conf) { MapFile.Reader reader = null; Writable value = null; LOGGER.debug("MapFile URI: {}.", dirURI); try { final Path inputPath = new Path(dirURI); final FileSystem fs = inputPath.getFileSystem(conf); reader = new MapFile.Reader(fs, dirURI.toString(), conf); value = reader.get(key, new Text()); } catch (IOException ioe) { ioe.printStackTrace(); } finally { closeStreams(reader); } LOGGER.debug("Returning value: {}, for key: {}.", value, key); return value; } static Writable findInMapFile(final Text key, URI dirURI, final Configuration conf); @SuppressWarnings("resource") static URI createMapFile(URI inputURI, final Configuration conf); static URI compressFile(final URI uncompressedURI, final String codecName, final Configuration conf); static String addExtension(String filename, final String newExtension, final boolean removeExistingExtension); static String removeExtension(String filename); static URI uncompressFile(final URI archiveURI, final Configuration conf); static final Logger LOGGER; } | @Test public void testKeyFound() { final String key = "3858243"; final String expectedValue = "1975 5485 1973 \"FR\" \"\" 445095 3 12 2 6 63 7 2 0.8571 0 0.2778 6 8.1429 0 0 0 0"; final Writable actualValue = findInMapFile(new Text(key), dirURI, conf); Assert.assertNotNull("Value for key: " + key + " shouldn't be null", actualValue); Assert.assertEquals("Wrong value retirned for key: " + key, expectedValue, actualValue.toString()); }
@Test public void testKeyNotFound() { final String key = "1"; final Writable actualValue = findInMapFile(new Text(key), dirURI, conf); Assert.assertNull("Value for key: " + key + " should be null", actualValue); } |
Sorter { public static int[] quickSort(int[] arr) { return recursiveQuickSort(arr, 0, arr.length - 1); } static int[] mergeSort(int[] arr); static int[] quickSort(int[] arr); static int[] bucketSort(int[] arr); static Integer[] countingSort(final int[] arr); } | @Test public void testQuickSort() { int[] arr = new int[] { 17, 3, 99, 51 }; int[] expected = new int[] { 3, 17, 51, 99 }; int[] actual = Sorter.quickSort(arr); Assert.assertArrayEquals(expected, actual); } |
Sorter { public static int[] bucketSort(int[] arr) { int[][] buckets = scatter(arr); ArrayDeque<int[]> stack = new ArrayDeque<int[]>(); for (int[] bucket : buckets) { if (bucket != null) { stack.add(mergeSort(bucket)); } } return gather(stack); } static int[] mergeSort(int[] arr); static int[] quickSort(int[] arr); static int[] bucketSort(int[] arr); static Integer[] countingSort(final int[] arr); } | @Test public void testBucketSort() { int[] arr = new int[] { 17, 3, 99, 51 }; int[] expected = new int[] { 3, 17, 51, 99 }; int[] actual = Sorter.bucketSort(arr); Assert.assertArrayEquals(expected, actual); } |
Sorter { public static Integer[] countingSort(final int[] arr) { final Map<Integer, Pair> countMap = new HashMap<>(); for (final int i : arr) { Pair p = new Pair(i, 1); if (countMap.containsKey(i)) { p.value += countMap.get(i).value; } countMap.put(i, p); } BinarySearchTree<Pair> bst = new BinarySearchTree<>(countMap.values()); final List<Pair> sortedPairs = BinaryTreeWalker.recursiveInorder(bst.root()); return CollectionUtils.collect(sortedPairs, TransformerUtils.<Pair, Integer> invokerTransformer("getKey")) .toArray(new Integer[] {}); } static int[] mergeSort(int[] arr); static int[] quickSort(int[] arr); static int[] bucketSort(int[] arr); static Integer[] countingSort(final int[] arr); } | @Test public void testCountingSort() { int[] arr = new int[] { 17, 3, 99, 51 }; Integer[] expected = { 3, 17, 51, 99 }; Integer[] actual = Sorter.countingSort(arr); Assert.assertArrayEquals(expected, actual); } |
Searcher { public static <E extends Comparable<E>> BinaryTreeNode<E> binarySearch(BinarySearchTree<E> binTree, BinaryTreeNode<E> startNode, E value) { if (startNode == null || value.equals(startNode.data())) { return startNode; } if (value.compareTo(startNode.data()) < 0) { return binarySearch(binTree, startNode.leftChild(), value); } return binarySearch(binTree, startNode.rightChild(), value); } static BinaryTreeNode<E> binarySearch(BinarySearchTree<E> binTree,
BinaryTreeNode<E> startNode, E value); static BinaryTreeNode<E> binarySearch(BinarySearchTree<E> binTree, E value); static BinaryTreeNode<E> breadthFirstSearch(BinarySearchTree<E> binTree,
BinaryTreeNode<E> startNode, E value); static BinaryTreeNode<E> breadthFirstSearch(BinarySearchTree<E> binTree, E value); static BinaryTreeNode<E> depthFirstSearch(BinarySearchTree<E> binTree,
BinaryTreeNode<E> startNode, E value); static BinaryTreeNode<E> depthFirstSearch(BinarySearchTree<E> binTree, E value); static final Logger LOGGER; } | @Test public void testBinarySearch() { for (int i = 1; i < 6; i++) { Assert.assertNotNull(Searcher.binarySearch(binTree, i)); } Assert.assertNull(Searcher.binarySearch(binTree, 10)); BinaryTreeNode<Integer> four = Searcher.binarySearch(binTree, 4); Assert.assertNotNull(four); Assert.assertFalse(four.isLeaf()); Assert.assertNull(four.leftChild()); Assert.assertNotNull(four.rightChild()); Assert.assertEquals(Integer.valueOf(5), four.rightChild().data()); BinaryTreeNode<Integer> five = Searcher.binarySearch(binTree, 5); Assert.assertTrue(five.isLeaf()); } |
Searcher { public static <E extends Comparable<E>> BinaryTreeNode<E> breadthFirstSearch(BinarySearchTree<E> binTree, BinaryTreeNode<E> startNode, E value) { LOGGER.debug("Searching for: {}.", value); Set<BinaryTreeNode<E>> visited = new HashSet<BinaryTreeNode<E>>(); Queue<BinaryTreeNode<E>> queue = new Queue<BinaryTreeNode<E>>(); LOGGER.debug("Visited: {}.", startNode); visited.add(startNode); queue.enqueue(startNode); BinaryTreeNode<E> node = null; BinaryTreeNode<E> leftChild = null; BinaryTreeNode<E> rightChild = null; while (!queue.isEmpty()) { node = queue.dequeue(); if (node.data().equals(value)) { return node; } leftChild = node.leftChild(); rightChild = node.rightChild(); if (leftChild != null && !visited.contains(leftChild)) { LOGGER.debug("Visited: {}.", leftChild); visited.add(leftChild); queue.enqueue(leftChild); } if (rightChild != null && !visited.contains(rightChild)) { LOGGER.debug("Visited: {}.", rightChild); visited.add(rightChild); queue.enqueue(rightChild); } } return null; } static BinaryTreeNode<E> binarySearch(BinarySearchTree<E> binTree,
BinaryTreeNode<E> startNode, E value); static BinaryTreeNode<E> binarySearch(BinarySearchTree<E> binTree, E value); static BinaryTreeNode<E> breadthFirstSearch(BinarySearchTree<E> binTree,
BinaryTreeNode<E> startNode, E value); static BinaryTreeNode<E> breadthFirstSearch(BinarySearchTree<E> binTree, E value); static BinaryTreeNode<E> depthFirstSearch(BinarySearchTree<E> binTree,
BinaryTreeNode<E> startNode, E value); static BinaryTreeNode<E> depthFirstSearch(BinarySearchTree<E> binTree, E value); static final Logger LOGGER; } | @Test public void testBreadthFirstSearch() { for (int i = 1; i < 6; i++) { Assert.assertNotNull(Searcher.breadthFirstSearch(binTree, i)); } Assert.assertNull(Searcher.breadthFirstSearch(binTree, 10)); BinaryTreeNode<Integer> four = Searcher.breadthFirstSearch(binTree, 4); Assert.assertNotNull(four); Assert.assertFalse(four.isLeaf()); Assert.assertNull(four.leftChild()); Assert.assertNotNull(four.rightChild()); Assert.assertEquals(Integer.valueOf(5), four.rightChild().data()); BinaryTreeNode<Integer> five = Searcher.breadthFirstSearch(binTree, 5); Assert.assertTrue(five.isLeaf()); } |
Searcher { public static <E extends Comparable<E>> BinaryTreeNode<E> depthFirstSearch(BinarySearchTree<E> binTree, BinaryTreeNode<E> startNode, E value) { LOGGER.debug("Searching for: {}.", value); Stack<BinaryTreeNode<E>> stack = new Stack<BinaryTreeNode<E>>(); Set<BinaryTreeNode<E>> visited = new HashSet<BinaryTreeNode<E>>(); stack.push(startNode); BinaryTreeNode<E> leftChild = null; BinaryTreeNode<E> rightChild = null; BinaryTreeNode<E> currentNode = null; while (!stack.isEmpty()) { currentNode = stack.pop(); visited.add(currentNode); LOGGER.debug("Visited: {}.", visited); if (currentNode.data().equals(value)) { return currentNode; } rightChild = currentNode.rightChild(); if (rightChild != null && !visited.contains(rightChild)) { stack.push(rightChild); } leftChild = currentNode.leftChild(); if (leftChild != null && !visited.contains(leftChild)) { stack.push(leftChild); } } return null; } static BinaryTreeNode<E> binarySearch(BinarySearchTree<E> binTree,
BinaryTreeNode<E> startNode, E value); static BinaryTreeNode<E> binarySearch(BinarySearchTree<E> binTree, E value); static BinaryTreeNode<E> breadthFirstSearch(BinarySearchTree<E> binTree,
BinaryTreeNode<E> startNode, E value); static BinaryTreeNode<E> breadthFirstSearch(BinarySearchTree<E> binTree, E value); static BinaryTreeNode<E> depthFirstSearch(BinarySearchTree<E> binTree,
BinaryTreeNode<E> startNode, E value); static BinaryTreeNode<E> depthFirstSearch(BinarySearchTree<E> binTree, E value); static final Logger LOGGER; } | @Test public void testDepthFirstSearch() { for (int i = 1; i < 6; i++) { Assert.assertNotNull(Searcher.depthFirstSearch(binTree, i)); } Assert.assertNull(Searcher.depthFirstSearch(binTree, 10)); BinaryTreeNode<Integer> four = Searcher.depthFirstSearch(binTree, 4); Assert.assertNotNull(four); Assert.assertFalse(four.isLeaf()); Assert.assertNull(four.leftChild()); Assert.assertNotNull(four.rightChild()); Assert.assertEquals(Integer.valueOf(5), four.rightChild().data()); BinaryTreeNode<Integer> five = Searcher.depthFirstSearch(binTree, 5); Assert.assertTrue(five.isLeaf()); } |
Rentals extends ArrayList<AbstractRental> { public Rentals(String customerName) { this.customerName = customerName; } Rentals(String customerName); String rentalStatement(); } | @Test public void testRentals() { Rentals rentals = new Rentals("John Doe"); Assert.assertEquals("Wrong size", 0, rentals.size()); Movie theShining = new Movie("The Shining", Movie.REGULAR); AbstractRental theShiningRentalForADay = new RegularRental(theShining, 1); rentals.add(theShiningRentalForADay); Movie topGun = new Movie("Top Gun", Movie.REGULAR); AbstractRental topGunRentalFor3Days = new RegularRental(topGun, 3); rentals.add(topGunRentalFor3Days); Assert.assertEquals("Wrong size", 2, rentals.size()); AbstractRental firstRental = rentals.get(0); AbstractRental secondRental = rentals.get(1); Assert.assertEquals("Wrong number of rental days", 1, firstRental.getDaysRented()); Assert.assertEquals("Wrong number of rental days", 3, secondRental.getDaysRented()); Assert.assertEquals("Wrong movie title", "The Shining", firstRental .getMovie().getTitle()); Assert.assertEquals("Wrong movie title", "Top Gun", secondRental .getMovie().getTitle()); } |
CustomerRefactored { public String getName() { return name; } CustomerRefactored(String name); String getName(); } | @Test public void testRegularMovieRentalForADay() { CustomerRefactored cust = new CustomerRefactored("John Doe"); Movie theShining = new Movie("The Shining", Movie.REGULAR); Rentals rentals = new Rentals(cust.getName()); AbstractRental theShiningRentalForADay = new RegularRental(theShining, 1); rentals.add(theShiningRentalForADay); String[] movieTitles = new String[] { theShining.getTitle() }; double[] thisAmount = new double[] { 2.0d }; double totalAmount = 2.0d; int frequentRenterPoints = 1; String expectedStatement = getRentalStatement(cust.getName(), movieTitles, thisAmount, totalAmount, frequentRenterPoints); Assert.assertEquals("Wrong statement", expectedStatement, rentals.rentalStatement()); }
@Test public void testRegularMovieRentalFor3Days() { CustomerRefactored cust = new CustomerRefactored("John Doe"); Movie theShining = new Movie("The Shining", Movie.REGULAR); Rentals rentals = new Rentals(cust.getName()); AbstractRental theShiningRentalFor3Days = new RegularRental(theShining, 3); rentals.add(theShiningRentalFor3Days); String[] movieTitles = new String[] { theShining.getTitle() }; double[] thisAmount = new double[] { 3.5d }; double totalAmount = 3.5d; int frequentRenterPoints = 1; String expectedStatement = getRentalStatement(cust.getName(), movieTitles, thisAmount, totalAmount, frequentRenterPoints); Assert.assertEquals("Wrong statement", expectedStatement, rentals.rentalStatement()); }
@Test public void test2RegularMovieRentalsFor3Days() { CustomerRefactored cust = new CustomerRefactored("John Doe"); Movie theShining = new Movie("The Shining", Movie.REGULAR); Movie topGun = new Movie("Top Gun", Movie.REGULAR); Rentals rentals = new Rentals(cust.getName()); AbstractRental theShiningRentalFor3Days = new RegularRental(theShining, 3); rentals.add(theShiningRentalFor3Days); AbstractRental topGunRentalFor3Days = new RegularRental(topGun, 3); rentals.add(topGunRentalFor3Days); String[] movieTitles = new String[] { theShining.getTitle(), topGun.getTitle() }; double[] thisAmount = new double[] { 3.5d, 3.5d }; double totalAmount = 7.0d; int frequentRenterPoints = 2; String expectedStatement = getRentalStatement(cust.getName(), movieTitles, thisAmount, totalAmount, frequentRenterPoints); Assert.assertEquals("Wrong statement", expectedStatement, rentals.rentalStatement()); }
@Test public void testChildrensMovieRentalFor5Days() { CustomerRefactored cust = new CustomerRefactored("John Doe"); Movie theLionKing = new Movie("The Lion King", Movie.CHILDRENS); Rentals rentals = new Rentals(cust.getName()); AbstractRental theLionKingRentalFor5Days = new ChildrensRental( theLionKing, 5); rentals.add(theLionKingRentalFor5Days); String[] movieTitles = new String[] { theLionKing.getTitle() }; double[] thisAmount = new double[] { 4.5d }; double totalAmount = 4.5d; int frequentRenterPoints = 1; String expectedStatement = getRentalStatement(cust.getName(), movieTitles, thisAmount, totalAmount, frequentRenterPoints); Assert.assertEquals("Wrong statement", expectedStatement, rentals.rentalStatement()); }
@Test public void test1RegularAnd1ChidrensMovieRentalsFor3Days() { CustomerRefactored cust = new CustomerRefactored("John Doe"); Movie theShining = new Movie("The Shining", Movie.REGULAR); Movie theLionKing = new Movie("The Lion King", Movie.CHILDRENS); Rentals rentals = new Rentals(cust.getName()); AbstractRental theShiningRentalFor3Days = new RegularRental(theShining, 3); rentals.add(theShiningRentalFor3Days); AbstractRental theLionKingRentalFor3Days = new ChildrensRental( theLionKing, 3); rentals.add(theLionKingRentalFor3Days); String[] movieTitles = new String[] { theShining.getTitle(), theLionKing.getTitle() }; double[] thisAmount = new double[] { 3.5d, 1.5d }; double totalAmount = 5.0d; int frequentRenterPoints = 2; String expectedStatement = getRentalStatement(cust.getName(), movieTitles, thisAmount, totalAmount, frequentRenterPoints); Assert.assertEquals("Wrong statement", expectedStatement, rentals.rentalStatement()); }
@Test public void testNewMovieRentalFor5Days() { CustomerRefactored cust = new CustomerRefactored("John Doe"); Movie tdkRises = new Movie("The Dark Knight Rises", Movie.NEW_RELEASE); Rentals rentals = new Rentals(cust.getName()); AbstractRental tdkRisesRentalFor5Days = new NewReleaseRental(tdkRises, 5); rentals.add(tdkRisesRentalFor5Days); String[] movieTitles = new String[] { tdkRises.getTitle() }; double[] thisAmount = new double[] { 15.0d }; double totalAmount = 15.0d; int frequentRenterPoints = 2; String expectedStatement = getRentalStatement(cust.getName(), movieTitles, thisAmount, totalAmount, frequentRenterPoints); Assert.assertEquals("Wrong statement", expectedStatement, rentals.rentalStatement()); } |
HttpHeadTask implements Callable<String> { @Override public String call() { CloseableHttpResponse response = null; try { response = httpClient.execute(httpHead, context); response.getEntity(); log.info("Successfully received response from: {}.", httpHead.getURI().getHost()); return httpHead.getURI().getHost(); } catch (IOException ex) { log.error("Something bad happened while getting from: {}.", ex, httpHead.getURI().getHost()); return ""; } finally { if (response != null) { try { response.close(); } catch (IOException e) { log.error("Failed to close response: {}.", e, httpHead.getURI().getHost()); } } } } HttpHeadTask(CloseableHttpClient httpClient, String uri); @Override String call(); } | @Test @DisplayName("Keep alive doesn't prevent a connection from being used for a different route") public void test1() throws IOException, InterruptedException { connMgr.setDefaultMaxPerRoute(5); connMgr.setMaxTotal(5); CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connMgr) .setDefaultRequestConfig(requestConfig) .setKeepAliveStrategy((response, context) -> 10000l) .build(); StepVerifier.create(Flux.range(1, 5) .parallel(10) .runOn(Schedulers.parallel()) .map(i -> "https: .flatMap(uri -> Mono.fromCallable(new HttpHeadTask(httpClient, uri)) .delayElement(Duration.ofMillis(3000l)))) .recordWith(ArrayList::new) .expectNextCount(5) .consumeRecordedWith(results -> assertThat(results) .hasSize(5) .allSatisfy(verifier)) .verifyComplete(); HttpHeadTask headFromYahooTask = new HttpHeadTask(httpClient, "https: assertThat(headFromYahooTask.call()).isEqualTo("www.yahoo.com"); httpClient.close(); } |
JackOfAllTrades { public static IntegerNode reverseList(IntegerNode head) { IntegerNode first = reverse(head.next(), head); return IntegerNode.builder() .next(first) .build(); } static IntegerNode reverseList(IntegerNode head); } | @Test void testReverseList() { IntegerNode head = LinkedListFactory.newLinkedList(); for (IntegerNode current = head; current != null; current = current.next()) { System.out.printf("%s%s", current.toString(), current.next() == null ? "\n" : "--->"); } head = JackOfAllTrades.reverseList(head); for (IntegerNode current = head; current != null; current = current.next()) { System.out.printf("%s%s", current.toString(), current.next() == null ? "\n" : "--->"); } } |
BinaryTreeUtil { public static int height(IntegerNode root) { if (root == null) { return 0; } return Math.max(height(root.left()), height(root.right())) + 1; } private BinaryTreeUtil(); static int height(IntegerNode root); static boolean isBST(ParentAwareIntegerNode root); static boolean isSame(IntegerNode root1, IntegerNode root2); static IntegerNode lowestCommonAncestor(IntegerNode root, int value1, int value2); } | @Test void testHeight() { assertThat(BinaryTreeUtil.height(ROOT)).isEqualTo(4); } |
BinaryTreeUtil { public static boolean isSame(IntegerNode root1, IntegerNode root2) { boolean same = false; if (root1 == root2) { same = true; } else if (root1 != null && root2 != null && root1.value() == root2.value()) { same = isSame(root1.left(), root2.left()) && isSame(root1.right(), root2.right()); } return same; } private BinaryTreeUtil(); static int height(IntegerNode root); static boolean isBST(ParentAwareIntegerNode root); static boolean isSame(IntegerNode root1, IntegerNode root2); static IntegerNode lowestCommonAncestor(IntegerNode root, int value1, int value2); } | @Test void testIsSame() { IntegerNode sameAsRoot = newBinaryTree(); assertThat(isSame(ROOT, sameAsRoot)).isTrue(); IntegerNode five = IntegerNode.builder() .value(5) .build(); IntegerNode three = IntegerNode.builder() .left(five) .value(3) .build(); IntegerNode six = IntegerNode.builder() .value(6) .build(); IntegerNode fifteen = IntegerNode.builder() .left(three) .right(six) .value(15) .build(); assertThat(isSame(ROOT, fifteen)).isFalse(); } |
BinaryTreeUtil { public static IntegerNode lowestCommonAncestor(IntegerNode root, int value1, int value2) { Map.Entry<IntegerNode, Boolean> lca = internalLCA(root, value1, value2); return lca != null && lca.getValue() ? lca.getKey() : null; } private BinaryTreeUtil(); static int height(IntegerNode root); static boolean isBST(ParentAwareIntegerNode root); static boolean isSame(IntegerNode root1, IntegerNode root2); static IntegerNode lowestCommonAncestor(IntegerNode root, int value1, int value2); } | @Test void testLowestCommonAncestor() { IntegerNode five = IntegerNode.builder() .value(5) .build(); IntegerNode nine = IntegerNode.builder() .value(9) .build(); IntegerNode eleven = IntegerNode.builder() .left(nine) .right(five) .value(11) .build(); IntegerNode two = IntegerNode.builder() .value(2) .build(); IntegerNode six = IntegerNode.builder() .left(two) .right(eleven) .value(6) .build(); IntegerNode seven = IntegerNode.builder() .value(7) .build(); IntegerNode thirteen = IntegerNode.builder() .left(seven) .value(13) .build(); IntegerNode eight = IntegerNode.builder() .right(thirteen) .value(8) .build(); IntegerNode three = IntegerNode.builder() .left(six) .right(eight) .value(3) .build(); print(three); IntegerNode lca = lowestCommonAncestor(three, 2, 5); assertThat(lca).isNotNull(); assertThat(lca.value()).isEqualTo(6); lca = lowestCommonAncestor(three, 8, 11); assertThat(lca).isNotNull(); assertThat(lca.value()).isEqualTo(3); lca = lowestCommonAncestor(three, 2, 19); assertThat(lca).isNull(); } |
BinarySearchTree { public List<Integer> nodes() { return unmodifiableList(nodes(rootNode)); } @Builder private BinarySearchTree(Integer root, @Singular List<Integer> nodes); ParentAwareIntegerNode root(); List<Integer> nodes(); final ParentAwareIntegerNode insert(int value); final boolean contains(int value); final ParentAwareIntegerNode delete(int value); } | @Test void testNodes() { List<Integer> nodes = TREE.nodes(); assertThat(nodes).hasSize(6); assertThat(nodes).containsExactlyInAnyOrder(10, -5, -8, 7, 16, 18); } |
BinarySearchTree { public final boolean contains(int value) { return find(value) != null; } @Builder private BinarySearchTree(Integer root, @Singular List<Integer> nodes); ParentAwareIntegerNode root(); List<Integer> nodes(); final ParentAwareIntegerNode insert(int value); final boolean contains(int value); final ParentAwareIntegerNode delete(int value); } | @Test void testContains() { assertThat(TREE.nodes().stream() .allMatch(TREE::contains)).isTrue(); assertThat(TREE.contains(99)).isFalse(); } |
IOUtils { public static String addExtension(String filename, final String newExtension, final boolean removeExistingExtension) { if (filename != null && filename.length() <= 1) { return filename; } LOGGER.debug("Received: {}.", filename); if (removeExistingExtension) { filename = removeExtension(filename); } LOGGER.debug("Returning: {}.", filename + newExtension); return filename + newExtension; } static Writable findInMapFile(final Text key, URI dirURI, final Configuration conf); @SuppressWarnings("resource") static URI createMapFile(URI inputURI, final Configuration conf); static URI compressFile(final URI uncompressedURI, final String codecName, final Configuration conf); static String addExtension(String filename, final String newExtension, final boolean removeExistingExtension); static String removeExtension(String filename); static URI uncompressFile(final URI archiveURI, final Configuration conf); static final Logger LOGGER; } | @Test public void testAddExtension() { Assert.assertEquals("Wrong extension", "/a/b/c.txt.log", addExtension("/a/b/c.txt", ".log", false)); Assert.assertEquals("Wrong extension", "/a/b/c.log", addExtension("/a/b/c.txt", ".log", true)); Assert.assertEquals("Wrong extension", ".log", addExtension(".txt", ".log", true)); Assert.assertEquals("Wrong extension", ".txt.log", addExtension(".txt", ".log", false)); Assert.assertEquals("Wrong extension", ".", addExtension(".", ".txt", true)); Assert.assertEquals("Wrong extension", ".", addExtension(".", ".txt", false)); Assert.assertEquals("Wrong extension", "a.txt", addExtension("a.", ".txt", true)); } |
BinarySearchTree { public ParentAwareIntegerNode root() { return rootNode; } @Builder private BinarySearchTree(Integer root, @Singular List<Integer> nodes); ParentAwareIntegerNode root(); List<Integer> nodes(); final ParentAwareIntegerNode insert(int value); final boolean contains(int value); final ParentAwareIntegerNode delete(int value); } | @Test void testIsBST() { assertThat(isBST(TREE.root())).isTrue(); ParentAwareIntegerNode fifteen = ParentAwareIntegerNode.builder() .value(15) .build(); ParentAwareIntegerNode three = ParentAwareIntegerNode.builder() .value(3) .build(); ParentAwareIntegerNode five = ParentAwareIntegerNode.builder() .left(fifteen) .right(three) .value(5) .build(); three.setParent(five); fifteen.setParent(five); assertThat(isBST(five)).isFalse(); } |
JackOfAllTrades { public static List<String> allPermutations(String str) { Map<Character, Integer> countMap = str.chars() .mapToObj(i -> (char) i) .collect(collectingAndThen(toMap(identity(), i -> 1, (i, j) -> i + j, TreeMap::new), Collections::unmodifiableMap)); return allPermutations(countMap, 0, str); } static List<String> allPermutations(String str); } | @Test void testAllPermutationsOfAString() { assertThat(JackOfAllTrades.allPermutations("AABC")) .containsExactlyInAnyOrder("AABC", "AACB", "ABAC", "ABCA", "ACAB", "ACBA", "BAAC", "BACA", "BCAA", "CAAB", "CABA", "CBAA"); } |
ClientConfig { @Bean Client omdbApiClient() { return new OmdbApiClient(env.getProperty("omdbapi.endpoint")); } } | @Test public void testOmdbApiClient() { assertNotNull(omdbApiClient); assertTrue(omdbApiClient instanceof OmdbApiClient); assertEquals("http: } |
ClientConfig { @Bean Client deanClatworthyClient() { return new DeanClatworthyClient( env.getProperty("deanclatworthyapi.endpoint")); } } | @Test public void testDeanClatworthyClient() { assertNotNull(deanClatworthyClient); assertTrue(deanClatworthyClient instanceof DeanClatworthyClient); assertEquals("http: deanClatworthyClient.getEndpoint()); } |
ClientConfig { @Bean RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(clientRequestFactory()); List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); messageConverters.add(jsonMessageConverter()); restTemplate.setMessageConverters(messageConverters); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(); interceptors.add(new HttpRequestInterceptor()); restTemplate.setInterceptors(interceptors); return restTemplate; } } | @Test public void testRestTemplate() { List<HttpMessageConverter<?>> messageConverters = restTemplate .getMessageConverters(); assertNotNull(messageConverters); assertTrue(messageConverters.size() == 1); HttpMessageConverter<?> messageConverter = messageConverters.get(0); assertNotNull(messageConverter); assertTrue(messageConverter instanceof MappingJacksonHttpMessageConverter); List<MediaType> mediaTypes = messageConverter.getSupportedMediaTypes(); assertNotNull(mediaTypes); assertTrue(mediaTypes.contains(MediaType.TEXT_HTML)); assertTrue(mediaTypes.contains(MediaType.APPLICATION_JSON)); ClientHttpRequestFactory requestFactory = restTemplate .getRequestFactory(); assertNotNull(requestFactory); } |
OmdbApiClient extends AbstractClient { @SafeVarargs public final Movie getMovieInfoByTitleAndYear(String title, short year, Map<String, String>... param) { Map<String, String> queryParam = getQueryParam(param); queryParam.put(getEnv().getProperty("omdbapi.title"), title); queryParam .put(getEnv().getProperty("omdbapi.year"), Short.toString(year)); return getMovieInfoInternal(queryParam, OmdbApiStyleMovie.class); } OmdbApiClient(String endpoint); @SafeVarargs final Movie getMovieInfoByTitleAndYear(String title, short year,
Map<String, String>... param); @SafeVarargs final Movie getMovieInfoByTitleOnly(String title,
Map<String, String>... param); @SafeVarargs final Movie getMovieInfoById(String id, Map<String, String>... param); } | @Test public void testGetMovieInfoByTitleAndYear() { @SuppressWarnings("unchecked") Movie omdbApiStyleMovie = client.getMovieInfoByTitleAndYear( "Star Trek", (short) 1996); assertNotNull("At least one Star Trek movie should've been found", omdbApiStyleMovie); assertEquals("Wrong IMDB Id", "tt0117731", omdbApiStyleMovie.getImdbId()); assertEquals("Wrong title", "Star Trek: First Contact", omdbApiStyleMovie.getTitle()); assertEquals("Wrong release year", 1996, omdbApiStyleMovie.getYear()); assertNotNull("Wrong genre", omdbApiStyleMovie.getGenre()); assertNotNull("Wrong rating", omdbApiStyleMovie.getImdbRating()); assertNotNull("Wrong runtime", omdbApiStyleMovie.getRuntime()); assertNotNull("Wrong votes", omdbApiStyleMovie.getImdbVotes()); System.out.println("testGetMovieInfoByTitleAndYear: " + omdbApiStyleMovie); } |
OmdbApiClient extends AbstractClient { @SafeVarargs public final Movie getMovieInfoById(String id, Map<String, String>... param) { Map<String, String> queryParam = getQueryParam(param); queryParam.put(getEnv().getProperty("omdbapi.id"), id); return getMovieInfoInternal(queryParam, OmdbApiStyleMovie.class); } OmdbApiClient(String endpoint); @SafeVarargs final Movie getMovieInfoByTitleAndYear(String title, short year,
Map<String, String>... param); @SafeVarargs final Movie getMovieInfoByTitleOnly(String title,
Map<String, String>... param); @SafeVarargs final Movie getMovieInfoById(String id, Map<String, String>... param); } | @Test public void testGetMovieInfoById() { @SuppressWarnings("unchecked") Movie omdbApiStyleMovie = client.getMovieInfoById("tt0117731"); assertNotNull("At least one Star Trek movie should've been found", omdbApiStyleMovie); assertEquals("Wrong IMDB Id", "tt0117731", omdbApiStyleMovie.getImdbId()); assertEquals("Wrong title", "Star Trek: First Contact", omdbApiStyleMovie.getTitle()); assertEquals("Wrong release year", 1996, omdbApiStyleMovie.getYear()); assertNotNull("Wrong genre", omdbApiStyleMovie.getGenre()); assertNotNull("Wrong rating", omdbApiStyleMovie.getImdbRating()); assertNotNull("Wrong runtime", omdbApiStyleMovie.getRuntime()); assertNotNull("Wrong votes", omdbApiStyleMovie.getImdbVotes()); System.out.println("testGetMovieInfoById: " + omdbApiStyleMovie); }
@Test public void testGetNoSuchMovieInfoById() { @SuppressWarnings("unchecked") Movie omdbApiStyleMovie = client.getMovieInfoById("NoMuchMovie"); System.out.println("testGetNoSuchMovieInfoById: " + omdbApiStyleMovie); assertNull("No such movie with this Id was ever released", omdbApiStyleMovie.getTitle()); } |
OmdbApiClient extends AbstractClient { @SafeVarargs public final Movie getMovieInfoByTitleOnly(String title, Map<String, String>... param) { Map<String, String> queryParam = getQueryParam(param); queryParam.put(getEnv().getProperty("omdbapi.title"), title); return getMovieInfoInternal(queryParam, OmdbApiStyleMovie.class); } OmdbApiClient(String endpoint); @SafeVarargs final Movie getMovieInfoByTitleAndYear(String title, short year,
Map<String, String>... param); @SafeVarargs final Movie getMovieInfoByTitleOnly(String title,
Map<String, String>... param); @SafeVarargs final Movie getMovieInfoById(String id, Map<String, String>... param); } | @Test public void testGetMovieInfoByTitleOnly() { @SuppressWarnings("unchecked") Movie omdbApiStyleMovie = client .getMovieInfoByTitleOnly("Star Trek"); assertNotNull("At least one Star Trek movie should've been found", omdbApiStyleMovie); assertEquals("Wrong IMDB Id", "tt0796366", omdbApiStyleMovie.getImdbId()); assertEquals("Wrong title", "Star Trek", omdbApiStyleMovie.getTitle()); assertEquals("Wrong release year", 2009, omdbApiStyleMovie.getYear()); assertNotNull("Wrong genre", omdbApiStyleMovie.getGenre()); assertNotNull("Wrong rating", omdbApiStyleMovie.getImdbRating()); assertNotNull("Wrong runtime", omdbApiStyleMovie.getRuntime()); assertNotNull("Wrong votes", omdbApiStyleMovie.getImdbVotes()); System.out.println("testGetMovieInfoByTitleOnly: " + omdbApiStyleMovie); } |
ClientFactory { public static final ClientFactory getInstance() { if (factory == null) factory = new ClientFactory(); return factory; } private ClientFactory(); static final ClientFactory getInstance(); final Client getClient(ClientType type); } | @Test public void testFactory() { assertNotNull(factory); assertSame(factory, ClientFactory.getInstance()); } |
IOUtils { public static String removeExtension(String filename) { if ((filename != null && filename.length() <= 1) || filename == null) { return filename; } LOGGER.debug("Received: {}.", filename); final int idx = filename.lastIndexOf('.'); if (idx >= 0) { filename = filename.substring(0, idx); } LOGGER.debug("Returning: {}.", filename); return filename; } static Writable findInMapFile(final Text key, URI dirURI, final Configuration conf); @SuppressWarnings("resource") static URI createMapFile(URI inputURI, final Configuration conf); static URI compressFile(final URI uncompressedURI, final String codecName, final Configuration conf); static String addExtension(String filename, final String newExtension, final boolean removeExistingExtension); static String removeExtension(String filename); static URI uncompressFile(final URI archiveURI, final Configuration conf); static final Logger LOGGER; } | @Test public void testRemoveExtension() { Assert.assertEquals("Wrong extension", "/a/b/c.txt", removeExtension("/a/b/c.txt.log")); Assert.assertEquals("Wrong extension", "/a/b/c", removeExtension("/a/b/c.log")); Assert.assertEquals("Wrong extension", "", removeExtension(".txt")); Assert.assertEquals("Wrong extension", ".", removeExtension(".")); Assert.assertEquals("Wrong extension", "a", removeExtension("a.txt")); } |
ClientFactory { public final Client getClient(ClientType type) { if (clients.get(type) == null) { switch (type) { case THE_OMDB_API: clients.put(type, ctx.getBean("omdbApiClient", Client.class)); break; case DEAN_CLATWORTHY: clients.put(type, ctx.getBean("deanClatworthyClient", Client.class)); break; } } return clients.get(type); } private ClientFactory(); static final ClientFactory getInstance(); final Client getClient(ClientType type); } | @Test public void testClients() { Client omdbApiClient = factory.getClient(ClientType.THE_OMDB_API); Client deanClatworthyClient = factory .getClient(ClientType.DEAN_CLATWORTHY); assertNotNull(omdbApiClient); assertTrue(omdbApiClient instanceof OmdbApiClient); assertNotNull(deanClatworthyClient); assertTrue(deanClatworthyClient instanceof DeanClatworthyClient); assertEquals("http: assertEquals("http: deanClatworthyClient.getEndpoint()); } |
TowerOfHanoi { public void move(int numDisks, int fromPeg, int toPeg) { if (numDisks == 1) { move(fromPeg, toPeg); } else { move(numDisks - 1, fromPeg, sparePeg(fromPeg, toPeg)); move(fromPeg, toPeg); move(numDisks - 1, sparePeg(fromPeg, toPeg), toPeg); } } TowerOfHanoi(int numPegs, int numDisks); List<Peg<Disk>> pegs(); void move(int numDisks, int fromPeg, int toPeg); static final Logger LOGGER; } | @Test public void testMove() { tower.move(3, 0, 2); List<Peg<Disk>> pegs = tower.pegs(); Assert.assertEquals(3, pegs.size()); Assert.assertEquals(3, pegs.get(2).size()); Assert.assertEquals(0, pegs.get(0).size()); Assert.assertEquals(0, pegs.get(1).size()); } |
LRUCache extends LinkedHashMap<K, V> { public LRUCache(final int capacity) { super(capacity, LOAD_FACTOR, ACCESS_ORDER); this.capacity = capacity; } LRUCache(final int capacity); } | @Test public void testLRUCache() { LRUCache<String, String> cache = new LRUCache<>(1); cache.put("k1", "v1"); Assert.assertTrue(cache.containsKey("k1")); cache.put("k2", "v2"); Assert.assertFalse(cache.containsKey("k1")); Assert.assertTrue(cache.containsKey("k2")); } |
Algorithms { public static String longestRepeatedSubstring(String str) { final String[] suffixArray = buildSuffixArray(str); Arrays.sort(suffixArray); String temp = ""; String lrs = ""; String aSuffix = null; String anotherSuffix = null; int len = -1; for (int i = 0; i < suffixArray.length - 1; ++i) { aSuffix = suffixArray[i]; anotherSuffix = suffixArray[i + 1]; if (aSuffix.trim().isEmpty() || anotherSuffix.trim().isEmpty()) { continue; } else if (anotherSuffix.startsWith(aSuffix)) { LOGGER.debug("\"{}\" starts with \"{}\".", anotherSuffix, aSuffix); temp = aSuffix; } else { len = Math.min(aSuffix.length(), anotherSuffix.length()); int j = 1; while (j <= len && aSuffix.regionMatches(0, anotherSuffix, 0, j)) { LOGGER.debug("Comparing \"{}\" and \"{}\".", aSuffix.substring(0, j), anotherSuffix.substring(0, j)); ++j; } temp = aSuffix.substring(0, --j); } lrs = temp.length() > lrs.length() ? temp : lrs; } return lrs; } static String longestRepeatedSubstring(String str); static final Logger LOGGER; } | @Test public void testLongestRepeatedSubstring() { Assert.assertEquals("ana", longestRepeatedSubstring("banana")); Assert.assertEquals( " can do for you", longestRepeatedSubstring("Ask not what your country can do for you, ask what you can do for your country")); } |
ReservationSystem { public static int makeReservation(final String customerName, final int seating, final Date date, final SpecialFeature... specialFeatures) { final Table table = TableManager.reserveTable(seating, specialFeatures); final String formattedDate = format(date); final StringBuilder message = new StringBuilder(); if (table != null) { final Reservation r = new Reservation(reservationNumber.incrementAndGet(), customerName); r.setTables(Arrays.asList(new Table[] { table })); r.setDate(date); addToReservationsList(r, formattedDate); message.append("Made reservation for ").append(customerName).append(" for date ").append(formattedDate) .append(" with seating ").append(seating).append(" and features ").append(specialFeatures) .append("."); LOGGER.info(message.toString()); return r.reservationNumber(); } message.delete(0, message.length() + 1); message.append("No table is available on ").append(formattedDate).append(" with seating ").append(seating) .append(" and features ").append(specialFeatures).append("."); throw new UnableToCompleteReservationException(message.toString()); } static int makeReservation(final String customerName, final int seating, final Date date,
final SpecialFeature... specialFeatures); static boolean cancelReservation(final String customerName, final Date date); } | @Test public void testMakeReservation() { final Date now = new Date(); int reservationID1 = ReservationSystem.makeReservation("Abhijit Sarkar", 2, now); Reservation r = ReservationSystem.lookUpReservation("Abhijit Sarkar", now); Assert.assertNotNull(r); int reservationID2 = ReservationSystem.makeReservation("Abhijit Sarkar", 2, now); r = ReservationSystem.lookUpReservation("Abhijit Sarkar", now); Assert.assertNotNull(r); Assert.assertTrue(reservationID2 > reservationID1); }
@Test(expected = UnableToCompleteReservationException.class) public void testMakeReservationsUntilTablesExhausted() { while (true) { ReservationSystem.makeReservation("Abhijit Sarkar", 2, new Date()); } } |
ReservationSystem { public static boolean cancelReservation(final String customerName, final Date date) { boolean cancelledReservation = false; final String formattedDate = format(date); synchronized (ReservationSystem.class) { final List<Reservation> allReservationsForADay = allReservations.get(formattedDate); if (allReservationsForADay != null) { final Reservation r = lookUpReservation(customerName, date); if (r != null) { final StringBuilder message = new StringBuilder(); message.append("Cancelled reservation for ").append(customerName).append(" for date ") .append(formattedDate).append("."); LOGGER.info(message.toString()); allReservationsForADay.remove(r); cancelledReservation = true; } } } return cancelledReservation; } static int makeReservation(final String customerName, final int seating, final Date date,
final SpecialFeature... specialFeatures); static boolean cancelReservation(final String customerName, final Date date); } | @Test public void testCancelReservation() { final Date now = new Date(); ReservationSystem.makeReservation("Abhijit Sarkar", 2, now); int reservationId = ReservationSystem.makeReservation("Abhijit Sarkar", 2, now, WINDOW_SIDE); boolean reservationCancelled = ReservationSystem.cancelReservation("Abhijit Sarkar", now); Assert.assertTrue(reservationCancelled); Reservation r = ReservationSystem.lookUpReservation("Abhijit Sarkar", now); Assert.assertEquals(reservationId, r.reservationNumber()); } |
TableManager { public static Table reserveTable(final int seating, final SpecialFeature... specialFeatures) { List<SpecialFeature> tableFeatures = null; Table table = null; outer: for (int availableTableId : availableTableIds) { table = findTableById(availableTableId); if (table.seatingCapacity() == seating) { tableFeatures = table.specialFeatures(); for (SpecialFeature requestedFeature : specialFeatures) { if (!tableFeatures.contains(requestedFeature)) { continue outer; } } availableTableIds.remove(availableTableId); break; } table = null; } return table; } static void setAllTables(Set<Table> allTables); static Table reserveTable(final int seating, final SpecialFeature... specialFeatures); } | @Test public void testReserveTable() { Table table = TableManager.reserveTable(2); Assert.assertEquals(blahTable, table); table = TableManager.reserveTable(2, WINDOW_SIDE); Assert.assertEquals(windowSideTable, table); }
@Test public void testReserveTableWhenNoneMatches() { Assert.assertNull(TableManager.reserveTable(4)); }
@Test public void testReserveMoreTablesThanAvailable() { Table table = TableManager.reserveTable(2); Assert.assertEquals(blahTable, table); table = TableManager.reserveTable(2, WINDOW_SIDE); Assert.assertEquals(windowSideTable, table); Assert.assertNull(TableManager.reserveTable(2)); } |
ReduceSideJoinReducer extends Reducer<TaggedKey, Text, IntWritable, Text> { @Override protected void reduce(TaggedKey key, Iterable<Text> values, Context ctx) throws IOException, InterruptedException { StringBuilder value = new StringBuilder(); LOGGER.debug("Entering reduce"); for (Text v : values) { LOGGER.debug("Loop - Key: {}, Value: {}.", key, value); value.append(v.toString()).append("|"); } value.delete(value.length() - 1, value.length()); LOGGER.debug("Key: {}, Value: {}.", key.getJoinKey(), value); ctx.write(key.getJoinKey(), new Text(value.toString())); } static final Logger LOGGER; } | @Test public void testReduce() { TaggedKey key = new TaggedKey(1, 1); List<Text> values = new ArrayList<Text>(); values.add(new Text("Stephanie Leung,555-555-5555,123 No Such St,Fantasyland,CA 99999")); values.add(new Text("A,99.99,01/01/2013")); Text expectedValue = new Text( "Stephanie Leung,555-555-5555,123 No Such St,Fantasyland,CA 99999|A,99.99,01/01/2013"); reduceDriver.withReducer(reducer).withInput(key, values).withOutput(new IntWritable(1), expectedValue) .runTest(); } |
Assignment { public long stringToLong(final String s) { final int asciiDecimalStart = 48; final AtomicInteger index = new AtomicInteger(0); final AtomicLong number = new AtomicLong(0); final int len = s.length(); if (s == null || s.isEmpty()) { throw new IllegalArgumentException(s + " can't be converted to a long."); } s.chars().map(i -> (i - asciiDecimalStart)).forEach(i -> { if (i < 0 || i > 9) { throw new IllegalArgumentException(s + " can't be converted to a long."); } number.set((long) (number.get() + i * Math.pow(10, len - index.addAndGet(1)))); }); return number.get(); } long stringToLong(final String s); } | @Test public void testStringToLongSuccess() { Assert.assertEquals(123l, assignment.stringToLong("123")); }
@Test(expected = IllegalArgumentException.class) public void testStringToLongFailure() { assignment.stringToLong("12a"); } |
Assignment { public String getLongestString(int n, List<String> inputs) { int[] lengths = new int[inputs.size()]; MultiValueMap<Integer, Integer> lengthToIndicesMap = new MultiValueMap<>(); int len = -1; for (int i = 0; i < inputs.size(); i++) { len = inputs.get(i).length(); lengths[i] = len; lengthToIndicesMap.put(len, i); } int maxLen = quickselect(lengths, 0, inputs.size() - 1, n - 1); return inputs.get(lengthToIndicesMap.getCollection(maxLen).iterator().next()); } String getLongestString(int n, List<String> inputs); boolean isPermutationOfEachOther(String s, String t); } | @Test public void testGetLongestString() { String[] input = new String[] { "Yuri", "Interview", "Nordstrom", "Cat", "Dog", "Telephone", "AVeryLongString", "This code puzzle is easy" }; Assert.assertEquals("This code puzzle is easy", assignment.getLongestString(1, Arrays.asList(input))); } |
Assignment { public boolean isPermutationOfEachOther(String s, String t) { if (s.length() != t.length()) { return false; } return sort(s).equals(sort(t)); } String getLongestString(int n, List<String> inputs); boolean isPermutationOfEachOther(String s, String t); } | @Test public void testIsPermutationOfEachOther() { Assert.assertTrue(assignment.isPermutationOfEachOther("abcd", "cdab")); Assert.assertFalse(assignment.isPermutationOfEachOther("abcd", "123")); } |
ParkingGarage { public Attendant getAttendant() { return attendant; } ParkingGarage(); Attendant getAttendant(); } | @Test public void testParkingOneCompact() { Car compact = new Car(COMPACT, "abc123"); Ticket ticket = parkingGarage.getAttendant().generateTicketAndOpenGate(compact); assertNotNull(ticket.getId()); assertEquals(COMPACT, ticket.getTypeOfCar()); assertEquals("1", ticket.getLevelId()); Receipt receipt = parkingGarage.getAttendant().acceptPaymentAndOpenGate(ticket, null); verifyReceipt(receipt, ticket); }
@Test public void testParkingOneHybrid() { Car hybrid = new Car(HYBRID, "abc123"); Ticket ticket = parkingGarage.getAttendant().generateTicketAndOpenGate(hybrid); assertNotNull(ticket.getId()); assertEquals(HYBRID, ticket.getTypeOfCar()); assertEquals("1", ticket.getLevelId()); Receipt receipt = parkingGarage.getAttendant().acceptPaymentAndOpenGate(ticket, null); verifyReceipt(receipt, ticket); }
@Test(expected = NoParkingSpaceAvailable.class) public void testParkingOneCompactAndHybrid() { Car compact = new Car(COMPACT, "abc123"); parkingGarage.getAttendant().generateTicketAndOpenGate(compact); Car hybrid = new Car(HYBRID, "abc123"); parkingGarage.getAttendant().generateTicketAndOpenGate(hybrid); }
@Test public void testParkingOneSUV() { Car hybrid = new Car(SUV, "abc123"); Ticket ticket = parkingGarage.getAttendant().generateTicketAndOpenGate(hybrid); assertNotNull(ticket.getId()); assertEquals(SUV, ticket.getTypeOfCar()); assertEquals("3", ticket.getLevelId()); Receipt receipt = parkingGarage.getAttendant().acceptPaymentAndOpenGate(ticket, null); verifyReceipt(receipt, ticket); } |
MovieServiceImpl implements MovieService { private boolean isParentNotASeries(String parent) { return (parent == null) ? false : parent.trim().matches( ".*(?:\\((\\d{4})\\))$"); } MovieServiceImpl(); @Override SortedSet<Movie> getMovieSet(String path); String getMovieDirectory(); @Override Set<Movie> filterMovieSetByGenre(Set<Movie> movieSet, String genre); @Override Map<String, Set<Movie>> groupMovieSetByGenre(Set<Movie> movieSet); @Override Summary getSummary(Map<String, Set<Movie>> movieSetGroupedByGenre); @SuppressWarnings("unused") @Override GenreSummary getSummaryByGenre(Set<Movie> movieSetFilteredByGenre,
String genre); } | @Test public void testIsParentNotASeries() { assertFalse("Testing \"Criminal Minds\"", this.isParentNotASeries("Criminal Minds")); assertFalse("Testing \"\"", this.isParentNotASeries("")); assertFalse("Testing \" \"", this.isParentNotASeries(" ")); assertFalse("Testing null", this.isParentNotASeries(null)); assertTrue("Testing \"Tesis (1996)\"", this.isParentNotASeries("Tesis (1996)")); } |
MovieServiceImpl implements MovieService { @Override public Set<Movie> filterMovieSetByGenre(Set<Movie> movieSet, String genre) { Set<Movie> filteredMovieListByGenre = new HashSet<Movie>(); Iterator<Movie> it = movieSet.iterator(); Movie movie = null; while (it.hasNext()) { movie = it.next(); if (movie.getGenre().equals(genre)) { filteredMovieListByGenre.add(movie); } } return filteredMovieListByGenre; } MovieServiceImpl(); @Override SortedSet<Movie> getMovieSet(String path); String getMovieDirectory(); @Override Set<Movie> filterMovieSetByGenre(Set<Movie> movieSet, String genre); @Override Map<String, Set<Movie>> groupMovieSetByGenre(Set<Movie> movieSet); @Override Summary getSummary(Map<String, Set<Movie>> movieSetGroupedByGenre); @SuppressWarnings("unused") @Override GenreSummary getSummaryByGenre(Set<Movie> movieSetFilteredByGenre,
String genre); } | @Test public void testFilterMovieSetByGenre() { Set<Movie> movieSetFilteredByGenre = null; Movie movie = null; movieSetFilteredByGenre = movieService.filterMovieSetByGenre(movieSet, ACTION_AND_ADVENTURE.toString()); movie = new Movie("Casino Royal", (short) 2006, ACTION_AND_ADVENTURE.toString(), 1571095307L, ".mkv"); assertEquals("Incorrect " + ACTION_AND_ADVENTURE.toString() + " size", 5, movieSetFilteredByGenre.size()); assertTrue("Filtered set does not contain movie " + movie, movieSetFilteredByGenre.contains(movie)); movieSetFilteredByGenre = movieService.filterMovieSetByGenre(movieSet, HORROR.toString()); movie = new Movie("Inferno", (short) 1980, HORROR.toString(), 2216523351L, ".mkv"); assertEquals("Incorrect " + HORROR.toString() + " size", 6, movieSetFilteredByGenre.size()); assertTrue("Filtered set does not contain movie " + movie, movieSetFilteredByGenre.contains(movie)); movieSetFilteredByGenre = movieService.filterMovieSetByGenre(movieSet, DOCUMENTARY.toString()); assertEquals("Incorrect " + DOCUMENTARY.toString() + " size", 0, movieSetFilteredByGenre.size()); } |
JSONParser { public static Map<String, Employee> employees(String file) throws JsonParseException, JsonMappingException, IOException { final TypeReference<Map<String, Employee>> employeeMapType = new TypeReference<Map<String, Employee>>() { }; return new ObjectMapper().readValue(JSONParser.class.getResource(file), employeeMapType); } static Map<String, Employee> employees(String file); } | @Test public void testEmployees() throws JsonParseException, JsonMappingException, IOException { Map<String, Employee> employeeMap = JSONParser.employees("/employees.json"); Assert.assertNotNull(employeeMap); Assert.assertEquals(2, employeeMap.size()); Employee employee123 = employeeMap.get("123"); Assert.assertNotNull(employee123); Assert.assertEquals("Abhijit", employee123.getName()); Assert.assertEquals("Software", employee123.getDepartment()); Employee employee456 = employeeMap.get("456"); Assert.assertNotNull(employee456); Assert.assertEquals("Sarkar", employee456.getName()); Assert.assertEquals("IT", employee456.getDepartment()); } |
MovieServiceImpl implements MovieService { @Override public Map<String, Set<Movie>> groupMovieSetByGenre(Set<Movie> movieSet) { Map<String, Set<Movie>> movieSetGroupedByGenre = new HashMap<String, Set<Movie>>(); Set<Movie> movieSetFilteredByGenre = null; for (String genre : genreList) { movieSetFilteredByGenre = this.filterMovieSetByGenre(movieSet, genre); movieSetGroupedByGenre.put(genre, movieSetFilteredByGenre); } return (movieSetGroupedByGenre.size() > 0) ? movieSetGroupedByGenre : null; } MovieServiceImpl(); @Override SortedSet<Movie> getMovieSet(String path); String getMovieDirectory(); @Override Set<Movie> filterMovieSetByGenre(Set<Movie> movieSet, String genre); @Override Map<String, Set<Movie>> groupMovieSetByGenre(Set<Movie> movieSet); @Override Summary getSummary(Map<String, Set<Movie>> movieSetGroupedByGenre); @SuppressWarnings("unused") @Override GenreSummary getSummaryByGenre(Set<Movie> movieSetFilteredByGenre,
String genre); } | @Test public void testGroupMovieSetByGenre() { Map<String, Set<Movie>> movieSetGroupedByGenre = null; Set<Movie> movieSetFilteredByGenre = null; Movie movie = null; movieSetGroupedByGenre = movieService.groupMovieSetByGenre(movieSet); movieSetFilteredByGenre = movieSetGroupedByGenre .get(ACTION_AND_ADVENTURE.toString()); movie = new Movie("Casino Royal", (short) 2006, ACTION_AND_ADVENTURE.toString(), 1571095307L, ".mkv"); assertEquals("Incorrect " + ACTION_AND_ADVENTURE.toString() + " size", 5, movieSetFilteredByGenre.size()); assertTrue("Filtered set does not contain movie " + movie, movieSetFilteredByGenre.contains(movie)); movieSetFilteredByGenre = movieSetGroupedByGenre.get(HORROR.toString()); movie = new Movie("Inferno", (short) 1980, HORROR.toString(), 2216523351L, ".mkv"); assertEquals("Incorrect " + HORROR.toString() + " size", 6, movieSetFilteredByGenre.size()); assertTrue("Filtered set does not contain movie " + movie, movieSetFilteredByGenre.contains(movie)); movieSetFilteredByGenre = movieSetGroupedByGenre.get(DOCUMENTARY .toString()); assertEquals("Incorrect " + DOCUMENTARY.toString() + " size", 0, movieSetFilteredByGenre.size()); } |
MovieServiceImpl implements MovieService { @SuppressWarnings("unused") @Override public GenreSummary getSummaryByGenre(Set<Movie> movieSetFilteredByGenre, String genre) { Iterator<Movie> it = null; Movie currentMovie = null; String currentMovieParent = null; short currentMovieYear = 0; Movie previousMovie = null; String previousMovieParent = null; int movieTitleCount = 0; int soapTitleCount = 0; long sumOfSizeOfAllTitlesInThisGenre = 0L; GenreSummary genreSummary = null; it = movieSetFilteredByGenre.iterator(); for (int i = 0; it.hasNext(); i++) { currentMovie = it.next(); currentMovieParent = currentMovie.getParent(); currentMovieYear = currentMovie.getYear(); logger.debug("Current movie: " + currentMovie); if (currentMovieYear == Movie.UNKNOWN_RELEASE_YEAR) { logger.debug("Current movie is a soap. " + "Soap count is incremented."); soapTitleCount++; } else { if (!isParentNotASeries(currentMovieParent)) { logger.debug("Current movie parent is a series. " + "Movie count is incremented."); movieTitleCount++; } else if (!isParentNotASeries(previousMovieParent)) { logger.debug("Previous movie parent is a series. " + "Movie count is incremented."); movieTitleCount++; } else if (!(currentMovieParent.equals(previousMovieParent))) { logger.debug("Current movie parent is not equal to " + "previous movie parent. " + "Movie count is incremented."); movieTitleCount++; } else { logger.debug("Movie count is not incremented."); } } logger.debug("Movie count: " + movieTitleCount); previousMovie = currentMovie; previousMovieParent = currentMovieParent; sumOfSizeOfAllTitlesInThisGenre += currentMovie.getFilesize(); } genreSummary = new GenreSummary(); genreSummary.setGenre(genre); genreSummary.setMovieTitleCount(movieTitleCount); genreSummary.setSoapTitleCount(soapTitleCount); genreSummary .setSumOfSizeOfAllTitlesInThisGenre(sumOfSizeOfAllTitlesInThisGenre); return genreSummary; } MovieServiceImpl(); @Override SortedSet<Movie> getMovieSet(String path); String getMovieDirectory(); @Override Set<Movie> filterMovieSetByGenre(Set<Movie> movieSet, String genre); @Override Map<String, Set<Movie>> groupMovieSetByGenre(Set<Movie> movieSet); @Override Summary getSummary(Map<String, Set<Movie>> movieSetGroupedByGenre); @SuppressWarnings("unused") @Override GenreSummary getSummaryByGenre(Set<Movie> movieSetFilteredByGenre,
String genre); } | @Test public void testGetSummaryByGenre() { GenreSummary genreSummary = null; genreSummary = movieService.getSummaryByGenre(movieService .filterMovieSetByGenre(movieSet, ACTION_AND_ADVENTURE.toString()), ACTION_AND_ADVENTURE .toString()); assertEquals( "Incorrect movieTitleCount for " + ACTION_AND_ADVENTURE.toString(), 5, genreSummary.getMovieTitleCount()); assertEquals( "Incorrect soapTitleCount for " + ACTION_AND_ADVENTURE.toString(), 0, genreSummary.getSoapTitleCount()); genreSummary = movieService .getSummaryByGenre( movieService.filterMovieSetByGenre(movieSet, HORROR.toString()), HORROR.toString()); assertEquals("Incorrect movieTitleCount for " + HORROR.toString(), 6, genreSummary.getMovieTitleCount()); assertEquals("Incorrect soapTitleCount for " + HORROR.toString(), 0, genreSummary.getSoapTitleCount()); } |
MovieServiceImpl implements MovieService { @Override public Summary getSummary(Map<String, Set<Movie>> movieSetGroupedByGenre) { Set<Movie> movieSetFilteredByGenre = null; int movieTitleCount = 0; int soapTitleCount = 0; long sumOfSizeOfAllTitles = 0L; GenreSummary genreSummary = null; List<GenreSummary> genreSummaryList = new ArrayList<GenreSummary>(); Summary summary = null; for (String genre : genreList) { movieSetFilteredByGenre = movieSetGroupedByGenre.get(genre); genreSummary = getSummaryByGenre(movieSetFilteredByGenre, genre); sumOfSizeOfAllTitles += genreSummary .getSumOfSizeOfAllTitlesInThisGenre(); movieTitleCount += genreSummary.getMovieTitleCount(); soapTitleCount += genreSummary.getSoapTitleCount(); genreSummaryList.add(genreSummary); } summary = new Summary(); summary.setGenreSummary(genreSummaryList); summary.setMovieTitleCount(movieTitleCount); summary.setSoapTitleCount(soapTitleCount); summary.setSumOfSizeOfAllTitles(sumOfSizeOfAllTitles); return summary; } MovieServiceImpl(); @Override SortedSet<Movie> getMovieSet(String path); String getMovieDirectory(); @Override Set<Movie> filterMovieSetByGenre(Set<Movie> movieSet, String genre); @Override Map<String, Set<Movie>> groupMovieSetByGenre(Set<Movie> movieSet); @Override Summary getSummary(Map<String, Set<Movie>> movieSetGroupedByGenre); @SuppressWarnings("unused") @Override GenreSummary getSummaryByGenre(Set<Movie> movieSetFilteredByGenre,
String genre); } | @Test public void testGetSummary() { Map<String, Set<Movie>> movieSetGroupedByGenre = movieService .groupMovieSetByGenre(movieSet); Summary summary = null; GenreSummary genreSummary = null; summary = movieService.getSummary(movieSetGroupedByGenre); genreSummary = new GenreSummary(); genreSummary.setGenre(ACTION_AND_ADVENTURE.toString()); genreSummary.setMovieTitleCount(5); genreSummary.setSoapTitleCount(0); assertTrue("Summary does not contain genre summary for " + ACTION_AND_ADVENTURE.toString(), summary.getGenreSummary() .contains(genreSummary)); genreSummary = new GenreSummary(); genreSummary.setGenre(HORROR.toString()); genreSummary.setMovieTitleCount(6); genreSummary.setSoapTitleCount(0); assertTrue( "Summary does not contain genre summary for " + HORROR.toString(), summary.getGenreSummary() .contains(genreSummary)); } |
MovieManager { public static void validateFile(File... files) throws FileNotFoundException { FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter( "Microsoft Excel", "xls", "xlsx"); for (File file : files) { if (file == null) { logger.error("File not found."); throw new FileNotFoundException("File not found."); } else if (!file.isDirectory() && !extensionFilter.accept(file)) { logger.error("File extension is not acceptable: " + file.getAbsolutePath()); throw new IllegalArgumentException( "File extension is not acceptable."); } else if (file.isDirectory() && (!file.canRead() || !file.canExecute())) { logger.error("Directory not found or is not readable: " + file.getAbsolutePath()); throw new IllegalArgumentException( "Directory not found or is not readable."); } } } MovieManager(); MovieManager(File inputDir, File outputFile); static void validateFile(File... files); static GenreSummary getSummaryByGenre(String genre); static Summary getSummary(); static Map<String, Set<Movie>> getMovieSetGroupedByGenre(); static void createSummarySheet(Summary summary); static void createGenreSheet(Set<Movie> filteredMovieSetByGenre,
String genre); static Summary getSummary(
Map<String, Set<Movie>> movieSetGroupedByGenre); static final String EMPTY; } | @Test(expected = IllegalArgumentException.class) public void testValidateUnreadableDirectory() throws FileNotFoundException { MovieManager.validateFile(new File("src/test/resources/unreadable")); }
@Test(expected = IllegalArgumentException.class) public void testValidateUnacceptableFileExtension() throws FileNotFoundException { MovieManager.validateFile(new File( "src/test/resources/invalid_extension.txt")); }
@Test public void testValidateGood() { try { MovieManager.validateFile(new File("src/test/resources")); MovieManager.validateFile(new File( "src/test/resources/valid_extension.xlsx")); } catch (Exception ex) { fail("Should not have been here."); } } |
MovieManager { public static void createSummarySheet(Summary summary) throws Exception { final String SUMMARY = "Summary"; final String MOVIE_COUNT = "Movie Count"; final String SOAP_COUNT = "Soap Count"; final String SIZE = "Size"; final String GENRE_SUMMARY = "Genre Summary"; Workbook wb = createWorkbook(outputFile); List<GenreSummary> genreSummaryList = summary.getGenreSummary(); Sheet summarySheet = null; Row row = null; CellStyle headerCellStyle = createHeaderCellStyle(wb.createCellStyle(), wb.createFont()); CellStyle bodyCellStyle = createBodyCellStyle(wb.createCellStyle(), wb.createFont()); summarySheet = createNewSheet(wb, SUMMARY); row = summarySheet.createRow(0); summarySheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2)); createCell(row, 0, headerCellStyle, SUMMARY, Cell.CELL_TYPE_STRING); row = summarySheet.createRow(1); createCell(row, 0, headerCellStyle, MOVIE_COUNT, Cell.CELL_TYPE_STRING); createCell(row, 1, headerCellStyle, SOAP_COUNT, Cell.CELL_TYPE_STRING); createCell(row, 2, headerCellStyle, SIZE, Cell.CELL_TYPE_STRING); row = summarySheet.createRow(2); createCell(row, 0, bodyCellStyle, summary.getMovieTitleCount(), Cell.CELL_TYPE_NUMERIC); createCell(row, 1, bodyCellStyle, summary.getSoapTitleCount(), Cell.CELL_TYPE_NUMERIC); createCell(row, 2, bodyCellStyle, formatter.format(summary.getSumOfSizeOfAllTitles()), Cell.CELL_TYPE_STRING); for (GenreSummary genreSummary : genreSummaryList) { row = summarySheet.createRow(summarySheet.getLastRowNum() + 2); summarySheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), 0, 2)); createCell(row, 0, headerCellStyle, GENRE_SUMMARY + " (" + genreSummary.getGenre() + ")", Cell.CELL_TYPE_STRING); row = summarySheet.createRow(summarySheet.getLastRowNum() + 1); createCell(row, 0, headerCellStyle, MOVIE_COUNT, Cell.CELL_TYPE_STRING); createCell(row, 1, headerCellStyle, SOAP_COUNT, Cell.CELL_TYPE_STRING); createCell(row, 2, headerCellStyle, SIZE, Cell.CELL_TYPE_STRING); row = summarySheet.createRow(summarySheet.getLastRowNum() + 1); createCell(row, 0, bodyCellStyle, genreSummary.getMovieTitleCount(), Cell.CELL_TYPE_NUMERIC); createCell(row, 1, bodyCellStyle, genreSummary.getSoapTitleCount(), Cell.CELL_TYPE_NUMERIC); createCell(row, 2, bodyCellStyle, formatter.format(genreSummary .getSumOfSizeOfAllTitlesInThisGenre()), Cell.CELL_TYPE_STRING); autoSizeColumns(summarySheet); } writeToDisk(wb); } MovieManager(); MovieManager(File inputDir, File outputFile); static void validateFile(File... files); static GenreSummary getSummaryByGenre(String genre); static Summary getSummary(); static Map<String, Set<Movie>> getMovieSetGroupedByGenre(); static void createSummarySheet(Summary summary); static void createGenreSheet(Set<Movie> filteredMovieSetByGenre,
String genre); static Summary getSummary(
Map<String, Set<Movie>> movieSetGroupedByGenre); static final String EMPTY; } | @Test public void testCreateSummarySheet() throws Exception { final String SUMMARY = "Summary"; final String MOVIE_COUNT = "Movie Count"; final String SOAP_COUNT = "Soap Count"; final String SIZE = "Size"; Sheet summarySheet = null; Row row = null; MovieManager.createSummarySheet(summary); InputStream input = new FileInputStream(outputFile); Workbook wb = WorkbookFactory.create(input); summarySheet = wb.getSheet(SUMMARY); assertNotNull(summarySheet); row = summarySheet.getRow(0); assertEquals(summarySheet.getMergedRegion(0).getFirstRow(), 0); assertEquals(summarySheet.getMergedRegion(0).getLastRow(), 0); assertEquals(summarySheet.getMergedRegion(0).getFirstColumn(), 0); assertEquals(summarySheet.getMergedRegion(0).getLastColumn(), 2); assertEquals(row.getCell(0).getStringCellValue(), SUMMARY); row = summarySheet.getRow(1); assertEquals(row.getCell(0).getStringCellValue(), MOVIE_COUNT); assertEquals(row.getCell(1).getStringCellValue(), SOAP_COUNT); assertEquals(row.getCell(2).getStringCellValue(), SIZE); input.close(); } |
MovieManager { public static void createGenreSheet(Set<Movie> filteredMovieSetByGenre, String genre) throws Exception { final String MOVIE_NAME = "Movie Name"; final String RELEASE_YEAR = "Release Year"; final String FILESIZE = "Filesize"; final String PARENT = "Parent"; Workbook wb = createWorkbook(outputFile); Sheet worksheet = null; Row row = null; CellStyle headerCellStyle = createHeaderCellStyle(wb.createCellStyle(), wb.createFont()); CellStyle bodyCellStyle = createBodyCellStyle(wb.createCellStyle(), wb.createFont()); Iterator<Movie> it = null; Movie movie = null; worksheet = createNewSheet(wb, genre.toString()); List<Movie> movies = new ArrayList<Movie>(); movies.addAll(filteredMovieSetByGenre); Collections.sort(movies, new MovieComparator<Movie>()); it = movies.iterator(); row = worksheet.createRow(0); createCell(row, 0, headerCellStyle, MOVIE_NAME, Cell.CELL_TYPE_STRING); createCell(row, 1, headerCellStyle, RELEASE_YEAR, Cell.CELL_TYPE_STRING); createCell(row, 2, headerCellStyle, FILESIZE, Cell.CELL_TYPE_STRING); createCell(row, 3, headerCellStyle, PARENT, Cell.CELL_TYPE_STRING); for (int i = 0; it.hasNext(); i++) { row = worksheet.createRow(i + 1); movie = it.next(); createCell(row, 0, bodyCellStyle, movie.getName() + movie.getFileExtension(), Cell.CELL_TYPE_STRING); createCell(row, 1, bodyCellStyle, movie.getYear(), Cell.CELL_TYPE_NUMERIC); createCell(row, 2, bodyCellStyle, formatter.format(movie.getFilesize()), Cell.CELL_TYPE_STRING); createCell(row, 3, bodyCellStyle, movie.getParent(), Cell.CELL_TYPE_STRING); Cell cell = row.getCell(1); if (((short) cell.getNumericCellValue()) == Movie.UNKNOWN_RELEASE_YEAR) { cell.setCellValue(EMPTY); } } autoSizeColumns(worksheet); writeToDisk(wb); } MovieManager(); MovieManager(File inputDir, File outputFile); static void validateFile(File... files); static GenreSummary getSummaryByGenre(String genre); static Summary getSummary(); static Map<String, Set<Movie>> getMovieSetGroupedByGenre(); static void createSummarySheet(Summary summary); static void createGenreSheet(Set<Movie> filteredMovieSetByGenre,
String genre); static Summary getSummary(
Map<String, Set<Movie>> movieSetGroupedByGenre); static final String EMPTY; } | @Test public void testCreateGenreSheets() throws Exception { Sheet genreSheet = null; Row row = null; MovieManager.createGenreSheet(movieService.filterMovieSetByGenre( movieSet, ACTION_AND_ADVENTURE.toString()), ACTION_AND_ADVENTURE.toString()); MovieManager .createGenreSheet( movieService.filterMovieSetByGenre(movieSet, HORROR.toString()), HORROR.toString()); InputStream input = new FileInputStream(outputFile); Workbook wb = WorkbookFactory.create(input); genreSheet = wb.getSheet(ACTION_AND_ADVENTURE.toString()); assertNotNull(genreSheet); row = genreSheet.getRow(1); assertEquals(row.getCell(0).getStringCellValue(), "3-10 To Yuma.mkv"); row = genreSheet.getRow(3); assertEquals(row.getCell(0).getStringCellValue(), "Casino Royal.mkv"); genreSheet = wb.getSheet(HORROR.toString()); assertNotNull(genreSheet); row = genreSheet.getRow(1); assertEquals(row.getCell(0).getStringCellValue(), "I Saw The Devil.mkv"); assertEquals(row.getCell(3).getStringCellValue(), "I Saw The Devil (2010)"); row = genreSheet.getRow(2); assertEquals(row.getCell(0).getStringCellValue(), "Inferno.mkv"); assertEquals(row.getCell(3).getStringCellValue(), "The Three Mothers Trilogy"); input.close(); } |
Movie implements Serializable { @Override public boolean equals(Object obj) { Movie m = null; boolean result = false; if (obj == this) { return true; } if (!(obj instanceof Movie)) { return false; } m = (Movie) obj; result = (name != null && name.equals(m.name)); result &= (year == m.year); result &= (genre != null && genre.equals(m.genre)); return result; } Movie(); Movie(String name, short year, String fileExtension); Movie(String name, short year, String genre, long filesize,
String fileExtension); String getName(); void setName(String name); short getYear(); void setYear(short year); String getGenre(); void setGenre(String genre); long getFilesize(); void setFilesize(long filesize); String getFileExtension(); void setFileExtension(String fileExtension); String getParent(); void setParent(String parent); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); static final short UNKNOWN_RELEASE_YEAR; static final String UNKNOWN_GENRE; } | @Test public void testEquals() { assertEquals(movie1, movie1); assertEquals(movie1, movie7); assertFalse(movie1.equals("abc")); assertFalse(movie1.equals(movie2)); assertFalse(movie1.equals(movie3)); assertFalse(movie1.equals(movie4)); assertFalse(movie1.equals(movie5)); assertFalse(movie1.equals(movie6)); }
@Test public void testListEquality() { SortedSet<Movie> movieList1 = new TreeSet<Movie>( new MovieComparator<Movie>()); SortedSet<Movie> movieList2 = new TreeSet<Movie>( new MovieComparator<Movie>()); SortedSet<Movie> movieList3 = new TreeSet<Movie>( new MovieComparator<Movie>()); movieList1.add(movie1); movieList2.add(movie1); assertEquals(movieList1, movieList1); assertEquals(movieList1, movieList2); assertFalse(movieList1.equals(movieList3)); } |
Movie implements Serializable { @Override public int hashCode() { int result = 17; int c = 0; c = ((name == null) ? 0 : name.hashCode()); result = 37 * result + c; c = (int) year; result = 37 * result + c; c = ((genre == null) ? 0 : genre.hashCode()); result = 37 * result + c; return result; } Movie(); Movie(String name, short year, String fileExtension); Movie(String name, short year, String genre, long filesize,
String fileExtension); String getName(); void setName(String name); short getYear(); void setYear(short year); String getGenre(); void setGenre(String genre); long getFilesize(); void setFilesize(long filesize); String getFileExtension(); void setFileExtension(String fileExtension); String getParent(); void setParent(String parent); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); static final short UNKNOWN_RELEASE_YEAR; static final String UNKNOWN_GENRE; } | @Test public void testHashCode() { assertEquals(movie1.hashCode(), movie1.hashCode()); assertEquals(movie1.hashCode(), movie7.hashCode()); assertTrue(movie1.hashCode() != "abc".hashCode()); assertTrue(movie1.hashCode() != movie2.hashCode()); assertTrue(movie1.hashCode() != movie3.hashCode()); assertTrue(movie1.hashCode() != movie4.hashCode()); assertTrue(movie1.hashCode() != movie5.hashCode()); assertTrue(movie1.hashCode() != movie6.hashCode()); } |
KeyStoreManager { public static KeyPair getKeyPair(String keystore, String storePassword, String keyPassword, String alias) throws Exception { KeyStore ks = loadKeyStore(keystore, storePassword); Key key = getKey(keystore, storePassword, keyPassword, alias); PublicKey publicKey = null; PrivateKey privateKey = null; key = ks.getKey(alias, keyPassword.toCharArray()); if (key instanceof PrivateKey) { Certificate cert = ks.getCertificate(alias); publicKey = cert.getPublicKey(); privateKey = (PrivateKey) key; return new KeyPair(publicKey, privateKey); } throw new NoSuchKeyException("Alias '" + alias + "' does not exist in keystore '" + keystore + "'."); } static KeyPair getKeyPair(String keystore, String storePassword,
String keyPassword, String alias); static SecretKey getSecKey(String keystore, String storePassword,
String keyPassword, String alias); static KeyInfo createKeyInfo(final XMLSignatureFactory fac,
final String certificateFile); static Certificate getCertificate(final String certificateFile); } | @Test public void testPublicKey() { try { KeyPair keyPair = KeyStoreManager.getKeyPair( KeyStoreManagerTest.class.getResource("/" + KEYSTORE) .getPath(), STORE_PASSWORD, KEY_PASSWORD, ALIAS); Assert.assertNotNull("Public Key must not be null", keyPair.getPublic()); Assert.assertNotNull("Private Key must not be null", keyPair.getPrivate()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Shouldn't be here."); } } |
GenreSummary implements Serializable { @Override public boolean equals(Object obj) { GenreSummary gs = null; boolean result = false; if (obj == this) { return true; } if (!(obj instanceof GenreSummary)) { return false; } gs = (GenreSummary) obj; result = (genre != null && genre.equals(gs.genre)); result &= (movieTitleCount == gs.movieTitleCount); result &= (soapTitleCount == gs.soapTitleCount); return result; } String getGenre(); void setGenre(String genre); int getMovieTitleCount(); void setMovieTitleCount(int movieTitleCount); int getSoapTitleCount(); void setSoapTitleCount(int soapTitleCount); long getSumOfSizeOfAllTitlesInThisGenre(); void setSumOfSizeOfAllTitlesInThisGenre(
long sumOfSizeOfAllTitlesInThisGenre); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); } | @Test public void testEquals() { assertEquals(genreSummary1, genreSummary1); assertEquals(genreSummary1, genreSummary2); assertFalse(genreSummary1.equals("abc")); assertFalse(genreSummary1.equals(genreSummary3)); assertFalse(genreSummary1.equals(genreSummary4)); assertFalse(genreSummary1.equals(genreSummary5)); assertFalse(genreSummary1.equals(genreSummary6)); } |
GenreSummary implements Serializable { @Override public int hashCode() { int result = 17; int c = 0; c = ((genre == null) ? 0 : genre.hashCode()); result = 37 * result + c; c = (int) (movieTitleCount); result = 37 * result + c; c = (int) (soapTitleCount); result = 37 * result + c; return result; } String getGenre(); void setGenre(String genre); int getMovieTitleCount(); void setMovieTitleCount(int movieTitleCount); int getSoapTitleCount(); void setSoapTitleCount(int soapTitleCount); long getSumOfSizeOfAllTitlesInThisGenre(); void setSumOfSizeOfAllTitlesInThisGenre(
long sumOfSizeOfAllTitlesInThisGenre); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); } | @Test public void testHashCode() { assertEquals(genreSummary1.hashCode(), genreSummary1.hashCode()); assertEquals(genreSummary1.hashCode(), genreSummary2.hashCode()); assertTrue(genreSummary1.hashCode() != "abc".hashCode()); assertTrue(genreSummary1.hashCode() != genreSummary3.hashCode()); assertTrue(genreSummary1.hashCode() != genreSummary4.hashCode()); assertTrue(genreSummary1.hashCode() != genreSummary5.hashCode()); assertTrue(genreSummary1.hashCode() != genreSummary6.hashCode()); } |
Summary implements Serializable { @Override public boolean equals(Object obj) { Summary s = null; if (obj == this) { return true; } if (!(obj instanceof Summary)) { return false; } s = (Summary) obj; return ((genreSummary == s.genreSummary) || (genreSummary != null && genreSummary .equals(s.genreSummary))); } List<GenreSummary> getGenreSummary(); void setGenreSummary(List<GenreSummary> genreSummary); int getMovieTitleCount(); void setMovieTitleCount(int movieTitleCount); int getSoapTitleCount(); void setSoapTitleCount(int soapTitleCount); long getSumOfSizeOfAllTitles(); void setSumOfSizeOfAllTitles(long sumOfSizeOfAllTitles); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); } | @Test public void testEquals() { assertEquals(summary1, summary1); assertEquals(summary2, summary2); assertEquals(summary2, summary3); assertFalse(summary2.equals("abc")); assertFalse(summary2.equals(summary4)); assertFalse(summary2.equals(summary5)); assertFalse(summary2.equals(summary6)); assertFalse(summary2.equals(summary7)); } |
Summary implements Serializable { @Override public int hashCode() { int result = 17; int c = 0; c = ((genreSummary == null) ? 0 : genreSummary.hashCode()); result = 37 * result + c; return result; } List<GenreSummary> getGenreSummary(); void setGenreSummary(List<GenreSummary> genreSummary); int getMovieTitleCount(); void setMovieTitleCount(int movieTitleCount); int getSoapTitleCount(); void setSoapTitleCount(int soapTitleCount); long getSumOfSizeOfAllTitles(); void setSumOfSizeOfAllTitles(long sumOfSizeOfAllTitles); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); } | @Test public void testHashCode() { assertEquals(summary1.hashCode(), summary1.hashCode()); assertEquals(summary2.hashCode(), summary2.hashCode()); assertEquals(summary2.hashCode(), summary3.hashCode()); assertTrue(summary2.hashCode() != "abc".hashCode()); assertTrue(summary2.hashCode() != summary4.hashCode()); assertTrue(summary2.hashCode() != summary5.hashCode()); assertTrue(summary2.hashCode() != summary6.hashCode()); assertTrue(summary2.hashCode() != summary7.hashCode()); } |
ConversionRulesEngine { public static long toDecimal(final String romanNumber) { final int len = romanNumber.length(); int difference = 0; long decimalNumber = 0L; char currentChar = '\u0000'; char lookAheadChar = '\u0000'; for (int index = 0; index < len;) { currentChar = Character.toUpperCase(romanNumber.charAt(index)); if (index != (len - 1) && subtractionMap.containsKey(currentChar)) { lookAheadChar = Character.toUpperCase(romanNumber .charAt(index + 1)); if (subtractionMap.get(currentChar).contains(lookAheadChar)) { difference = getDecimalValue(lookAheadChar) - getDecimalValue(currentChar); decimalNumber += difference; index += 2; } else { decimalNumber += getDecimalValue(currentChar); index++; } } else { decimalNumber += getDecimalValue(currentChar); index++; } } return decimalNumber; } static long toDecimal(final String romanNumber); static final Map<Character, List<Character>> subtractionMap; } | @Test public void testToDecimal() { Assert.assertEquals(1L, ConversionRulesEngine.toDecimal("I")); Assert.assertEquals(2L, ConversionRulesEngine.toDecimal("II")); Assert.assertEquals(3L, ConversionRulesEngine.toDecimal("III")); Assert.assertEquals(4L, ConversionRulesEngine.toDecimal("IV")); Assert.assertEquals(5L, ConversionRulesEngine.toDecimal("V")); Assert.assertEquals(6L, ConversionRulesEngine.toDecimal("VI")); Assert.assertEquals(7L, ConversionRulesEngine.toDecimal("VII")); Assert.assertEquals(8L, ConversionRulesEngine.toDecimal("VIII")); Assert.assertEquals(9L, ConversionRulesEngine.toDecimal("IX")); Assert.assertEquals(10L, ConversionRulesEngine.toDecimal("X")); Assert.assertEquals(11L, ConversionRulesEngine.toDecimal("XI")); Assert.assertEquals(12L, ConversionRulesEngine.toDecimal("XII")); Assert.assertEquals(13L, ConversionRulesEngine.toDecimal("XIII")); Assert.assertEquals(14L, ConversionRulesEngine.toDecimal("XIV")); Assert.assertEquals(15L, ConversionRulesEngine.toDecimal("XV")); Assert.assertEquals(1944L, ConversionRulesEngine.toDecimal("MCMXLIV")); Assert.assertEquals(1910L, ConversionRulesEngine.toDecimal("MDCCCCX")); Assert.assertEquals(1954L, ConversionRulesEngine.toDecimal("MCMLIV")); Assert.assertEquals(1990L, ConversionRulesEngine.toDecimal("MCMXC")); }
@Test(expected = IllegalArgumentException.class) public void testNullRomanNumber() { ConversionRulesEngine.toDecimal(null); }
@Test(expected = IllegalArgumentException.class) public void testEmptyRomanNumber() { ConversionRulesEngine.toDecimal(""); }
@Test(expected = IllegalArgumentException.class) public void testBlankRomanNumber() { ConversionRulesEngine.toDecimal(" "); }
@Test(expected = IllegalArgumentException.class) public void testInvalidRomanNumber1() { ConversionRulesEngine.toDecimal("A"); }
@Test(expected = IllegalArgumentException.class) public void testInvalidRomanNumber2() { ConversionRulesEngine.toDecimal("IA"); }
@Test(expected = IllegalArgumentException.class) public void testInvalidRomanNumber3() { ConversionRulesEngine.toDecimal("AI"); } |
XMLEncryptor { public void encrypt(String inputFile, String outputFile) throws Exception { File ipFile = new File(inputFile); File opFile = new File(outputFile); SecurityUtil.print(ipFile); encMgr.encrypt(ipFile, opFile); SecurityUtil.print(opFile); } void encrypt(String inputFile, String outputFile); void decrypt(String inputFile); } | @Test public void testEncrypt() throws Exception { String inputFile = XMLEncryptorTest.class.getResource("/" + INPUT_FILE) .getPath(); String outputFile = new File(inputFile).getParent() + File.separator + OUTPUT_FILE; XMLEncryptor.encrypt(inputFile, outputFile); } |
Validator { public static void validate(final String romanNumber) { if (romanNumber == null || romanNumber.trim().length() == 0) { throw new IllegalArgumentException(romanNumber + " is not a valid Roman number."); } final int len = romanNumber.length(); char currentChar = '\u0000'; for (int index = 0; index < len; index++) { currentChar = Character.toUpperCase(romanNumber.charAt(index)); if (romanNumber.toUpperCase().matches( Character.toUpperCase(currentChar) + "{" + (repeatMap.get(currentChar) + 1) + ",}")) { throw new IllegalArgumentException(currentChar + " can not be repeated more than " + repeatMap.get(currentChar) + " times in succession."); } } } static void validate(final String romanNumber); static final Map<Character, Integer> repeatMap; } | @Test public void testValidNumber1() { Validator.validate("III"); }
@Test public void testValidNumber2() { Validator.validate("XXX"); }
@Test public void testValidNumber3() { Validator.validate("IIIX"); }
@Test public void testValidNumber4() { Validator.validate("XXXIX"); }
@Test public void testValidNumber5() { Validator.validate("IV"); }
@Test(expected = IllegalArgumentException.class) public void testInvalidNumber1() { Validator.validate("IIII"); }
@Test(expected = IllegalArgumentException.class) public void testInvalidNumber2() { Validator.validate("MMMM"); }
@Test(expected = IllegalArgumentException.class) public void testInvalidNumber3() { Validator.validate("DD"); } |
XMLEncryptor { public void decrypt(String inputFile) throws Exception { File ipFile = new File(inputFile); SecurityUtil.print(ipFile); encMgr.decrypt(ipFile); } void encrypt(String inputFile, String outputFile); void decrypt(String inputFile); } | @Test public void testDecrypt() throws Exception { String inputFile = XMLEncryptorTest.class.getResource("/" + INPUT_FILE) .getPath(); String outputFile = new File(inputFile).getParent() + File.separator + OUTPUT_FILE; XMLEncryptor.decrypt(outputFile); } |
SpaceTaskAPIController { @RequestMapping(value = "/execute",method=RequestMethod.POST) public ModelAndView executeTask(@RequestParam String spaceName,@RequestParam String locators,@RequestBody SpaceTaskRequest body) { return execute(spaceName,locators,body); } SpaceTaskAPIController(); @RequestMapping(value = "/execute",method=RequestMethod.POST) ModelAndView executeTask(@RequestParam String spaceName,@RequestParam String locators,@RequestBody SpaceTaskRequest body); } | @Test public void sanityTest() { SpaceTaskAPIController controller=new SpaceTaskAPIController(); SpaceTaskRequest body=new SpaceTaskRequest(); body.language="groovy"; body.target="all"; body.code="println \"here\";return \"success\";"; ModelAndView result=controller.executeTask("space","localhost",body); assertEquals(1,result.getModel().size()); }
@Test public void writeToSpaceTest(){ space.clear(new Object()); SpaceTaskAPIController controller=new SpaceTaskAPIController(); SpaceTaskRequest body=new SpaceTaskRequest(); body.language="groovy"; body.target="all"; body.code="gigaSpace.write(new String(\"test\"));return \"success\";"; ModelAndView result=controller.executeTask("space","localhost",body); assertEquals(2,space.count(new Object())); }
@Test public void readSpaceBroadcastTest(){ space.getTypeManager().registerTypeDescriptor(new SpaceTypeDescriptorBuilder("test-type") .idProperty("id",false).addFixedProperty("val",String.class).create()); space.clear(new Object()); SpaceDocument d=new SpaceDocument("test-type"); d.setProperty("id",0); d.setProperty("val","val0"); space.write(d); d.setProperty("id",1); d.setProperty("val","val1"); space.write(d); SpaceTaskAPIController controller=new SpaceTaskAPIController(); SpaceTaskRequest body=new SpaceTaskRequest(); body.language="groovy"; body.target="all"; body.code="import com.gigaspaces.document.*;"+ "def newdoc=gigaSpace.read(new SpaceDocument(\"test-type\"));"+ "return newdoc.getProperty(\"val\");"; ModelAndView result=controller.executeTask("space","localhost",body); assertEquals(1,result.getModel().size()); assertEquals(2,((List)result.getModel().get("results")).size()); }
@Test public void readSpaceSinglePartitionTest(){ space.getTypeManager().registerTypeDescriptor(new SpaceTypeDescriptorBuilder("test-type") .idProperty("id",false).addFixedProperty("val",String.class).create()); space.clear(new Object()); SpaceDocument d=new SpaceDocument("test-type"); d.setProperty("id",0); d.setProperty("val","val0"); space.write(d); d.setProperty("id",1); d.setProperty("val","val1"); space.write(d); SpaceTaskAPIController controller=new SpaceTaskAPIController(); SpaceTaskRequest body=new SpaceTaskRequest(); body.language="groovy"; body.target=0; body.code="import com.gigaspaces.document.*;"+ "def newdoc=gigaSpace.read(new SpaceDocument(\"test-type\"));"+ "return newdoc.getProperty(\"val\");"; ModelAndView result=controller.executeTask("space","localhost",body); assertEquals(1,result.getModel().size()); assertEquals(1,((List)result.getModel().get("results")).size()); ObjectMapper om=new ObjectMapper(); try{ System.out.println(om.writeValueAsString(result.getModel().get("results"))); }catch(Exception e){ e.printStackTrace(); } } |
MajorityVotingTypeOverlapResolution implements TypeOverlapResolutionRepository { @Override public final void resolveTypeOverlapping(final TypeOverlappingConfig config, final List<Entity> entities) throws MappingNotExistsException, TypeNotExistsException { for (final Entity entity : entities) { StringBuilder newType = new StringBuilder(); for (final String singleType : entity.getType().split("\\|\\|")) { final String[] splittedType = singleType.split("from"); if (newType.toString().isEmpty()) { newType = new StringBuilder(this.resolveTypeMapping(splittedType[1].split("--")[0], config.getTo(), splittedType[0])); } else { newType.append("||"); newType.append(this.resolveTypeMapping(splittedType[1].split("--")[0], config.getTo(), splittedType[0])); } newType.append("--"); newType.append(config.getPriority().indexOf(splittedType[1].split("--")[1])); } entity.setType(newType.toString()); } this.majorityVote(entities); } MajorityVotingTypeOverlapResolution(); @Override final void resolveTypeOverlapping(final TypeOverlappingConfig config, final List<Entity> entities); } | @Test final void resolveTypeOverlappingHappyMajority() throws MappingNotExistsException, TypeNotExistsException { final TypeOverlappingConfig config = new TypeOverlappingConfig(); config.setTo("CoNLL"); config.setPriority(Arrays.asList("ann1", "ann2", "ann3")); final List<Entity> entities = new ArrayList<>(); final Entity entity = Entity.builder().type("PERfromCoNLL--ann1||dbo_PersonfromDBpedia--ann2||dbo_PlacefromDBpedia--ann3").build(); entities.add(entity); final Document document = Document.builder().entities(entities).build(); final TypeOverlapResolutionRepository voting = new MajorityVotingTypeOverlapResolution(); voting.resolveTypeOverlapping(config, document.getEntities()); Assertions.assertEquals("PER", document.getEntities().get(0).getType(), "Must be equals"); }
@Test final void resolveTypeOverlappingHappyDrawPerson() throws MappingNotExistsException, TypeNotExistsException { final TypeOverlappingConfig config = new TypeOverlappingConfig(); config.setTo("CoNLL"); config.setPriority(Arrays.asList("ann1", "ann3")); final List<Entity> entities = new ArrayList<>(); final Entity entity = Entity.builder().type("PERfromCoNLL--ann1||dbo_PlacefromDBpedia--ann3").build(); entities.add(entity); final Document document = Document.builder().entities(entities).build(); final TypeOverlapResolutionRepository voting = new MajorityVotingTypeOverlapResolution(); voting.resolveTypeOverlapping(config, document.getEntities()); Assertions.assertEquals("PER", document.getEntities().get(0).getType(), "Must be equals"); }
@Test final void resolveTypeOverlappingHappyDrawPlace() throws MappingNotExistsException, TypeNotExistsException { final TypeOverlappingConfig config = new TypeOverlappingConfig(); config.setTo("CoNLL"); config.setPriority(Arrays.asList("ann3", "ann1")); final List<Entity> entities = new ArrayList<>(); final Entity entity = Entity.builder().type("PERfromCoNLL--ann1||dbo_PlacefromDBpedia--ann3").build(); entities.add(entity); final Document document = Document.builder().entities(entities).build(); final TypeOverlapResolutionRepository voting = new MajorityVotingTypeOverlapResolution(); voting.resolveTypeOverlapping(config, document.getEntities()); Assertions.assertEquals("LOC", document.getEntities().get(0).getType(), "Must be equals"); }
@Test final void resolveTypeOverlappingUnHappyWrongMapping() { final TypeOverlappingConfig config = new TypeOverlappingConfig(); config.setTo("CoNLL"); config.setPriority(Arrays.asList("ann3", "ann1")); final List<Entity> entities = new ArrayList<>(); final Entity entity = Entity.builder().type("PERfromCNL--ann1||dbo_PlacefromDBpedia--ann3").build(); entities.add(entity); final Document document = Document.builder().entities(entities).build(); final TypeOverlapResolutionRepository voting = new MajorityVotingTypeOverlapResolution(); Assertions.assertThrows(MappingNotExistsException.class, () -> voting.resolveTypeOverlapping(config, document.getEntities())); }
@Test final void resolveTypeOverlappingUnHappyWrongType() { final TypeOverlappingConfig config = new TypeOverlappingConfig(); config.setTo("MUC"); config.setPriority(Arrays.asList("ann3", "ann1")); final List<Entity> entities = new ArrayList<>(); final Entity entity = Entity.builder().type("PEOPEOfromCoNLL--ann1||dbo_PlacefromDBpedia--ann3").build(); entities.add(entity); final Document document = Document.builder().entities(entities).build(); final TypeOverlapResolutionRepository voting = new MajorityVotingTypeOverlapResolution(); Assertions.assertThrows(TypeNotExistsException.class, () -> voting.resolveTypeOverlapping(config, document.getEntities())); } |
MergeMentionOverlapResolution implements MentionOverlapResolutionRepository { @Override public final List<Entity> resolveMentionOverlapping( final Map<AnnotatorConfig, List<Entity>> documents) { final List<Entity> finalEntities = new ArrayList<>(); for (final Map.Entry<AnnotatorConfig, List<Entity>> document : documents.entrySet()) { for (final Entity old : document.getValue()) { final List<Integer> overlapIndexes = this.overlappingIndex(finalEntities, old); if (overlapIndexes.isEmpty()) { if (!old.getType().isEmpty()) { old.setType( old.getType() + "from" + document.getKey().getFrom() + "--" + document.getKey().getName()); } finalEntities.add(old); } else { final Collection<Entity> newEntities = new ArrayList<>(); Entity newEntity = this.entityResolution(finalEntities.get(overlapIndexes.get(0)), old, document.getKey()); newEntities.add(newEntity); for (int i = 1;i < overlapIndexes.size();i++) { newEntity = this.entityResolution(finalEntities.get(overlapIndexes.get(i)), old, document.getKey()); newEntities.add(newEntity); } if (1 < newEntities.size()) { final StringBuilder newType = new StringBuilder(); for (final Entity entity : newEntities) { final String[] splitTypes = entity.getType().split("\\|\\|"); for (final String splitType : splitTypes) { if (!newType.toString().contains(splitType)) { newType.append(splitType); newType.append("||"); } } } newEntity.setType(newType.substring(0, newType.length() - 2)); } final Collection<Entity> entitiesToRemove = new ArrayList<>(); for (final Integer overlapIndexe : overlapIndexes) { entitiesToRemove.add(finalEntities.get(overlapIndexe)); } finalEntities.removeAll(entitiesToRemove); finalEntities.add(newEntity); } } } return finalEntities; } @Override final List<Entity> resolveMentionOverlapping(
final Map<AnnotatorConfig, List<Entity>> documents); } | @Test final void resolveMentionOverlappingHappy6() { final AnnotatorConfig config1 = new AnnotatorConfig(); config1.setName("ann1"); config1.setFrom("CoNLL"); final AnnotatorConfig config2 = new AnnotatorConfig(); config2.setName("ann2"); config2.setFrom("CoNLL"); final Entity entity1 = Entity.builder().phrase("United States of America").cleanPhrase("United States of America").startOffset(0).endOffset(24).type("").build(); final Entity entity2 = Entity.builder().phrase("States").cleanPhrase("States").startOffset(7).endOffset(13).type("").build(); final Document doc1 = Document.builder().entities(Collections.singletonList(entity1)).text("United States of America").build(); final Document doc2 = Document.builder().entities(Collections.singletonList(entity2)).text("United States of America").build(); final Map<AnnotatorConfig, List<Entity>> documents = new HashMap<>(); documents.put(config1, doc1.getEntities()); documents.put(config2, doc2.getEntities()); final MentionOverlapResolutionRepository mergeMentionOverlapResolution = new MergeMentionOverlapResolution(); final List<Entity> newEntities = mergeMentionOverlapResolution.resolveMentionOverlapping(documents); Assertions.assertEquals(1, newEntities.size(), "Must be equals"); Assertions.assertEquals(0, newEntities.get(0).getStartOffset().intValue(), "Must be equals"); Assertions.assertEquals(24, newEntities.get(0).getEndOffset().intValue(), "Must be equals"); Assertions.assertEquals("", newEntities.get(0).getType(), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getPhrase(), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getCleanPhrase(), "Must be equals"); }
@Test final void resolveMentionOverlappingHappy7() { final AnnotatorConfig config1 = new AnnotatorConfig(); config1.setName("ann1"); config1.setFrom("CoNLL"); final AnnotatorConfig config2 = new AnnotatorConfig(); config2.setName("ann2"); config2.setFrom("CoNLL"); final Entity entity1 = Entity.builder().phrase("United States of America").cleanPhrase("United States of America").startOffset(0).endOffset(24).type("LOCATION").build(); final Entity entity2 = Entity.builder().phrase("States").cleanPhrase("States").startOffset(7).endOffset(13).type("").build(); final Document doc1 = Document.builder().entities(Collections.singletonList(entity1)).text("United States of America").build(); final Document doc2 = Document.builder().entities(Collections.singletonList(entity2)).text("United States of America").build(); final Map<AnnotatorConfig, List<Entity>> documents = new HashMap<>(); documents.put(config1, doc1.getEntities()); documents.put(config2, doc2.getEntities()); final MentionOverlapResolutionRepository mergeMentionOverlapResolution = new MergeMentionOverlapResolution(); final List<Entity> newEntities = mergeMentionOverlapResolution.resolveMentionOverlapping(documents); Assertions.assertEquals(1, newEntities.size(), "Must be equals"); Assertions.assertEquals(0, newEntities.get(0).getStartOffset().intValue(), "Must be equals"); Assertions.assertEquals(24, newEntities.get(0).getEndOffset().intValue(), "Must be equals"); Assertions.assertTrue("LOCATIONfromCoNLL--ann2".equals(newEntities.get(0).getType()) || "LOCATIONfromCoNLL--ann1".equals(newEntities.get(0).getType()), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getPhrase(), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getCleanPhrase(), "Must be equals"); }
@Test final void resolveMentionOverlappingHappy8() { final AnnotatorConfig config1 = new AnnotatorConfig(); config1.setName("ann1"); config1.setFrom("CoNLL"); final AnnotatorConfig config2 = new AnnotatorConfig(); config2.setName("ann2"); config2.setFrom("CoNLL"); final Entity entity1 = Entity.builder().phrase("United States of America").cleanPhrase("United States of America").startOffset(0).endOffset(24).type("").build(); final Entity entity2 = Entity.builder().phrase("States").cleanPhrase("States").startOffset(7).endOffset(13).type("LOCATION").build(); final Document doc1 = Document.builder().entities(Collections.singletonList(entity1)).text("United States of America").build(); final Document doc2 = Document.builder().entities(Collections.singletonList(entity2)).text("United States of America").build(); final Map<AnnotatorConfig, List<Entity>> documents = new HashMap<>(); documents.put(config1, doc1.getEntities()); documents.put(config2, doc2.getEntities()); final MentionOverlapResolutionRepository mergeMentionOverlapResolution = new MergeMentionOverlapResolution(); final List<Entity> newEntities = mergeMentionOverlapResolution.resolveMentionOverlapping(documents); Assertions.assertEquals(1, newEntities.size(), "Must be equals"); Assertions.assertEquals(0, newEntities.get(0).getStartOffset().intValue(), "Must be equals"); Assertions.assertEquals(24, newEntities.get(0).getEndOffset().intValue(), "Must be equals"); Assertions.assertTrue("LOCATIONfromCoNLL--ann2".equals(newEntities.get(0).getType()) || "LOCATIONfromCoNLL--ann1".equals(newEntities.get(0).getType()), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getPhrase(), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getCleanPhrase(), "Must be equals"); }
@Test final void resolveMentionOverlappingHappy9() { final AnnotatorConfig config1 = new AnnotatorConfig(); config1.setName("ann1"); config1.setFrom("CoNLL"); final AnnotatorConfig config2 = new AnnotatorConfig(); config2.setName("ann2"); config2.setFrom("CoNLL"); final AnnotatorConfig config3 = new AnnotatorConfig(); config3.setName("ann3"); config3.setFrom("CoNLL"); final Entity entity1 = Entity.builder().phrase("United States of America").cleanPhrase("United States of America").startOffset(0).endOffset(24).type("LOCATION").build(); final Entity entity2 = Entity.builder().phrase("States").cleanPhrase("States").startOffset(7).endOffset(13).type("LOCATION").build(); final Entity entity3 = Entity.builder().phrase("America").cleanPhrase("America").startOffset(17).endOffset(24).type("LOCATION").build(); final Document doc1 = Document.builder().entities(Collections.singletonList(entity1)).text("United States of America").build(); final Document doc2 = Document.builder().entities(Collections.singletonList(entity2)).text("United States of America").build(); final Document doc3 = Document.builder().entities(Collections.singletonList(entity3)).text("United States of America").build(); final Map<AnnotatorConfig, List<Entity>> documents = new HashMap<>(); documents.put(config1, doc1.getEntities()); documents.put(config2, doc2.getEntities()); documents.put(config3, doc3.getEntities()); final MentionOverlapResolutionRepository mergeMentionOverlapResolution = new MergeMentionOverlapResolution(); final List<Entity> newEntities = mergeMentionOverlapResolution.resolveMentionOverlapping(documents); Assertions.assertEquals(1, newEntities.size(), "Must be equals"); Assertions.assertEquals(0, newEntities.get(0).getStartOffset().intValue(), "Must be equals"); Assertions.assertEquals(24, newEntities.get(0).getEndOffset().intValue(), "Must be equals"); Assertions.assertTrue("LOCATIONfromCoNLL--ann1||LOCATIONfromCoNLL--ann2||LOCATIONfromCoNLL--ann3".equals(newEntities.get(0).getType()) || "LOCATIONfromCoNLL--ann1||LOCATIONfromCoNLL--ann3||LOCATIONfromCoNLL--ann2".equals(newEntities.get(0).getType()) || "LOCATIONfromCoNLL--ann2||LOCATIONfromCoNLL--ann1||LOCATIONfromCoNLL--ann3".equals(newEntities.get(0).getType()) || "LOCATIONfromCoNLL--ann2||LOCATIONfromCoNLL--ann3||LOCATIONfromCoNLL--ann1".equals(newEntities.get(0).getType()) || "LOCATIONfromCoNLL--ann3||LOCATIONfromCoNLL--ann2||LOCATIONfromCoNLL--ann1".equals(newEntities.get(0).getType()) || "LOCATIONfromCoNLL--ann3||LOCATIONfromCoNLL--ann1||LOCATIONfromCoNLL--ann2".equals(newEntities.get(0).getType()), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getPhrase(), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getCleanPhrase(), "Must be equals"); }
@Test final void resolveMentionOverlappingHappy1() { final AnnotatorConfig config1 = new AnnotatorConfig(); config1.setName("ann1"); config1.setFrom("CoNLL"); final AnnotatorConfig config2 = new AnnotatorConfig(); config2.setName("ann2"); config2.setFrom("CoNLL"); final Entity entity1 = Entity.builder().phrase("United States").cleanPhrase("United States").startOffset(0).endOffset(13).type("LOCATION").build(); final Entity entity2 = Entity.builder().phrase("States of America").cleanPhrase("States of America").startOffset(7).endOffset(24).type("LOCATION").build(); final Document doc1 = Document.builder().entities(Collections.singletonList(entity1)).text("United States of America").build(); final Document doc2 = Document.builder().entities(Collections.singletonList(entity2)).text("United States of America").build(); final Map<AnnotatorConfig, List<Entity>> documents = new HashMap<>(); documents.put(config1, doc1.getEntities()); documents.put(config2, doc2.getEntities()); final MentionOverlapResolutionRepository mergeMentionOverlapResolution = new MergeMentionOverlapResolution(); final List<Entity> newEntities = mergeMentionOverlapResolution.resolveMentionOverlapping(documents); Assertions.assertEquals(1, newEntities.size(), "Must be equals"); Assertions.assertEquals(0, newEntities.get(0).getStartOffset().intValue(), "Must be equals"); Assertions.assertEquals(24, newEntities.get(0).getEndOffset().intValue(), "Must be equals"); Assertions.assertTrue("LOCATIONfromCoNLL--ann2||LOCATIONfromCoNLL--ann1".equals(newEntities.get(0).getType()) || "LOCATIONfromCoNLL--ann1||LOCATIONfromCoNLL--ann2".equals(newEntities.get(0).getType()), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getPhrase(), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getCleanPhrase(), "Must be equals"); }
@Test final void resolveMentionOverlappingHappy2() { final AnnotatorConfig config1 = new AnnotatorConfig(); config1.setName("ann1"); config1.setFrom("CoNLL"); final AnnotatorConfig config2 = new AnnotatorConfig(); config2.setName("ann2"); config2.setFrom("CoNLL"); final Entity entity1 = Entity.builder().phrase("United States").cleanPhrase("United States").startOffset(0).endOffset(13).type("LOCATION").build(); final Entity entity2 = Entity.builder().phrase("United States of America").cleanPhrase("United States of America").startOffset(0).endOffset(24).type("LOCATION").build(); final Document doc1 = Document.builder().entities(Collections.singletonList(entity1)).text("United States of America").build(); final Document doc2 = Document.builder().entities(Collections.singletonList(entity2)).text("United States of America").build(); final Map<AnnotatorConfig, List<Entity>> documents = new HashMap<>(); documents.put(config1, doc1.getEntities()); documents.put(config2, doc2.getEntities()); final MentionOverlapResolutionRepository mergeMentionOverlapResolution = new MergeMentionOverlapResolution(); final List<Entity> newEntities = mergeMentionOverlapResolution.resolveMentionOverlapping(documents); Assertions.assertEquals(1, newEntities.size(), "Must be equals"); Assertions.assertEquals(0, newEntities.get(0).getStartOffset().intValue(), "Must be equals"); Assertions.assertEquals(24, newEntities.get(0).getEndOffset().intValue(), "Must be equals"); Assertions.assertTrue("LOCATIONfromCoNLL--ann2||LOCATIONfromCoNLL--ann1".equals(newEntities.get(0).getType()) || "LOCATIONfromCoNLL--ann1||LOCATIONfromCoNLL--ann2".equals(newEntities.get(0).getType()), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getPhrase(), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getCleanPhrase(), "Must be equals"); }
@Test final void resolveMentionOverlappingHappy3() { final AnnotatorConfig config1 = new AnnotatorConfig(); config1.setName("ann1"); config1.setFrom("CoNLL"); final AnnotatorConfig config2 = new AnnotatorConfig(); config2.setName("ann2"); config2.setFrom("CoNLL"); final Entity entity1 = Entity.builder().phrase("America").cleanPhrase("America").startOffset(17).endOffset(24).type("LOCATION").build(); final Entity entity2 = Entity.builder().phrase("United States of America").cleanPhrase("United States of America").startOffset(0).endOffset(24).type("LOCATION").build(); final Document doc1 = Document.builder().entities(Collections.singletonList(entity1)).text("United States of America").build(); final Document doc2 = Document.builder().entities(Collections.singletonList(entity2)).text("United States of America").build(); final Map<AnnotatorConfig, List<Entity>> documents = new HashMap<>(); documents.put(config1, doc1.getEntities()); documents.put(config2, doc2.getEntities()); final MentionOverlapResolutionRepository mergeMentionOverlapResolution = new MergeMentionOverlapResolution(); final List<Entity> newEntities = mergeMentionOverlapResolution.resolveMentionOverlapping(documents); Assertions.assertEquals(1, newEntities.size(), "Must be equals"); Assertions.assertEquals(0, newEntities.get(0).getStartOffset().intValue(), "Must be equals"); Assertions.assertEquals(24, newEntities.get(0).getEndOffset().intValue(), "Must be equals"); Assertions.assertTrue("LOCATIONfromCoNLL--ann2||LOCATIONfromCoNLL--ann1".equals(newEntities.get(0).getType()) || "LOCATIONfromCoNLL--ann1||LOCATIONfromCoNLL--ann2".equals(newEntities.get(0).getType()), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getPhrase(), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getCleanPhrase(), "Must be equals"); }
@Test final void resolveMentionOverlappingHappy4() { final AnnotatorConfig config1 = new AnnotatorConfig(); config1.setName("ann1"); config1.setFrom("CoNLL"); final AnnotatorConfig config2 = new AnnotatorConfig(); config2.setName("ann2"); config2.setFrom("CoNLL"); final Entity entity1 = Entity.builder().phrase("States").cleanPhrase("States").startOffset(7).endOffset(13).type("LOCATION").build(); final Entity entity2 = Entity.builder().phrase("United States of America").cleanPhrase("United States of America").startOffset(0).endOffset(24).type("LOCATION").build(); final Document doc1 = Document.builder().entities(Collections.singletonList(entity1)).text("United States of America").build(); final Document doc2 = Document.builder().entities(Collections.singletonList(entity2)).text("United States of America").build(); final Map<AnnotatorConfig, List<Entity>> documents = new HashMap<>(); documents.put(config1, doc1.getEntities()); documents.put(config2, doc2.getEntities()); final MentionOverlapResolutionRepository mergeMentionOverlapResolution = new MergeMentionOverlapResolution(); final List<Entity> newEntities = mergeMentionOverlapResolution.resolveMentionOverlapping(documents); Assertions.assertEquals(1, newEntities.size(), "Must be equals"); Assertions.assertEquals(0, newEntities.get(0).getStartOffset().intValue(), "Must be equals"); Assertions.assertEquals(24, newEntities.get(0).getEndOffset().intValue(), "Must be equals"); Assertions.assertTrue("LOCATIONfromCoNLL--ann2||LOCATIONfromCoNLL--ann1".equals(newEntities.get(0).getType()) || "LOCATIONfromCoNLL--ann1||LOCATIONfromCoNLL--ann2".equals(newEntities.get(0).getType()), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getPhrase(), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getCleanPhrase(), "Must be equals"); }
@Test final void resolveMentionOverlappingHappy5() { final AnnotatorConfig config1 = new AnnotatorConfig(); config1.setName("ann1"); config1.setFrom("CoNLL"); final AnnotatorConfig config2 = new AnnotatorConfig(); config2.setName("ann2"); config2.setFrom("CoNLL"); final Entity entity2 = Entity.builder().phrase("States").cleanPhrase("States").startOffset(7).endOffset(13).type("LOCATION").build(); final Entity entity1 = Entity.builder().phrase("United States of America").cleanPhrase("United States of America").startOffset(0).endOffset(24).type("LOCATION").build(); final Document doc2 = Document.builder().entities(Collections.singletonList(entity1)).text("United States of America").build(); final Document doc1 = Document.builder().entities(Collections.singletonList(entity2)).text("United States of America").build(); final Map<AnnotatorConfig, List<Entity>> documents = new HashMap<>(); documents.put(config1, doc1.getEntities()); documents.put(config2, doc2.getEntities()); final MentionOverlapResolutionRepository mergeMentionOverlapResolution = new MergeMentionOverlapResolution(); final List<Entity> newEntities = mergeMentionOverlapResolution.resolveMentionOverlapping(documents); Assertions.assertEquals(1, newEntities.size(), "Must be equals"); Assertions.assertEquals(0, newEntities.get(0).getStartOffset().intValue(), "Must be equals"); Assertions.assertEquals(24, newEntities.get(0).getEndOffset().intValue(), "Must be equals"); Assertions.assertTrue("LOCATIONfromCoNLL--ann2||LOCATIONfromCoNLL--ann1".equals(newEntities.get(0).getType()) || "LOCATIONfromCoNLL--ann1||LOCATIONfromCoNLL--ann2".equals(newEntities.get(0).getType()), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getPhrase(), "Must be equals"); Assertions.assertEquals("United States of America", newEntities.get(0).getCleanPhrase(), "Must be equals"); } |
Strings { public static String camelToUnderscore(final String input) { String result = input; if (input instanceof String) { result = input.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase(); } return result; } static String camelToUnderscore(final String input); static String join(final String delim, final String... strings); static String canonicalize(final String name); } | @Test public void testCamelToUnderscore() { String input = "myCamelCaseTest"; String expected = "my_camel_case_test"; String actual = Strings.camelToUnderscore(input); assertEquals(expected, actual); }
@Test public void testCamelToUnderscoreSucceedsOnEmptyString() throws Exception { String input = ""; String expected = ""; String actual = Strings.camelToUnderscore(input); assertEquals(expected, actual); }
@Test public void testCamelToUnderscorePassesThroughNull() throws Exception { String input = null; String output = Strings.camelToUnderscore(input); assertEquals(input, output); }
@Test public void testCamelToUnderscoreConvertsConsecutiveCapitalsToLowercase() throws Exception { String input = "mySQLTest"; String expected = "my_sqltest"; String actual = Strings.camelToUnderscore(input); assertEquals(expected, actual); } |
StringValidations { public static boolean isAlphanumeric(final String textWithDigits) { if (textWithDigits != null) { return textWithDigits.matches("^[a-zA-Z\\d]*$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsAlphaNumericReturnsTrueForAlphanumericInput() { assertTrue(StringValidations.isAlphanumeric("T3st")); }
@Test public void testIsAlphaNumericReturnsTrueForAlphabeticInput() { assertTrue(StringValidations.isAlphanumeric("Test")); }
@Test public void testIsAlphaNumericReturnsFalseForSpecialChar() { assertFalse(StringValidations.isAlphanumeric("@#3st!")); } |
StringValidations { public static boolean isEmptyString(final String text) { if (text != null) { return text.matches(""); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsEmptyStringReturnsTrueForEmptyString() { assertTrue(StringValidations.isEmptyString("")); }
@Test public void testIsEmptyStringReturnsFalseForNonEmptyString() { assertFalse(StringValidations.isEmptyString("asdWsonciw aski")); }
@Test public void testIsEmptyStringReturnsFalseForSpecialChar() { assertFalse(StringValidations.isEmptyString("@#3st!")); } |
StringValidations { public static boolean isPunctuatedText(final String text) { if (text != null) { return text.matches("^[a-zA-Z/\\d\\s._?!,;':\"~`$%&()+=\\[\\]-]*$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsPunctuatedTextReturnsTrueForAlphabeticOnly() { assertTrue(StringValidations.isPunctuatedText("This is a test")); }
@Test public void testIsPunctuatedTextReturnsTrueForTextWithPunctuation() { assertTrue(StringValidations.isPunctuatedText(",./?;':\"~`!$%&()-_+=[]")); }
@Test public void testIsPunctuatedTextReturnsTrueForTextWithSingleQuote() { assertTrue(StringValidations.isPunctuatedText("Quote's test")); }
@Test public void testIsPunctuatedTextReturnsFalseForGreaterThanOrLessThan() { assertFalse(StringValidations.isPunctuatedText("BAD<Name>")); } |
StringValidations { public static boolean isPunctuatedTextWithoutSpace(final String text) { if (text != null) { return text.matches("^[a-zA-Z/\\d._?!,;':\"~`$%&()+=\\[\\]-]*$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsPunctuatedTextWithoutSpaceReturnsTrueForTextWithPunctuation() { assertTrue(StringValidations.isPunctuatedTextWithoutSpace(",./?;':\"~`!$%&()-_+=[]")); }
@Test public void testIsPunctuatedTextWithoutSpaceReturnsTrueOneWord() { assertTrue(StringValidations.isPunctuatedTextWithoutSpace("text")); }
@Test public void testIsPunctuatedTextWithoutSpaceReturnsTrueOneWordWithNumbers() { assertTrue(StringValidations.isPunctuatedTextWithoutSpace("C3PO")); }
@Test public void testIsPunctuatedTextWithoutSpaceReturnsTrueConcatWords() { assertTrue(StringValidations.isPunctuatedTextWithoutSpace("WhatDoYouWant")); }
@Test public void testIsPunctuatedTextWithoutSpaceReturnsTrueOnePunctuatedWord() { assertTrue(StringValidations.isPunctuatedTextWithoutSpace("name.")); }
@Test public void testIsPunctuatedTextWithoutSpaceReturnsFalseMoreThanOneWord() { assertFalse(StringValidations.isPunctuatedTextWithoutSpace("Who am I")); }
@Test public void testIsPunctuatedTextWithoutSpaceReturnsFalseMoreThanOneWordWithNumbers() { assertFalse(StringValidations.isPunctuatedTextWithoutSpace("C3PO R2D2")); }
@Test public void testIsPunctuatedTextWithoutSpaceReturnsFalseMoreThanOneWordPunctuated() { assertFalse(StringValidations.isPunctuatedTextWithoutSpace("How are you?")); } |
StringValidations { public static boolean isDecimal(final String number) { if (number != null) { return number.matches("([0-9]+(\\.[0-9]+)?)|([0-9]*\\.[0-9]+)"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsDecimalReturnsTrueForNumericInputWithDecimalPoint() { assertTrue(StringValidations.isDecimal("9.00")); }
@Test public void testIsDecimalReturnsTrueForNumericInputWithoutDecimalPoint() { assertTrue(StringValidations.isDecimal("7")); }
@Test public void testIsDecimalReturnsFalseForAlphabeticInput() { assertFalse(StringValidations.isDecimal("t")); }
@Test public void testIsDecimalReturnsTrueForWholeNumber() throws Exception { assertTrue(StringValidations.isDecimal("5")); }
@Test public void testIsDecimalReturnsTrueForDecimalOnly() throws Exception { assertTrue(StringValidations.isDecimal(".5")); }
@Test public void testIsDecimalReturnsFalseForPeriodOnly() throws Exception { assertFalse(StringValidations.isDecimal(".")); }
@Test public void testIsDecimalReturnsTrueForCompleteDecimal() throws Exception { assertTrue(StringValidations.isDecimal("34.178")); }
@Test public void testIsDecimalReturnsFalseForEmpty() throws Exception { assertFalse(StringValidations.isDecimal("")); } |
StringValidations { public static boolean isDigit(final String digit) { if (digit != null) { return digit.matches("^\\d$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsDigitReturnsTrueForSingleDigit() { assertTrue(StringValidations.isDigit("4")); }
@Test public void testIsDigitReturnsFalseForMultipleDigit() { assertFalse(StringValidations.isDigit("43")); }
@Test public void testIsDigitReturnsFalseForNumberWithDecimalPoint() { assertFalse(StringValidations.isDigit("4.0")); }
@Test public void testIsDigitReturnsFalseForInputWithAlphabeticAndSpecial() { assertFalse(StringValidations.isDigit("ia*")); } |
StringValidations { public static boolean isEmailAddress(final String email) { if (email != null) { return email.matches("^" + EMAIL_REGEX + "$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsEmailAddressReturnsTrueForValidEmail() { assertTrue(StringValidations.isEmailAddress("[email protected]")); }
@Test public void testIsEmailAddressReturnsTrueForValidEmailUppercase() { assertTrue(StringValidations.isEmailAddress("[email protected]")); }
@Test public void testIsEmailAddressReturnsFalseForInvalidEmail() { assertFalse(StringValidations.isEmailAddress("..com")); }
@Test public void testIsEmailAddressReturnsTrueForValidEmail2() { assertTrue(StringValidations.isEmailAddress("[email protected]")); } |
StringValidations { public static boolean isZipCode(final String zipCode) { if (zipCode != null) { return zipCode.matches("\\d{5}((-| +)\\d{4})?$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsZipCodeReturnsTrueForShortZip() { assertTrue(StringValidations.isZipCode("28212")); }
@Test public void testIsZipCodeReturnsTrueForLongZip() { assertTrue(StringValidations.isZipCode("78415 0158")); }
@Test public void testIsZipCodeReturnsFalseForBadZip() { assertFalse(StringValidations.isZipCode("75126=0465")); }
@Test public void testIsZipCodeReturnsFalseForBadZipAlphabetic() { assertFalse(StringValidations.isZipCode("7pe26=0A65")); } |
StringValidations { public static boolean isPhoneNumber(final String phoneNumber) { if (phoneNumber != null) { return phoneNumber.matches("^(?:\\([2-9]\\d{2}\\)\\ ?|[2-9]\\d{2}(?:\\-?|\\ ?))[2-9]\\d{2}[- ]?\\d{4}$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsPhoneNumberReturnsTruePhoneNumberWithSpecialChars() { assertTrue(StringValidations.isPhoneNumber("(704)546-7542")); }
@Test public void testIsPhoneNumberReturnsTrueWithoutSpecialChars() { assertTrue(StringValidations.isPhoneNumber("5038751238")); }
@Test public void testIsPhoneNumberReturnsFalseInvalidInputShortLenght() { assertFalse(StringValidations.isPhoneNumber("555555")); }
@Test public void testIsPhoneNumberReturnsFalseInvalidInput() { assertFalse(StringValidations.isPhoneNumber("(8e074d/874")); } |
StringValidations { public static boolean isPassword(final String password) { if (password != null) { return password.matches("^[a-zA-Z0-9!@#$%^&*\\s\\(\\)_\\+=-]{8,}$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsPasswordReturnsTrueWithoutSpecialChars() { assertTrue(StringValidations.isPassword("Test1234")); }
@Test public void testIsPasswordReturnsTrueWithSpecialChars() { assertTrue(StringValidations.isPassword("abc!DE&fj87")); }
@Test public void testIsPasswordReturnsFalseShortLength() { assertFalse(StringValidations.isPassword("r$8")); }
@Test public void testIsPasswordReturnsTrueLongLength() { assertTrue(StringValidations.isPassword("qwerty!io$%pasdasdfdsfsdfg8")); }
@Test public void testIsPasswordReturnsTrueWithSpaces() { assertTrue(StringValidations.isPassword("qwerty!io$% pasdasd fdsfsdfg8")); }
@Test public void testIsPasswordReturnsFalseInvalidCharacters() { assertFalse(StringValidations.isPassword("alphabeta}{")); } |
Strings { public static String canonicalize(final String name) { String result = null; if (name != null) { result = name.toLowerCase().replace(' ', '-').replaceAll("[^a-z0-9-]*", "").replaceAll("-+", "-"); } return result; } static String camelToUnderscore(final String input); static String join(final String delim, final String... strings); static String canonicalize(final String name); } | @Test public void testCanonicalize() { String input = "Project#$% Name"; String expected = "project-name"; String actual = Strings.canonicalize(input); assertEquals(expected, actual); }
@Test public void testCanonicalizeStripsExtraDashes() { String input = "Project#$%--- Name"; String expected = "project-name"; String actual = Strings.canonicalize(input); assertEquals(expected, actual); }
@Test public void testCanonicalizeLeavesDigits() { String input = "Project#$%--- Name99"; String expected = "project-name99"; String actual = Strings.canonicalize(input); assertEquals(expected, actual); } |
StringValidations { public static boolean isStrictPassword(final String password) { if (password != null) { return password.matches("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\\d!@#$%^&*\\s\\(\\)_\\+=-]{8,}$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsStrictPasswordReturnsFalseWithoutCapitalChars() { assertFalse(StringValidations.isStrictPassword("test1234")); }
@Test public void testIsStrictPasswordReturnsFalseWithoutNumbers() { assertFalse(StringValidations.isStrictPassword("Testasdfd")); }
@Test public void testIsStrictPasswordReturnsTrueWithoutSpecialChars() { assertTrue(StringValidations.isStrictPassword("Test1234")); }
@Test public void testIsStrictPasswordReturnsTrueWithSpecialChars() { assertTrue(StringValidations.isStrictPassword("abc!DE&fj87")); }
@Test public void testIsStrictPasswordReturnsFalseShortLength() { assertFalse(StringValidations.isStrictPassword("r$8")); }
@Test public void testIsStrictPasswordReturnsTrueLongLength() { assertTrue(StringValidations.isStrictPassword("qwT4rty!io$%asdfasdfdspasdfg8")); }
@Test public void testIsStrictPasswordReturnsWithSpace() { assertTrue(StringValidations.isStrictPassword("qwT4rty! io$%asdfasdfdspasdfg8")); }
@Test public void testIsStrictPasswordReturnsFalseInvalidCharacters() { assertFalse(StringValidations.isStrictPassword("alphabeta}{")); } |
StringValidations { public static boolean isState(final String state) { if (state != null) { return state.toUpperCase().matches( "^(AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|FA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|" + "MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|" + "UT|VT|VI|VA|WA|WV|WI|WY)$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsStateReturnsTrueForAllStateAbbreviations() throws Exception { String[] states = ("AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|FA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|" + "MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|" + "UT|VT|VI|VA|WA|WV|WI|WY").split("\\|"); for (String state : states) { assertTrue(StringValidations.isState(state)); } }
@Test public void testIsStateReturnsTrueForAllStateAbbreviationsLowerCase() throws Exception { String[] states = ("al|ak|as|az|ar|ca|co|ct|de|dc|fm|fl|fa|gu|hi|id|il|in|ia|ks|ky|la|me|mh|md|" + "ma|mi|mn|ms|mo|mt|ne|nv|nh|nj|nm|ny|nc|nd|mp|oh|ok|or|pw|pa|pr|ri|sc|sd|tn|tx|" + "ut|vt|vi|va|wa|wv|wi|wy").split("\\|"); for (String state : states) { assertTrue(StringValidations.isState(state)); } }
@Test public void testIsStateReturnsFalseForNonStateAbbreviations() throws Exception { String[] states = ("sdf|North|S|E|W|MONT|MON|AF|34| |*|<>|`|Num3r1c|oMg").split("\\|"); for (String state : states) { assertFalse(StringValidations.isState(state)); } } |
StringValidations { public static boolean isAlphanumericSpaceUnderscore(final String textWithDigits) { if (textWithDigits != null) { return textWithDigits.matches("^[a-zA-Z\\d_ ]*$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsAlphanumericSpaceUnderscoreReturnsTrueWithAlphanumericTextAndSpaces() { assertTrue(StringValidations.isAlphanumericSpaceUnderscore("This is plain text")); }
@Test public void testIsAlphanumericSpaceUnderscoreReturnsTrueWithAlphanumericTextSpacesAndUnderscore() { assertTrue(StringValidations.isAlphanumericSpaceUnderscore("This is plain_text")); }
@Test public void testIsAlphanumericSpaceUnderscoreReturnsFalseWithTabs() { assertFalse(StringValidations.isAlphanumericSpaceUnderscore("This\tis plain_text")); }
@Test public void testIsAlphanumericSpaceUnderscoreReturnsFalseWithSpecialChars() { assertFalse(StringValidations.isAlphanumericSpaceUnderscore("This &^ is plain_text")); }
@Test public void testIsAlphanumericSpaceUnderscoreReturnsFalseWithAltCharacters() { assertFalse(StringValidations.isAlphanumericSpaceUnderscore("This???????")); } |
StringValidations { public static boolean hasData(final String value) { return (value != null) && (value.length() > 0) && value.matches(".*\\S.*"); } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testHasDataReturnsTrueWithData() throws Exception { assertTrue(StringValidations.hasData("Yes")); }
@Test public void testHasDataReturnsFalseWithNullValue() throws Exception { assertFalse(StringValidations.hasData(null)); }
@Test public void testHasDataReturnsFalseWithEmptyString() throws Exception { assertFalse(StringValidations.hasData("")); } |
StringValidations { public static boolean isWholeNumber(final String number) { if (number != null) { return number.matches("[0-9]+"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsWholeNumberReturnsTrueForValidInput() throws Exception { assertTrue(StringValidations.isWholeNumber("5")); }
@Test public void testIsWholeNumberReturnsFalseForAlphabeticInput() throws Exception { assertFalse(StringValidations.isWholeNumber("as")); }
@Test public void testIsWholeNumberReturnsFalseForNoInput() throws Exception { assertFalse(StringValidations.isWholeNumber("")); }
@Test public void testIsWholeNumberReturnsFalseForDecimalInput() throws Exception { assertFalse(StringValidations.isWholeNumber("12.1234")); } |
StringValidations { public static boolean isAlphabetic(final String text) { if (text != null) { return text.matches("^[a-zA-Z]*$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testIsAlphabeticReturnsTrueForValidInput() { assertTrue(StringValidations.isAlphabetic("Test")); }
@Test public void testIsAlphabeticReturnsFalseForNumericChar() { assertFalse(StringValidations.isAlphabetic("T3st")); }
@Test public void testIsAlphabeticReturnsFalseForSpecialCharacter() { assertFalse(StringValidations.isAlphabetic("t5@a")); } |
StringValidations { public static boolean length(final int length, final String value) { return (value != null) && (value.length() == length); } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testLengthReturnsFalseIfNull() throws Exception { assertFalse(StringValidations.length(4, null)); }
@Test public void testLengthReturnsTrueIfLengthMatches() throws Exception { assertTrue(StringValidations.length(4, "four")); }
@Test public void testLengthReturnsFalseIfShorter() throws Exception { assertFalse(StringValidations.length(4, "two")); }
@Test public void testLengthReturnsFalseIfLonger() throws Exception { assertFalse(StringValidations.length(4, "seven")); } |
StringValidations { public static boolean minLength(final int length, final String value) { return (value != null) && (value.length() >= length); } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testMinLengthReturnsFalseIfNull() throws Exception { assertFalse(StringValidations.minLength(4, null)); }
@Test public void testMinLengthReturnsTrueIfLengthMatches() throws Exception { assertTrue(StringValidations.minLength(4, "four")); }
@Test public void testMinLengthReturnsFalseIfShorter() throws Exception { assertFalse(StringValidations.minLength(4, "two")); }
@Test public void testMinLengthReturnsTrueIfLonger() throws Exception { assertTrue(StringValidations.minLength(4, "seven")); } |
StringValidations { public static boolean maxLength(final int length, final String value) { return (value != null) && (value.length() <= length); } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; } | @Test public void testMaxLengthReturnsFalseIfNull() throws Exception { assertFalse(StringValidations.maxLength(4, null)); }
@Test public void testMaxLengthReturnsTrueIfLengthMatches() throws Exception { assertTrue(StringValidations.maxLength(4, "four")); }
@Test public void testMaxLengthReturnsTrueIfShorter() throws Exception { assertTrue(StringValidations.maxLength(4, "two")); }
@Test public void testMaxLengthReturnsFalseIfLonger() throws Exception { assertFalse(StringValidations.maxLength(4, "seven")); } |
Timer { public Timer start() { if (this.startTime != null) { throw new IllegalStateException("Must reset Timer before starting again"); } this.startTime = System.currentTimeMillis(); this.lapTime = this.startTime; return this; } private Timer(); static Timer getTimer(); Timer start(); Timer stop(); Timer lap(); Timer reset(); long getElapsedMilliseconds(); long getLapMilliseconds(); } | @Test public void testStart() throws InterruptedException { Timer timer = Timer.getTimer(); assertEquals(0, timer.getElapsedMilliseconds()); assertEquals(0, timer.getLapMilliseconds()); timer.start(); Thread.sleep(1); assertTrue(timer.getElapsedMilliseconds() > 0); } |
Timer { public Timer lap() { if (this.startTime == null) { throw new IllegalStateException("Timer must be started before lapping."); } this.lapTime = this.getFinalTime(); return this; } private Timer(); static Timer getTimer(); Timer start(); Timer stop(); Timer lap(); Timer reset(); long getElapsedMilliseconds(); long getLapMilliseconds(); } | @Test public void testLap() throws InterruptedException { Timer timer = Timer.getTimer(); timer.start(); Thread.sleep(1); timer.lap(); Thread.sleep(1); assertTrue(timer.getLapMilliseconds() > 0); assertTrue(timer.getElapsedMilliseconds() > timer.getLapMilliseconds()); } |
Timer { public Timer reset() { this.stopTime = null; this.startTime = null; this.lapTime = null; return this; } private Timer(); static Timer getTimer(); Timer start(); Timer stop(); Timer lap(); Timer reset(); long getElapsedMilliseconds(); long getLapMilliseconds(); } | @Test public void testReset() throws InterruptedException { Timer timer = Timer.getTimer(); timer.start(); timer.lap(); Thread.sleep(1); timer.reset(); assertEquals(0, timer.getElapsedMilliseconds()); assertEquals(0, timer.getLapMilliseconds()); } |
Timer { public long getElapsedMilliseconds() { if (this.startTime != null) { return this.getFinalTime() - this.startTime; } return 0; } private Timer(); static Timer getTimer(); Timer start(); Timer stop(); Timer lap(); Timer reset(); long getElapsedMilliseconds(); long getLapMilliseconds(); } | @Test public void testGetElapsedMilliseconds() throws InterruptedException { Timer timer = Timer.getTimer(); assertEquals(0, timer.getElapsedMilliseconds()); timer.start(); timer.lap(); Thread.sleep(1); assertTrue(timer.getLapMilliseconds() > 0); } |
Timer { public long getLapMilliseconds() { if (this.lapTime != null) { return this.getFinalTime() - this.lapTime; } return 0; } private Timer(); static Timer getTimer(); Timer start(); Timer stop(); Timer lap(); Timer reset(); long getElapsedMilliseconds(); long getLapMilliseconds(); } | @Test public void testGetLapMilliseconds() throws InterruptedException { Timer timer = Timer.getTimer(); assertEquals(0, timer.getElapsedMilliseconds()); timer.start(); timer.lap(); Thread.sleep(1); assertTrue(timer.getElapsedMilliseconds() > 0); } |
XOR32ShiftRandom extends Random32 { @Override public boolean equals(final Object obj) { return obj instanceof XOR32ShiftRandom && ((XOR32ShiftRandom)obj)._x == _x && Objects.equals(((XOR32ShiftRandom)obj)._param, _param); } XOR32ShiftRandom(
final Shift shift,
final Param param,
final byte[] seed
); XOR32ShiftRandom(final Param param, final byte[] seed); XOR32ShiftRandom(final Param param, final long seed); XOR32ShiftRandom(final Param param); XOR32ShiftRandom(final byte[] seed); XOR32ShiftRandom(final long seed); XOR32ShiftRandom(); void setSeed(final byte[] seed); @Override synchronized void setSeed(final long seed); @Override int nextInt(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); static byte[] seedBytes(); static final int SEED_BYTES; } | @Test public void paramSelectorShiftParam() { final List<Shift> shifts = singletonList(Shift.DEFAULT); final List<Param> params = singletonList(Param.DEFAULT); final ParamSelector selector = new ParamSelector(shifts, params); final byte[] seed = selector.seed(); Assert.assertSame(selector.shift(), shifts.get(0)); Assert.assertSame(selector.param(), params.get(0)); for (int i = 0; i < 100; ++i) { selector.next(); Assert.assertFalse(Arrays.equals(seed, selector.seed())); Assert.assertSame(selector.shift(), shifts.get(0)); Assert.assertSame(selector.param(), params.get(0)); } }
@Test public void paramSelectorShift() { final List<Shift> shifts = singletonList(Shift.DEFAULT); final List<Param> params = Param.PARAMS; final ParamSelector selector = new ParamSelector(shifts, params); final byte[] seed = selector.seed(); for (Param param : params) { Assert.assertTrue(Arrays.equals(seed, selector.seed())); Assert.assertSame(selector.shift(), shifts.get(0)); Assert.assertSame(selector.param(), param); selector.next(); } for (Param param : params) { Assert.assertFalse(Arrays.equals(seed, selector.seed())); Assert.assertSame(selector.shift(), shifts.get(0)); Assert.assertSame(selector.param(), param); selector.next(); } }
@Test public void paramSelector() { final List<Shift> shifts = asList(Shift.values()); final List<Param> params = Param.PARAMS; final ParamSelector selector = new ParamSelector(shifts, params); final byte[] seed = selector.seed(); for (Shift shift : shifts) { for (Param param : params) { Assert.assertTrue(Arrays.equals(seed, selector.seed())); Assert.assertSame(selector.shift(), shift); Assert.assertSame(selector.param(), param); selector.next(); } } for (Shift shift : shifts) { for (Param param : params) { Assert.assertFalse(Arrays.equals(seed, selector.seed())); Assert.assertSame(selector.shift(), shift); Assert.assertSame(selector.param(), param); selector.next(); } } } |
PRNG extends Random { public long nextLong(final long origin, final long bound) { return nextLong(origin, bound, this); } protected PRNG(final long seed); protected PRNG(); int nextInt(final int origin, final int bound); long nextLong(final long origin, final long bound); long nextLong(final long n); float nextFloat(final float origin, final float bound); double nextDouble(final double origin, final double bound); static int nextInt(
final int origin, final int bound,
final Random random
); static long nextLong(
final long origin, final long bound,
final Random random
); static long nextLong(final long n, final Random random); static float nextFloat(
final float origin, final float bound,
final Random random
); static double nextDouble(
final double origin, final double bound,
final Random random
); static byte[] seedBytes(final int length); static byte[] seedBytes(final byte[] seed); static byte[] seedBytes(final long seed, final byte[] seedBytes); static byte[] seedBytes(final long seed, final int length); static long seed(); static long seed(final long base); } | @Test public void nextLongMax() { final long max = 100000; for (int i = 0; i < 1000; ++i) { final long value = prng.nextLong(max); Assert.assertTrue(value < max); Assert.assertTrue(value >= 0); } }
@Test(expectedExceptions = IllegalArgumentException.class) public void nextLongIllegalArgumentException() { prng.nextLong(1000, 10); }
@Test public void nextLongMinMax() { final long min = 10; final long max = Long.MAX_VALUE; for (int i = 0; i < 1000; ++i) { final long value = prng.nextLong(min, max - i); Assert.assertTrue(value < max - 1); Assert.assertTrue(value >= min); } }
@Test public void nextLongMinMaxCompatibility() { final Random random1 = new Random(123); final Random random2 = new Random(123); final int origin = 100; final int bound = 100_000_000; random1.longs(origin, bound).limit(1000).forEach(i -> { Assert.assertEquals(i, PRNG.nextLong(origin, bound, random2)); }); } |
PRNG extends Random { public float nextFloat(final float origin, final float bound) { return nextFloat(origin, bound, this); } protected PRNG(final long seed); protected PRNG(); int nextInt(final int origin, final int bound); long nextLong(final long origin, final long bound); long nextLong(final long n); float nextFloat(final float origin, final float bound); double nextDouble(final double origin, final double bound); static int nextInt(
final int origin, final int bound,
final Random random
); static long nextLong(
final long origin, final long bound,
final Random random
); static long nextLong(final long n, final Random random); static float nextFloat(
final float origin, final float bound,
final Random random
); static double nextDouble(
final double origin, final double bound,
final Random random
); static byte[] seedBytes(final int length); static byte[] seedBytes(final byte[] seed); static byte[] seedBytes(final long seed, final byte[] seedBytes); static byte[] seedBytes(final long seed, final int length); static long seed(); static long seed(final long base); } | @Test public void nextFloatMinMax() { final float min = 10; final float max = 100000; for (int i = 0; i < 1000; ++i) { final float value = prng.nextFloat(min, max); Assert.assertTrue(value < max); Assert.assertTrue(value >= min); } } |
PRNG extends Random { public double nextDouble(final double origin, final double bound) { return nextDouble(origin, bound, this); } protected PRNG(final long seed); protected PRNG(); int nextInt(final int origin, final int bound); long nextLong(final long origin, final long bound); long nextLong(final long n); float nextFloat(final float origin, final float bound); double nextDouble(final double origin, final double bound); static int nextInt(
final int origin, final int bound,
final Random random
); static long nextLong(
final long origin, final long bound,
final Random random
); static long nextLong(final long n, final Random random); static float nextFloat(
final float origin, final float bound,
final Random random
); static double nextDouble(
final double origin, final double bound,
final Random random
); static byte[] seedBytes(final int length); static byte[] seedBytes(final byte[] seed); static byte[] seedBytes(final long seed, final byte[] seedBytes); static byte[] seedBytes(final long seed, final int length); static long seed(); static long seed(final long base); } | @Test public void nextDoubleMinMax() { final double min = 10; final double max = 100000; for (int i = 0; i < 1000; ++i) { final double value = prng.nextDouble(min, max); Assert.assertTrue(value < max); Assert.assertTrue(value >= min); } }
@Test public void nextDoubleMinMaxCompatibility() { final Random random1 = new Random(123); final Random random2 = new Random(123); final int origin = 100; final int bound = 100_000_000; random1.doubles(origin, bound).limit(1000).forEach(i -> { Assert.assertEquals(i, PRNG.nextDouble(origin, bound, random2)); }); } |
PRNG extends Random { public static byte[] seedBytes(final int length) { return seedBytes(new byte[length]); } protected PRNG(final long seed); protected PRNG(); int nextInt(final int origin, final int bound); long nextLong(final long origin, final long bound); long nextLong(final long n); float nextFloat(final float origin, final float bound); double nextDouble(final double origin, final double bound); static int nextInt(
final int origin, final int bound,
final Random random
); static long nextLong(
final long origin, final long bound,
final Random random
); static long nextLong(final long n, final Random random); static float nextFloat(
final float origin, final float bound,
final Random random
); static double nextDouble(
final double origin, final double bound,
final Random random
); static byte[] seedBytes(final int length); static byte[] seedBytes(final byte[] seed); static byte[] seedBytes(final long seed, final byte[] seedBytes); static byte[] seedBytes(final long seed, final int length); static long seed(); static long seed(final long base); } | @Test public void seedBytes() { final byte[] bytes = PRNG.seedBytes(-11234124332123234L, 20); } |
utils { static int readInt(final byte[] bytes, final int index) { final int offset = index*Integer.BYTES; if (offset + Integer.BYTES > bytes.length) { throw new IndexOutOfBoundsException(format( "Not enough data to read int value (index=%d, bytes=%d).", index, bytes.length )); } return ((bytes[offset ] & 255) << 24) + ((bytes[offset + 1] & 255) << 16) + ((bytes[offset + 2] & 255) << 8) + ((bytes[offset + 3] & 255)); } private utils(); } | @Test public void readInt() { for (int i = 1; i < 100; ++i) { final byte[] data = new byte[i*4]; final Random random = new Random(i); for (int j = 0; j < i; ++j) { System.arraycopy(utils.toBytes(random.nextInt()), 0, data, j*4, 4); } random.setSeed(i); for (int j = 0; j < i; ++j) { Assert.assertEquals(utils.readInt(data, j), random.nextInt()); } } } |
utils { static long readLong(final byte[] bytes, final int index) { final int offset = index*Long.BYTES; if (offset + Long.BYTES > bytes.length) { throw new IndexOutOfBoundsException(format( "Not enough data to read long value (index=%d, bytes=%d).", index, bytes.length )); } return ((long)(bytes[offset ] & 255) << 56) + ((long)(bytes[offset + 1] & 255) << 48) + ((long)(bytes[offset + 2] & 255) << 40) + ((long)(bytes[offset + 3] & 255) << 32) + ((long)(bytes[offset + 4] & 255) << 24) + ((bytes[offset + 5] & 255) << 16) + ((bytes[offset + 6] & 255) << 8) + (bytes[offset + 7] & 255); } private utils(); } | @Test public void readLong() { for (int i = 1; i < 100; ++i) { final byte[] data = new byte[i*8]; final Random random = new Random(i); for (int j = 0; j < i; ++j) { System.arraycopy(utils.toBytes(random.nextLong()), 0, data, j*8, 8); } random.setSeed(i); for (int j = 0; j < i; ++j) { Assert.assertEquals(utils.readLong(data, j), random.nextLong()); } } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.