Merge branch 'master' into BAEL-2977-stream-skip-limit
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
package com.baeldung.folding;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
* Calculate a hash value for the strings using the folding technique.
|
||||
*
|
||||
* The implementation serves only to the illustration purposes and is far
|
||||
* from being the most efficient.
|
||||
*
|
||||
* @author A.Shcherbakov
|
||||
*
|
||||
*/
|
||||
public class FoldingHash {
|
||||
|
||||
/**
|
||||
* Calculate the hash value of a given string.
|
||||
*
|
||||
* @param str Assume it is not null
|
||||
* @param groupSize the group size in the folding technique
|
||||
* @param maxValue defines a max value that the hash may acquire (exclusive)
|
||||
* @return integer value from 0 (inclusive) to maxValue (exclusive)
|
||||
*/
|
||||
public int hash(String str, int groupSize, int maxValue) {
|
||||
final int[] codes = this.toAsciiCodes(str);
|
||||
return IntStream.range(0, str.length())
|
||||
.filter(i -> i % groupSize == 0)
|
||||
.mapToObj(i -> extract(codes, i, groupSize))
|
||||
.map(block -> concatenate(block))
|
||||
.reduce(0, (a, b) -> (a + b) % maxValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new array of given length whose elements are take from
|
||||
* the original one starting from the offset.
|
||||
*
|
||||
* If the original array has not enough elements, the returning array will contain
|
||||
* element from the offset till the end of the original array.
|
||||
*
|
||||
* @param numbers original array. Assume it is not null.
|
||||
* @param offset index of the element to start from. Assume it is less than the size of the array
|
||||
* @param length max size of the resulting array
|
||||
* @return
|
||||
*/
|
||||
public int[] extract(int[] numbers, int offset, int length) {
|
||||
final int defect = numbers.length - (offset + length);
|
||||
final int s = defect < 0 ? length + defect : length;
|
||||
int[] result = new int[s];
|
||||
for (int index = 0; index < s; index++) {
|
||||
result[index] = numbers[index + offset];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Concatenate the numbers into a single number as if they were strings.
|
||||
* Assume that the procedure does not suffer from the overflow.
|
||||
* @param numbers integers to concatenate
|
||||
* @return
|
||||
*/
|
||||
public int concatenate(int[] numbers) {
|
||||
final String merged = IntStream.of(numbers)
|
||||
.mapToObj(number -> "" + number)
|
||||
.collect(Collectors.joining());
|
||||
return Integer.parseInt(merged, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the string into its characters' ASCII codes.
|
||||
* @param str input string
|
||||
* @return
|
||||
*/
|
||||
private int[] toAsciiCodes(String str) {
|
||||
return str.chars()
|
||||
.toArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.folding;
|
||||
|
||||
/**
|
||||
* Code snippet for article "A Guide to the Folding Technique".
|
||||
*
|
||||
* @author A.Shcherbakov
|
||||
*
|
||||
*/
|
||||
public class Main {
|
||||
|
||||
public static void main(String... arg) {
|
||||
FoldingHash hasher = new FoldingHash();
|
||||
final String str = "Java language";
|
||||
System.out.println(hasher.hash(str, 2, 100_000));
|
||||
System.out.println(hasher.hash(str, 3, 1_000));
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.folding;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FoldingHashUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception {
|
||||
final FoldingHash hasher = new FoldingHash();
|
||||
final int value = hasher.hash("Java language", 2, 100_000);
|
||||
assertEquals(value, 48933);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception {
|
||||
final FoldingHash hasher = new FoldingHash();
|
||||
final int java = hasher.hash("Java language", 2, 100_000);
|
||||
final int vaja = hasher.hash("vaJa language", 2, 100_000);
|
||||
assertTrue(java == vaja);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception {
|
||||
final FoldingHash hasher = new FoldingHash();
|
||||
final int[] value = hasher.extract(new int[] { 5 }, 0, 2);
|
||||
assertArrayEquals(new int[] { 5 }, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception {
|
||||
final FoldingHash hasher = new FoldingHash();
|
||||
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 0, 3);
|
||||
assertArrayEquals(new int[] { 1, 2, 3 }, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception {
|
||||
final FoldingHash hasher = new FoldingHash();
|
||||
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 1, 2);
|
||||
assertArrayEquals(new int[] { 2, 3 }, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception {
|
||||
final FoldingHash hasher = new FoldingHash();
|
||||
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 2, 2000);
|
||||
assertArrayEquals(new int[] { 3, 4, 5 }, value);
|
||||
}
|
||||
|
||||
}
|
||||
+3
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.delay;
|
||||
package com.baeldung.concurrent.delay;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
@@ -61,6 +61,7 @@ public class Delay {
|
||||
|
||||
executorService.schedule(Delay::someTask1, delayInSeconds, TimeUnit.SECONDS);
|
||||
|
||||
executorService.shutdown();
|
||||
}
|
||||
|
||||
private static void fixedRateServiceTask(Integer delayInSeconds) {
|
||||
@@ -78,6 +79,7 @@ public class Delay {
|
||||
|
||||
sf.cancel(true);
|
||||
|
||||
executorService.shutdown();
|
||||
}
|
||||
|
||||
private static void someTask1() {
|
||||
@@ -1,3 +0,0 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables)
|
||||
@@ -0,0 +1,3 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Determine File Creating Date in Java](https://www.baeldung.com/file-creation-date-java)
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.creationdate;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
public class CreationDateResolver {
|
||||
|
||||
public Instant resolveCreationTimeWithBasicAttributes(Path path) {
|
||||
try {
|
||||
final BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
|
||||
final FileTime fileTime = attr.creationTime();
|
||||
|
||||
return fileTime.toInstant();
|
||||
} catch (IOException ex) {
|
||||
throw new RuntimeException("An issue occured went wrong when resolving creation time", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<Instant> resolveCreationTimeWithAttribute(Path path) {
|
||||
try {
|
||||
final FileTime creationTime = (FileTime) Files.getAttribute(path, "creationTime");
|
||||
|
||||
return Optional
|
||||
.ofNullable(creationTime)
|
||||
.map((FileTime::toInstant));
|
||||
} catch (IOException ex) {
|
||||
throw new RuntimeException("An issue occured went wrong when resolving creation time", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.creationdate;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CreationDateResolverUnitTest {
|
||||
|
||||
private final CreationDateResolver creationDateResolver = new CreationDateResolver();
|
||||
|
||||
@Test
|
||||
public void givenFile_whenGettingCreationDateTimeFromBasicAttributes_thenReturnDate() throws Exception {
|
||||
|
||||
final File file = File.createTempFile("createdFile", ".txt");
|
||||
final Path path = file.toPath();
|
||||
|
||||
final Instant response = creationDateResolver.resolveCreationTimeWithBasicAttributes(path);
|
||||
|
||||
assertTrue(Instant
|
||||
.now()
|
||||
.isAfter(response));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenGettingCreationDateTimeFromAttribute_thenReturnDate() throws Exception {
|
||||
|
||||
final File file = File.createTempFile("createdFile", ".txt");
|
||||
final Path path = file.toPath();
|
||||
|
||||
final Optional<Instant> response = creationDateResolver.resolveCreationTimeWithAttribute(path);
|
||||
|
||||
response.ifPresent((value) -> {
|
||||
assertTrue(Instant
|
||||
.now()
|
||||
.isAfter(value));
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,13 @@
|
||||
<artifactId>jackson-dataformat-yaml</artifactId>
|
||||
<version>2.9.8</version>
|
||||
</dependency>
|
||||
|
||||
<!-- CSV -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-csv</artifactId>
|
||||
<version>2.9.8</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Allow use of LocalDate -->
|
||||
<dependency>
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.jackson.csv;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.entities.OrderLine;
|
||||
import com.baeldung.jackson.mixin.OrderLineForCsv;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.MappingIterator;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
|
||||
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
|
||||
import com.fasterxml.jackson.dataformat.csv.CsvSchema.Builder;
|
||||
|
||||
public class JsonCsvConverter {
|
||||
|
||||
public static void JsonToCsv(File jsonFile, File csvFile) throws IOException {
|
||||
JsonNode jsonTree = new ObjectMapper().readTree(jsonFile);
|
||||
|
||||
Builder csvSchemaBuilder = CsvSchema.builder();
|
||||
JsonNode firstObject = jsonTree.elements().next();
|
||||
firstObject.fieldNames().forEachRemaining(fieldName -> {csvSchemaBuilder.addColumn(fieldName);} );
|
||||
CsvSchema csvSchema = csvSchemaBuilder
|
||||
.build()
|
||||
.withHeader();
|
||||
|
||||
CsvMapper csvMapper = new CsvMapper();
|
||||
csvMapper.writerFor(JsonNode.class)
|
||||
.with(csvSchema)
|
||||
.writeValue(csvFile, jsonTree);
|
||||
}
|
||||
|
||||
public static void csvToJson(File csvFile, File jsonFile) throws IOException {
|
||||
CsvSchema orderLineSchema = CsvSchema.emptySchema().withHeader();
|
||||
CsvMapper csvMapper = new CsvMapper();
|
||||
MappingIterator<OrderLine> orderLines = csvMapper.readerFor(OrderLine.class)
|
||||
.with(orderLineSchema)
|
||||
.readValues(csvFile);
|
||||
|
||||
new ObjectMapper()
|
||||
.configure(SerializationFeature.INDENT_OUTPUT, true)
|
||||
.writeValue(jsonFile, orderLines.readAll());
|
||||
}
|
||||
|
||||
public static void JsonToFormattedCsv(File jsonFile, File csvFile) throws IOException {
|
||||
CsvMapper csvMapper = new CsvMapper();
|
||||
CsvSchema csvSchema = csvMapper
|
||||
.schemaFor(OrderLineForCsv.class)
|
||||
.withHeader();
|
||||
csvMapper.addMixIn(OrderLine.class, OrderLineForCsv.class);
|
||||
|
||||
OrderLine[] orderLines = new ObjectMapper()
|
||||
.readValue(jsonFile, OrderLine[].class);
|
||||
csvMapper.writerFor(OrderLine[].class)
|
||||
.with(csvSchema)
|
||||
.writeValue(csvFile, orderLines);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.jackson.mixin;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
|
||||
|
||||
@JsonPropertyOrder({
|
||||
"count",
|
||||
"name"
|
||||
})
|
||||
public abstract class OrderLineForCsv {
|
||||
|
||||
@JsonProperty("name")
|
||||
private String item;
|
||||
|
||||
@JsonProperty("count")
|
||||
private int quantity;
|
||||
|
||||
@JsonIgnore
|
||||
private BigDecimal unitPrice;
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
item,quantity,unitPrice
|
||||
"No. 9 Sprockets",12,1.23
|
||||
"Widget (10mm)",4,3.45
|
||||
|
@@ -0,0 +1,9 @@
|
||||
[ {
|
||||
"item" : "No. 9 Sprockets",
|
||||
"quantity" : 12,
|
||||
"unitPrice" : 1.23
|
||||
}, {
|
||||
"item" : "Widget (10mm)",
|
||||
"quantity" : 4,
|
||||
"unitPrice" : 3.45
|
||||
} ]
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.jackson.csv;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.google.common.io.Files;
|
||||
|
||||
|
||||
public class CsvUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenJsonInput_thenWriteCsv() throws JsonParseException, JsonMappingException, IOException {
|
||||
JsonCsvConverter.JsonToCsv(new File("src/main/resources/orderLines.json"),
|
||||
new File("src/main/resources/csvFromJson.csv"));
|
||||
|
||||
assertEquals(readFile("src/main/resources/csvFromJson.csv"),
|
||||
readFile("src/test/resources/expectedCsvFromJson.csv"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCsvInput_thenWritesJson() throws JsonParseException, JsonMappingException, IOException {
|
||||
JsonCsvConverter.csvToJson(new File("src/main/resources/orderLines.csv"),
|
||||
new File("src/main/resources/jsonFromCsv.json"));
|
||||
|
||||
assertEquals(readFile("src/main/resources/jsonFromCsv.json"),
|
||||
readFile("src/test/resources/expectedJsonFromCsv.json"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJsonInput_thenWriteFormattedCsvOutput() throws JsonParseException, JsonMappingException, IOException {
|
||||
JsonCsvConverter.JsonToFormattedCsv(new File("src/main/resources/orderLines.json"),
|
||||
new File("src/main/resources/formattedCsvFromJson.csv"));
|
||||
|
||||
assertEquals(readFile("src/main/resources/formattedCsvFromJson.csv"),
|
||||
readFile("src/test/resources/expectedFormattedCsvFromJson.csv"));
|
||||
|
||||
}
|
||||
|
||||
private List<String> readFile(String filename) throws IOException {
|
||||
return Files.readLines(new File(filename), Charset.forName("utf-8"));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
;
|
||||
@@ -0,0 +1,3 @@
|
||||
item,quantity,unitPrice
|
||||
"No. 9 Sprockets",12,1.23
|
||||
"Widget (10mm)",4,3.45
|
||||
|
@@ -0,0 +1,3 @@
|
||||
count,name
|
||||
12,"No. 9 Sprockets"
|
||||
4,"Widget (10mm)"
|
||||
|
@@ -0,0 +1,9 @@
|
||||
[ {
|
||||
"item" : "No. 9 Sprockets",
|
||||
"quantity" : 12,
|
||||
"unitPrice" : 1.23
|
||||
}, {
|
||||
"item" : "Widget (10mm)",
|
||||
"quantity" : 4,
|
||||
"unitPrice" : 3.45
|
||||
} ]
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.baeldung.convertiteratortolist;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
|
||||
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.apache.commons.collections4.IteratorUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class ConvertIteratorToListServiceUnitTest {
|
||||
|
||||
Iterator<Integer> iterator;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
iterator = Arrays.asList(1, 2, 3)
|
||||
.iterator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIterator_whenConvertIteratorToListUsingWhileLoop_thenReturnAList() {
|
||||
|
||||
List<Integer> actualList = new ArrayList<Integer>();
|
||||
|
||||
// Convert Iterator to List using while loop dsf
|
||||
while (iterator.hasNext()) {
|
||||
actualList.add(iterator.next());
|
||||
}
|
||||
|
||||
assertThat(actualList, hasSize(3));
|
||||
assertThat(actualList, containsInAnyOrder(1, 2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIterator_whenConvertIteratorToListAfterJava8_thenReturnAList() {
|
||||
List<Integer> actualList = new ArrayList<Integer>();
|
||||
|
||||
// Convert Iterator to List using Java 8
|
||||
iterator.forEachRemaining(actualList::add);
|
||||
|
||||
assertThat(actualList, hasSize(3));
|
||||
assertThat(actualList, containsInAnyOrder(1, 2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIterator_whenConvertIteratorToListJava8Stream_thenReturnAList() {
|
||||
|
||||
// Convert iterator to iterable
|
||||
Iterable<Integer> iterable = () -> iterator;
|
||||
|
||||
// Extract List from stream
|
||||
List<Integer> actualList = StreamSupport
|
||||
.stream(iterable.spliterator(), false)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(actualList, hasSize(3));
|
||||
assertThat(actualList, containsInAnyOrder(1, 2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIterator_whenConvertIteratorToImmutableListWithGuava_thenReturnAList() {
|
||||
|
||||
// Convert Iterator to an Immutable list using Guava library in Java
|
||||
List<Integer> actualList = ImmutableList.copyOf(iterator);
|
||||
|
||||
assertThat(actualList, hasSize(3));
|
||||
assertThat(actualList, containsInAnyOrder(1, 2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIterator_whenConvertIteratorToMutableListWithGuava_thenReturnAList() {
|
||||
|
||||
// Convert Iterator to a mutable list using Guava library in Java
|
||||
List<Integer> actualList = Lists.newArrayList(iterator);
|
||||
|
||||
assertThat(actualList, hasSize(3));
|
||||
assertThat(actualList, containsInAnyOrder(1, 2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIterator_whenConvertIteratorToMutableListWithApacheCommons_thenReturnAList() {
|
||||
|
||||
// Convert Iterator to a mutable list using Apache Commons library in Java
|
||||
List<Integer> actualList = IteratorUtils.toList(iterator);
|
||||
|
||||
assertThat(actualList, hasSize(3));
|
||||
assertThat(actualList, containsInAnyOrder(1, 2, 3));
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package org.baeldung.java.collections;
|
||||
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Spliterator;
|
||||
import java.util.Spliterators;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.apache.commons.collections4.IterableUtils;
|
||||
import org.apache.commons.collections4.IteratorUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class IterableToCollectionUnitTest {
|
||||
|
||||
Iterable<String> iterable = Arrays.asList("john", "tom", "jane");
|
||||
Iterator<String> iterator = iterable.iterator();
|
||||
|
||||
@Test
|
||||
public void whenConvertIterableToListUsingJava_thenSuccess() {
|
||||
List<String> result = new ArrayList<String>();
|
||||
for (String str : iterable) {
|
||||
result.add(str);
|
||||
}
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIterableToListUsingJava8_thenSuccess() {
|
||||
List<String> result = new ArrayList<String>();
|
||||
iterable.forEach(result::add);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIterableToListUsingJava8WithSpliterator_thenSuccess() {
|
||||
List<String> result = StreamSupport.stream(iterable.spliterator(), false)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIterableToListUsingGuava_thenSuccess() {
|
||||
List<String> result = Lists.newArrayList(iterable);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIterableToImmutableListUsingGuava_thenSuccess() {
|
||||
List<String> result = ImmutableList.copyOf(iterable);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIterableToListUsingApacheCommons_thenSuccess() {
|
||||
List<String> result = IterableUtils.toList(iterable);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
// ======================== Iterator
|
||||
|
||||
@Test
|
||||
public void whenConvertIteratorToListUsingJava_thenSuccess() {
|
||||
List<String> result = new ArrayList<String>();
|
||||
while (iterator.hasNext()) {
|
||||
result.add(iterator.next());
|
||||
}
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIteratorToListUsingJava8_thenSuccess() {
|
||||
List<String> result = new ArrayList<String>();
|
||||
iterator.forEachRemaining(result::add);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIteratorToListUsingJava8WithSpliterator_thenSuccess() {
|
||||
List<String> result = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIteratorToListUsingGuava_thenSuccess() {
|
||||
List<String> result = Lists.newArrayList(iterator);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIteratorToImmutableListUsingGuava_thenSuccess() {
|
||||
List<String> result = ImmutableList.copyOf(iterator);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIteratorToListUsingApacheCommons_thenSuccess() {
|
||||
List<String> result = IteratorUtils.toList(iterator);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.intstreams.conversion;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class IntStreamsConversionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void intStreamToArray() {
|
||||
int[] first50EvenNumbers = IntStream.iterate(0, i -> i + 2)
|
||||
.limit(50)
|
||||
.toArray();
|
||||
|
||||
assertThat(first50EvenNumbers).hasSize(50);
|
||||
assertThat(first50EvenNumbers[2]).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void intStreamToList() {
|
||||
List<Integer> first50IntegerNumbers = IntStream.range(0, 50)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(first50IntegerNumbers).hasSize(50);
|
||||
assertThat(first50IntegerNumbers.get(2)).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void intStreamToString() {
|
||||
String first3numbers = IntStream.of(0, 1, 2)
|
||||
.mapToObj(String::valueOf)
|
||||
.collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
assertThat(first3numbers).isEqualTo("[0, 1, 2]");
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,17 @@
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>${spring-boot-starter.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.openhft</groupId>
|
||||
<artifactId>chronicle-map</artifactId>
|
||||
<version>${chronicle.map.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>com.sun.java</groupId>
|
||||
<artifactId>tools</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- Dependencies for response decoder with okhttp -->
|
||||
<dependency>
|
||||
@@ -95,6 +106,7 @@
|
||||
<classgraph.version>4.8.28</classgraph.version>
|
||||
<jbpm.version>6.0.0.Final</jbpm.version>
|
||||
<picocli.version>3.9.6</picocli.version>
|
||||
<chronicle.map.version>3.17.2</chronicle.map.version>
|
||||
<crawler4j.version>4.4.0</crawler4j.version>
|
||||
<spring-boot-starter.version>2.1.4.RELEASE</spring-boot-starter.version>
|
||||
</properties>
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.baeldung.chroniclemap;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import net.openhft.chronicle.core.values.LongValue;
|
||||
import net.openhft.chronicle.map.ChronicleMap;
|
||||
import net.openhft.chronicle.map.ExternalMapQueryContext;
|
||||
import net.openhft.chronicle.map.MapEntry;
|
||||
import net.openhft.chronicle.values.Values;
|
||||
|
||||
public class ChronicleMapUnitTest {
|
||||
|
||||
static ChronicleMap<LongValue, CharSequence> persistedCountryMap = null;
|
||||
|
||||
static ChronicleMap<LongValue, CharSequence> inMemoryCountryMap = null;
|
||||
|
||||
static ChronicleMap<Integer, Set<Integer>> multiMap = null;
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@BeforeClass
|
||||
public static void init() {
|
||||
try {
|
||||
inMemoryCountryMap = ChronicleMap.of(LongValue.class, CharSequence.class)
|
||||
.name("country-map")
|
||||
.entries(50)
|
||||
.averageValue("America")
|
||||
.create();
|
||||
|
||||
persistedCountryMap = ChronicleMap.of(LongValue.class, CharSequence.class)
|
||||
.name("country-map")
|
||||
.entries(50)
|
||||
.averageValue("America")
|
||||
.createPersistedTo(new File(System.getProperty("user.home") + "/country-details.dat"));
|
||||
|
||||
Set<Integer> averageValue = IntStream.of(1, 2)
|
||||
.boxed()
|
||||
.collect(Collectors.toSet());
|
||||
multiMap = ChronicleMap.of(Integer.class, (Class<Set<Integer>>) (Class) Set.class)
|
||||
.name("multi-map")
|
||||
.entries(50)
|
||||
.averageValue(averageValue)
|
||||
.create();
|
||||
|
||||
LongValue qatarKey = Values.newHeapInstance(LongValue.class);
|
||||
qatarKey.setValue(1);
|
||||
inMemoryCountryMap.put(qatarKey, "Qatar");
|
||||
|
||||
LongValue key = Values.newHeapInstance(LongValue.class);
|
||||
key.setValue(1);
|
||||
persistedCountryMap.put(key, "Romania");
|
||||
key.setValue(2);
|
||||
persistedCountryMap.put(key, "India");
|
||||
|
||||
Set<Integer> set1 = new HashSet<>();
|
||||
set1.add(1);
|
||||
set1.add(2);
|
||||
multiMap.put(1, set1);
|
||||
|
||||
Set<Integer> set2 = new HashSet<>();
|
||||
set2.add(3);
|
||||
multiMap.put(2, set2);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGetQuery_whenCalled_shouldReturnResult() {
|
||||
LongValue key = Values.newHeapInstance(LongValue.class);
|
||||
key.setValue(1);
|
||||
CharSequence country = inMemoryCountryMap.get(key);
|
||||
assertThat(country.toString(), is(equalTo("Qatar")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGetUsingQuery_whenCalled_shouldReturnResult() {
|
||||
LongValue key = Values.newHeapInstance(LongValue.class);
|
||||
StringBuilder country = new StringBuilder();
|
||||
key.setValue(1);
|
||||
persistedCountryMap.getUsing(key, country);
|
||||
assertThat(country.toString(), is(equalTo("Romania")));
|
||||
key.setValue(2);
|
||||
persistedCountryMap.getUsing(key, country);
|
||||
assertThat(country.toString(), is(equalTo("India")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleKeyQuery_whenProcessed_shouldChangeTheValue() {
|
||||
try (ExternalMapQueryContext<Integer, Set<Integer>, ?> fistContext = multiMap.queryContext(1)) {
|
||||
try (ExternalMapQueryContext<Integer, Set<Integer>, ?> secondContext = multiMap.queryContext(2)) {
|
||||
fistContext.updateLock()
|
||||
.lock();
|
||||
secondContext.updateLock()
|
||||
.lock();
|
||||
MapEntry<Integer, Set<Integer>> firstEntry = fistContext.entry();
|
||||
Set<Integer> firstSet = firstEntry.value()
|
||||
.get();
|
||||
firstSet.remove(2);
|
||||
MapEntry<Integer, Set<Integer>> secondEntry = secondContext.entry();
|
||||
Set<Integer> secondSet = secondEntry.value()
|
||||
.get();
|
||||
secondSet.add(4);
|
||||
firstEntry.doReplaceValue(fistContext.wrapValueAsData(firstSet));
|
||||
secondEntry.doReplaceValue(secondContext.wrapValueAsData(secondSet));
|
||||
}
|
||||
} finally {
|
||||
assertThat(multiMap.get(1)
|
||||
.size(), is(equalTo(1)));
|
||||
assertThat(multiMap.get(2)
|
||||
.size(), is(equalTo(2)));
|
||||
}
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void finish() {
|
||||
persistedCountryMap.close();
|
||||
inMemoryCountryMap.close();
|
||||
multiMap.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
This is a parent module for projects that want to take advantage of the latest Spring Boot improvements/features.
|
||||
@@ -0,0 +1,91 @@
|
||||
<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>
|
||||
<artifactId>parent-boot-performance</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>parent-boot-performance</name>
|
||||
<packaging>pom</packaging>
|
||||
<description>Parent for all modules that want to take advantage of the latest Spring Boot improvements/features. Current version: 2.2</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<rest-assured.version>3.1.0</rest-assured.version>
|
||||
<!-- plugins -->
|
||||
<thin.version>1.0.21.RELEASE</thin.version>
|
||||
<spring-boot.version>2.2.0.M3</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<configuration>
|
||||
<mainClass>${start-class}</mainClass>
|
||||
<!-- this is necessary as we're not using the Boot parent -->
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>thin-jar</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<dependencies>
|
||||
<!-- The following enables the "thin jar" deployment option. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot.experimental</groupId>
|
||||
<artifactId>spring-boot-thin-layout</artifactId>
|
||||
<version>${thin.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
@@ -0,0 +1,29 @@
|
||||
HELP.md
|
||||
/target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
@@ -0,0 +1,31 @@
|
||||
<?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>elasticsearch</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>elasticsearch</name>
|
||||
<description>Demo project for Java Elasticsearch libraries</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.searchbox</groupId>
|
||||
<artifactId>jest</artifactId>
|
||||
<version>6.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.9.6</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.jest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Employee {
|
||||
String name;
|
||||
String title;
|
||||
List<String> skills;
|
||||
int yearsOfService;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public List<String> getSkills() {
|
||||
return skills;
|
||||
}
|
||||
|
||||
public void setSkills(List<String> skills) {
|
||||
this.skills = skills;
|
||||
}
|
||||
|
||||
public int getYearsOfService() {
|
||||
return yearsOfService;
|
||||
}
|
||||
|
||||
public void setYearsOfService(int yearsOfService) {
|
||||
this.yearsOfService = yearsOfService;
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
package com.baeldung.jest;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.searchbox.client.JestClient;
|
||||
import io.searchbox.client.JestClientFactory;
|
||||
import io.searchbox.client.JestResult;
|
||||
import io.searchbox.client.JestResultHandler;
|
||||
import io.searchbox.client.config.HttpClientConfig;
|
||||
import io.searchbox.core.*;
|
||||
import io.searchbox.indices.CreateIndex;
|
||||
import io.searchbox.indices.IndicesExists;
|
||||
import io.searchbox.indices.aliases.AddAliasMapping;
|
||||
import io.searchbox.indices.aliases.ModifyAliases;
|
||||
import io.searchbox.indices.aliases.RemoveAliasMapping;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
public class JestDemoApplication {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
|
||||
// Demo the JestClient
|
||||
JestClient jestClient = jestClient();
|
||||
|
||||
// Check an index
|
||||
JestResult result = jestClient.execute(new IndicesExists.Builder("employees").build());
|
||||
if(!result.isSucceeded()) {
|
||||
System.out.println(result.getErrorMessage());
|
||||
}
|
||||
|
||||
// Create an index
|
||||
jestClient.execute(new CreateIndex.Builder("employees").build());
|
||||
|
||||
// Create an index with options
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
settings.put("number_of_shards", 11);
|
||||
settings.put("number_of_replicas", 2);
|
||||
jestClient.execute(new CreateIndex.Builder("employees").settings(settings).build());
|
||||
|
||||
// Create an alias, then remove it
|
||||
jestClient.execute(new ModifyAliases.Builder(
|
||||
new AddAliasMapping.Builder(
|
||||
"employees",
|
||||
"e")
|
||||
.build())
|
||||
.build());
|
||||
JestResult jestResult = jestClient.execute(new ModifyAliases.Builder(
|
||||
new RemoveAliasMapping.Builder(
|
||||
"employees",
|
||||
"e")
|
||||
.build())
|
||||
.build());
|
||||
|
||||
if(jestResult.isSucceeded()) {
|
||||
System.out.println("Success!");
|
||||
}
|
||||
else {
|
||||
System.out.println(jestResult.getErrorMessage());
|
||||
}
|
||||
|
||||
// Sample JSON for indexing
|
||||
|
||||
// {
|
||||
// "name": "Michael Pratt",
|
||||
// "title": "Java Developer",
|
||||
// "skills": ["java", "spring", "elasticsearch"],
|
||||
// "yearsOfService": 2
|
||||
// }
|
||||
|
||||
// Index a document from String
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
JsonNode employeeJsonNode = mapper.createObjectNode()
|
||||
.put("name", "Michael Pratt")
|
||||
.put("title", "Java Developer")
|
||||
.put("yearsOfService", 2)
|
||||
.set("skills", mapper.createArrayNode()
|
||||
.add("java")
|
||||
.add("spring")
|
||||
.add("elasticsearch"));
|
||||
jestClient.execute(new Index.Builder(employeeJsonNode.toString()).index("employees").build());
|
||||
|
||||
// Index a document from Map
|
||||
Map<String, Object> employeeHashMap = new LinkedHashMap<>();
|
||||
employeeHashMap.put("name", "Michael Pratt");
|
||||
employeeHashMap.put("title", "Java Developer");
|
||||
employeeHashMap.put("yearsOfService", 2);
|
||||
employeeHashMap.put("skills", Arrays.asList("java", "spring", "elasticsearch"));
|
||||
jestClient.execute(new Index.Builder(employeeHashMap).index("employees").build());
|
||||
|
||||
// Index a document from POJO
|
||||
Employee employee = new Employee();
|
||||
employee.setName("Michael Pratt");
|
||||
employee.setTitle("Java Developer");
|
||||
employee.setYearsOfService(2);
|
||||
employee.setSkills(Arrays.asList("java", "spring", "elasticsearch"));
|
||||
jestClient.execute(new Index.Builder(employee).index("employees").build());
|
||||
|
||||
// Read document by ID
|
||||
Employee getResult = jestClient.execute(new Get.Builder("employees", "1").build()).getSourceAsObject(Employee.class);
|
||||
|
||||
// Search documents
|
||||
String search = "{\n" +
|
||||
" \"query\": {\n" +
|
||||
" \"bool\": {\n" +
|
||||
" \"must\": [\n" +
|
||||
" { \"match\": { \"name\": \"Michael Pratt\" }}\n" +
|
||||
" ]\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
List<SearchResult.Hit<Employee, Void>> searchResults =
|
||||
jestClient.execute(new Search.Builder(search).build())
|
||||
.getHits(Employee.class);
|
||||
|
||||
searchResults.forEach(hit -> {
|
||||
System.out.println(String.format("Document %s has score %s", hit.id, hit.score));
|
||||
});
|
||||
|
||||
// Update document
|
||||
employee.setYearsOfService(3);
|
||||
jestClient.execute(new Update.Builder(employee).index("employees").id("1").build());
|
||||
|
||||
// Delete documents
|
||||
jestClient.execute(new Delete.Builder("2") .index("employees") .build());
|
||||
|
||||
// Bulk operations
|
||||
Employee employeeObject1 = new Employee();
|
||||
employee.setName("John Smith");
|
||||
employee.setTitle("Python Developer");
|
||||
employee.setYearsOfService(10);
|
||||
employee.setSkills(Arrays.asList("python"));
|
||||
|
||||
Employee employeeObject2 = new Employee();
|
||||
employee.setName("Kate Smith");
|
||||
employee.setTitle("Senior JavaScript Developer");
|
||||
employee.setYearsOfService(10);
|
||||
employee.setSkills(Arrays.asList("javascript", "angular"));
|
||||
|
||||
jestClient.execute(new Bulk.Builder().defaultIndex("employees")
|
||||
.addAction(new Index.Builder(employeeObject1).build())
|
||||
.addAction(new Index.Builder(employeeObject2).build())
|
||||
.addAction(new Delete.Builder("3").build()) .build());
|
||||
|
||||
// Async operations
|
||||
Employee employeeObject3 = new Employee();
|
||||
employee.setName("Jane Doe");
|
||||
employee.setTitle("Manager");
|
||||
employee.setYearsOfService(20);
|
||||
employee.setSkills(Arrays.asList("managing"));
|
||||
|
||||
jestClient.executeAsync( new Index.Builder(employeeObject3).build(), new JestResultHandler<JestResult>() {
|
||||
@Override public void completed(JestResult result) {
|
||||
// handle result
|
||||
}
|
||||
@Override public void failed(Exception ex) {
|
||||
// handle exception
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static JestClient jestClient()
|
||||
{
|
||||
JestClientFactory factory = new JestClientFactory();
|
||||
factory.setHttpClientConfig(
|
||||
new HttpClientConfig.Builder("http://localhost:9200")
|
||||
.multiThreaded(true)
|
||||
.defaultMaxTotalConnectionPerRoute(2)
|
||||
.maxTotalConnection(20)
|
||||
.build());
|
||||
return factory.getObject();
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
<module>apache-cayenne</module>
|
||||
<module>core-java-persistence</module>
|
||||
<module>deltaspike</module>
|
||||
<module>elasticsearch</module>
|
||||
<module>flyway</module>
|
||||
<module>hbase</module>
|
||||
<module>hibernate5</module>
|
||||
|
||||
@@ -46,6 +46,13 @@
|
||||
<artifactId>reactor-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.cassandraunit</groupId>
|
||||
<artifactId>cassandra-unit-spring</artifactId>
|
||||
<version>${cassandra-unit-spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
@@ -53,6 +60,7 @@
|
||||
<project.reporting.outputEncoding>UTF-8
|
||||
</project.reporting.outputEncoding>
|
||||
<spring-data-cassandra.version>2.1.2.RELEASE</spring-data-cassandra.version>
|
||||
<cassandra-unit-spring.version>3.11.2.0</cassandra-unit-spring.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user