diff --git a/core-java-9/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java b/core-java-9/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java new file mode 100644 index 0000000000..50766502ec --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java @@ -0,0 +1,106 @@ +package com.baeldung.java9.varhandles; + +import org.junit.Test; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; + +import static org.assertj.core.api.Assertions.assertThat; + +public class VariableHandlesTest { + + public int publicTestVariable = 1; + private int privateTestVariable = 1; + public int variableToSet = 1; + public int variableToCompareAndSet = 1; + public int variableToGetAndAdd = 0; + public byte variableToBitwiseOr = 0; + + @Test + public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException { + VarHandle publicIntHandle = MethodHandles + .lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class); + + assertThat(publicIntHandle.coordinateTypes().size() == 1); + assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandles.class); + + } + + @Test + public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException { + VarHandle privateIntHandle = MethodHandles + .privateLookupIn(VariableHandlesTest.class, MethodHandles.lookup()) + .findVarHandle(VariableHandlesTest.class, "privateTestVariable", int.class); + + assertThat(privateIntHandle.coordinateTypes().size() == 1); + assertThat(privateIntHandle.coordinateTypes().get(0) == VariableHandlesTest.class); + + } + + @Test + public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException { + VarHandle arrayVarHandle = MethodHandles + .arrayElementVarHandle(int[].class); + + assertThat(arrayVarHandle.coordinateTypes().size() == 2); + assertThat(arrayVarHandle.coordinateTypes().get(0) == int[].class); + } + + @Test + public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException { + VarHandle publicIntHandle = MethodHandles + .lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class); + + assertThat((int) publicIntHandle.get(this) == 1); + } + + @Test + public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { + VarHandle publicIntHandle = MethodHandles + .lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class, "variableToSet", int.class); + publicIntHandle.set(this, 15); + + assertThat((int) publicIntHandle.get(this) == 15); + } + + @Test + public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { + VarHandle publicIntHandle = MethodHandles + .lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class, "variableToCompareAndSet", int.class); + publicIntHandle.compareAndSet(this, 1, 100); + + assertThat((int) publicIntHandle.get(this) == 100); + } + + @Test + public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { + VarHandle publicIntHandle = MethodHandles + .lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class, "variableToGetAndAdd", int.class); + int before = (int) publicIntHandle.getAndAdd(this, 200); + + assertThat(before == 0); + assertThat((int) publicIntHandle.get(this) == 200); + } + + @Test + public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException { + VarHandle publicIntHandle = MethodHandles + .lookup() + .in(VariableHandlesTest.class) + .findVarHandle(VariableHandlesTest.class, "variableToBitwiseOr", byte.class); + byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127); + + assertThat(before == 0); + assertThat(variableToBitwiseOr == 127); + } +} diff --git a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java b/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java index 8b44138b32..199ebdf036 100644 --- a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java +++ b/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java @@ -10,78 +10,60 @@ import java.util.concurrent.TimeUnit; @OutputTimeUnit(TimeUnit.MICROSECONDS) public class SearchArrayTest { + @State(Scope.Benchmark) + public static class SearchData { + static int count = 1000; + static String[] strings = seedArray(1000); + } + + @Benchmark public void searchArrayLoop() { - - int count = 1000; - String[] strings = seedArray(count); - for (int i = 0; i < count; i++) { - searchLoop(strings, "T"); + for (int i = 0; i < SearchData.count; i++) { + searchLoop(SearchData.strings, "T"); } } @Benchmark public void searchArrayAllocNewList() { - - int count = 1000; - String[] strings = seedArray(count); - for (int i = 0; i < count; i++) { - searchList(strings, "W"); + for (int i = 0; i < SearchData.count; i++) { + searchList(SearchData.strings, "T"); } } @Benchmark public void searchArrayAllocNewSet() { - - int count = 1000; - String[] strings = seedArray(count); - for (int i = 0; i < count; i++) { - searchSet(strings, "S"); + for (int i = 0; i < SearchData.count; i++) { + searchSet(SearchData.strings, "T"); } } @Benchmark public void searchArrayReuseList() { - - int count = 1000; - String[] strings = seedArray(count); - - List asList = Arrays.asList(strings); - - for (int i = 0; i < count; i++) { - asList.contains("W"); + List asList = Arrays.asList(SearchData.strings); + for (int i = 0; i < SearchData.count; i++) { + asList.contains("T"); } } @Benchmark public void searchArrayReuseSet() { - - int count = 1000; - String[] strings = seedArray(count); - Set asSet = new HashSet<>(Arrays.asList(strings)); - for (int i = 0; i < count; i++) { - asSet.contains("S"); + Set asSet = new HashSet<>(Arrays.asList(SearchData.strings)); + for (int i = 0; i < SearchData.count; i++) { + asSet.contains("T"); } } @Benchmark public void searchArrayBinarySearch() { - - int count = 1000; - String[] strings = seedArray(count); - Arrays.sort(strings); - - long startTime = System.nanoTime(); - for (int i = 0; i < count; i++) { - Arrays.binarySearch(strings, "A"); + Arrays.sort(SearchData.strings); + for (int i = 0; i < SearchData.count; i++) { + Arrays.binarySearch(SearchData.strings, "T"); } - long duration = System.nanoTime() - startTime; - //System.out.println("Binary search: " + duration / 10000); - } private boolean searchList(String[] strings, String searchString) { @@ -101,8 +83,7 @@ public class SearchArrayTest { return false; } - private String[] seedArray(int length) { - + private static String[] seedArray(int length) { String[] strings = new String[length]; Random random = new Random(); for (int i = 0; i < length; i++) diff --git a/core-java/src/main/java/com/baeldung/stream/FileCopy.java b/core-java/src/main/java/com/baeldung/stream/FileCopy.java new file mode 100644 index 0000000000..ccc2066b36 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/stream/FileCopy.java @@ -0,0 +1,48 @@ +package com.baeldung.stream; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.channels.FileChannel; +import java.nio.file.Files; + +import org.apache.commons.io.FileUtils; + +public class FileCopy { + + public static void copyFileUsingStream(File source, File dest) throws IOException { + InputStream is = null; + OutputStream os = null; + is = new FileInputStream(source); + os = new FileOutputStream(dest); + byte[] buffer = new byte[1024]; + int length; + while ((length = is.read(buffer)) > 0) { + os.write(buffer, 0, length); + } + is.close(); + os.close(); + } + + public static void copyFileUsingChannel(File source, File dest) throws IOException { + FileChannel sourceChannel = null; + FileChannel destChannel = null; + sourceChannel = new FileInputStream(source).getChannel(); + destChannel = new FileOutputStream(dest).getChannel(); + destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); + sourceChannel.close(); + destChannel.close(); + } + + public static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException { + FileUtils.copyFile(source, dest); + } + + public static void copyFileUsingJavaFiles(File source, File dest) throws IOException { + Files.copy(source.toPath(), dest.toPath()); + } + +} diff --git a/core-java/src/main/java/com/baeldung/tree/BinaryTree.java b/core-java/src/main/java/com/baeldung/tree/BinaryTree.java index 3cc496e348..285dc12219 100644 --- a/core-java/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/core-java/src/main/java/com/baeldung/tree/BinaryTree.java @@ -16,29 +16,23 @@ public class BinaryTree { return; } - Node parent = root; - Node current = root; + addRecursive(root, value); + } - while (true) { + private Node addRecursive(Node current, int value) { - if (newNode.value < parent.value) { - current = parent.left; - - if (current == null) { - parent.left = newNode; - break; - } - } else { - current = parent.right; - - if (current == null) { - parent.right = newNode; - break; - } - } - - parent = current; + if (current == null) { + return new Node(value); } + + if (value < current.value) { + current.left = addRecursive(current.left, value); + } else { + current.right = addRecursive(current.right, value); + } + + return current; + } public boolean isEmpty() { @@ -46,115 +40,69 @@ public class BinaryTree { } public boolean containsNode(int value) { - - Node current = root; - - while (current != null) { - - if (value == current.value) { - return true; - } - - if (value < current.value) { - current = current.left; - } else { - current = current.right; - } - - } - - return false; + return containsNodeRecursive(root, value); } - public void delete(int value) { + private boolean containsNodeRecursive(Node current, int value) { - Node current = root; - Node parent = root; - Node nodeToDelete = null; - boolean isLeftChild = false; - - while (nodeToDelete == null && current != null) { - - if (value == current.value) { - nodeToDelete = current; - } else if (value < current.value) { - parent = current; - current = current.left; - isLeftChild = true; - } else { - parent = current; - current = current.right; - isLeftChild = false; - } - - } - - if (nodeToDelete == null) { - return; - } - - // Case 1: no children - if (nodeToDelete.left == null && nodeToDelete.right == null) { - if (nodeToDelete == root) { - root = null; - } else if (isLeftChild) { - parent.left = null; - } else { - parent.right = null; - } - } - // Case 2: only 1 child - else if (nodeToDelete.right == null) { - if (nodeToDelete == root) { - root = nodeToDelete.left; - } else if (isLeftChild) { - parent.left = nodeToDelete.left; - } else { - parent.right = nodeToDelete.left; - } - } else if (nodeToDelete.left == null) { - if (nodeToDelete == root) { - root = nodeToDelete.right; - } else if (isLeftChild) { - parent.left = nodeToDelete.right; - } else { - parent.right = nodeToDelete.right; - } - } - // Case 3: 2 children - else if (nodeToDelete.left != null && nodeToDelete.right != null) { - Node replacement = findReplacement(nodeToDelete); - if (nodeToDelete == root) { - root = replacement; - } else if (isLeftChild) { - parent.left = replacement; - } else { - parent.right = replacement; - } + if (current == null) { + return false; + } else if (value == current.value) { + return true; + } else if (value < current.value) { + return containsNodeRecursive(current.left, value); + } else { + return containsNodeRecursive(current.right, value); } } - private Node findReplacement(Node nodeToDelete) { + public void delete(int value) { + deleteRecursive(root, value); + } - Node replacement = nodeToDelete; - Node parentReplacement = nodeToDelete; - Node current = nodeToDelete.right; - - while (current != null) { - parentReplacement = replacement; - replacement = current; - current = current.left; + private Node deleteRecursive(Node current, int value) { + if (current == null) { + return null; } - if (replacement != nodeToDelete.right) { - parentReplacement.left = replacement.right; - replacement.right = nodeToDelete.right; + if (value == current.value) { + // Case 1: no children + if (current.left == null && current.right == null) { + return null; + } + + // Case 2: only 1 child + if (current.right == null) { + return current.left; + } + + if (current.left == null) { + return current.right; + } + + // Case 3: 2 children + int smallestValue = findSmallestValue(current.right); + current.value = smallestValue; + current.right = deleteRecursive(current.right, smallestValue); + return current; + + } else if (value < current.value) { + current.left = deleteRecursive(current.left, value); + return current; + } else { + current.right = deleteRecursive(current.right, value); + return current; + } + } + + private int findSmallestValue(Node root) { + + if (root.left == null) { + return root.value; } - replacement.left = nodeToDelete.left; - - return replacement; + return findSmallestValue(root.left); } public void traverseInOrder(Node node) { diff --git a/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java b/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java new file mode 100644 index 0000000000..52d5b08813 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/collection/WhenUsingTreeSet.java @@ -0,0 +1,228 @@ +package com.baeldung.collection; + +import java.util.Comparator; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import java.util.NavigableSet; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; + +import org.junit.Assert; +import org.junit.Test; + +public class WhenUsingTreeSet { + + private static class Element { + private Integer id; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Override + public String toString() { + return id.toString(); + } + } + + private Comparator comparator = (ele1, ele2) -> { + return ele1.getId() + .compareTo(ele2.getId()); + }; + + @Test + public void whenAddingElement_shouldAddElement() { + Set treeSet = new TreeSet<>(); + Assert.assertTrue(treeSet.add("String Added")); + } + + @Test + public void whenCheckingForElement_shouldSearchForElement() { + Set treeSetContains = new TreeSet<>(); + treeSetContains.add("String Added"); + Assert.assertTrue(treeSetContains.contains("String Added")); + } + + @Test + public void whenRemovingElement_shouldRemoveElement() { + Set removeFromTreeSet = new TreeSet<>(); + removeFromTreeSet.add("String Added"); + Assert.assertTrue(removeFromTreeSet.remove("String Added")); + } + + @Test + public void whenClearingTreeSet_shouldClearTreeSet() { + Set clearTreeSet = new TreeSet<>(); + clearTreeSet.add("String Added"); + clearTreeSet.clear(); + Assert.assertTrue(clearTreeSet.isEmpty()); + } + + @Test + public void whenCheckingTheSizeOfTreeSet_shouldReturnThesize() { + Set treeSetSize = new TreeSet<>(); + treeSetSize.add("String Added"); + Assert.assertEquals(1, treeSetSize.size()); + } + + @Test + public void whenCheckingForEmptyTreeSet_shouldCheckForEmpty() { + Set emptyTreeSet = new TreeSet<>(); + Assert.assertTrue(emptyTreeSet.isEmpty()); + } + + @Test + public void whenIteratingTreeSet_shouldIterateTreeSetInAscendingOrder() { + Set treeSet = new TreeSet<>(); + treeSet.add("First"); + treeSet.add("Second"); + treeSet.add("Third"); + Iterator itr = treeSet.iterator(); + while (itr.hasNext()) { + System.out.println(itr.next()); + } + } + + @Test + public void whenIteratingTreeSet_shouldIterateTreeSetInDescendingOrder() { + TreeSet treeSet = new TreeSet<>(); + treeSet.add("First"); + treeSet.add("Second"); + treeSet.add("Third"); + Iterator itr = treeSet.descendingIterator(); + while (itr.hasNext()) { + System.out.println(itr.next()); + } + } + + @Test(expected = ConcurrentModificationException.class) + public void whenModifyingTreeSetWhileIterating_shouldThrowException() { + Set treeSet = new TreeSet<>(); + treeSet.add("First"); + treeSet.add("Second"); + treeSet.add("Third"); + Iterator itr = treeSet.iterator(); + while (itr.hasNext()) { + itr.next(); + treeSet.remove("Second"); + } + } + + @Test + public void whenRemovingElementUsingIterator_shouldRemoveElement() { + Set treeSet = new TreeSet<>(); + treeSet.add("First"); + treeSet.add("Second"); + treeSet.add("Third"); + Iterator itr = treeSet.iterator(); + while (itr.hasNext()) { + String element = itr.next(); + if (element.equals("Second")) + itr.remove(); + } + Assert.assertEquals(2, treeSet.size()); + } + + @Test(expected = NullPointerException.class) + public void whenAddingNullToNonEmptyTreeSet_shouldThrowException() { + Set treeSet = new TreeSet<>(); + treeSet.add("First"); + treeSet.add(null); + } + + @Test + public void whenCheckingFirstElement_shouldReturnFirstElement() { + TreeSet treeSet = new TreeSet<>(); + treeSet.add("First"); + Assert.assertEquals("First", treeSet.first()); + } + + @Test + public void whenCheckingLastElement_shouldReturnLastElement() { + TreeSet treeSet = new TreeSet<>(); + treeSet.add("First"); + treeSet.add("Last"); + Assert.assertEquals("Last", treeSet.last()); + } + + @Test + public void whenUsingComparator_shouldSortAndInsertElements() { + Set treeSet = new TreeSet<>(comparator); + Element ele1 = new Element(); + ele1.setId(100); + Element ele2 = new Element(); + ele2.setId(200); + + treeSet.add(ele1); + treeSet.add(ele2); + + System.out.println(treeSet); + } + + @Test + public void whenUsingHeadSet_shouldReturnElementsLessThanSpecifiedElement() { + Set treeSet = new TreeSet<>(comparator); + Element ele1 = new Element(); + ele1.setId(100); + Element ele2 = new Element(); + ele2.setId(200); + + treeSet.add(ele1); + treeSet.add(ele2); + + System.out.println(treeSet); + } + + @Test + public void whenUsingSubSet_shouldReturnSubSetElements() { + SortedSet treeSet = new TreeSet<>(); + treeSet.add(1); + treeSet.add(2); + treeSet.add(3); + treeSet.add(4); + treeSet.add(5); + treeSet.add(6); + + Set expectedSet = new TreeSet<>(); + expectedSet.add(2); + expectedSet.add(3); + expectedSet.add(4); + expectedSet.add(5); + + Set subSet = treeSet.subSet(2, 6); + Assert.assertEquals(expectedSet, subSet); + } + + @Test + public void whenUsingHeadSet_shouldReturnHeadSetElements() { + SortedSet treeSet = new TreeSet<>(); + treeSet.add(1); + treeSet.add(2); + treeSet.add(3); + treeSet.add(4); + treeSet.add(5); + treeSet.add(6); + + Set subSet = treeSet.headSet(6); + Assert.assertEquals(subSet, treeSet.subSet(1, 6)); + } + + @Test + public void whenUsingTailSet_shouldReturnTailSetElements() { + NavigableSet treeSet = new TreeSet<>(); + treeSet.add(1); + treeSet.add(2); + treeSet.add(3); + treeSet.add(4); + treeSet.add(5); + treeSet.add(6); + + Set subSet = treeSet.tailSet(3); + Assert.assertEquals(subSet, treeSet.subSet(3, true, 6, true)); + } +} diff --git a/core-java/src/test/java/com/baeldung/stream/FileCopyTest.java b/core-java/src/test/java/com/baeldung/stream/FileCopyTest.java new file mode 100644 index 0000000000..3b915a3829 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/FileCopyTest.java @@ -0,0 +1,47 @@ +package com.baeldung.stream; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; + +public class FileCopyTest { + + @Test + public void whenUsingStream_thenCopyFile() throws IOException { + File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt"); + File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt"); + FileCopy.copyFileUsingStream(src, dest); + assertTrue(dest.exists()); + dest.delete(); + } + + @Test + public void whenUsingFiles_thenCopyFile() throws IOException { + File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt"); + File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt"); + FileCopy.copyFileUsingJavaFiles(src, dest); + assertTrue(dest.exists()); + dest.delete(); + } + + @Test + public void whenUsingChannel_thenCopyFile() throws IOException { + File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt"); + File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt"); + FileCopy.copyFileUsingChannel(src, dest); + assertTrue(dest.exists()); + dest.delete(); + } + + @Test + public void whenUsingApache_thenCopyFile() throws IOException { + File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt"); + File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt"); + FileCopy.copyFileUsingApacheCommonsIO(src, dest); + assertTrue(dest.exists()); + dest.delete(); + } +} diff --git a/core-java/src/test/resources/copyTest/dest/readme.txt b/core-java/src/test/resources/copyTest/dest/readme.txt new file mode 100644 index 0000000000..dfda31ee9f --- /dev/null +++ b/core-java/src/test/resources/copyTest/dest/readme.txt @@ -0,0 +1,2 @@ +files will be copied here and then deleted +remove `file.delete()` to see the files here diff --git a/core-java/src/test/resources/copyTest/src/test_apache.txt b/core-java/src/test/resources/copyTest/src/test_apache.txt new file mode 100644 index 0000000000..a6b651973d --- /dev/null +++ b/core-java/src/test/resources/copyTest/src/test_apache.txt @@ -0,0 +1 @@ +apache diff --git a/core-java/src/test/resources/copyTest/src/test_channel.txt b/core-java/src/test/resources/copyTest/src/test_channel.txt new file mode 100644 index 0000000000..6dca835871 --- /dev/null +++ b/core-java/src/test/resources/copyTest/src/test_channel.txt @@ -0,0 +1 @@ +channel diff --git a/core-java/src/test/resources/copyTest/src/test_files.txt b/core-java/src/test/resources/copyTest/src/test_files.txt new file mode 100644 index 0000000000..027271b9b2 --- /dev/null +++ b/core-java/src/test/resources/copyTest/src/test_files.txt @@ -0,0 +1 @@ +files diff --git a/core-java/src/test/resources/copyTest/src/test_stream.txt b/core-java/src/test/resources/copyTest/src/test_stream.txt new file mode 100644 index 0000000000..eac9b41cbe --- /dev/null +++ b/core-java/src/test/resources/copyTest/src/test_stream.txt @@ -0,0 +1 @@ +stream diff --git a/libraries/README.md b/libraries/README.md index ae2522ca9e..990a50e711 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -30,7 +30,7 @@ - [Introduction to Neuroph](http://www.baeldung.com/neuroph) - [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) - [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) -- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception) +- [Introduction to NoException](http://www.baeldung.com/introduction-to-noexception) - [Introduction to PCollections](http://www.baeldung.com/java-pcollections) - [Introduction to Hoverfly in Java](http://www.baeldung.com/hoverfly) - [Apache Commons Chain](http://www.baeldung.com/apache-commons-chain) diff --git a/lucene/.gitignore b/lucene/.gitignore new file mode 100644 index 0000000000..3ed87faec7 --- /dev/null +++ b/lucene/.gitignore @@ -0,0 +1 @@ +/index/ diff --git a/lucene/src/main/java/com/baeldung/lucene/LuceneFileSearch.java b/lucene/src/main/java/com/baeldung/lucene/LuceneFileSearch.java new file mode 100644 index 0000000000..1d090d55fc --- /dev/null +++ b/lucene/src/main/java/com/baeldung/lucene/LuceneFileSearch.java @@ -0,0 +1,80 @@ +package com.baeldung.lucene; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Field; +import org.apache.lucene.document.StringField; +import org.apache.lucene.document.TextField; +import org.apache.lucene.index.DirectoryReader; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.IndexWriter; +import org.apache.lucene.index.IndexWriterConfig; +import org.apache.lucene.queryparser.classic.ParseException; +import org.apache.lucene.queryparser.classic.QueryParser; +import org.apache.lucene.search.IndexSearcher; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.ScoreDoc; +import org.apache.lucene.search.TopDocs; +import org.apache.lucene.store.Directory; + +public class LuceneFileSearch { + + private Directory indexDirectory; + private StandardAnalyzer analyzer; + + public LuceneFileSearch(Directory fsDirectory, StandardAnalyzer analyzer) { + super(); + this.indexDirectory = fsDirectory; + this.analyzer = analyzer; + } + + public void addFileToIndex(String filepath) throws IOException, URISyntaxException { + + Path path = Paths.get(getClass().getClassLoader().getResource(filepath).toURI()); + File file = path.toFile(); + IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer); + IndexWriter indexWriter = new IndexWriter(indexDirectory, indexWriterConfig); + Document document = new Document(); + + FileReader fileReader = new FileReader(file); + document.add(new TextField("contents", fileReader)); + document.add(new StringField("path", file.getPath(), Field.Store.YES)); + document.add(new StringField("filename", file.getName(), Field.Store.YES)); + + indexWriter.addDocument(document); + + indexWriter.close(); + } + + public List searchFiles(String inField, String queryString) { + try { + Query query = new QueryParser(inField, analyzer).parse(queryString); + + IndexReader indexReader = DirectoryReader.open(indexDirectory); + IndexSearcher searcher = new IndexSearcher(indexReader); + TopDocs topDocs = searcher.search(query, 10); + List documents = new ArrayList<>(); + for (ScoreDoc scoreDoc : topDocs.scoreDocs) { + documents.add(searcher.doc(scoreDoc.doc)); + } + + return documents; + } catch (IOException | ParseException e) { + e.printStackTrace(); + } + return null; + + } + +} + + diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchTest.java new file mode 100644 index 0000000000..4345057ff7 --- /dev/null +++ b/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchTest.java @@ -0,0 +1,32 @@ +package com.baeldung.lucene; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Paths; +import java.util.List; + +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.FSDirectory; +import org.junit.Assert; +import org.junit.Test; + +public class LuceneFileSearchTest { + + @Test + public void givenSearchQueryWhenFetchedFileNamehenCorrect() throws IOException, URISyntaxException { + String indexPath = "index"; + String dataPath = "data/file1.txt"; + + Directory directory = FSDirectory.open(Paths.get(indexPath)); + LuceneFileSearch luceneFileSearch = new LuceneFileSearch(directory, new StandardAnalyzer()); + + luceneFileSearch.addFileToIndex(dataPath); + + List docs = luceneFileSearch.searchFiles("contents", "consectetur"); + + Assert.assertEquals("file1.txt", docs.get(0).get("filename")); + } + +} \ No newline at end of file diff --git a/lucene/src/test/resources/data/file1.txt b/lucene/src/test/resources/data/file1.txt new file mode 100644 index 0000000000..6f915d3927 --- /dev/null +++ b/lucene/src/test/resources/data/file1.txt @@ -0,0 +1,3 @@ +Cras auctor viverra arcu, id consequat diam posuere id. Pellentesque hendrerit felis tortor, et ornare nibh ullamcorper sed. Aenean sed mauris vitae purus auctor gravida. Nam aliquam egestas orci, sit amet imperdiet leo porttitor quis. Integer commodo sodales orci, ultrices vulputate arcu vestibulum non. Nunc at tellus id urna tristique ultrices in in massa. Vestibulum laoreet ullamcorper nulla vel porttitor. Duis blandit commodo elit at consequat. Vestibulum faucibus lectus eget mi tincidunt, quis molestie lacus mollis. Duis elementum urna eros, non iaculis est facilisis in. Praesent et neque vel ipsum viverra euismod ac ac metus. Ut vitae libero ex. + +Proin consectetur, neque nec feugiat facilisis, metus libero mollis arcu, id pharetra nibh sapien in elit. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam pulvinar fringilla orci in posuere. Duis ut turpis dignissim nisl eleifend posuere nec a massa. Cras fringilla iaculis ipsum a aliquet. Nunc ultrices nisl ipsum, vitae consectetur tellus vehicula in. Aliquam lacinia elit nec scelerisque dapibus. Duis pharetra mauris vitae quam tincidunt, viverra iaculis orci iaculis. Nunc gravida sem arcu, et mollis leo porttitor nec. Ut dictum tempor est, at fringilla ex feugiat sed. Nullam purus mi, aliquet eu libero ut, finibus efficitur metus. \ No newline at end of file diff --git a/persistence-modules/spring-data-eclipselink/pom.xml b/persistence-modules/spring-data-eclipselink/pom.xml new file mode 100644 index 0000000000..65793fd1e0 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/pom.xml @@ -0,0 +1,80 @@ + + + 4.0.0 + + com.baeldung + spring-data-eclipselink + 1.0.0-SNAPSHOT + + spring-data-eclipselink + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + UTF-8 + UTF-8 + 1.8 + 1.5.9.RELEASE + 2.7.0 + 1.4.196 + + + + + org.springframework.boot + spring-boot-dependencies + ${spring.version} + pom + import + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring.version} + + + org.hibernate + hibernate-entitymanager + + + org.hibernate + hibernate-core + + + + + org.springframework.boot + spring-boot-starter-test + ${spring.version} + test + + + org.eclipse.persistence + org.eclipse.persistence.jpa + ${eclipselink.version} + + + com.h2database + h2 + runtime + ${h2.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.version} + + + + + diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/EclipselinkSpringDataApplication.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/EclipselinkSpringDataApplication.java new file mode 100644 index 0000000000..63ce778022 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/EclipselinkSpringDataApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.eclipselink.springdata; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class EclipselinkSpringDataApplication { + + public static void main(String[] args) { + SpringApplication.run(EclipselinkSpringDataApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/JpaConfiguration.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/JpaConfiguration.java new file mode 100644 index 0000000000..60ff7909be --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/JpaConfiguration.java @@ -0,0 +1,44 @@ +package com.baeldung.eclipselink.springdata; + +import org.eclipse.persistence.config.PersistenceUnitProperties; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; +import org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers; +import org.springframework.context.annotation.Configuration; +import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver; +import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter; +import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter; +import org.springframework.transaction.jta.JtaTransactionManager; + +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.Map; + +/** + * Created by adam. + */ +@Configuration +public class JpaConfiguration extends JpaBaseConfiguration { + + protected JpaConfiguration(DataSource dataSource, JpaProperties properties, ObjectProvider jtaTransactionManager, ObjectProvider transactionManagerCustomizers) { + super(dataSource, properties, jtaTransactionManager, transactionManagerCustomizers); + } + + @Override + protected AbstractJpaVendorAdapter createJpaVendorAdapter() { + return new EclipseLinkJpaVendorAdapter(); + } + + @Override + protected Map getVendorProperties() { + HashMap map = new HashMap<>(); + map.put(PersistenceUnitProperties.WEAVING, detectWeavingMode()); + map.put(PersistenceUnitProperties.DDL_GENERATION, "drop-and-create-tables"); + return map; + } + + private String detectWeavingMode() { + return InstrumentationLoadTimeWeaver.isInstrumentationAvailable() ? "true" : "static"; + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/model/Person.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/model/Person.java new file mode 100644 index 0000000000..75161875bd --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/model/Person.java @@ -0,0 +1,43 @@ +package com.baeldung.eclipselink.springdata.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +/** + * Created by adam. + */ +@Entity +public class Person { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + private String firstName; + private String lastName; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/repo/PersonsRepository.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/repo/PersonsRepository.java new file mode 100644 index 0000000000..86cd85d5fe --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/repo/PersonsRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.eclipselink.springdata.repo; + +import org.springframework.data.repository.CrudRepository; + +import com.baeldung.eclipselink.springdata.model.Person; + +/** + * Created by adam. + */ +public interface PersonsRepository extends CrudRepository { + + Person findByFirstName(String firstName); + +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/resources/application.properties b/persistence-modules/spring-data-eclipselink/src/main/resources/application.properties new file mode 100644 index 0000000000..549c0b4ada --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.datasource.url=jdbc:h2:mem:test +spring.jpa.show-sql=true \ No newline at end of file diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java new file mode 100644 index 0000000000..1a7c28df6c --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java @@ -0,0 +1,51 @@ +package com.baeldung.eclipselink.springdata.repo; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.eclipselink.springdata.model.Person; +import com.baeldung.eclipselink.springdata.repo.PersonsRepository; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.notNullValue; + +/** + * Created by adam. + */ +@RunWith(SpringRunner.class) +@SpringBootTest +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) +public class PersonsRepositoryTest { + + @Autowired + private PersonsRepository personsRepository; + + @Test + public void givenPerson_whenSave_thenAddOnePersonToDB() { + personsRepository.save(new Person()); + assertThat(personsRepository.findAll().spliterator().getExactSizeIfKnown(), equalTo(1l)); + } + + @Test + public void givenPersons_whenSearch_thenFindOk() { + Person person1 = new Person(); + person1.setFirstName("Adam"); + + Person person2 = new Person(); + person2.setFirstName("Dave"); + + personsRepository.save(person1); + personsRepository.save(person2); + + Person foundPerson = personsRepository.findByFirstName("Adam"); + + assertThat(foundPerson.getFirstName(), equalTo("Adam")); + assertThat(foundPerson.getId(), notNullValue()); + } + +} diff --git a/pom.xml b/pom.xml index 943c03c091..5eb1bb257d 100644 --- a/pom.xml +++ b/pom.xml @@ -171,6 +171,7 @@ persistence-modules/spring-hibernate-3 spring-hibernate4 persistence-modules/spring-hibernate-5 + persistence-modules/spring-data-eclipselink spring-integration spring-jenkins-pipeline spring-jersey diff --git a/spring-jenkins-pipeline/scripted-pipeline-unix-nonunix b/spring-jenkins-pipeline/scripted-pipeline-unix-nonunix index e9cae64d3d..fab940ad3d 100644 --- a/spring-jenkins-pipeline/scripted-pipeline-unix-nonunix +++ b/spring-jenkins-pipeline/scripted-pipeline-unix-nonunix @@ -1,6 +1,6 @@ node { stage 'Clone the project' - git 'https://github.com/dassiorleando/tutorials.git' + git 'https://github.com/eugenp/tutorials.git' dir('spring-jenkins-pipeline') { stage("Compilation and Analysis") {