Merge remote-tracking branch 'origin/master'
This commit is contained in:
commit
6c2ed878c0
1
.gitignore
vendored
1
.gitignore
vendored
@ -27,3 +27,4 @@ target/
|
|||||||
|
|
||||||
spring-openid/src/main/resources/application.properties
|
spring-openid/src/main/resources/application.properties
|
||||||
.recommenders/
|
.recommenders/
|
||||||
|
/spring-hibernate4/nbproject/
|
@ -18,9 +18,7 @@ public class Dijkstra {
|
|||||||
while (unsettledNodes.size() != 0) {
|
while (unsettledNodes.size() != 0) {
|
||||||
Node currentNode = getLowestDistanceNode(unsettledNodes);
|
Node currentNode = getLowestDistanceNode(unsettledNodes);
|
||||||
unsettledNodes.remove(currentNode);
|
unsettledNodes.remove(currentNode);
|
||||||
for (Entry<Node, Integer> adjacencyPair : currentNode
|
for (Entry<Node, Integer> adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
|
||||||
.getAdjacentNodes()
|
|
||||||
.entrySet()) {
|
|
||||||
Node adjacentNode = adjacencyPair.getKey();
|
Node adjacentNode = adjacencyPair.getKey();
|
||||||
Integer edgeWeigh = adjacencyPair.getValue();
|
Integer edgeWeigh = adjacencyPair.getValue();
|
||||||
|
|
||||||
|
@ -55,29 +55,19 @@ public class DijkstraAlgorithmTest {
|
|||||||
for (Node node : graph.getNodes()) {
|
for (Node node : graph.getNodes()) {
|
||||||
switch (node.getName()) {
|
switch (node.getName()) {
|
||||||
case "B":
|
case "B":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeB));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeB));
|
|
||||||
break;
|
break;
|
||||||
case "C":
|
case "C":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeC));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeC));
|
|
||||||
break;
|
break;
|
||||||
case "D":
|
case "D":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeD));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeD));
|
|
||||||
break;
|
break;
|
||||||
case "E":
|
case "E":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeE));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeE));
|
|
||||||
break;
|
break;
|
||||||
case "F":
|
case "F":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeF));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeF));
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -27,17 +27,12 @@ public class BuilderProcessor extends AbstractProcessor {
|
|||||||
|
|
||||||
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
|
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
|
||||||
|
|
||||||
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream()
|
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream().collect(Collectors.partitioningBy(element -> ((ExecutableType) element.asType()).getParameterTypes().size() == 1 && element.getSimpleName().toString().startsWith("set")));
|
||||||
.collect(Collectors.partitioningBy(element ->
|
|
||||||
((ExecutableType) element.asType()).getParameterTypes().size() == 1
|
|
||||||
&& element.getSimpleName().toString().startsWith("set")));
|
|
||||||
|
|
||||||
List<Element> setters = annotatedMethods.get(true);
|
List<Element> setters = annotatedMethods.get(true);
|
||||||
List<Element> otherMethods = annotatedMethods.get(false);
|
List<Element> otherMethods = annotatedMethods.get(false);
|
||||||
|
|
||||||
otherMethods.forEach(element ->
|
otherMethods.forEach(element -> processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@BuilderProperty must be applied to a setXxx method with a single argument", element));
|
||||||
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
|
|
||||||
"@BuilderProperty must be applied to a setXxx method with a single argument", element));
|
|
||||||
|
|
||||||
if (setters.isEmpty()) {
|
if (setters.isEmpty()) {
|
||||||
continue;
|
continue;
|
||||||
@ -45,11 +40,7 @@ public class BuilderProcessor extends AbstractProcessor {
|
|||||||
|
|
||||||
String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString();
|
String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString();
|
||||||
|
|
||||||
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(
|
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(setter -> setter.getSimpleName().toString(), setter -> ((ExecutableType) setter.asType()).getParameterTypes().get(0).toString()));
|
||||||
setter -> setter.getSimpleName().toString(),
|
|
||||||
setter -> ((ExecutableType) setter.asType())
|
|
||||||
.getParameterTypes().get(0).toString()
|
|
||||||
));
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeBuilderFile(className, setterMap);
|
writeBuilderFile(className, setterMap);
|
||||||
|
@ -9,10 +9,7 @@ public class PersonBuilderTest {
|
|||||||
@Test
|
@Test
|
||||||
public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
|
public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
|
||||||
|
|
||||||
Person person = new PersonBuilder()
|
Person person = new PersonBuilder().setAge(25).setName("John").build();
|
||||||
.setAge(25)
|
|
||||||
.setName("John")
|
|
||||||
.build();
|
|
||||||
|
|
||||||
assertEquals(25, person.getAge());
|
assertEquals(25, person.getAge());
|
||||||
assertEquals("John", person.getName());
|
assertEquals("John", person.getName());
|
||||||
|
@ -38,8 +38,7 @@ public class AssertJCoreTest {
|
|||||||
public void whenCheckingForElement_thenContains() throws Exception {
|
public void whenCheckingForElement_thenContains() throws Exception {
|
||||||
List<String> list = Arrays.asList("1", "2", "3");
|
List<String> list = Arrays.asList("1", "2", "3");
|
||||||
|
|
||||||
assertThat(list)
|
assertThat(list).contains("1");
|
||||||
.contains("1");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -50,12 +49,7 @@ public class AssertJCoreTest {
|
|||||||
assertThat(list).startsWith("1");
|
assertThat(list).startsWith("1");
|
||||||
assertThat(list).doesNotContainNull();
|
assertThat(list).doesNotContainNull();
|
||||||
|
|
||||||
assertThat(list)
|
assertThat(list).isNotEmpty().contains("1").startsWith("1").doesNotContainNull().containsSequence("2", "3");
|
||||||
.isNotEmpty()
|
|
||||||
.contains("1")
|
|
||||||
.startsWith("1")
|
|
||||||
.doesNotContainNull()
|
|
||||||
.containsSequence("2", "3");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -67,11 +61,7 @@ public class AssertJCoreTest {
|
|||||||
public void whenCheckingCharacter_thenIsUnicode() throws Exception {
|
public void whenCheckingCharacter_thenIsUnicode() throws Exception {
|
||||||
char someCharacter = 'c';
|
char someCharacter = 'c';
|
||||||
|
|
||||||
assertThat(someCharacter)
|
assertThat(someCharacter).isNotEqualTo('a').inUnicode().isGreaterThanOrEqualTo('b').isLowerCase();
|
||||||
.isNotEqualTo('a')
|
|
||||||
.inUnicode()
|
|
||||||
.isGreaterThanOrEqualTo('b')
|
|
||||||
.isLowerCase();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -94,11 +84,7 @@ public class AssertJCoreTest {
|
|||||||
final File someFile = File.createTempFile("aaa", "bbb");
|
final File someFile = File.createTempFile("aaa", "bbb");
|
||||||
someFile.deleteOnExit();
|
someFile.deleteOnExit();
|
||||||
|
|
||||||
assertThat(someFile)
|
assertThat(someFile).exists().isFile().canRead().canWrite();
|
||||||
.exists()
|
|
||||||
.isFile()
|
|
||||||
.canRead()
|
|
||||||
.canWrite();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -113,20 +99,14 @@ public class AssertJCoreTest {
|
|||||||
public void whenGivenMap_then() throws Exception {
|
public void whenGivenMap_then() throws Exception {
|
||||||
Map<Integer, String> map = Maps.newHashMap(2, "a");
|
Map<Integer, String> map = Maps.newHashMap(2, "a");
|
||||||
|
|
||||||
assertThat(map)
|
assertThat(map).isNotEmpty().containsKey(2).doesNotContainKeys(10).contains(entry(2, "a"));
|
||||||
.isNotEmpty()
|
|
||||||
.containsKey(2)
|
|
||||||
.doesNotContainKeys(10)
|
|
||||||
.contains(entry(2, "a"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGivenException_then() throws Exception {
|
public void whenGivenException_then() throws Exception {
|
||||||
Exception ex = new Exception("abc");
|
Exception ex = new Exception("abc");
|
||||||
|
|
||||||
assertThat(ex)
|
assertThat(ex).hasNoCause().hasMessageEndingWith("c");
|
||||||
.hasNoCause()
|
|
||||||
.hasMessageEndingWith("c");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Ignore // IN ORDER TO TEST, REMOVE THIS LINE
|
@Ignore // IN ORDER TO TEST, REMOVE THIS LINE
|
||||||
@ -134,8 +114,6 @@ public class AssertJCoreTest {
|
|||||||
public void whenRunningAssertion_thenDescribed() throws Exception {
|
public void whenRunningAssertion_thenDescribed() throws Exception {
|
||||||
Person person = new Person("Alex", 34);
|
Person person = new Person("Alex", 34);
|
||||||
|
|
||||||
assertThat(person.getAge())
|
assertThat(person.getAge()).as("%s's age should be equal to 100").isEqualTo(100);
|
||||||
.as("%s's age should be equal to 100")
|
|
||||||
.isEqualTo(100);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -26,9 +26,7 @@ public class AssertJGuavaTest {
|
|||||||
final File temp1 = File.createTempFile("bael", "dung1");
|
final File temp1 = File.createTempFile("bael", "dung1");
|
||||||
final File temp2 = File.createTempFile("bael", "dung2");
|
final File temp2 = File.createTempFile("bael", "dung2");
|
||||||
|
|
||||||
assertThat(Files.asByteSource(temp1))
|
assertThat(Files.asByteSource(temp1)).hasSize(0).hasSameContentAs(Files.asByteSource(temp2));
|
||||||
.hasSize(0)
|
|
||||||
.hasSameContentAs(Files.asByteSource(temp2));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -37,11 +35,7 @@ public class AssertJGuavaTest {
|
|||||||
mmap.put(1, "one");
|
mmap.put(1, "one");
|
||||||
mmap.put(1, "1");
|
mmap.put(1, "1");
|
||||||
|
|
||||||
assertThat(mmap)
|
assertThat(mmap).hasSize(2).containsKeys(1).contains(entry(1, "one")).contains(entry(1, "1"));
|
||||||
.hasSize(2)
|
|
||||||
.containsKeys(1)
|
|
||||||
.contains(entry(1, "one"))
|
|
||||||
.contains(entry(1, "1"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -62,31 +56,21 @@ public class AssertJGuavaTest {
|
|||||||
mmap2.put(1, "one");
|
mmap2.put(1, "one");
|
||||||
mmap2.put(1, "1");
|
mmap2.put(1, "1");
|
||||||
|
|
||||||
assertThat(mmap1)
|
assertThat(mmap1).containsAllEntriesOf(mmap2).containsAllEntriesOf(mmap1_clone).hasSameEntriesAs(mmap1_clone);
|
||||||
.containsAllEntriesOf(mmap2)
|
|
||||||
.containsAllEntriesOf(mmap1_clone)
|
|
||||||
.hasSameEntriesAs(mmap1_clone);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
|
public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
|
||||||
final Optional<String> something = Optional.of("something");
|
final Optional<String> something = Optional.of("something");
|
||||||
|
|
||||||
assertThat(something)
|
assertThat(something).isPresent().extractingValue().isEqualTo("something");
|
||||||
.isPresent()
|
|
||||||
.extractingValue()
|
|
||||||
.isEqualTo("something");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
|
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||||
final Range<String> range = Range.openClosed("a", "g");
|
final Range<String> range = Range.openClosed("a", "g");
|
||||||
|
|
||||||
assertThat(range)
|
assertThat(range).hasOpenedLowerBound().isNotEmpty().hasClosedUpperBound().contains("b");
|
||||||
.hasOpenedLowerBound()
|
|
||||||
.isNotEmpty()
|
|
||||||
.hasClosedUpperBound()
|
|
||||||
.contains("b");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -96,10 +80,7 @@ public class AssertJGuavaTest {
|
|||||||
map.put(Range.closed(0, 60), "F");
|
map.put(Range.closed(0, 60), "F");
|
||||||
map.put(Range.closed(61, 70), "D");
|
map.put(Range.closed(61, 70), "D");
|
||||||
|
|
||||||
assertThat(map)
|
assertThat(map).isNotEmpty().containsKeys(0).contains(MapEntry.entry(34, "F"));
|
||||||
.isNotEmpty()
|
|
||||||
.containsKeys(0)
|
|
||||||
.contains(MapEntry.entry(34, "F"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -109,13 +90,7 @@ public class AssertJGuavaTest {
|
|||||||
table.put(1, "A", "PRESENT");
|
table.put(1, "A", "PRESENT");
|
||||||
table.put(1, "B", "ABSENT");
|
table.put(1, "B", "ABSENT");
|
||||||
|
|
||||||
assertThat(table)
|
assertThat(table).hasRowCount(1).containsValues("ABSENT").containsCell(1, "B", "ABSENT");
|
||||||
.hasRowCount(1)
|
|
||||||
.containsValues("ABSENT")
|
|
||||||
.containsCell(1, "B", "ABSENT");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -20,20 +20,14 @@ public class AssertJJava8Test {
|
|||||||
public void givenOptional_shouldAssert() throws Exception {
|
public void givenOptional_shouldAssert() throws Exception {
|
||||||
final Optional<String> givenOptional = Optional.of("something");
|
final Optional<String> givenOptional = Optional.of("something");
|
||||||
|
|
||||||
assertThat(givenOptional)
|
assertThat(givenOptional).isPresent().hasValue("something");
|
||||||
.isPresent()
|
|
||||||
.hasValue("something");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPredicate_shouldAssert() throws Exception {
|
public void givenPredicate_shouldAssert() throws Exception {
|
||||||
final Predicate<String> predicate = s -> s.length() > 4;
|
final Predicate<String> predicate = s -> s.length() > 4;
|
||||||
|
|
||||||
assertThat(predicate)
|
assertThat(predicate).accepts("aaaaa", "bbbbb").rejects("a", "b").acceptsAll(asList("aaaaa", "bbbbb")).rejectsAll(asList("a", "b"));
|
||||||
.accepts("aaaaa", "bbbbb")
|
|
||||||
.rejects("a", "b")
|
|
||||||
.acceptsAll(asList("aaaaa", "bbbbb"))
|
|
||||||
.rejectsAll(asList("a", "b"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -41,74 +35,58 @@ public class AssertJJava8Test {
|
|||||||
final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
|
final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
|
||||||
final LocalDate todayDate = LocalDate.now();
|
final LocalDate todayDate = LocalDate.now();
|
||||||
|
|
||||||
assertThat(givenLocalDate)
|
assertThat(givenLocalDate).isBefore(LocalDate.of(2020, 7, 8)).isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
||||||
.isBefore(LocalDate.of(2020, 7, 8))
|
|
||||||
.isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
|
||||||
|
|
||||||
assertThat(todayDate)
|
assertThat(todayDate).isAfter(LocalDate.of(1989, 7, 8)).isToday();
|
||||||
.isAfter(LocalDate.of(1989, 7, 8))
|
|
||||||
.isToday();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenLocalDateTime_shouldAssert() throws Exception {
|
public void givenLocalDateTime_shouldAssert() throws Exception {
|
||||||
final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
|
final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
|
||||||
|
|
||||||
assertThat(givenLocalDate)
|
assertThat(givenLocalDate).isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
||||||
.isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenLocalTime_shouldAssert() throws Exception {
|
public void givenLocalTime_shouldAssert() throws Exception {
|
||||||
final LocalTime givenLocalTime = LocalTime.of(12, 15);
|
final LocalTime givenLocalTime = LocalTime.of(12, 15);
|
||||||
|
|
||||||
assertThat(givenLocalTime)
|
assertThat(givenLocalTime).isAfter(LocalTime.of(1, 0)).hasSameHourAs(LocalTime.of(12, 0));
|
||||||
.isAfter(LocalTime.of(1, 0))
|
|
||||||
.hasSameHourAs(LocalTime.of(12, 0));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldAssertFlatExtracting() throws Exception {
|
public void givenList_shouldAssertFlatExtracting() throws Exception {
|
||||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).flatExtracting(LocalDate::getYear).contains(2015);
|
||||||
.flatExtracting(LocalDate::getYear)
|
|
||||||
.contains(2015);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
|
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
|
||||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).flatExtracting(LocalDate::isLeapYear).contains(true);
|
||||||
.flatExtracting(LocalDate::isLeapYear)
|
|
||||||
.contains(true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldAssertFlatExtractingClass() throws Exception {
|
public void givenList_shouldAssertFlatExtractingClass() throws Exception {
|
||||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).flatExtracting(Object::getClass).contains(LocalDate.class);
|
||||||
.flatExtracting(Object::getClass)
|
|
||||||
.contains(LocalDate.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
|
public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
|
||||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth).contains(2015, 6);
|
||||||
.flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth)
|
|
||||||
.contains(2015, 6);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_shouldSatisfy() throws Exception {
|
public void givenString_shouldSatisfy() throws Exception {
|
||||||
final String givenString = "someString";
|
final String givenString = "someString";
|
||||||
|
|
||||||
assertThat(givenString)
|
assertThat(givenString).satisfies(s -> {
|
||||||
.satisfies(s -> {
|
|
||||||
assertThat(s).isNotEmpty();
|
assertThat(s).isNotEmpty();
|
||||||
assertThat(s).hasSize(10);
|
assertThat(s).hasSize(10);
|
||||||
});
|
});
|
||||||
@ -118,15 +96,13 @@ public class AssertJJava8Test {
|
|||||||
public void givenString_shouldMatch() throws Exception {
|
public void givenString_shouldMatch() throws Exception {
|
||||||
final String emptyString = "";
|
final String emptyString = "";
|
||||||
|
|
||||||
assertThat(emptyString)
|
assertThat(emptyString).matches(String::isEmpty);
|
||||||
.matches(String::isEmpty);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
|
public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
|
||||||
final List<String> givenList = Arrays.asList("");
|
final List<String> givenList = Arrays.asList("");
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
||||||
.hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,18 +1,20 @@
|
|||||||
package com.baeldung.autovalue;
|
package com.baeldung.autovalue;
|
||||||
|
|
||||||
public final class ImmutableMoney {
|
public final class ImmutableMoney {
|
||||||
private final long amount;
|
private final long amount;
|
||||||
private final String currency;
|
private final String currency;
|
||||||
|
|
||||||
public ImmutableMoney(long amount, String currency) {
|
public ImmutableMoney(long amount, String currency) {
|
||||||
this.amount = amount;
|
this.amount = amount;
|
||||||
this.currency = currency;
|
this.currency = currency;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
final int prime = 31;
|
final int prime = 31;
|
||||||
int result = 1;
|
int result = 1;
|
||||||
result = prime * result + (int) (amount ^ (amount >>> 32));
|
result = prime * result + (int) (amount ^ (amount >>> 32));
|
||||||
result = prime * result
|
result = prime * result + ((currency == null) ? 0 : currency.hashCode());
|
||||||
+ ((currency == null) ? 0 : currency.hashCode());
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -45,8 +47,7 @@ public final class ImmutableMoney {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "ImmutableMoney [amount=" + amount + ", currency=" + currency
|
return "ImmutableMoney [amount=" + amount + ", currency=" + currency + "]";
|
||||||
+ "]";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -3,8 +3,7 @@ package com.baeldung.autovalue;
|
|||||||
public class MutableMoney {
|
public class MutableMoney {
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "MutableMoney [amount=" + amount + ", currency=" + currency
|
return "MutableMoney [amount=" + amount + ", currency=" + currency + "]";
|
||||||
+ "]";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public long getAmount() {
|
public long getAmount() {
|
||||||
|
@ -32,24 +32,28 @@ public class MoneyUnitTest {
|
|||||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||||
assertTrue(m1.equals(m2));
|
assertTrue(m1.equals(m2));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
|
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
|
||||||
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
|
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
|
||||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||||
assertFalse(m1.equals(m2));
|
assertFalse(m1.equals(m2));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() {
|
public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() {
|
||||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||||
assertTrue(m1.equals(m2));
|
assertTrue(m1.equals(m2));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
|
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
|
||||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
|
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
|
||||||
assertFalse(m1.equals(m2));
|
assertFalse(m1.equals(m2));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
|
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
|
||||||
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||||
|
@ -8,7 +8,6 @@ import java.time.Duration;
|
|||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
|
||||||
public class ProcessUtils {
|
public class ProcessUtils {
|
||||||
|
|
||||||
public static String getClassPath() {
|
public static String getClassPath() {
|
||||||
|
@ -8,7 +8,6 @@ public class ServiceMain {
|
|||||||
ProcessHandle thisProcess = ProcessHandle.current();
|
ProcessHandle thisProcess = ProcessHandle.current();
|
||||||
long pid = thisProcess.getPid();
|
long pid = thisProcess.getPid();
|
||||||
|
|
||||||
|
|
||||||
Optional<String[]> opArgs = Optional.ofNullable(args);
|
Optional<String[]> opArgs = Optional.ofNullable(args);
|
||||||
String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command"));
|
String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command"));
|
||||||
|
|
||||||
|
@ -19,10 +19,7 @@ public class Java9OptionalsStreamTest {
|
|||||||
public void filterOutPresentOptionalsWithFilter() {
|
public void filterOutPresentOptionalsWithFilter() {
|
||||||
assertEquals(4, listOfOptionals.size());
|
assertEquals(4, listOfOptionals.size());
|
||||||
|
|
||||||
List<String> filteredList = listOfOptionals.stream()
|
List<String> filteredList = listOfOptionals.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
|
||||||
.filter(Optional::isPresent)
|
|
||||||
.map(Optional::get)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(2, filteredList.size());
|
assertEquals(2, filteredList.size());
|
||||||
assertEquals("foo", filteredList.get(0));
|
assertEquals("foo", filteredList.get(0));
|
||||||
@ -33,9 +30,7 @@ public class Java9OptionalsStreamTest {
|
|||||||
public void filterOutPresentOptionalsWithFlatMap() {
|
public void filterOutPresentOptionalsWithFlatMap() {
|
||||||
assertEquals(4, listOfOptionals.size());
|
assertEquals(4, listOfOptionals.size());
|
||||||
|
|
||||||
List<String> filteredList = listOfOptionals.stream()
|
List<String> filteredList = listOfOptionals.stream().flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()).collect(Collectors.toList());
|
||||||
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
assertEquals(2, filteredList.size());
|
assertEquals(2, filteredList.size());
|
||||||
|
|
||||||
assertEquals("foo", filteredList.get(0));
|
assertEquals("foo", filteredList.get(0));
|
||||||
@ -46,9 +41,7 @@ public class Java9OptionalsStreamTest {
|
|||||||
public void filterOutPresentOptionalsWithFlatMap2() {
|
public void filterOutPresentOptionalsWithFlatMap2() {
|
||||||
assertEquals(4, listOfOptionals.size());
|
assertEquals(4, listOfOptionals.size());
|
||||||
|
|
||||||
List<String> filteredList = listOfOptionals.stream()
|
List<String> filteredList = listOfOptionals.stream().flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)).collect(Collectors.toList());
|
||||||
.flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
assertEquals(2, filteredList.size());
|
assertEquals(2, filteredList.size());
|
||||||
|
|
||||||
assertEquals("foo", filteredList.get(0));
|
assertEquals("foo", filteredList.get(0));
|
||||||
@ -59,9 +52,7 @@ public class Java9OptionalsStreamTest {
|
|||||||
public void filterOutPresentOptionalsWithJava9() {
|
public void filterOutPresentOptionalsWithJava9() {
|
||||||
assertEquals(4, listOfOptionals.size());
|
assertEquals(4, listOfOptionals.size());
|
||||||
|
|
||||||
List<String> filteredList = listOfOptionals.stream()
|
List<String> filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList());
|
||||||
.flatMap(Optional::stream)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(2, filteredList.size());
|
assertEquals(2, filteredList.size());
|
||||||
assertEquals("foo", filteredList.get(0));
|
assertEquals("foo", filteredList.get(0));
|
||||||
|
@ -13,7 +13,6 @@ import org.junit.Test;
|
|||||||
|
|
||||||
public class MultiResultionImageTest {
|
public class MultiResultionImageTest {
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void baseMultiResImageTest() {
|
public void baseMultiResImageTest() {
|
||||||
int baseIndex = 1;
|
int baseIndex = 1;
|
||||||
@ -38,10 +37,8 @@ public class MultiResultionImageTest {
|
|||||||
return 8 * (i + 1);
|
return 8 * (i + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private static BufferedImage createImage(int i) {
|
private static BufferedImage createImage(int i) {
|
||||||
return new BufferedImage(getSize(i), getSize(i),
|
return new BufferedImage(getSize(i), getSize(i), BufferedImage.TYPE_INT_RGB);
|
||||||
BufferedImage.TYPE_INT_RGB);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,5 @@
|
|||||||
package com.baeldung.java9.httpclient;
|
package com.baeldung.java9.httpclient;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
import static java.net.HttpURLConnection.HTTP_OK;
|
import static java.net.HttpURLConnection.HTTP_OK;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
@ -117,7 +115,9 @@ public class SimpleHttpRequestsTest {
|
|||||||
sb.append(k).append(":");
|
sb.append(k).append(":");
|
||||||
List<String> l = hMap.get(k);
|
List<String> l = hMap.get(k);
|
||||||
if (l != null) {
|
if (l != null) {
|
||||||
l.forEach( s -> { sb.append(s).append(","); } );
|
l.forEach(s -> {
|
||||||
|
sb.append(s).append(",");
|
||||||
|
});
|
||||||
}
|
}
|
||||||
sb.append("\n");
|
sb.append("\n");
|
||||||
}
|
}
|
||||||
|
@ -57,7 +57,6 @@ public class TryWithResourcesTest {
|
|||||||
assertEquals("Expected and Actual does not match", 5, closeCount);
|
assertEquals("Expected and Actual does not match", 5, closeCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
static class CloseableException extends Exception implements AutoCloseable {
|
static class CloseableException extends Exception implements AutoCloseable {
|
||||||
@Override
|
@Override
|
||||||
public void close() {
|
public void close() {
|
||||||
@ -66,5 +65,3 @@ public class TryWithResourcesTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -0,0 +1,61 @@
|
|||||||
|
package com.baeldung.java9.language.stream;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class CollectorImprovementTest {
|
||||||
|
@Test
|
||||||
|
public void givenList_whenSatifyPredicate_thenMapValueWithOccurences() {
|
||||||
|
List<Integer> numbers = List.of(1, 2, 3, 5, 5);
|
||||||
|
|
||||||
|
Map<Integer, Long> result = numbers.stream().filter(val -> val > 3).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
|
||||||
|
result = numbers.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.filtering(val -> val > 3, Collectors.counting())));
|
||||||
|
|
||||||
|
assertEquals(4, result.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenListOfBlogs_whenAuthorName_thenMapAuthorWithComments() {
|
||||||
|
Blog blog1 = new Blog("1", "Nice", "Very Nice");
|
||||||
|
Blog blog2 = new Blog("2", "Disappointing", "Ok", "Could be better");
|
||||||
|
List<Blog> blogs = List.of(blog1, blog2);
|
||||||
|
|
||||||
|
Map<String, List<List<String>>> authorComments1 = blogs.stream().collect(Collectors.groupingBy(Blog::getAuthorName, Collectors.mapping(Blog::getComments, Collectors.toList())));
|
||||||
|
|
||||||
|
assertEquals(2, authorComments1.size());
|
||||||
|
assertEquals(2, authorComments1.get("1").get(0).size());
|
||||||
|
assertEquals(3, authorComments1.get("2").get(0).size());
|
||||||
|
|
||||||
|
Map<String, List<String>> authorComments2 = blogs.stream().collect(Collectors.groupingBy(Blog::getAuthorName, Collectors.flatMapping(blog -> blog.getComments().stream(), Collectors.toList())));
|
||||||
|
|
||||||
|
assertEquals(2, authorComments2.size());
|
||||||
|
assertEquals(2, authorComments2.get("1").size());
|
||||||
|
assertEquals(3, authorComments2.get("2").size());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Blog {
|
||||||
|
private String authorName;
|
||||||
|
private List<String> comments;
|
||||||
|
|
||||||
|
public Blog(String authorName, String... comments) {
|
||||||
|
this.authorName = authorName;
|
||||||
|
this.comments = List.of(comments);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAuthorName() {
|
||||||
|
return this.authorName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> getComments() {
|
||||||
|
return this.comments;
|
||||||
|
}
|
||||||
|
}
|
@ -17,16 +17,11 @@ public class StreamFeaturesTest {
|
|||||||
public static class TakeAndDropWhileTest {
|
public static class TakeAndDropWhileTest {
|
||||||
|
|
||||||
public Stream<String> getStreamAfterTakeWhileOperation() {
|
public Stream<String> getStreamAfterTakeWhileOperation() {
|
||||||
return Stream
|
return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10);
|
||||||
.iterate("", s -> s + "s")
|
|
||||||
.takeWhile(s -> s.length() < 10);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Stream<String> getStreamAfterDropWhileOperation() {
|
public Stream<String> getStreamAfterDropWhileOperation() {
|
||||||
return Stream
|
return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10).dropWhile(s -> !s.contains("sssss"));
|
||||||
.iterate("", s -> s + "s")
|
|
||||||
.takeWhile(s -> s.length() < 10)
|
|
||||||
.dropWhile(s -> !s.contains("sssss"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -75,19 +70,19 @@ public class StreamFeaturesTest {
|
|||||||
public static class OfNullableTest {
|
public static class OfNullableTest {
|
||||||
|
|
||||||
private List<String> collection = Arrays.asList("A", "B", "C");
|
private List<String> collection = Arrays.asList("A", "B", "C");
|
||||||
private Map<String, Integer> map = new HashMap<>() {{
|
private Map<String, Integer> map = new HashMap<>() {
|
||||||
|
{
|
||||||
put("A", 10);
|
put("A", 10);
|
||||||
put("C", 30);
|
put("C", 30);
|
||||||
}};
|
}
|
||||||
|
};
|
||||||
|
|
||||||
private Stream<Integer> getStreamWithOfNullable() {
|
private Stream<Integer> getStreamWithOfNullable() {
|
||||||
return collection.stream()
|
return collection.stream().flatMap(s -> Stream.ofNullable(map.get(s)));
|
||||||
.flatMap(s -> Stream.ofNullable(map.get(s)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Stream<Integer> getStream() {
|
private Stream<Integer> getStream() {
|
||||||
return collection.stream()
|
return collection.stream().flatMap(s -> {
|
||||||
.flatMap(s -> {
|
|
||||||
Integer temp = map.get(s);
|
Integer temp = map.get(s);
|
||||||
return temp != null ? Stream.of(temp) : Stream.empty();
|
return temp != null ? Stream.of(temp) : Stream.empty();
|
||||||
});
|
});
|
||||||
@ -107,10 +102,7 @@ public class StreamFeaturesTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testOfNullable() {
|
public void testOfNullable() {
|
||||||
|
|
||||||
assertEquals(
|
assertEquals(testOfNullableFrom(getStream()), testOfNullableFrom(getStreamWithOfNullable()));
|
||||||
testOfNullableFrom(getStream()),
|
|
||||||
testOfNullableFrom(getStreamWithOfNullable())
|
|
||||||
);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -22,7 +22,6 @@ import static org.junit.Assert.assertTrue;
|
|||||||
|
|
||||||
public class ProcessApi {
|
public class ProcessApi {
|
||||||
|
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void init() {
|
public void init() {
|
||||||
|
|
||||||
|
@ -15,8 +15,7 @@ public class RunAlgorithm {
|
|||||||
int decision = in.nextInt();
|
int decision = in.nextInt();
|
||||||
switch (decision) {
|
switch (decision) {
|
||||||
case 1:
|
case 1:
|
||||||
System.out.println(
|
System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||||
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
|
||||||
break;
|
break;
|
||||||
case 2:
|
case 2:
|
||||||
SlopeOne.slopeOne(3);
|
SlopeOne.slopeOne(3);
|
||||||
|
@ -12,8 +12,7 @@ import lombok.Data;
|
|||||||
@Data
|
@Data
|
||||||
public class InputData {
|
public class InputData {
|
||||||
|
|
||||||
protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"),
|
protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), new Item("Snacks"));
|
||||||
new Item("Snacks"));
|
|
||||||
|
|
||||||
public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) {
|
public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) {
|
||||||
Map<User, HashMap<Item, Double>> data = new HashMap<>();
|
Map<User, HashMap<Item, Double>> data = new HashMap<>();
|
||||||
|
@ -23,8 +23,7 @@ public class LogWithChain {
|
|||||||
try {
|
try {
|
||||||
howIsManager();
|
howIsManager();
|
||||||
} catch (ManagerUpsetException e) {
|
} catch (ManagerUpsetException e) {
|
||||||
throw new TeamLeadUpsetException(
|
throw new TeamLeadUpsetException("Team lead is not in good mood", e);
|
||||||
"Team lead is not in good mood", e);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,9 +35,7 @@ public class LogWithChain {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void howIsGirlFriendOfManager()
|
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||||
throws GirlFriendOfManagerUpsetException {
|
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
|
||||||
throw new GirlFriendOfManagerUpsetException(
|
|
||||||
"Girl friend of manager is in bad mood");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -25,8 +25,7 @@ public class LogWithoutChain {
|
|||||||
howIsManager();
|
howIsManager();
|
||||||
} catch (ManagerUpsetException e) {
|
} catch (ManagerUpsetException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
throw new TeamLeadUpsetException(
|
throw new TeamLeadUpsetException("Team lead is not in good mood");
|
||||||
"Team lead is not in good mood");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -39,9 +38,7 @@ public class LogWithoutChain {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void howIsGirlFriendOfManager()
|
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||||
throws GirlFriendOfManagerUpsetException {
|
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
|
||||||
throw new GirlFriendOfManagerUpsetException(
|
|
||||||
"Girl friend of manager is in bad mood");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.concurrent.blockingqueue;
|
||||||
|
|
||||||
|
import java.util.concurrent.BlockingQueue;
|
||||||
|
import java.util.concurrent.LinkedBlockingQueue;
|
||||||
|
|
||||||
|
public class BlockingQueueUsage {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
int BOUND = 10;
|
||||||
|
int N_PRODUCERS = 4;
|
||||||
|
int N_CONSUMERS = Runtime.getRuntime().availableProcessors();
|
||||||
|
int poisonPill = Integer.MAX_VALUE;
|
||||||
|
int poisonPillPerProducer = N_CONSUMERS / N_PRODUCERS;
|
||||||
|
|
||||||
|
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(BOUND);
|
||||||
|
|
||||||
|
for (int i = 0; i < N_PRODUCERS; i++) {
|
||||||
|
new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer)).start();
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int j = 0; j < N_CONSUMERS; j++) {
|
||||||
|
new Thread(new NumbersConsumer(queue, poisonPill)).start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.concurrent.blockingqueue;
|
||||||
|
|
||||||
|
import java.util.concurrent.BlockingQueue;
|
||||||
|
|
||||||
|
public class NumbersConsumer implements Runnable {
|
||||||
|
private final BlockingQueue<Integer> queue;
|
||||||
|
private final int poisonPill;
|
||||||
|
|
||||||
|
public NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) {
|
||||||
|
this.queue = queue;
|
||||||
|
this.poisonPill = poisonPill;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
Integer number = queue.take();
|
||||||
|
if (number.equals(poisonPill)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String result = number.toString();
|
||||||
|
System.out.println(Thread.currentThread().getName() + " result: " + result);
|
||||||
|
}
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.concurrent.blockingqueue;
|
||||||
|
|
||||||
|
import java.util.concurrent.BlockingQueue;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
public class NumbersProducer implements Runnable {
|
||||||
|
|
||||||
|
private final BlockingQueue<Integer> numbersQueue;
|
||||||
|
private final int poisonPill;
|
||||||
|
private final int poisonPillPerProducer;
|
||||||
|
|
||||||
|
public NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) {
|
||||||
|
this.numbersQueue = numbersQueue;
|
||||||
|
this.poisonPill = poisonPill;
|
||||||
|
this.poisonPillPerProducer = poisonPillPerProducer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
try {
|
||||||
|
generateNumbers();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void generateNumbers() throws InterruptedException {
|
||||||
|
for (int i = 0; i < 100; i++) {
|
||||||
|
numbersQueue.put(ThreadLocalRandom.current().nextInt(100));
|
||||||
|
}
|
||||||
|
for (int j = 0; j < poisonPillPerProducer; j++) {
|
||||||
|
numbersQueue.put(poisonPill);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.concurrent.countdownlatch;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
|
||||||
|
public class BrokenWorker implements Runnable {
|
||||||
|
private final List<String> outputScraper;
|
||||||
|
private final CountDownLatch countDownLatch;
|
||||||
|
|
||||||
|
public BrokenWorker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||||
|
this.outputScraper = outputScraper;
|
||||||
|
this.countDownLatch = countDownLatch;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
if (true) {
|
||||||
|
throw new RuntimeException("Oh dear");
|
||||||
|
}
|
||||||
|
countDownLatch.countDown();
|
||||||
|
outputScraper.add("Counted down");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.concurrent.countdownlatch;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
|
||||||
|
public class WaitingWorker implements Runnable {
|
||||||
|
|
||||||
|
private final List<String> outputScraper;
|
||||||
|
private final CountDownLatch readyThreadCounter;
|
||||||
|
private final CountDownLatch callingThreadBlocker;
|
||||||
|
private final CountDownLatch completedThreadCounter;
|
||||||
|
|
||||||
|
public WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
|
||||||
|
|
||||||
|
this.outputScraper = outputScraper;
|
||||||
|
this.readyThreadCounter = readyThreadCounter;
|
||||||
|
this.callingThreadBlocker = callingThreadBlocker;
|
||||||
|
this.completedThreadCounter = completedThreadCounter;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
// Mark this thread as read / started
|
||||||
|
readyThreadCounter.countDown();
|
||||||
|
try {
|
||||||
|
callingThreadBlocker.await();
|
||||||
|
outputScraper.add("Counted down");
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
} finally {
|
||||||
|
completedThreadCounter.countDown();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.concurrent.countdownlatch;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
|
||||||
|
public class Worker implements Runnable {
|
||||||
|
private final List<String> outputScraper;
|
||||||
|
private final CountDownLatch countDownLatch;
|
||||||
|
|
||||||
|
public Worker(final List<String> outputScraper, final CountDownLatch countDownLatch) {
|
||||||
|
this.outputScraper = outputScraper;
|
||||||
|
this.countDownLatch = countDownLatch;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
// Do some work
|
||||||
|
System.out.println("Doing some logic");
|
||||||
|
outputScraper.add("Counted down");
|
||||||
|
countDownLatch.countDown();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.concurrent.future;
|
||||||
|
|
||||||
|
import java.util.concurrent.RecursiveTask;
|
||||||
|
|
||||||
|
public class FactorialSquareCalculator extends RecursiveTask<Integer> {
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
final private Integer n;
|
||||||
|
|
||||||
|
public FactorialSquareCalculator(Integer n) {
|
||||||
|
this.n = n;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Integer compute() {
|
||||||
|
if (n <= 1) {
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
FactorialSquareCalculator calculator = new FactorialSquareCalculator(n - 1);
|
||||||
|
|
||||||
|
calculator.fork();
|
||||||
|
|
||||||
|
return n * n + calculator.join();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.concurrent.future;
|
||||||
|
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
|
public class SquareCalculator {
|
||||||
|
|
||||||
|
private final ExecutorService executor;
|
||||||
|
|
||||||
|
public SquareCalculator(ExecutorService executor) {
|
||||||
|
this.executor = executor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Future<Integer> calculate(Integer input) {
|
||||||
|
return executor.submit(new Callable<Integer>() {
|
||||||
|
@Override
|
||||||
|
public Integer call() throws Exception {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
return input * input;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -11,12 +11,10 @@ public class MyLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
|
|||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
private static final int MAX_ENTRIES = 5;
|
private static final int MAX_ENTRIES = 5;
|
||||||
|
|
||||||
|
|
||||||
public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
|
public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
|
||||||
super(initialCapacity, loadFactor, accessOrder);
|
super(initialCapacity, loadFactor, accessOrder);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean removeEldestEntry(Map.Entry eldest) {
|
protected boolean removeEldestEntry(Map.Entry eldest) {
|
||||||
return size() > MAX_ENTRIES;
|
return size() > MAX_ENTRIES;
|
||||||
|
@ -42,116 +42,80 @@ public class Java8CollectorsUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
||||||
final List<String> result = givenList
|
final List<String> result = givenList.stream().collect(toList());
|
||||||
.stream()
|
|
||||||
.collect(toList());
|
|
||||||
|
|
||||||
assertThat(result).containsAll(givenList);
|
assertThat(result).containsAll(givenList);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
||||||
final Set<String> result = givenList
|
final Set<String> result = givenList.stream().collect(toSet());
|
||||||
.stream()
|
|
||||||
.collect(toSet());
|
|
||||||
|
|
||||||
assertThat(result).containsAll(givenList);
|
assertThat(result).containsAll(givenList);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
||||||
final List<String> result = givenList
|
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
|
||||||
.stream()
|
|
||||||
.collect(toCollection(LinkedList::new));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
|
||||||
.containsAll(givenList)
|
|
||||||
.isInstanceOf(LinkedList.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
||||||
assertThatThrownBy(() -> {
|
assertThatThrownBy(() -> {
|
||||||
givenList
|
givenList.stream().collect(toCollection(ImmutableList::of));
|
||||||
.stream()
|
|
||||||
.collect(toCollection(ImmutableList::of));
|
|
||||||
}).isInstanceOf(UnsupportedOperationException.class);
|
}).isInstanceOf(UnsupportedOperationException.class);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
||||||
final Map<String, Integer> result = givenList
|
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
|
||||||
.stream()
|
|
||||||
.collect(toMap(Function.identity(), String::length));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||||
.containsEntry("a", 1)
|
|
||||||
.containsEntry("bb", 2)
|
|
||||||
.containsEntry("ccc", 3)
|
|
||||||
.containsEntry("dd", 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
||||||
final Map<String, Integer> result = givenList
|
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||||
.stream()
|
|
||||||
.collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||||
.containsEntry("a", 1)
|
|
||||||
.containsEntry("bb", 2)
|
|
||||||
.containsEntry("ccc", 3)
|
|
||||||
.containsEntry("dd", 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
||||||
final List<String> result = givenList
|
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||||
.stream()
|
|
||||||
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
|
||||||
.containsAll(givenList)
|
|
||||||
.isInstanceOf(ImmutableList.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoining_shouldJoin() throws Exception {
|
public void whenJoining_shouldJoin() throws Exception {
|
||||||
final String result = givenList
|
final String result = givenList.stream().collect(joining());
|
||||||
.stream()
|
|
||||||
.collect(joining());
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo("abbcccdd");
|
assertThat(result).isEqualTo("abbcccdd");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
||||||
final String result = givenList
|
final String result = givenList.stream().collect(joining(" "));
|
||||||
.stream()
|
|
||||||
.collect(joining(" "));
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo("a bb ccc dd");
|
assertThat(result).isEqualTo("a bb ccc dd");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
||||||
final String result = givenList
|
final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
|
||||||
.stream()
|
|
||||||
.collect(joining(" ", "PRE-", "-POST"));
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPartitioningBy_shouldPartition() throws Exception {
|
public void whenPartitioningBy_shouldPartition() throws Exception {
|
||||||
final Map<Boolean, List<String>> result = givenList
|
final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
|
||||||
.stream()
|
|
||||||
.collect(partitioningBy(s -> s.length() > 2));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
|
||||||
.containsKeys(true, false)
|
|
||||||
.satisfies(booleanListMap -> {
|
|
||||||
assertThat(booleanListMap.get(true)).contains("ccc");
|
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||||
|
|
||||||
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
|
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
|
||||||
@ -160,18 +124,14 @@ public class Java8CollectorsUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCounting_shouldCount() throws Exception {
|
public void whenCounting_shouldCount() throws Exception {
|
||||||
final Long result = givenList
|
final Long result = givenList.stream().collect(counting());
|
||||||
.stream()
|
|
||||||
.collect(counting());
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo(4);
|
assertThat(result).isEqualTo(4);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSummarizing_shouldSummarize() throws Exception {
|
public void whenSummarizing_shouldSummarize() throws Exception {
|
||||||
final DoubleSummaryStatistics result = givenList
|
final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
|
||||||
.stream()
|
|
||||||
.collect(summarizingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result.getAverage()).isEqualTo(2);
|
assertThat(result.getAverage()).isEqualTo(2);
|
||||||
assertThat(result.getCount()).isEqualTo(4);
|
assertThat(result.getCount()).isEqualTo(4);
|
||||||
@ -182,55 +142,37 @@ public class Java8CollectorsUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAveraging_shouldAverage() throws Exception {
|
public void whenAveraging_shouldAverage() throws Exception {
|
||||||
final Double result = givenList
|
final Double result = givenList.stream().collect(averagingDouble(String::length));
|
||||||
.stream()
|
|
||||||
.collect(averagingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo(2);
|
assertThat(result).isEqualTo(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSumming_shouldSum() throws Exception {
|
public void whenSumming_shouldSum() throws Exception {
|
||||||
final Double result = givenList
|
final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length));
|
||||||
.stream()
|
|
||||||
.filter(i -> true)
|
|
||||||
.collect(summingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo(8);
|
assertThat(result).isEqualTo(8);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
||||||
final Optional<String> result = givenList
|
final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
|
||||||
.stream()
|
|
||||||
.collect(maxBy(Comparator.naturalOrder()));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isPresent().hasValue("dd");
|
||||||
.isPresent()
|
|
||||||
.hasValue("dd");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
||||||
final Map<Integer, Set<String>> result = givenList
|
final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
|
||||||
.stream()
|
|
||||||
.collect(groupingBy(String::length, toSet()));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
|
||||||
.containsEntry(1, newHashSet("a"))
|
|
||||||
.containsEntry(2, newHashSet("bb", "dd"))
|
|
||||||
.containsEntry(3, newHashSet("ccc"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
||||||
final ImmutableSet<String> result = givenList
|
final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
|
||||||
.stream()
|
|
||||||
.collect(toImmutableSet());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
|
||||||
.isInstanceOf(ImmutableSet.class)
|
|
||||||
.contains("a", "bb", "ccc", "dd");
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -0,0 +1,70 @@
|
|||||||
|
package com.baeldung.concurrent.countdownlatch;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static java.util.stream.Collectors.toList;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
public class CountdownLatchExampleTest {
|
||||||
|
@Test
|
||||||
|
public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() throws InterruptedException {
|
||||||
|
// Given
|
||||||
|
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
|
||||||
|
CountDownLatch countDownLatch = new CountDownLatch(5);
|
||||||
|
List<Thread> workers = Stream.generate(() -> new Thread(new Worker(outputScraper, countDownLatch))).limit(5).collect(toList());
|
||||||
|
|
||||||
|
// When
|
||||||
|
workers.forEach(Thread::start);
|
||||||
|
countDownLatch.await(); // Block until workers finish
|
||||||
|
outputScraper.add("Latch released");
|
||||||
|
|
||||||
|
// Then
|
||||||
|
outputScraper.forEach(Object::toString);
|
||||||
|
assertThat(outputScraper).containsExactly("Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Latch released");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFailingToParallelProcess_thenMainThreadShouldTimeout() throws InterruptedException {
|
||||||
|
// Given
|
||||||
|
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
|
||||||
|
CountDownLatch countDownLatch = new CountDownLatch(5);
|
||||||
|
List<Thread> workers = Stream.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch))).limit(5).collect(toList());
|
||||||
|
|
||||||
|
// When
|
||||||
|
workers.forEach(Thread::start);
|
||||||
|
final boolean result = countDownLatch.await(3L, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
// Then
|
||||||
|
assertThat(result).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDoingLotsOfThreadsInParallel_thenStartThemAtTheSameTime() throws InterruptedException {
|
||||||
|
// Given
|
||||||
|
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
|
||||||
|
CountDownLatch readyThreadCounter = new CountDownLatch(5);
|
||||||
|
CountDownLatch callingThreadBlocker = new CountDownLatch(1);
|
||||||
|
CountDownLatch completedThreadCounter = new CountDownLatch(5);
|
||||||
|
List<Thread> workers = Stream.generate(() -> new Thread(new WaitingWorker(outputScraper, readyThreadCounter, callingThreadBlocker, completedThreadCounter))).limit(5).collect(toList());
|
||||||
|
|
||||||
|
// When
|
||||||
|
workers.forEach(Thread::start);
|
||||||
|
readyThreadCounter.await(); // Block until workers start
|
||||||
|
outputScraper.add("Workers ready");
|
||||||
|
callingThreadBlocker.countDown(); // Start workers
|
||||||
|
completedThreadCounter.await(); // Block until workers finish
|
||||||
|
outputScraper.add("Workers complete");
|
||||||
|
|
||||||
|
// Then
|
||||||
|
outputScraper.forEach(Object::toString);
|
||||||
|
assertThat(outputScraper).containsExactly("Workers ready", "Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Workers complete");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.concurrent.future;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.concurrent.ForkJoinPool;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class FactorialSquareCalculatorUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCalculatesFactorialSquare_thenReturnCorrectValue() {
|
||||||
|
ForkJoinPool forkJoinPool = new ForkJoinPool();
|
||||||
|
|
||||||
|
FactorialSquareCalculator calculator = new FactorialSquareCalculator(10);
|
||||||
|
|
||||||
|
forkJoinPool.execute(calculator);
|
||||||
|
|
||||||
|
assertEquals("The sum of the squares from 1 to 10 is 385", 385, calculator.join().intValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,94 @@
|
|||||||
|
package com.baeldung.concurrent.future;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.concurrent.CancellationException;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.TimeoutException;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.rules.TestName;
|
||||||
|
|
||||||
|
public class SquareCalculatorUnitTest {
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public TestName name = new TestName();
|
||||||
|
|
||||||
|
private long start;
|
||||||
|
|
||||||
|
private SquareCalculator squareCalculator;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExecutorIsSingleThreaded_whenTwoExecutionsAreTriggered_thenRunInSequence() throws InterruptedException, ExecutionException {
|
||||||
|
squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor());
|
||||||
|
|
||||||
|
Future<Integer> result1 = squareCalculator.calculate(4);
|
||||||
|
Future<Integer> result2 = squareCalculator.calculate(1000);
|
||||||
|
|
||||||
|
while (!result1.isDone() || !result2.isDone()) {
|
||||||
|
System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done"));
|
||||||
|
|
||||||
|
Thread.sleep(300);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(16, result1.get().intValue());
|
||||||
|
assertEquals(1000000, result2.get().intValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = TimeoutException.class)
|
||||||
|
public void whenGetWithTimeoutLowerThanExecutionTime_thenThrowException() throws InterruptedException, ExecutionException, TimeoutException {
|
||||||
|
squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor());
|
||||||
|
|
||||||
|
Future<Integer> result = squareCalculator.calculate(4);
|
||||||
|
|
||||||
|
result.get(500, TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExecutorIsMultiThreaded_whenTwoExecutionsAreTriggered_thenRunInParallel() throws InterruptedException, ExecutionException {
|
||||||
|
squareCalculator = new SquareCalculator(Executors.newFixedThreadPool(2));
|
||||||
|
|
||||||
|
Future<Integer> result1 = squareCalculator.calculate(4);
|
||||||
|
Future<Integer> result2 = squareCalculator.calculate(1000);
|
||||||
|
|
||||||
|
while (!result1.isDone() || !result2.isDone()) {
|
||||||
|
System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done"));
|
||||||
|
|
||||||
|
Thread.sleep(300);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(16, result1.get().intValue());
|
||||||
|
assertEquals(1000000, result2.get().intValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = CancellationException.class)
|
||||||
|
public void whenCancelFutureAndCallGet_thenThrowException() throws InterruptedException, ExecutionException, TimeoutException {
|
||||||
|
squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor());
|
||||||
|
|
||||||
|
Future<Integer> result = squareCalculator.calculate(4);
|
||||||
|
|
||||||
|
boolean canceled = result.cancel(true);
|
||||||
|
|
||||||
|
assertTrue("Future was canceled", canceled);
|
||||||
|
assertTrue("Future was canceled", result.isCancelled());
|
||||||
|
|
||||||
|
result.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void start() {
|
||||||
|
start = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void end() {
|
||||||
|
System.out.println(String.format("Test %s took %s ms \n", name.getMethodName(), System.currentTimeMillis() - start));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,76 @@
|
|||||||
|
package com.baeldung.java.concurrentmap;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotEquals;
|
||||||
|
|
||||||
|
public class ConcurrentMapAggregateStatusTest {
|
||||||
|
|
||||||
|
private ExecutorService executorService;
|
||||||
|
private Map<String, Integer> concurrentMap;
|
||||||
|
private List<Integer> mapSizes;
|
||||||
|
private int MAX_SIZE = 100000;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
executorService = Executors.newFixedThreadPool(2);
|
||||||
|
concurrentMap = new ConcurrentHashMap<>();
|
||||||
|
mapSizes = new ArrayList<>(MAX_SIZE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenConcurrentMap_whenSizeWithoutConcurrentUpdates_thenCorrect() throws InterruptedException {
|
||||||
|
Runnable collectMapSizes = () -> {
|
||||||
|
for (int i = 0; i < MAX_SIZE; i++) {
|
||||||
|
concurrentMap.put(String.valueOf(i), i);
|
||||||
|
mapSizes.add(concurrentMap.size());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Runnable retrieveMapData = () -> {
|
||||||
|
for (int i = 0; i < MAX_SIZE; i++) {
|
||||||
|
concurrentMap.get(String.valueOf(i));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
executorService.execute(retrieveMapData);
|
||||||
|
executorService.execute(collectMapSizes);
|
||||||
|
executorService.shutdown();
|
||||||
|
executorService.awaitTermination(1, TimeUnit.MINUTES);
|
||||||
|
|
||||||
|
for (int i = 1; i <= MAX_SIZE; i++) {
|
||||||
|
assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1).intValue());
|
||||||
|
}
|
||||||
|
assertEquals(MAX_SIZE, concurrentMap.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenConcurrentMap_whenUpdatingAndGetSize_thenError() throws InterruptedException {
|
||||||
|
Runnable collectMapSizes = () -> {
|
||||||
|
for (int i = 0; i < MAX_SIZE; i++) {
|
||||||
|
mapSizes.add(concurrentMap.size());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Runnable updateMapData = () -> {
|
||||||
|
for (int i = 0; i < MAX_SIZE; i++) {
|
||||||
|
concurrentMap.put(String.valueOf(i), i);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
executorService.execute(updateMapData);
|
||||||
|
executorService.execute(collectMapSizes);
|
||||||
|
executorService.shutdown();
|
||||||
|
executorService.awaitTermination(1, TimeUnit.MINUTES);
|
||||||
|
|
||||||
|
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1).intValue());
|
||||||
|
assertEquals(MAX_SIZE, concurrentMap.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,160 @@
|
|||||||
|
package com.baeldung.java.concurrentmap;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.ConcurrentMap;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
|
||||||
|
public class ConcurrentMapNullKeyValueTest {
|
||||||
|
|
||||||
|
ConcurrentMap<String, Object> concurrentMap;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() {
|
||||||
|
concurrentMap = new ConcurrentHashMap<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenGetWithNullKey_thenThrowsNPE() {
|
||||||
|
concurrentMap.get(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenGetOrDefaultWithNullKey_thenThrowsNPE() {
|
||||||
|
concurrentMap.getOrDefault(null, new Object());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenPutWithNullKey_thenThrowsNPE() {
|
||||||
|
concurrentMap.put(null, new Object());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenPutNullValue_thenThrowsNPE() {
|
||||||
|
concurrentMap.put("test", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMapAndKeyAbsent_whenPutWithNullKey_thenThrowsNPE() {
|
||||||
|
concurrentMap.putIfAbsent(null, new Object());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMapAndMapWithNullKey_whenPutNullKeyMap_thenThrowsNPE() {
|
||||||
|
Map<String, Object> nullKeyMap = new HashMap<>();
|
||||||
|
nullKeyMap.put(null, new Object());
|
||||||
|
concurrentMap.putAll(nullKeyMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMapAndMapWithNullValue_whenPutNullValueMap_thenThrowsNPE() {
|
||||||
|
Map<String, Object> nullValueMap = new HashMap<>();
|
||||||
|
nullValueMap.put("test", null);
|
||||||
|
concurrentMap.putAll(nullValueMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenReplaceNullKeyWithValues_thenThrowsNPE() {
|
||||||
|
concurrentMap.replace(null, new Object(), new Object());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenReplaceWithNullNewValue_thenThrowsNPE() {
|
||||||
|
Object o = new Object();
|
||||||
|
concurrentMap.replace("test", o, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenReplaceOldNullValue_thenThrowsNPE() {
|
||||||
|
Object o = new Object();
|
||||||
|
concurrentMap.replace("test", null, o);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenReplaceWithNullValue_thenThrowsNPE() {
|
||||||
|
concurrentMap.replace("test", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenReplaceNullKey_thenThrowsNPE() {
|
||||||
|
concurrentMap.replace(null, "test");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenReplaceAllMappingNull_thenThrowsNPE() {
|
||||||
|
concurrentMap.put("test", new Object());
|
||||||
|
concurrentMap.replaceAll((s, o) -> null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenRemoveNullKey_thenThrowsNPE() {
|
||||||
|
concurrentMap.remove(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenRemoveNullKeyWithValue_thenThrowsNPE() {
|
||||||
|
concurrentMap.remove(null, new Object());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenMergeNullKeyWithValue_thenThrowsNPE() {
|
||||||
|
concurrentMap.merge(null, new Object(), (o, o2) -> o2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenMergeKeyWithNullValue_thenThrowsNPE() {
|
||||||
|
concurrentMap.put("test", new Object());
|
||||||
|
concurrentMap.merge("test", null, (o, o2) -> o2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMapAndAssumeKeyAbsent_whenComputeWithNullKey_thenThrowsNPE() {
|
||||||
|
concurrentMap.computeIfAbsent(null, s -> s);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMapAndAssumeKeyPresent_whenComputeWithNullKey_thenThrowsNPE() {
|
||||||
|
concurrentMap.computeIfPresent(null, (s, o) -> o);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void givenConcurrentHashMap_whenComputeWithNullKey_thenThrowsNPE() {
|
||||||
|
concurrentMap.compute(null, (s, o) -> o);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenConcurrentHashMap_whenMergeKeyRemappingNull_thenRemovesMapping() {
|
||||||
|
Object oldValue = new Object();
|
||||||
|
concurrentMap.put("test", oldValue);
|
||||||
|
concurrentMap.merge("test", new Object(), (o, o2) -> null);
|
||||||
|
assertNull(concurrentMap.get("test"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenConcurrentHashMapAndKeyAbsent_whenComputeWithKeyRemappingNull_thenRemainsAbsent() {
|
||||||
|
concurrentMap.computeIfPresent("test", (s, o) -> null);
|
||||||
|
assertNull(concurrentMap.get("test"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenKeyPresent_whenComputeIfPresentRemappingNull_thenMappingRemoved() {
|
||||||
|
Object oldValue = new Object();
|
||||||
|
concurrentMap.put("test", oldValue);
|
||||||
|
concurrentMap.computeIfPresent("test", (s, o) -> null);
|
||||||
|
assertNull(concurrentMap.get("test"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenKeyPresent_whenComputeRemappingNull_thenMappingRemoved() {
|
||||||
|
Object oldValue = new Object();
|
||||||
|
concurrentMap.put("test", oldValue);
|
||||||
|
concurrentMap.compute("test", (s, o) -> null);
|
||||||
|
assertNull(concurrentMap.get("test"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,95 @@
|
|||||||
|
package com.baeldung.java.concurrentmap;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Hashtable;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class ConcurrentMapPerformanceTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMaps_whenGetPut500KTimes_thenConcurrentMapFaster() throws Exception {
|
||||||
|
Map<String, Object> hashtable = new Hashtable<>();
|
||||||
|
Map<String, Object> synchronizedHashMap = Collections.synchronizedMap(new HashMap<>());
|
||||||
|
Map<String, Object> concurrentHashMap = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
long hashtableAvgRuntime = timeElapseForGetPut(hashtable);
|
||||||
|
long syncHashMapAvgRuntime = timeElapseForGetPut(synchronizedHashMap);
|
||||||
|
long concurrentHashMapAvgRuntime = timeElapseForGetPut(concurrentHashMap);
|
||||||
|
|
||||||
|
System.out.println(String.format("Hashtable: %s, syncHashMap: %s, ConcurrentHashMap: %s", hashtableAvgRuntime, syncHashMapAvgRuntime, concurrentHashMapAvgRuntime));
|
||||||
|
|
||||||
|
assertTrue(hashtableAvgRuntime > concurrentHashMapAvgRuntime);
|
||||||
|
assertTrue(syncHashMapAvgRuntime > concurrentHashMapAvgRuntime);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private long timeElapseForGetPut(Map<String, Object> map) throws InterruptedException {
|
||||||
|
ExecutorService executorService = Executors.newFixedThreadPool(4);
|
||||||
|
long startTime = System.nanoTime();
|
||||||
|
for (int i = 0; i < 4; i++) {
|
||||||
|
executorService.execute(() -> {
|
||||||
|
for (int j = 0; j < 500_000; j++) {
|
||||||
|
int value = ThreadLocalRandom.current().nextInt(10000);
|
||||||
|
String key = String.valueOf(value);
|
||||||
|
map.put(key, value);
|
||||||
|
map.get(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
executorService.shutdown();
|
||||||
|
executorService.awaitTermination(1, TimeUnit.MINUTES);
|
||||||
|
return (System.nanoTime() - startTime) / 500_000;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenConcurrentMap_whenKeyWithSameHashCode_thenPerformanceDegrades() throws InterruptedException {
|
||||||
|
class SameHash {
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int executeTimes = 5000;
|
||||||
|
|
||||||
|
Map<SameHash, Integer> mapOfSameHash = new ConcurrentHashMap<>();
|
||||||
|
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||||
|
long sameHashStartTime = System.currentTimeMillis();
|
||||||
|
for (int i = 0; i < 2; i++) {
|
||||||
|
executorService.execute(() -> {
|
||||||
|
for (int j = 0; j < executeTimes; j++) {
|
||||||
|
mapOfSameHash.put(new SameHash(), 1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
executorService.shutdown();
|
||||||
|
executorService.awaitTermination(5, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
long mapOfSameHashDuration = System.currentTimeMillis() - sameHashStartTime;
|
||||||
|
Map<Object, Integer> mapOfDefaultHash = new ConcurrentHashMap<>();
|
||||||
|
executorService = Executors.newFixedThreadPool(2);
|
||||||
|
long defaultHashStartTime = System.currentTimeMillis();
|
||||||
|
for (int i = 0; i < 2; i++) {
|
||||||
|
executorService.execute(() -> {
|
||||||
|
for (int j = 0; j < executeTimes; j++) {
|
||||||
|
mapOfDefaultHash.put(new Object(), 1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
executorService.shutdown();
|
||||||
|
executorService.awaitTermination(5, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
long mapOfDefaultHashDuration = System.currentTimeMillis() - defaultHashStartTime;
|
||||||
|
assertEquals(executeTimes * 2, mapOfDefaultHash.size());
|
||||||
|
assertEquals(executeTimes * 2, mapOfSameHash.size());
|
||||||
|
System.out.println(String.format("same-hash: %s, default-hash: %s", mapOfSameHashDuration, mapOfDefaultHashDuration));
|
||||||
|
assertTrue("same hashCode() should greatly degrade performance", mapOfSameHashDuration > mapOfDefaultHashDuration * 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,60 @@
|
|||||||
|
package com.baeldung.java.concurrentmap;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class ConcurretMapMemoryConsistencyTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
|
||||||
|
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||||
|
List<Integer> sumList = parallelSum100(map, 1000);
|
||||||
|
assertEquals(1, sumList.stream().distinct().count());
|
||||||
|
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
||||||
|
assertEquals(0, wrongResultCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenHashtable_whenSumParallel_thenCorrect() throws Exception {
|
||||||
|
Map<String, Integer> map = new Hashtable<>();
|
||||||
|
List<Integer> sumList = parallelSum100(map, 1000);
|
||||||
|
assertEquals(1, sumList.stream().distinct().count());
|
||||||
|
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
||||||
|
assertEquals(0, wrongResultCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenHashMap_whenSumParallel_thenError() throws Exception {
|
||||||
|
Map<String, Integer> map = new HashMap<>();
|
||||||
|
List<Integer> sumList = parallelSum100(map, 100);
|
||||||
|
assertNotEquals(1, sumList.stream().distinct().count());
|
||||||
|
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
||||||
|
assertTrue(wrongResultCount > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Integer> parallelSum100(Map<String, Integer> map, int executionTimes) throws InterruptedException {
|
||||||
|
List<Integer> sumList = new ArrayList<>(1000);
|
||||||
|
for (int i = 0; i < executionTimes; i++) {
|
||||||
|
map.put("test", 0);
|
||||||
|
ExecutorService executorService = Executors.newFixedThreadPool(4);
|
||||||
|
for (int j = 0; j < 10; j++) {
|
||||||
|
executorService.execute(() -> {
|
||||||
|
for (int k = 0; k < 10; k++)
|
||||||
|
map.computeIfPresent("test", (key, value) -> value + 1);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
executorService.shutdown();
|
||||||
|
executorService.awaitTermination(5, TimeUnit.SECONDS);
|
||||||
|
sumList.add(map.get("test"));
|
||||||
|
}
|
||||||
|
return sumList;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -24,8 +24,7 @@ public class IterableStreamConversionTest {
|
|||||||
public void whenConvertedToList_thenCorrect() {
|
public void whenConvertedToList_thenCorrect() {
|
||||||
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||||
|
|
||||||
List<String> result = StreamSupport.stream(iterable.spliterator(), false)
|
List<String> result = StreamSupport.stream(iterable.spliterator(), false).map(String::toUpperCase).collect(Collectors.toList());
|
||||||
.map(String::toUpperCase).collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
|
assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
|
||||||
}
|
}
|
||||||
|
@ -201,8 +201,6 @@ public class MapTest {
|
|||||||
assertEquals("val1", rtnVal);
|
assertEquals("val1", rtnVal);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCallsEqualsOnCollision_thenCorrect() {
|
public void whenCallsEqualsOnCollision_thenCorrect() {
|
||||||
HashMap<MyKey, String> map = new HashMap<>();
|
HashMap<MyKey, String> map = new HashMap<>();
|
||||||
@ -311,13 +309,7 @@ public class MapTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() {
|
public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() {
|
||||||
TreeMap<Integer, String> map = new TreeMap<>(new Comparator<Integer>() {
|
TreeMap<Integer, String> map = new TreeMap<>(Comparator.reverseOrder());
|
||||||
|
|
||||||
@Override
|
|
||||||
public int compare(Integer o1, Integer o2) {
|
|
||||||
return o2 - o1;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
map.put(3, "val");
|
map.put(3, "val");
|
||||||
map.put(2, "val");
|
map.put(2, "val");
|
||||||
map.put(1, "val");
|
map.put(1, "val");
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
package com.baeldung.java8;
|
package com.baeldung.java8;
|
||||||
|
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
@ -28,11 +27,7 @@ public class Java8FindAnyFindFirstTest {
|
|||||||
@Test
|
@Test
|
||||||
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception {
|
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception {
|
||||||
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
|
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
|
||||||
Optional<Integer> result = list
|
Optional<Integer> result = list.stream().parallel().filter(num -> num < 4).findAny();
|
||||||
.stream()
|
|
||||||
.parallel()
|
|
||||||
.filter(num -> num < 4)
|
|
||||||
.findAny();
|
|
||||||
|
|
||||||
assertTrue(result.isPresent());
|
assertTrue(result.isPresent());
|
||||||
assertThat(result.get(), anyOf(is(1), is(2), is(3)));
|
assertThat(result.get(), anyOf(is(1), is(2), is(3)));
|
||||||
|
@ -56,9 +56,7 @@ public class NashornTest {
|
|||||||
Map<String, Object> map = (Map<String, Object>) obj;
|
Map<String, Object> map = (Map<String, Object>) obj;
|
||||||
|
|
||||||
Assert.assertEquals("hello", map.get("greet"));
|
Assert.assertEquals("hello", map.get("greet"));
|
||||||
Assert.assertTrue(List.class.isAssignableFrom(map
|
Assert.assertTrue(List.class.isAssignableFrom(map.get("primes").getClass()));
|
||||||
.get("primes")
|
|
||||||
.getClass()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -9,7 +9,8 @@ public class Person implements CouchbaseEntity {
|
|||||||
private String name;
|
private String name;
|
||||||
private String homeTown;
|
private String homeTown;
|
||||||
|
|
||||||
Person() {}
|
Person() {
|
||||||
|
}
|
||||||
|
|
||||||
public Person(Builder b) {
|
public Person(Builder b) {
|
||||||
this.id = b.id;
|
this.id = b.id;
|
||||||
|
@ -13,9 +13,7 @@ import com.baeldung.couchbase.async.service.BucketService;
|
|||||||
public class PersonCrudService extends AbstractCrudService<Person> {
|
public class PersonCrudService extends AbstractCrudService<Person> {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public PersonCrudService(
|
public PersonCrudService(@Qualifier("TutorialBucketService") BucketService bucketService, PersonDocumentConverter converter) {
|
||||||
@Qualifier("TutorialBucketService") BucketService bucketService,
|
|
||||||
PersonDocumentConverter converter) {
|
|
||||||
super(bucketService, converter);
|
super(bucketService, converter);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter<Person> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public JsonDocument toDocument(Person p) {
|
public JsonDocument toDocument(Person p) {
|
||||||
JsonObject content = JsonObject.empty()
|
JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown());
|
||||||
.put("type", "Person")
|
|
||||||
.put("name", p.getName())
|
|
||||||
.put("homeTown", p.getHomeTown());
|
|
||||||
return JsonDocument.create(p.getId(), content);
|
return JsonDocument.create(p.getId(), content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -21,8 +21,7 @@ public class RegistrationService {
|
|||||||
public Person findRegistrant(String id) {
|
public Person findRegistrant(String id) {
|
||||||
try {
|
try {
|
||||||
return crud.read(id);
|
return crud.read(id);
|
||||||
}
|
} catch (CouchbaseException e) {
|
||||||
catch(CouchbaseException e) {
|
|
||||||
return crud.readFromReplica(id);
|
return crud.readFromReplica(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -73,9 +73,7 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements
|
|||||||
@Override
|
@Override
|
||||||
public List<T> readBulk(Iterable<String> ids) {
|
public List<T> readBulk(Iterable<String> ids) {
|
||||||
final AsyncBucket asyncBucket = bucket.async();
|
final AsyncBucket asyncBucket = bucket.async();
|
||||||
Observable<JsonDocument> asyncOperation = Observable
|
Observable<JsonDocument> asyncOperation = Observable.from(ids).flatMap(new Func1<String, Observable<JsonDocument>>() {
|
||||||
.from(ids)
|
|
||||||
.flatMap(new Func1<String, Observable<JsonDocument>>() {
|
|
||||||
public Observable<JsonDocument> call(String key) {
|
public Observable<JsonDocument> call(String key) {
|
||||||
return asyncBucket.get(key);
|
return asyncBucket.get(key);
|
||||||
}
|
}
|
||||||
@ -83,8 +81,7 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements
|
|||||||
|
|
||||||
final List<T> items = new ArrayList<T>();
|
final List<T> items = new ArrayList<T>();
|
||||||
try {
|
try {
|
||||||
asyncOperation.toBlocking()
|
asyncOperation.toBlocking().forEach(new Action1<JsonDocument>() {
|
||||||
.forEach(new Action1<JsonDocument>() {
|
|
||||||
public void call(JsonDocument doc) {
|
public void call(JsonDocument doc) {
|
||||||
T item = converter.fromDocument(doc);
|
T item = converter.fromDocument(doc);
|
||||||
items.add(item);
|
items.add(item);
|
||||||
@ -100,9 +97,7 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements
|
|||||||
@Override
|
@Override
|
||||||
public void createBulk(Iterable<T> items) {
|
public void createBulk(Iterable<T> items) {
|
||||||
final AsyncBucket asyncBucket = bucket.async();
|
final AsyncBucket asyncBucket = bucket.async();
|
||||||
Observable
|
Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() {
|
||||||
.from(items)
|
|
||||||
.flatMap(new Func1<T, Observable<JsonDocument>>() {
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@Override
|
@Override
|
||||||
public Observable<JsonDocument> call(final T t) {
|
public Observable<JsonDocument> call(final T t) {
|
||||||
@ -110,62 +105,34 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements
|
|||||||
t.setId(UUID.randomUUID().toString());
|
t.setId(UUID.randomUUID().toString());
|
||||||
}
|
}
|
||||||
JsonDocument doc = converter.toDocument(t);
|
JsonDocument doc = converter.toDocument(t);
|
||||||
return asyncBucket.insert(doc)
|
return asyncBucket.insert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
|
||||||
.retryWhen(RetryBuilder
|
|
||||||
.anyOf(BackpressureException.class)
|
|
||||||
.delay(Delay.exponential(TimeUnit.MILLISECONDS, 100))
|
|
||||||
.max(10)
|
|
||||||
.build());
|
|
||||||
}
|
}
|
||||||
})
|
}).last().toBlocking().single();
|
||||||
.last()
|
|
||||||
.toBlocking()
|
|
||||||
.single();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void updateBulk(Iterable<T> items) {
|
public void updateBulk(Iterable<T> items) {
|
||||||
final AsyncBucket asyncBucket = bucket.async();
|
final AsyncBucket asyncBucket = bucket.async();
|
||||||
Observable
|
Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() {
|
||||||
.from(items)
|
|
||||||
.flatMap(new Func1<T, Observable<JsonDocument>>() {
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@Override
|
@Override
|
||||||
public Observable<JsonDocument> call(final T t) {
|
public Observable<JsonDocument> call(final T t) {
|
||||||
JsonDocument doc = converter.toDocument(t);
|
JsonDocument doc = converter.toDocument(t);
|
||||||
return asyncBucket.upsert(doc)
|
return asyncBucket.upsert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
|
||||||
.retryWhen(RetryBuilder
|
|
||||||
.anyOf(BackpressureException.class)
|
|
||||||
.delay(Delay.exponential(TimeUnit.MILLISECONDS, 100))
|
|
||||||
.max(10)
|
|
||||||
.build());
|
|
||||||
}
|
}
|
||||||
})
|
}).last().toBlocking().single();
|
||||||
.last()
|
|
||||||
.toBlocking()
|
|
||||||
.single();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void deleteBulk(Iterable<String> ids) {
|
public void deleteBulk(Iterable<String> ids) {
|
||||||
final AsyncBucket asyncBucket = bucket.async();
|
final AsyncBucket asyncBucket = bucket.async();
|
||||||
Observable
|
Observable.from(ids).flatMap(new Func1<String, Observable<JsonDocument>>() {
|
||||||
.from(ids)
|
|
||||||
.flatMap(new Func1<String, Observable<JsonDocument>>() {
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@Override
|
@Override
|
||||||
public Observable<JsonDocument> call(String key) {
|
public Observable<JsonDocument> call(String key) {
|
||||||
return asyncBucket.remove(key)
|
return asyncBucket.remove(key).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
|
||||||
.retryWhen(RetryBuilder
|
|
||||||
.anyOf(BackpressureException.class)
|
|
||||||
.delay(Delay.exponential(TimeUnit.MILLISECONDS, 100))
|
|
||||||
.max(10)
|
|
||||||
.build());
|
|
||||||
}
|
}
|
||||||
})
|
}).last().toBlocking().single();
|
||||||
.last()
|
|
||||||
.toBlocking()
|
|
||||||
.single();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -20,10 +20,7 @@ public class CodeSnippets {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static Cluster loadClusterWithCustomEnvironment() {
|
static Cluster loadClusterWithCustomEnvironment() {
|
||||||
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
|
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder().connectTimeout(10000).kvTimeout(3000).build();
|
||||||
.connectTimeout(10000)
|
|
||||||
.kvTimeout(3000)
|
|
||||||
.build();
|
|
||||||
return CouchbaseCluster.create(env, "localhost");
|
return CouchbaseCluster.create(env, "localhost");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,12 +33,7 @@ public class CodeSnippets {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static JsonDocument insertExample(Bucket bucket) {
|
static JsonDocument insertExample(Bucket bucket) {
|
||||||
JsonObject content = JsonObject.empty()
|
JsonObject content = JsonObject.empty().put("name", "John Doe").put("type", "Person").put("email", "john.doe@mydomain.com").put("homeTown", "Chicago");
|
||||||
.put("name", "John Doe")
|
|
||||||
.put("type", "Person")
|
|
||||||
.put("email", "john.doe@mydomain.com")
|
|
||||||
.put("homeTown", "Chicago")
|
|
||||||
;
|
|
||||||
String id = UUID.randomUUID().toString();
|
String id = UUID.randomUUID().toString();
|
||||||
JsonDocument document = JsonDocument.create(id, content);
|
JsonDocument document = JsonDocument.create(id, content);
|
||||||
JsonDocument inserted = bucket.insert(document);
|
JsonDocument inserted = bucket.insert(document);
|
||||||
@ -72,8 +64,7 @@ public class CodeSnippets {
|
|||||||
static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) {
|
static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) {
|
||||||
try {
|
try {
|
||||||
return bucket.get(id);
|
return bucket.get(id);
|
||||||
}
|
} catch (CouchbaseException e) {
|
||||||
catch(CouchbaseException e) {
|
|
||||||
List<JsonDocument> list = bucket.getFromReplica(id, ReplicaMode.FIRST);
|
List<JsonDocument> list = bucket.getFromReplica(id, ReplicaMode.FIRST);
|
||||||
if (!list.isEmpty()) {
|
if (!list.isEmpty()) {
|
||||||
return list.get(0);
|
return list.get(0);
|
||||||
|
@ -7,7 +7,8 @@ public class Person {
|
|||||||
private String name;
|
private String name;
|
||||||
private String homeTown;
|
private String homeTown;
|
||||||
|
|
||||||
Person() {}
|
Person() {
|
||||||
|
}
|
||||||
|
|
||||||
public Person(Builder b) {
|
public Person(Builder b) {
|
||||||
this.id = b.id;
|
this.id = b.id;
|
||||||
|
@ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter<Person> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public JsonDocument toDocument(Person p) {
|
public JsonDocument toDocument(Person p) {
|
||||||
JsonObject content = JsonObject.empty()
|
JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown());
|
||||||
.put("type", "Person")
|
|
||||||
.put("name", p.getName())
|
|
||||||
.put("homeTown", p.getHomeTown());
|
|
||||||
return JsonDocument.create(p.getId(), content);
|
return JsonDocument.create(p.getId(), content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -21,8 +21,7 @@ public class RegistrationService {
|
|||||||
public Person findRegistrant(String id) {
|
public Person findRegistrant(String id) {
|
||||||
try {
|
try {
|
||||||
return crud.read(id);
|
return crud.read(id);
|
||||||
}
|
} catch (CouchbaseException e) {
|
||||||
catch(CouchbaseException e) {
|
|
||||||
return crud.readFromReplica(id);
|
return crud.readFromReplica(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -59,9 +59,7 @@ public class ClusterServiceImpl implements ClusterService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<JsonDocument> getDocumentsAsync(final AsyncBucket asyncBucket, Iterable<String> keys) {
|
public List<JsonDocument> getDocumentsAsync(final AsyncBucket asyncBucket, Iterable<String> keys) {
|
||||||
Observable<JsonDocument> asyncBulkGet = Observable
|
Observable<JsonDocument> asyncBulkGet = Observable.from(keys).flatMap(new Func1<String, Observable<JsonDocument>>() {
|
||||||
.from(keys)
|
|
||||||
.flatMap(new Func1<String, Observable<JsonDocument>>() {
|
|
||||||
public Observable<JsonDocument> call(String key) {
|
public Observable<JsonDocument> call(String key) {
|
||||||
return asyncBucket.get(key);
|
return asyncBucket.get(key);
|
||||||
}
|
}
|
||||||
@ -69,8 +67,7 @@ public class ClusterServiceImpl implements ClusterService {
|
|||||||
|
|
||||||
final List<JsonDocument> docs = new ArrayList<>();
|
final List<JsonDocument> docs = new ArrayList<>();
|
||||||
try {
|
try {
|
||||||
asyncBulkGet.toBlocking()
|
asyncBulkGet.toBlocking().forEach(new Action1<JsonDocument>() {
|
||||||
.forEach(new Action1<JsonDocument>() {
|
|
||||||
public void call(JsonDocument doc) {
|
public void call(JsonDocument doc) {
|
||||||
docs.add(doc);
|
docs.add(doc);
|
||||||
}
|
}
|
||||||
|
@ -207,17 +207,10 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Person randomPerson() {
|
private Person randomPerson() {
|
||||||
return Person.Builder.newInstance()
|
return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build();
|
||||||
.name(RandomStringUtils.randomAlphabetic(10))
|
|
||||||
.homeTown(RandomStringUtils.randomAlphabetic(10))
|
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Person randomPersonWithId() {
|
private Person randomPersonWithId() {
|
||||||
return Person.Builder.newInstance()
|
return Person.Builder.newInstance().id(UUID.randomUUID().toString()).name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build();
|
||||||
.id(UUID.randomUUID().toString())
|
|
||||||
.name(RandomStringUtils.randomAlphabetic(10))
|
|
||||||
.homeTown(RandomStringUtils.randomAlphabetic(10))
|
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -66,17 +66,10 @@ public class PersonCrudServiceIntegrationTest extends IntegrationTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Person buildClarkKent() {
|
private Person buildClarkKent() {
|
||||||
return Person.Builder.newInstance()
|
return Person.Builder.newInstance().id(CLARK_KENT_ID).name(CLARK_KENT).homeTown(SMALLVILLE).build();
|
||||||
.id(CLARK_KENT_ID)
|
|
||||||
.name(CLARK_KENT)
|
|
||||||
.homeTown(SMALLVILLE)
|
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Person randomPerson() {
|
private Person randomPerson() {
|
||||||
return Person.Builder.newInstance()
|
return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build();
|
||||||
.name(RandomStringUtils.randomAlphabetic(10))
|
|
||||||
.homeTown(RandomStringUtils.randomAlphabetic(10))
|
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -35,9 +35,6 @@ public abstract class MemberRepository extends AbstractEntityRepository<Member,
|
|||||||
|
|
||||||
public List<Member> findAllOrderedByNameWithQueryDSL() {
|
public List<Member> findAllOrderedByNameWithQueryDSL() {
|
||||||
final QMember member = QMember.member;
|
final QMember member = QMember.member;
|
||||||
return jpaQuery()
|
return jpaQuery().from(member).orderBy(member.email.asc()).list(member);
|
||||||
.from(member)
|
|
||||||
.orderBy(member.email.asc())
|
|
||||||
.list(member);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -64,7 +64,6 @@ public class MemberRegistration {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public void register(Member member) throws Exception {
|
public void register(Member member) throws Exception {
|
||||||
log.info("Registering " + member.getName());
|
log.info("Registering " + member.getName());
|
||||||
validateMember(member);
|
validateMember(member);
|
||||||
|
@ -41,27 +41,13 @@ import org.junit.runner.RunWith;
|
|||||||
public class MemberRegistrationTest {
|
public class MemberRegistrationTest {
|
||||||
@Deployment
|
@Deployment
|
||||||
public static Archive<?> createTestArchive() {
|
public static Archive<?> createTestArchive() {
|
||||||
File[] files = Maven.resolver().loadPomFromFile("pom.xml")
|
File[] files = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile();
|
||||||
.importRuntimeDependencies().resolve().withTransitivity().asFile();
|
|
||||||
|
|
||||||
return ShrinkWrap.create(WebArchive.class, "test.war")
|
return ShrinkWrap.create(WebArchive.class, "test.war")
|
||||||
.addClasses(
|
.addClasses(EntityManagerProducer.class, Member.class, MemberRegistration.class, MemberRepository.class, Resources.class, QueryDslRepositoryExtension.class, QueryDslSupport.class, SecondaryPersistenceUnit.class,
|
||||||
EntityManagerProducer.class,
|
SecondaryEntityManagerProducer.class, SecondaryEntityManagerResolver.class)
|
||||||
Member.class,
|
.addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml").addAsResource("META-INF/apache-deltaspike.properties").addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml").addAsWebInfResource("test-ds.xml")
|
||||||
MemberRegistration.class,
|
.addAsWebInfResource("test-secondary-ds.xml").addAsLibraries(files);
|
||||||
MemberRepository.class,
|
|
||||||
Resources.class,
|
|
||||||
QueryDslRepositoryExtension.class,
|
|
||||||
QueryDslSupport.class,
|
|
||||||
SecondaryPersistenceUnit.class,
|
|
||||||
SecondaryEntityManagerProducer.class,
|
|
||||||
SecondaryEntityManagerResolver.class)
|
|
||||||
.addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml")
|
|
||||||
.addAsResource("META-INF/apache-deltaspike.properties")
|
|
||||||
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
|
|
||||||
.addAsWebInfResource("test-ds.xml")
|
|
||||||
.addAsWebInfResource("test-secondary-ds.xml")
|
|
||||||
.addAsLibraries(files);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
|
@ -11,16 +11,9 @@ import lombok.Getter;
|
|||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
public class BookControllerFeignClientBuilder {
|
public class BookControllerFeignClientBuilder {
|
||||||
private BookClient bookClient = createClient(BookClient.class,
|
private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books");
|
||||||
"http://localhost:8081/api/books");
|
|
||||||
|
|
||||||
private static <T> T createClient(Class<T> type, String uri) {
|
private static <T> T createClient(Class<T> type, String uri) {
|
||||||
return Feign.builder()
|
return Feign.builder().client(new OkHttpClient()).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger(type)).logLevel(Logger.Level.FULL).target(type, uri);
|
||||||
.client(new OkHttpClient())
|
|
||||||
.encoder(new GsonEncoder())
|
|
||||||
.decoder(new GsonDecoder())
|
|
||||||
.logger(new Slf4jLogger(type))
|
|
||||||
.logLevel(Logger.Level.FULL)
|
|
||||||
.target(type, uri);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -31,9 +31,7 @@ public class BookClientTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenBookClient_shouldRunSuccessfully() throws Exception {
|
public void givenBookClient_shouldRunSuccessfully() throws Exception {
|
||||||
List<Book> books = bookClient.findAll().stream()
|
List<Book> books = bookClient.findAll().stream().map(BookResource::getBook).collect(Collectors.toList());
|
||||||
.map(BookResource::getBook)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
assertTrue(books.size() > 2);
|
assertTrue(books.size() > 2);
|
||||||
log.info("{}", books);
|
log.info("{}", books);
|
||||||
}
|
}
|
||||||
|
@ -57,6 +57,12 @@
|
|||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -100,6 +106,7 @@
|
|||||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||||
<junit.version>4.12</junit.version>
|
<junit.version>4.12</junit.version>
|
||||||
<mockito.version>1.10.19</mockito.version>
|
<mockito.version>1.10.19</mockito.version>
|
||||||
|
<assertj.version>3.6.1</assertj.version>
|
||||||
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
|
@ -0,0 +1,157 @@
|
|||||||
|
package org.baeldung.guava;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import org.junit.Test;
|
||||||
|
import static com.google.common.base.Preconditions.*;
|
||||||
|
|
||||||
|
public class GuavaPreConditionsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCheckArgumentEvaluatesFalse_throwsException() {
|
||||||
|
int age = -18;
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkArgument(age > 0))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
|
.hasMessage(null)
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenErrorMessage_whenCheckArgumentEvaluatesFalse_throwsException() {
|
||||||
|
final int age = -18;
|
||||||
|
final String message = "Age can't be zero or less than zero";
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkArgument(age > 0, message))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
|
.hasMessage(message)
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTemplatedErrorMessage_whenCheckArgumentEvaluatesFalse_throwsException() {
|
||||||
|
final int age = -18;
|
||||||
|
final String message = "Age can't be zero or less than zero, you supplied %s.";
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkArgument(age > 0, message, age))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
|
.hasMessage(message, age)
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenArrayOfIntegers_whenCheckElementIndexEvaluatesFalse_throwsException() {
|
||||||
|
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkElementIndex(6, numbers.length - 1))
|
||||||
|
.isInstanceOf(IndexOutOfBoundsException.class)
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenArrayOfIntegersAndMessage_whenCheckElementIndexEvaluatesFalse_throwsException() {
|
||||||
|
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||||
|
final String message = "Please check the bound of an array and retry";
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkElementIndex(6, numbers.length - 1, message))
|
||||||
|
.isInstanceOf(IndexOutOfBoundsException.class)
|
||||||
|
.hasMessageStartingWith(message)
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNullString_whenCheckNotNullCalled_throwsException() {
|
||||||
|
final String nullObject = null;
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkNotNull(nullObject))
|
||||||
|
.isInstanceOf(NullPointerException.class)
|
||||||
|
.hasMessage(null)
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNullString_whenCheckNotNullCalledWithMessage_throwsException() {
|
||||||
|
final String nullObject = null;
|
||||||
|
final String message = "Please check the Object supplied, its null!";
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkNotNull(nullObject, message))
|
||||||
|
.isInstanceOf(NullPointerException.class)
|
||||||
|
.hasMessage(message)
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNullString_whenCheckNotNullCalledWithTemplatedMessage_throwsException() {
|
||||||
|
final String nullObject = null;
|
||||||
|
final String message = "Please check the Object supplied, its %s!";
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkNotNull(nullObject, message, nullObject))
|
||||||
|
.isInstanceOf(NullPointerException.class)
|
||||||
|
.hasMessage(message, nullObject)
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenArrayOfIntegers_whenCheckPositionIndexEvaluatesFalse_throwsException() {
|
||||||
|
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkPositionIndex(6, numbers.length - 1))
|
||||||
|
.isInstanceOf(IndexOutOfBoundsException.class)
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenArrayOfIntegersAndMessage_whenCheckPositionIndexEvaluatesFalse_throwsException() {
|
||||||
|
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||||
|
final String message = "Please check the bound of an array and retry";
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkPositionIndex(6, numbers.length - 1, message))
|
||||||
|
.isInstanceOf(IndexOutOfBoundsException.class)
|
||||||
|
.hasMessageStartingWith(message)
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenArrayOfIntegers_whenCheckPositionIndexesEvaluatesFalse_throwsException() {
|
||||||
|
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkPositionIndexes(6, 0, numbers.length - 1))
|
||||||
|
.isInstanceOf(IndexOutOfBoundsException.class)
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidStates_whenCheckStateEvaluatesFalse_throwsException() {
|
||||||
|
final int[] validStates = { -1, 0, 1 };
|
||||||
|
final int givenState = 10;
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0))
|
||||||
|
.isInstanceOf(IllegalStateException.class)
|
||||||
|
.hasMessage(null)
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidStatesAndMessage_whenCheckStateEvaluatesFalse_throwsException() {
|
||||||
|
final int[] validStates = { -1, 0, 1 };
|
||||||
|
final int givenState = 10;
|
||||||
|
final String message = "You have entered an invalid state";
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0, message))
|
||||||
|
.isInstanceOf(IllegalStateException.class)
|
||||||
|
.hasMessageStartingWith(message)
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidStatesAndTemplatedMessage_whenCheckStateEvaluatesFalse_throwsException() {
|
||||||
|
final int[] validStates = { -1, 0, 1 };
|
||||||
|
final int givenState = 10;
|
||||||
|
final String message = "State can't be %s, It can be one of %s.";
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0, message, givenState, Arrays.toString(validStates)))
|
||||||
|
.isInstanceOf(IllegalStateException.class)
|
||||||
|
.hasMessage(message, givenState, Arrays.toString(validStates))
|
||||||
|
.hasNoCause();
|
||||||
|
}
|
||||||
|
}
|
178
guava/src/test/java/org/baeldung/guava/GuavaTableTest.java
Normal file
178
guava/src/test/java/org/baeldung/guava/GuavaTableTest.java
Normal file
@ -0,0 +1,178 @@
|
|||||||
|
package org.baeldung.guava;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import org.junit.Test;
|
||||||
|
import com.google.common.collect.ArrayTable;
|
||||||
|
import com.google.common.collect.HashBasedTable;
|
||||||
|
import com.google.common.collect.ImmutableTable;
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
|
import com.google.common.collect.Table;
|
||||||
|
import com.google.common.collect.TreeBasedTable;
|
||||||
|
|
||||||
|
public class GuavaTableTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTable_whenGet_returnsSuccessfully() {
|
||||||
|
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||||
|
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||||
|
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||||
|
|
||||||
|
final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
|
||||||
|
final Integer seatCountForNoEntry = universityCourseSeatTable.get("Oxford", "IT");
|
||||||
|
|
||||||
|
assertThat(seatCount).isEqualTo(60);
|
||||||
|
assertThat(seatCountForNoEntry).isEqualTo(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTable_whenContains_returnsSuccessfully() {
|
||||||
|
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||||
|
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||||
|
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||||
|
|
||||||
|
final boolean entryIsPresent = universityCourseSeatTable.contains("Mumbai", "IT");
|
||||||
|
final boolean entryIsAbsent = universityCourseSeatTable.contains("Oxford", "IT");
|
||||||
|
final boolean courseIsPresent = universityCourseSeatTable.containsColumn("IT");
|
||||||
|
final boolean universityIsPresent = universityCourseSeatTable.containsRow("Mumbai");
|
||||||
|
final boolean seatCountIsPresent = universityCourseSeatTable.containsValue(60);
|
||||||
|
|
||||||
|
assertThat(entryIsPresent).isEqualTo(true);
|
||||||
|
assertThat(entryIsAbsent).isEqualTo(false);
|
||||||
|
assertThat(courseIsPresent).isEqualTo(true);
|
||||||
|
assertThat(universityIsPresent).isEqualTo(true);
|
||||||
|
assertThat(seatCountIsPresent).isEqualTo(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTable_whenRemove_returnsSuccessfully() {
|
||||||
|
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||||
|
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||||
|
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||||
|
|
||||||
|
final int seatCount = universityCourseSeatTable.remove("Mumbai", "IT");
|
||||||
|
|
||||||
|
assertThat(seatCount).isEqualTo(60);
|
||||||
|
assertThat(universityCourseSeatTable.remove("Mumbai", "IT")).isEqualTo(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTable_whenColumn_returnsSuccessfully() {
|
||||||
|
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||||
|
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||||
|
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||||
|
|
||||||
|
final Map<String, Integer> universitySeatMap = universityCourseSeatTable.column("IT");
|
||||||
|
|
||||||
|
assertThat(universitySeatMap).hasSize(2);
|
||||||
|
assertThat(universitySeatMap.get("Mumbai")).isEqualTo(60);
|
||||||
|
assertThat(universitySeatMap.get("Harvard")).isEqualTo(120);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTable_whenColumnMap_returnsSuccessfully() {
|
||||||
|
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||||
|
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||||
|
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||||
|
|
||||||
|
final Map<String, Map<String, Integer>> courseKeyUniversitySeatMap = universityCourseSeatTable.columnMap();
|
||||||
|
|
||||||
|
assertThat(courseKeyUniversitySeatMap).hasSize(3);
|
||||||
|
assertThat(courseKeyUniversitySeatMap.get("IT")).hasSize(2);
|
||||||
|
assertThat(courseKeyUniversitySeatMap.get("Electrical")).hasSize(1);
|
||||||
|
assertThat(courseKeyUniversitySeatMap.get("Chemical")).hasSize(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTable_whenRow_returnsSuccessfully() {
|
||||||
|
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||||
|
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||||
|
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||||
|
|
||||||
|
final Map<String, Integer> courseSeatMap = universityCourseSeatTable.row("Mumbai");
|
||||||
|
|
||||||
|
assertThat(courseSeatMap).hasSize(2);
|
||||||
|
assertThat(courseSeatMap.get("IT")).isEqualTo(60);
|
||||||
|
assertThat(courseSeatMap.get("Chemical")).isEqualTo(120);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTable_whenRowKeySet_returnsSuccessfully() {
|
||||||
|
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||||
|
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||||
|
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||||
|
|
||||||
|
final Set<String> universitySet = universityCourseSeatTable.rowKeySet();
|
||||||
|
|
||||||
|
assertThat(universitySet).hasSize(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTable_whenColKeySet_returnsSuccessfully() {
|
||||||
|
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||||
|
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||||
|
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||||
|
|
||||||
|
final Set<String> courseSet = universityCourseSeatTable.columnKeySet();
|
||||||
|
|
||||||
|
assertThat(courseSet).hasSize(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTreeTable_whenGet_returnsSuccessfully() {
|
||||||
|
final Table<String, String, Integer> universityCourseSeatTable = TreeBasedTable.create();
|
||||||
|
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||||
|
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||||
|
|
||||||
|
final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
|
||||||
|
|
||||||
|
assertThat(seatCount).isEqualTo(60);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenImmutableTable_whenGet_returnsSuccessfully() {
|
||||||
|
final Table<String, String, Integer> universityCourseSeatTable = ImmutableTable.<String, String, Integer> builder()
|
||||||
|
.put("Mumbai", "Chemical", 120)
|
||||||
|
.put("Mumbai", "IT", 60)
|
||||||
|
.put("Harvard", "Electrical", 60)
|
||||||
|
.put("Harvard", "IT", 120)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
|
||||||
|
|
||||||
|
assertThat(seatCount).isEqualTo(60);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenArrayTable_whenGet_returnsSuccessfully() {
|
||||||
|
final List<String> universityRowTable = Lists.newArrayList("Mumbai", "Harvard");
|
||||||
|
final List<String> courseColumnTables = Lists.newArrayList("Chemical", "IT", "Electrical");
|
||||||
|
final Table<String, String, Integer> universityCourseSeatTable = ArrayTable.create(universityRowTable, courseColumnTables);
|
||||||
|
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||||
|
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||||
|
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||||
|
|
||||||
|
final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
|
||||||
|
|
||||||
|
assertThat(seatCount).isEqualTo(60);
|
||||||
|
}
|
||||||
|
}
|
@ -80,12 +80,8 @@ public class BookRepository {
|
|||||||
* @param book
|
* @param book
|
||||||
*/
|
*/
|
||||||
public void insertBookBatch(Book book) {
|
public void insertBookBatch(Book book) {
|
||||||
StringBuilder sb = new StringBuilder("BEGIN BATCH ")
|
StringBuilder sb = new StringBuilder("BEGIN BATCH ").append("INSERT INTO ").append(TABLE_NAME).append("(id, title, author, subject) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("', '").append(book.getAuthor())
|
||||||
.append("INSERT INTO ").append(TABLE_NAME).append("(id, title, author, subject) ")
|
.append("', '").append(book.getSubject()).append("');").append("INSERT INTO ").append(TABLE_NAME_BY_TITLE).append("(id, title) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("');")
|
||||||
.append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("', '").append(book.getAuthor()).append("', '")
|
|
||||||
.append(book.getSubject()).append("');")
|
|
||||||
.append("INSERT INTO ").append(TABLE_NAME_BY_TITLE).append("(id, title) ")
|
|
||||||
.append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("');")
|
|
||||||
.append("APPLY BATCH;");
|
.append("APPLY BATCH;");
|
||||||
|
|
||||||
final String query = sb.toString();
|
final String query = sb.toString();
|
||||||
|
@ -28,9 +28,8 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
|
|
||||||
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
|
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<artifactId>kotlin-maven-plugin</artifactId>
|
<artifactId>kotlin-maven-plugin</artifactId>
|
||||||
@ -39,16 +38,50 @@
|
|||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<id>compile</id>
|
<id>compile</id>
|
||||||
<goals>
|
<goals> <goal>compile</goal> </goals>
|
||||||
<goal>compile</goal>
|
<configuration>
|
||||||
</goals>
|
<sourceDirs>
|
||||||
|
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
|
||||||
|
<sourceDir>${project.basedir}/src/main/java</sourceDir>
|
||||||
|
</sourceDirs>
|
||||||
|
</configuration>
|
||||||
</execution>
|
</execution>
|
||||||
|
|
||||||
<execution>
|
<execution>
|
||||||
<id>test-compile</id>
|
<id>test-compile</id>
|
||||||
<goals>
|
<goals> <goal>test-compile</goal> </goals>
|
||||||
<goal>test-compile</goal>
|
<configuration>
|
||||||
</goals>
|
<sourceDirs>
|
||||||
|
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
|
||||||
|
<sourceDir>${project.basedir}/src/test/java</sourceDir>
|
||||||
|
</sourceDirs>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.5.1</version>
|
||||||
|
<executions>
|
||||||
|
<!-- Replacing default-compile as it is treated specially by maven -->
|
||||||
|
<execution>
|
||||||
|
<id>default-compile</id>
|
||||||
|
<phase>none</phase>
|
||||||
|
</execution>
|
||||||
|
<!-- Replacing default-testCompile as it is treated specially by maven -->
|
||||||
|
<execution>
|
||||||
|
<id>default-testCompile</id>
|
||||||
|
<phase>none</phase>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>java-compile</id>
|
||||||
|
<phase>compile</phase>
|
||||||
|
<goals> <goal>compile</goal> </goals>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>java-test-compile</id>
|
||||||
|
<phase>test-compile</phase>
|
||||||
|
<goals> <goal>testCompile</goal> </goals>
|
||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
@ -57,9 +90,10 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<junit.version>4.12</junit.version>
|
<junit.version>4.12</junit.version>
|
||||||
<kotlin-test-junit.version>1.0.4</kotlin-test-junit.version>
|
<kotlin-maven-plugin.version>1.0.6</kotlin-maven-plugin.version>
|
||||||
<kotlin-stdlib.version>1.0.4</kotlin-stdlib.version>
|
<kotlin-test-junit.version>1.0.6</kotlin-test-junit.version>
|
||||||
<kotlin-maven-plugin.version>1.0.4</kotlin-maven-plugin.version>
|
<kotlin-stdlib.version>1.0.6</kotlin-stdlib.version>
|
||||||
|
<kotlin-maven-plugin.version>1.0.6</kotlin-maven-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
7
kotlin/src/main/java/com/baeldung/java/StringUtils.java
Normal file
7
kotlin/src/main/java/com/baeldung/java/StringUtils.java
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
package com.baeldung.java;
|
||||||
|
|
||||||
|
public class StringUtils {
|
||||||
|
public static String toUpperCase(String name) {
|
||||||
|
return name.toUpperCase();
|
||||||
|
}
|
||||||
|
}
|
@ -24,29 +24,41 @@ class ItemManager(val categoryId: String, val dbConnection: String) {
|
|||||||
fun makeAnalyisOfCategory(catId: String): Unit {
|
fun makeAnalyisOfCategory(catId: String): Unit {
|
||||||
val result = if (catId == "100") "Yes" else "No"
|
val result = if (catId == "100") "Yes" else "No"
|
||||||
println(result)
|
println(result)
|
||||||
|
`object`()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun sum(a: Int, b: Int): Int {
|
||||||
|
return a + b
|
||||||
|
}
|
||||||
|
|
||||||
|
fun `object`(): String {
|
||||||
|
return "this is object"
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun main(args: Array<String>) {
|
fun main(args: Array<String>) {
|
||||||
val numbers = arrayOf("first", "second", "third", "fourth")
|
val numbers = arrayOf("first", "second", "third", "fourth")
|
||||||
|
|
||||||
var concat = ""
|
|
||||||
for (n in numbers) {
|
for (n in numbers) {
|
||||||
concat += n
|
println(n)
|
||||||
}
|
}
|
||||||
|
|
||||||
var sum = 0
|
for (i in 2..9 step 2) {
|
||||||
for (i in 2..9) {
|
println(i)
|
||||||
sum += i
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val res = 1.rangeTo(10).map { it * 2 }
|
||||||
|
println(res)
|
||||||
|
|
||||||
val firstName = "Tom"
|
val firstName = "Tom"
|
||||||
val secondName = "Mary"
|
val secondName = "Mary"
|
||||||
val concatOfNames = "$firstName + $secondName"
|
val concatOfNames = "$firstName + $secondName"
|
||||||
println("Names: $concatOfNames")
|
println("Names: $concatOfNames")
|
||||||
|
val sum = "four: ${2 + 2}"
|
||||||
|
|
||||||
val itemManager = ItemManager("cat_id", "db://connection")
|
val itemManager = ItemManager("cat_id", "db://connection")
|
||||||
|
ItemManager(categoryId = "catId", dbConnection = "db://Connection")
|
||||||
val result = "function result: ${itemManager.isFromSpecificCategory("1")}"
|
val result = "function result: ${itemManager.isFromSpecificCategory("1")}"
|
||||||
println(result)
|
println(result)
|
||||||
|
|
||||||
@ -63,4 +75,9 @@ fun main(args: Array<String>) {
|
|||||||
"Alice" -> println("Hi lady")
|
"Alice" -> println("Hi lady")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val items = listOf(1, 2, 3, 4)
|
||||||
|
|
||||||
|
|
||||||
|
val rwList = mutableListOf(1, 2, 3)
|
||||||
|
rwList.add(5)
|
||||||
}
|
}
|
@ -0,0 +1,7 @@
|
|||||||
|
package com.baeldung.kotlin
|
||||||
|
|
||||||
|
class MathematicsOperations {
|
||||||
|
fun addTwoNumbers(a: Int, b: Int): Int {
|
||||||
|
return a + b
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.kotlin;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class JavaCallToKotlinTest {
|
||||||
|
@Test
|
||||||
|
public void givenKotlinClass_whenCallFromJava_shouldProduceResults() {
|
||||||
|
//when
|
||||||
|
int res = new MathematicsOperations().addTwoNumbers(2, 4);
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertEquals(6, res);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.kotlin
|
||||||
|
|
||||||
|
import com.baeldung.java.StringUtils
|
||||||
|
import org.junit.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
|
||||||
|
|
||||||
|
class KotlinScalaInteroperabilityTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenLowercaseString_whenExecuteMethodFromJavaStringUtils_shouldReturnStringUppercase() {
|
||||||
|
//given
|
||||||
|
val name = "tom"
|
||||||
|
|
||||||
|
//whene
|
||||||
|
val res = StringUtils.toUpperCase(name)
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertEquals(res, "TOM")
|
||||||
|
}
|
||||||
|
}
|
19
kotlin/src/test/kotlin/com/baeldung/kotlin/LambdaTest.kt
Normal file
19
kotlin/src/test/kotlin/com/baeldung/kotlin/LambdaTest.kt
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
package com.baeldung.kotlin
|
||||||
|
|
||||||
|
import org.junit.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
|
||||||
|
|
||||||
|
class LambdaTest {
|
||||||
|
@Test
|
||||||
|
fun givenListOfNumber_whenDoingOperationsUsingLambda_shouldReturnProperResult() {
|
||||||
|
//given
|
||||||
|
val listOfNumbers = listOf(1, 2, 3)
|
||||||
|
|
||||||
|
//when
|
||||||
|
val sum = listOfNumbers.reduce { a, b -> a + b }
|
||||||
|
|
||||||
|
//then
|
||||||
|
assertEquals(6, sum)
|
||||||
|
}
|
||||||
|
}
|
1
pom.xml
1
pom.xml
@ -185,6 +185,7 @@
|
|||||||
<module>xstream</module>
|
<module>xstream</module>
|
||||||
|
|
||||||
<module>struts2</module>
|
<module>struts2</module>
|
||||||
|
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
package com.baeldung.sparkjava;
|
package com.baeldung.sparkjava;
|
||||||
|
|
||||||
import static spark.Spark.*;
|
import static spark.Spark.*;
|
||||||
|
|
||||||
public class HelloWorldService {
|
public class HelloWorldService {
|
||||||
|
@ -24,17 +24,13 @@ public class SparkRestExample {
|
|||||||
get("/users", (request, response) -> {
|
get("/users", (request, response) -> {
|
||||||
response.type("application/json");
|
response.type("application/json");
|
||||||
|
|
||||||
return new Gson().toJson(
|
return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, new Gson().toJsonTree(userService.getUsers())));
|
||||||
new StandardResponse(StatusResponse.SUCCESS,new Gson()
|
|
||||||
.toJsonTree(userService.getUsers())));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
get("/users/:id", (request, response) -> {
|
get("/users/:id", (request, response) -> {
|
||||||
response.type("application/json");
|
response.type("application/json");
|
||||||
|
|
||||||
return new Gson().toJson(
|
return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, new Gson().toJsonTree(userService.getUser(request.params(":id")))));
|
||||||
new StandardResponse(StatusResponse.SUCCESS,new Gson()
|
|
||||||
.toJsonTree(userService.getUser(request.params(":id")))));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
put("/users/:id", (request, response) -> {
|
put("/users/:id", (request, response) -> {
|
||||||
@ -44,13 +40,9 @@ public class SparkRestExample {
|
|||||||
User editedUser = userService.editUser(toEdit);
|
User editedUser = userService.editUser(toEdit);
|
||||||
|
|
||||||
if (editedUser != null) {
|
if (editedUser != null) {
|
||||||
return new Gson().toJson(
|
return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, new Gson().toJsonTree(editedUser)));
|
||||||
new StandardResponse(StatusResponse.SUCCESS,new Gson()
|
|
||||||
.toJsonTree(editedUser)));
|
|
||||||
} else {
|
} else {
|
||||||
return new Gson().toJson(
|
return new Gson().toJson(new StandardResponse(StatusResponse.ERROR, new Gson().toJson("User not found or error in edit")));
|
||||||
new StandardResponse(StatusResponse.ERROR,new Gson()
|
|
||||||
.toJson("User not found or error in edit")));
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -58,17 +50,13 @@ public class SparkRestExample {
|
|||||||
response.type("application/json");
|
response.type("application/json");
|
||||||
|
|
||||||
userService.deleteUser(request.params(":id"));
|
userService.deleteUser(request.params(":id"));
|
||||||
return new Gson().toJson(
|
return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, "user deleted"));
|
||||||
new StandardResponse(StatusResponse.SUCCESS, "user deleted"));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
options("/users/:id", (request, response) -> {
|
options("/users/:id", (request, response) -> {
|
||||||
response.type("application/json");
|
response.type("application/json");
|
||||||
|
|
||||||
return new Gson().toJson(
|
return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, (userService.userExist(request.params(":id"))) ? "User exists" : "User does not exists"));
|
||||||
new StandardResponse(StatusResponse.SUCCESS,
|
|
||||||
(userService.userExist(
|
|
||||||
request.params(":id"))) ? "User exists" : "User does not exists" ));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,7 @@
|
|||||||
package com.baeldung.sparkjava;
|
package com.baeldung.sparkjava;
|
||||||
|
|
||||||
public enum StatusResponse {
|
public enum StatusResponse {
|
||||||
SUCCESS ("Success"),
|
SUCCESS("Success"), ERROR("Error");
|
||||||
ERROR ("Error");
|
|
||||||
|
|
||||||
final private String status;
|
final private String status;
|
||||||
|
|
||||||
|
@ -4,9 +4,14 @@ import java.util.Collection;
|
|||||||
|
|
||||||
public interface UserService {
|
public interface UserService {
|
||||||
public void addUser(User user);
|
public void addUser(User user);
|
||||||
|
|
||||||
public Collection<User> getUsers();
|
public Collection<User> getUsers();
|
||||||
|
|
||||||
public User getUser(String id);
|
public User getUser(String id);
|
||||||
|
|
||||||
public User editUser(User user) throws UserException;
|
public User editUser(User user) throws UserException;
|
||||||
|
|
||||||
public void deleteUser(String id);
|
public void deleteUser(String id);
|
||||||
|
|
||||||
public boolean userExist(String id);
|
public boolean userExist(String id);
|
||||||
}
|
}
|
||||||
|
@ -1,39 +0,0 @@
|
|||||||
<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>MyFirstSpringBoot</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
|
||||||
<version>1.4.3.RELEASE</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<name>MyFirstSpringBoot</name>
|
|
||||||
<url>http://maven.apache.org</url>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>junit</groupId>
|
|
||||||
<artifactId>junit</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
</project>
|
|
@ -1,18 +0,0 @@
|
|||||||
package com.baeldung.controller;
|
|
||||||
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
public class HomeController {
|
|
||||||
|
|
||||||
@RequestMapping("/")
|
|
||||||
public String root(){
|
|
||||||
return "Index Page";
|
|
||||||
}
|
|
||||||
|
|
||||||
@RequestMapping("/local")
|
|
||||||
public String local(){
|
|
||||||
return "/local";
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,8 +0,0 @@
|
|||||||
<html>
|
|
||||||
<head>
|
|
||||||
<title>RESOURCE NOT FOUND</title>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h1>404 RESOURCE NOT FOUND</h1>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
@ -1,39 +0,0 @@
|
|||||||
package com.baeldung;
|
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
|
||||||
import org.springframework.test.web.servlet.MockMvc;
|
|
||||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
|
||||||
@SpringBootTest
|
|
||||||
@AutoConfigureMockMvc
|
|
||||||
public class AppTest {
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private MockMvc mvc;
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void getIndex() throws Exception {
|
|
||||||
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andExpect(content().string(equalTo("Index Page")));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void getLocal() throws Exception {
|
|
||||||
mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andExpect(content().string(equalTo("/local")));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -18,12 +18,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
http.authorizeRequests()
|
http.authorizeRequests().anyRequest().hasRole("SYSTEM").and().httpBasic().and().csrf().disable();
|
||||||
.anyRequest().hasRole("SYSTEM")
|
|
||||||
.and()
|
|
||||||
.httpBasic()
|
|
||||||
.and()
|
|
||||||
.csrf()
|
|
||||||
.disable();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -22,19 +22,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
http.sessionManagement()
|
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and().requestMatchers().antMatchers("/eureka/**").and().authorizeRequests().antMatchers("/eureka/**").hasRole("SYSTEM").anyRequest().denyAll().and().httpBasic().and().csrf()
|
||||||
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
|
|
||||||
.and()
|
|
||||||
.requestMatchers()
|
|
||||||
.antMatchers("/eureka/**")
|
|
||||||
.and()
|
|
||||||
.authorizeRequests()
|
|
||||||
.antMatchers("/eureka/**").hasRole("SYSTEM")
|
|
||||||
.anyRequest().denyAll()
|
|
||||||
.and()
|
|
||||||
.httpBasic()
|
|
||||||
.and()
|
|
||||||
.csrf()
|
|
||||||
.disable();
|
.disable();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -42,24 +30,15 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
// no order tag means this is the last security filter to be evaluated
|
// no order tag means this is the last security filter to be evaluated
|
||||||
public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter {
|
public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
@Autowired
|
||||||
|
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||||
auth.inMemoryAuthentication();
|
auth.inMemoryAuthentication();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override protected void configure(HttpSecurity http) throws Exception {
|
@Override
|
||||||
http
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
.sessionManagement()
|
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and().httpBasic().disable().authorizeRequests().antMatchers(HttpMethod.GET, "/").hasRole("ADMIN").antMatchers("/info", "/health").authenticated().anyRequest().denyAll()
|
||||||
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
|
.and().csrf().disable();
|
||||||
.and()
|
|
||||||
.httpBasic()
|
|
||||||
.disable()
|
|
||||||
.authorizeRequests()
|
|
||||||
.antMatchers(HttpMethod.GET, "/").hasRole("ADMIN")
|
|
||||||
.antMatchers("/info","/health").authenticated()
|
|
||||||
.anyRequest().denyAll()
|
|
||||||
.and()
|
|
||||||
.csrf()
|
|
||||||
.disable();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,11 +5,7 @@ import org.springframework.cloud.netflix.feign.FeignClient;
|
|||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
|
||||||
@FeignClient(
|
@FeignClient(name = "rest-producer", url = "http://localhost:9090", fallback = GreetingClient.GreetingClientFallback.class)
|
||||||
name = "rest-producer",
|
|
||||||
url = "http://localhost:9090",
|
|
||||||
fallback = GreetingClient.GreetingClientFallback.class
|
|
||||||
)
|
|
||||||
public interface GreetingClient extends GreetingController {
|
public interface GreetingClient extends GreetingController {
|
||||||
@Component
|
@Component
|
||||||
public static class GreetingClientFallback implements GreetingClient {
|
public static class GreetingClientFallback implements GreetingClient {
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
|
spring.application.name=resource
|
||||||
|
#server.port=0
|
||||||
|
|
||||||
#### cloud
|
#### cloud
|
||||||
spring.application.name=spring-cloud-eureka-client
|
|
||||||
server.port=0
|
|
||||||
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://system:systemPass@localhost:8761/eureka}
|
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://system:systemPass@localhost:8761/eureka}
|
||||||
eureka.instance.preferIpAddress=true
|
eureka.instance.preferIpAddress=true
|
||||||
|
|
@ -1,5 +1,9 @@
|
|||||||
#### cloud
|
spring.application.name=spring-cloud-rest-server
|
||||||
server.port=8761
|
server.port=8761
|
||||||
|
|
||||||
|
#### cloud
|
||||||
|
eureka.instance.hostname=localhost
|
||||||
|
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://system:systemPass@localhost:8761/eureka}
|
||||||
eureka.client.registerWithEureka=false
|
eureka.client.registerWithEureka=false
|
||||||
eureka.client.fetchRegistry=false
|
eureka.client.fetchRegistry=false
|
||||||
|
|
@ -7,9 +7,10 @@
|
|||||||
<artifactId>spring-cloud-rest</artifactId>
|
<artifactId>spring-cloud-rest</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
<modules>
|
<modules>
|
||||||
|
<module>spring-cloud-rest-config</module>
|
||||||
<module>spring-cloud-rest-server</module>
|
<module>spring-cloud-rest-server</module>
|
||||||
<module>spring-cloud-rest-client-1</module>
|
<module>spring-cloud-rest-books-api</module>
|
||||||
<module>spring-cloud-rest-client-2</module>
|
<module>spring-cloud-rest-reviews-api</module>
|
||||||
</modules>
|
</modules>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
@ -4,12 +4,12 @@
|
|||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>org.baeldung</groupId>
|
<groupId>org.baeldung</groupId>
|
||||||
<artifactId>spring-cloud-rest-client-1</artifactId>
|
<artifactId>spring-cloud-rest-books-api</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<name>spring-cloud-rest</name>
|
<name>spring-cloud-rest-books-api</name>
|
||||||
<description>Demo project for Spring Boot</description>
|
<description>Simple books API</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
@ -26,6 +26,10 @@
|
|||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-starter-config</artifactId>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.cloud</groupId>
|
<groupId>org.springframework.cloud</groupId>
|
||||||
<artifactId>spring-cloud-starter-eureka</artifactId>
|
<artifactId>spring-cloud-starter-eureka</artifactId>
|
@ -6,9 +6,9 @@ import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
|
|||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
@EnableEurekaClient
|
@EnableEurekaClient
|
||||||
public class SpringCloudRestClientApplication {
|
public class BooksApiApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(SpringCloudRestClientApplication.class, args);
|
SpringApplication.run(BooksApiApplication.class, args);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -104,13 +104,7 @@ public class Book {
|
|||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
final StringBuilder builder = new StringBuilder();
|
final StringBuilder builder = new StringBuilder();
|
||||||
builder.append("Book [id=")
|
builder.append("Book [id=").append(id).append(", title=").append(title).append(", author=").append(author).append("]");
|
||||||
.append(id)
|
|
||||||
.append(", title=")
|
|
||||||
.append(title)
|
|
||||||
.append(", author=")
|
|
||||||
.append(author)
|
|
||||||
.append("]");
|
|
||||||
return builder.toString();
|
return builder.toString();
|
||||||
}
|
}
|
||||||
|
|
@ -0,0 +1,9 @@
|
|||||||
|
spring.cloud.config.name=resource
|
||||||
|
spring.cloud.config.discovery.service-id=config
|
||||||
|
spring.cloud.config.discovery.enabled=true
|
||||||
|
spring.cloud.config.username=configUser
|
||||||
|
spring.cloud.config.password=configPassword
|
||||||
|
|
||||||
|
eureka.client.serviceUrl.defaultZone=http://system:systemPass@localhost:8761/eureka
|
||||||
|
|
||||||
|
server.port=8084
|
@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner;
|
|||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest
|
@SpringBootTest
|
||||||
public class SpringCloudRestClientApplicationTests {
|
public class BooksApiIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void contextLoads() {
|
public void contextLoads() {
|
@ -19,7 +19,7 @@ import org.springframework.http.MediaType;
|
|||||||
import org.springframework.test.context.junit4.SpringRunner;
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest(classes = { SpringCloudRestClientApplication.class }, webEnvironment = WebEnvironment.DEFINED_PORT)
|
@SpringBootTest(classes = { BooksApiApplication.class }, webEnvironment = WebEnvironment.DEFINED_PORT)
|
||||||
public class RestApiLiveTest {
|
public class RestApiLiveTest {
|
||||||
|
|
||||||
private static final String API_URI = "http://localhost:8084/books";
|
private static final String API_URI = "http://localhost:8084/books";
|
||||||
@ -44,8 +44,7 @@ public class RestApiLiveTest {
|
|||||||
|
|
||||||
final Response response = RestAssured.get(location);
|
final Response response = RestAssured.get(location);
|
||||||
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||||
assertEquals(book.getTitle(), response.jsonPath()
|
assertEquals(book.getTitle(), response.jsonPath().get("title"));
|
||||||
.get("title"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -55,8 +54,7 @@ public class RestApiLiveTest {
|
|||||||
|
|
||||||
final Response response = RestAssured.get(API_URI + "/search/findByTitle?title=" + book.getTitle());
|
final Response response = RestAssured.get(API_URI + "/search/findByTitle?title=" + book.getTitle());
|
||||||
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||||
assertTrue(response.jsonPath()
|
assertTrue(response.jsonPath().getLong("page.totalElements") > 0);
|
||||||
.getLong("page.totalElements") > 0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -69,8 +67,7 @@ public class RestApiLiveTest {
|
|||||||
public void whenGetNotExistBookByName_thenNotFound() {
|
public void whenGetNotExistBookByName_thenNotFound() {
|
||||||
final Response response = RestAssured.get(API_URI + "/search/findByTitle?title=" + randomAlphabetic(20));
|
final Response response = RestAssured.get(API_URI + "/search/findByTitle?title=" + randomAlphabetic(20));
|
||||||
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||||
assertTrue(response.jsonPath()
|
assertTrue(response.jsonPath().getLong("page.totalElements") == 0);
|
||||||
.getLong("page.totalElements") == 0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// POST
|
// POST
|
||||||
@ -78,10 +75,7 @@ public class RestApiLiveTest {
|
|||||||
public void whenCreateNewBook_thenCreated() {
|
public void whenCreateNewBook_thenCreated() {
|
||||||
final Book book = createRandomBook();
|
final Book book = createRandomBook();
|
||||||
|
|
||||||
final Response response = RestAssured.given()
|
final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).post(API_URI);
|
||||||
.contentType(MediaType.APPLICATION_JSON_VALUE)
|
|
||||||
.body(book)
|
|
||||||
.post(API_URI);
|
|
||||||
assertEquals(HttpStatus.CREATED.value(), response.getStatusCode());
|
assertEquals(HttpStatus.CREATED.value(), response.getStatusCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -91,10 +85,7 @@ public class RestApiLiveTest {
|
|||||||
createBookAsUri(book);
|
createBookAsUri(book);
|
||||||
|
|
||||||
// duplicate
|
// duplicate
|
||||||
final Response response = RestAssured.given()
|
final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).post(API_URI);
|
||||||
.contentType(MediaType.APPLICATION_JSON_VALUE)
|
|
||||||
.body(book)
|
|
||||||
.post(API_URI);
|
|
||||||
assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode());
|
assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -103,10 +94,7 @@ public class RestApiLiveTest {
|
|||||||
final Book book = createRandomBook();
|
final Book book = createRandomBook();
|
||||||
book.setAuthor(null);
|
book.setAuthor(null);
|
||||||
|
|
||||||
final Response response = RestAssured.given()
|
final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).post(API_URI);
|
||||||
.contentType(MediaType.APPLICATION_JSON_VALUE)
|
|
||||||
.body(book)
|
|
||||||
.post(API_URI);
|
|
||||||
assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode());
|
assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -118,17 +106,13 @@ public class RestApiLiveTest {
|
|||||||
|
|
||||||
// update
|
// update
|
||||||
book.setAuthor("newAuthor");
|
book.setAuthor("newAuthor");
|
||||||
Response response = RestAssured.given()
|
Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).put(location);
|
||||||
.contentType(MediaType.APPLICATION_JSON_VALUE)
|
|
||||||
.body(book)
|
|
||||||
.put(location);
|
|
||||||
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||||
|
|
||||||
// check if changes saved
|
// check if changes saved
|
||||||
response = RestAssured.get(location);
|
response = RestAssured.get(location);
|
||||||
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||||
assertEquals("newAuthor", response.jsonPath()
|
assertEquals("newAuthor", response.jsonPath().get("author"));
|
||||||
.get("author"));
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -163,12 +147,8 @@ public class RestApiLiveTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String createBookAsUri(Book book) {
|
private String createBookAsUri(Book book) {
|
||||||
final Response response = RestAssured.given()
|
final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).post(API_URI);
|
||||||
.contentType(MediaType.APPLICATION_JSON_VALUE)
|
return response.jsonPath().get("_links.self.href");
|
||||||
.body(book)
|
|
||||||
.post(API_URI);
|
|
||||||
return response.jsonPath()
|
|
||||||
.get("_links.self.href");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -18,7 +18,7 @@ import org.springframework.test.context.junit4.SpringRunner;
|
|||||||
import redis.clients.jedis.Jedis;
|
import redis.clients.jedis.Jedis;
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest(classes = { SpringCloudRestClientApplication.class, SessionConfig.class }, webEnvironment = WebEnvironment.DEFINED_PORT)
|
@SpringBootTest(classes = { BooksApiApplication.class, SessionConfig.class }, webEnvironment = WebEnvironment.DEFINED_PORT)
|
||||||
public class SessionLiveTest {
|
public class SessionLiveTest {
|
||||||
|
|
||||||
private Jedis jedis;
|
private Jedis jedis;
|
||||||
@ -45,11 +45,7 @@ public class SessionLiveTest {
|
|||||||
@Test
|
@Test
|
||||||
public void givenAuthorizedUser_whenDeleteSession_thenUnauthorized() {
|
public void givenAuthorizedUser_whenDeleteSession_thenUnauthorized() {
|
||||||
// authorize User
|
// authorize User
|
||||||
Response response = RestAssured.given()
|
Response response = RestAssured.given().auth().preemptive().basic("user", "userPass").get(API_URI);
|
||||||
.auth()
|
|
||||||
.preemptive()
|
|
||||||
.basic("user", "userPass")
|
|
||||||
.get(API_URI);
|
|
||||||
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||||
final String sessionCookie = response.getCookie("SESSION");
|
final String sessionCookie = response.getCookie("SESSION");
|
||||||
|
|
||||||
@ -58,18 +54,14 @@ public class SessionLiveTest {
|
|||||||
assertTrue(redisResult.size() > 0);
|
assertTrue(redisResult.size() > 0);
|
||||||
|
|
||||||
// login with cookie
|
// login with cookie
|
||||||
response = RestAssured.given()
|
response = RestAssured.given().cookie("SESSION", sessionCookie).get(API_URI);
|
||||||
.cookie("SESSION", sessionCookie)
|
|
||||||
.get(API_URI);
|
|
||||||
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||||
|
|
||||||
// empty redis
|
// empty redis
|
||||||
jedis.flushAll();
|
jedis.flushAll();
|
||||||
|
|
||||||
// login with cookie again
|
// login with cookie again
|
||||||
response = RestAssured.given()
|
response = RestAssured.given().cookie("SESSION", sessionCookie).get(API_URI);
|
||||||
.cookie("SESSION", sessionCookie)
|
|
||||||
.get(API_URI);
|
|
||||||
assertEquals(HttpStatus.UNAUTHORIZED.value(), response.getStatusCode());
|
assertEquals(HttpStatus.UNAUTHORIZED.value(), response.getStatusCode());
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,19 +0,0 @@
|
|||||||
#### cloud
|
|
||||||
spring.application.name=spring-cloud-eureka-client
|
|
||||||
server.port=8084
|
|
||||||
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://system:systemPass@localhost:8761/eureka}
|
|
||||||
eureka.instance.preferIpAddress=true
|
|
||||||
|
|
||||||
#### persistence
|
|
||||||
spring.datasource.driver-class-name=org.h2.Driver
|
|
||||||
spring.datasource.url=jdbc:h2:mem:cloud_rest;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
|
|
||||||
spring.datasource.username=sa
|
|
||||||
spring.datasource.password=
|
|
||||||
|
|
||||||
#### security
|
|
||||||
security.basic.enabled=true
|
|
||||||
security.basic.path=/**
|
|
||||||
security.user.name=user
|
|
||||||
security.user.password=userPass
|
|
||||||
security.user.role=USER
|
|
||||||
security.sessions=always
|
|
24
spring-cloud/spring-cloud-rest/spring-cloud-rest-config/.gitignore
vendored
Normal file
24
spring-cloud/spring-cloud-rest/spring-cloud-rest-config/.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
target/
|
||||||
|
!.mvn/wrapper/maven-wrapper.jar
|
||||||
|
|
||||||
|
### STS ###
|
||||||
|
.apt_generated
|
||||||
|
.classpath
|
||||||
|
.factorypath
|
||||||
|
.project
|
||||||
|
.settings
|
||||||
|
.springBeans
|
||||||
|
|
||||||
|
### IntelliJ IDEA ###
|
||||||
|
.idea
|
||||||
|
*.iws
|
||||||
|
*.iml
|
||||||
|
*.ipr
|
||||||
|
|
||||||
|
### NetBeans ###
|
||||||
|
nbproject/private/
|
||||||
|
build/
|
||||||
|
nbbuild/
|
||||||
|
dist/
|
||||||
|
nbdist/
|
||||||
|
.nb-gradle/
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user