This commit is contained in:
Seun Matt 2017-12-18 20:22:53 +01:00
commit f4903c6118
25 changed files with 888 additions and 161 deletions

View File

@ -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);
}
}

View File

@ -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<String> asList = Arrays.asList(strings);
for (int i = 0; i < count; i++) {
asList.contains("W");
List<String> 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<String> asSet = new HashSet<>(Arrays.asList(strings));
for (int i = 0; i < count; i++) {
asSet.contains("S");
Set<String> 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++)

View File

@ -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());
}
}

View File

@ -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) {

View File

@ -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<Element> comparator = (ele1, ele2) -> {
return ele1.getId()
.compareTo(ele2.getId());
};
@Test
public void whenAddingElement_shouldAddElement() {
Set<String> treeSet = new TreeSet<>();
Assert.assertTrue(treeSet.add("String Added"));
}
@Test
public void whenCheckingForElement_shouldSearchForElement() {
Set<String> treeSetContains = new TreeSet<>();
treeSetContains.add("String Added");
Assert.assertTrue(treeSetContains.contains("String Added"));
}
@Test
public void whenRemovingElement_shouldRemoveElement() {
Set<String> removeFromTreeSet = new TreeSet<>();
removeFromTreeSet.add("String Added");
Assert.assertTrue(removeFromTreeSet.remove("String Added"));
}
@Test
public void whenClearingTreeSet_shouldClearTreeSet() {
Set<String> clearTreeSet = new TreeSet<>();
clearTreeSet.add("String Added");
clearTreeSet.clear();
Assert.assertTrue(clearTreeSet.isEmpty());
}
@Test
public void whenCheckingTheSizeOfTreeSet_shouldReturnThesize() {
Set<String> treeSetSize = new TreeSet<>();
treeSetSize.add("String Added");
Assert.assertEquals(1, treeSetSize.size());
}
@Test
public void whenCheckingForEmptyTreeSet_shouldCheckForEmpty() {
Set<String> emptyTreeSet = new TreeSet<>();
Assert.assertTrue(emptyTreeSet.isEmpty());
}
@Test
public void whenIteratingTreeSet_shouldIterateTreeSetInAscendingOrder() {
Set<String> treeSet = new TreeSet<>();
treeSet.add("First");
treeSet.add("Second");
treeSet.add("Third");
Iterator<String> itr = treeSet.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
@Test
public void whenIteratingTreeSet_shouldIterateTreeSetInDescendingOrder() {
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("First");
treeSet.add("Second");
treeSet.add("Third");
Iterator<String> itr = treeSet.descendingIterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
@Test(expected = ConcurrentModificationException.class)
public void whenModifyingTreeSetWhileIterating_shouldThrowException() {
Set<String> treeSet = new TreeSet<>();
treeSet.add("First");
treeSet.add("Second");
treeSet.add("Third");
Iterator<String> itr = treeSet.iterator();
while (itr.hasNext()) {
itr.next();
treeSet.remove("Second");
}
}
@Test
public void whenRemovingElementUsingIterator_shouldRemoveElement() {
Set<String> treeSet = new TreeSet<>();
treeSet.add("First");
treeSet.add("Second");
treeSet.add("Third");
Iterator<String> 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<String> treeSet = new TreeSet<>();
treeSet.add("First");
treeSet.add(null);
}
@Test
public void whenCheckingFirstElement_shouldReturnFirstElement() {
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("First");
Assert.assertEquals("First", treeSet.first());
}
@Test
public void whenCheckingLastElement_shouldReturnLastElement() {
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("First");
treeSet.add("Last");
Assert.assertEquals("Last", treeSet.last());
}
@Test
public void whenUsingComparator_shouldSortAndInsertElements() {
Set<Element> 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<Element> 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<Integer> treeSet = new TreeSet<>();
treeSet.add(1);
treeSet.add(2);
treeSet.add(3);
treeSet.add(4);
treeSet.add(5);
treeSet.add(6);
Set<Integer> expectedSet = new TreeSet<>();
expectedSet.add(2);
expectedSet.add(3);
expectedSet.add(4);
expectedSet.add(5);
Set<Integer> subSet = treeSet.subSet(2, 6);
Assert.assertEquals(expectedSet, subSet);
}
@Test
public void whenUsingHeadSet_shouldReturnHeadSetElements() {
SortedSet<Integer> treeSet = new TreeSet<>();
treeSet.add(1);
treeSet.add(2);
treeSet.add(3);
treeSet.add(4);
treeSet.add(5);
treeSet.add(6);
Set<Integer> subSet = treeSet.headSet(6);
Assert.assertEquals(subSet, treeSet.subSet(1, 6));
}
@Test
public void whenUsingTailSet_shouldReturnTailSetElements() {
NavigableSet<Integer> treeSet = new TreeSet<>();
treeSet.add(1);
treeSet.add(2);
treeSet.add(3);
treeSet.add(4);
treeSet.add(5);
treeSet.add(6);
Set<Integer> subSet = treeSet.tailSet(3);
Assert.assertEquals(subSet, treeSet.subSet(3, true, 6, true));
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,2 @@
files will be copied here and then deleted
remove `file.delete()` to see the files here

View File

@ -0,0 +1 @@
apache

View File

@ -0,0 +1 @@
channel

View File

@ -0,0 +1 @@
files

View File

@ -0,0 +1 @@
stream

View File

@ -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)

1
lucene/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/index/

View File

@ -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<Document> 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<Document> documents = new ArrayList<>();
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
documents.add(searcher.doc(scoreDoc.doc));
}
return documents;
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -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<Document> docs = luceneFileSearch.searchFiles("contents", "consectetur");
Assert.assertEquals("file1.txt", docs.get(0).get("filename"));
}
}

View File

@ -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.

View File

@ -0,0 +1,80 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-data-eclipselink</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>spring-data-eclipselink</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring.version>1.5.9.RELEASE</spring.version>
<eclipselink.version>2.7.0</eclipselink.version>
<h2.version>1.4.196</h2.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</exclusion>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>${eclipselink.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>${h2.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring.version}</version>
</plugin>
</plugins>
</build>
</project>

View File

@ -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);
}
}

View File

@ -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> jtaTransactionManager, ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
super(dataSource, properties, jtaTransactionManager, transactionManagerCustomizers);
}
@Override
protected AbstractJpaVendorAdapter createJpaVendorAdapter() {
return new EclipseLinkJpaVendorAdapter();
}
@Override
protected Map<String, Object> getVendorProperties() {
HashMap<String, Object> 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";
}
}

View File

@ -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;
}
}

View File

@ -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, Long> {
Person findByFirstName(String firstName);
}

View File

@ -0,0 +1,2 @@
spring.datasource.url=jdbc:h2:mem:test
spring.jpa.show-sql=true

View File

@ -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());
}
}

View File

@ -171,6 +171,7 @@
<module>persistence-modules/spring-hibernate-3</module>
<module>spring-hibernate4</module>
<module>persistence-modules/spring-hibernate-5</module>
<module>persistence-modules/spring-data-eclipselink</module>
<module>spring-integration</module>
<module>spring-jenkins-pipeline</module>
<module>spring-jersey</module>

View File

@ -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") {