Merge remote-tracking branch 'origin/master'
This commit is contained in:
commit
6c2ed878c0
|
@ -27,3 +27,4 @@ target/
|
|||
|
||||
spring-openid/src/main/resources/application.properties
|
||||
.recommenders/
|
||||
/spring-hibernate4/nbproject/
|
|
@ -18,9 +18,7 @@ public class Dijkstra {
|
|||
while (unsettledNodes.size() != 0) {
|
||||
Node currentNode = getLowestDistanceNode(unsettledNodes);
|
||||
unsettledNodes.remove(currentNode);
|
||||
for (Entry<Node, Integer> adjacencyPair : currentNode
|
||||
.getAdjacentNodes()
|
||||
.entrySet()) {
|
||||
for (Entry<Node, Integer> adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
|
||||
Node adjacentNode = adjacencyPair.getKey();
|
||||
Integer edgeWeigh = adjacencyPair.getValue();
|
||||
|
||||
|
|
|
@ -55,29 +55,19 @@ public class DijkstraAlgorithmTest {
|
|||
for (Node node : graph.getNodes()) {
|
||||
switch (node.getName()) {
|
||||
case "B":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeB));
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeB));
|
||||
break;
|
||||
case "C":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeC));
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeC));
|
||||
break;
|
||||
case "D":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeD));
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeD));
|
||||
break;
|
||||
case "E":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeE));
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeE));
|
||||
break;
|
||||
case "F":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeF));
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeF));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -27,17 +27,12 @@ public class BuilderProcessor extends AbstractProcessor {
|
|||
|
||||
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
|
||||
|
||||
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream()
|
||||
.collect(Collectors.partitioningBy(element ->
|
||||
((ExecutableType) element.asType()).getParameterTypes().size() == 1
|
||||
&& element.getSimpleName().toString().startsWith("set")));
|
||||
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream().collect(Collectors.partitioningBy(element -> ((ExecutableType) element.asType()).getParameterTypes().size() == 1 && element.getSimpleName().toString().startsWith("set")));
|
||||
|
||||
List<Element> setters = annotatedMethods.get(true);
|
||||
List<Element> otherMethods = annotatedMethods.get(false);
|
||||
|
||||
otherMethods.forEach(element ->
|
||||
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
|
||||
"@BuilderProperty must be applied to a setXxx method with a single argument", element));
|
||||
otherMethods.forEach(element -> processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@BuilderProperty must be applied to a setXxx method with a single argument", element));
|
||||
|
||||
if (setters.isEmpty()) {
|
||||
continue;
|
||||
|
@ -45,11 +40,7 @@ public class BuilderProcessor extends AbstractProcessor {
|
|||
|
||||
String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString();
|
||||
|
||||
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(
|
||||
setter -> setter.getSimpleName().toString(),
|
||||
setter -> ((ExecutableType) setter.asType())
|
||||
.getParameterTypes().get(0).toString()
|
||||
));
|
||||
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(setter -> setter.getSimpleName().toString(), setter -> ((ExecutableType) setter.asType()).getParameterTypes().get(0).toString()));
|
||||
|
||||
try {
|
||||
writeBuilderFile(className, setterMap);
|
||||
|
|
|
@ -9,10 +9,7 @@ public class PersonBuilderTest {
|
|||
@Test
|
||||
public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
|
||||
|
||||
Person person = new PersonBuilder()
|
||||
.setAge(25)
|
||||
.setName("John")
|
||||
.build();
|
||||
Person person = new PersonBuilder().setAge(25).setName("John").build();
|
||||
|
||||
assertEquals(25, person.getAge());
|
||||
assertEquals("John", person.getName());
|
||||
|
|
|
@ -8,7 +8,7 @@ public class Server {
|
|||
String address = "http://localhost:8080/baeldung";
|
||||
Endpoint.publish(address, implementor);
|
||||
System.out.println("Server ready...");
|
||||
Thread.sleep(60 * 1000);
|
||||
Thread.sleep(60 * 1000);
|
||||
System.out.println("Server exiting");
|
||||
System.exit(0);
|
||||
}
|
||||
|
|
|
@ -11,7 +11,7 @@ public class RestfulServer {
|
|||
factoryBean.setResourceProvider(new SingletonResourceProvider(new CourseRepository()));
|
||||
factoryBean.setAddress("http://localhost:8080/");
|
||||
Server server = factoryBean.create();
|
||||
|
||||
|
||||
System.out.println("Server ready...");
|
||||
Thread.sleep(60 * 1000);
|
||||
System.out.println("Server exiting");
|
||||
|
|
|
@ -38,8 +38,7 @@ public class AssertJCoreTest {
|
|||
public void whenCheckingForElement_thenContains() throws Exception {
|
||||
List<String> list = Arrays.asList("1", "2", "3");
|
||||
|
||||
assertThat(list)
|
||||
.contains("1");
|
||||
assertThat(list).contains("1");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -50,12 +49,7 @@ public class AssertJCoreTest {
|
|||
assertThat(list).startsWith("1");
|
||||
assertThat(list).doesNotContainNull();
|
||||
|
||||
assertThat(list)
|
||||
.isNotEmpty()
|
||||
.contains("1")
|
||||
.startsWith("1")
|
||||
.doesNotContainNull()
|
||||
.containsSequence("2", "3");
|
||||
assertThat(list).isNotEmpty().contains("1").startsWith("1").doesNotContainNull().containsSequence("2", "3");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -67,11 +61,7 @@ public class AssertJCoreTest {
|
|||
public void whenCheckingCharacter_thenIsUnicode() throws Exception {
|
||||
char someCharacter = 'c';
|
||||
|
||||
assertThat(someCharacter)
|
||||
.isNotEqualTo('a')
|
||||
.inUnicode()
|
||||
.isGreaterThanOrEqualTo('b')
|
||||
.isLowerCase();
|
||||
assertThat(someCharacter).isNotEqualTo('a').inUnicode().isGreaterThanOrEqualTo('b').isLowerCase();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -94,11 +84,7 @@ public class AssertJCoreTest {
|
|||
final File someFile = File.createTempFile("aaa", "bbb");
|
||||
someFile.deleteOnExit();
|
||||
|
||||
assertThat(someFile)
|
||||
.exists()
|
||||
.isFile()
|
||||
.canRead()
|
||||
.canWrite();
|
||||
assertThat(someFile).exists().isFile().canRead().canWrite();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -113,20 +99,14 @@ public class AssertJCoreTest {
|
|||
public void whenGivenMap_then() throws Exception {
|
||||
Map<Integer, String> map = Maps.newHashMap(2, "a");
|
||||
|
||||
assertThat(map)
|
||||
.isNotEmpty()
|
||||
.containsKey(2)
|
||||
.doesNotContainKeys(10)
|
||||
.contains(entry(2, "a"));
|
||||
assertThat(map).isNotEmpty().containsKey(2).doesNotContainKeys(10).contains(entry(2, "a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGivenException_then() throws Exception {
|
||||
Exception ex = new Exception("abc");
|
||||
|
||||
assertThat(ex)
|
||||
.hasNoCause()
|
||||
.hasMessageEndingWith("c");
|
||||
assertThat(ex).hasNoCause().hasMessageEndingWith("c");
|
||||
}
|
||||
|
||||
@Ignore // IN ORDER TO TEST, REMOVE THIS LINE
|
||||
|
@ -134,8 +114,6 @@ public class AssertJCoreTest {
|
|||
public void whenRunningAssertion_thenDescribed() throws Exception {
|
||||
Person person = new Person("Alex", 34);
|
||||
|
||||
assertThat(person.getAge())
|
||||
.as("%s's age should be equal to 100")
|
||||
.isEqualTo(100);
|
||||
assertThat(person.getAge()).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 temp2 = File.createTempFile("bael", "dung2");
|
||||
|
||||
assertThat(Files.asByteSource(temp1))
|
||||
.hasSize(0)
|
||||
.hasSameContentAs(Files.asByteSource(temp2));
|
||||
assertThat(Files.asByteSource(temp1)).hasSize(0).hasSameContentAs(Files.asByteSource(temp2));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -37,11 +35,7 @@ public class AssertJGuavaTest {
|
|||
mmap.put(1, "one");
|
||||
mmap.put(1, "1");
|
||||
|
||||
assertThat(mmap)
|
||||
.hasSize(2)
|
||||
.containsKeys(1)
|
||||
.contains(entry(1, "one"))
|
||||
.contains(entry(1, "1"));
|
||||
assertThat(mmap).hasSize(2).containsKeys(1).contains(entry(1, "one")).contains(entry(1, "1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -62,31 +56,21 @@ public class AssertJGuavaTest {
|
|||
mmap2.put(1, "one");
|
||||
mmap2.put(1, "1");
|
||||
|
||||
assertThat(mmap1)
|
||||
.containsAllEntriesOf(mmap2)
|
||||
.containsAllEntriesOf(mmap1_clone)
|
||||
.hasSameEntriesAs(mmap1_clone);
|
||||
assertThat(mmap1).containsAllEntriesOf(mmap2).containsAllEntriesOf(mmap1_clone).hasSameEntriesAs(mmap1_clone);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
|
||||
final Optional<String> something = Optional.of("something");
|
||||
|
||||
assertThat(something)
|
||||
.isPresent()
|
||||
.extractingValue()
|
||||
.isEqualTo("something");
|
||||
assertThat(something).isPresent().extractingValue().isEqualTo("something");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||
final Range<String> range = Range.openClosed("a", "g");
|
||||
|
||||
assertThat(range)
|
||||
.hasOpenedLowerBound()
|
||||
.isNotEmpty()
|
||||
.hasClosedUpperBound()
|
||||
.contains("b");
|
||||
assertThat(range).hasOpenedLowerBound().isNotEmpty().hasClosedUpperBound().contains("b");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -96,10 +80,7 @@ public class AssertJGuavaTest {
|
|||
map.put(Range.closed(0, 60), "F");
|
||||
map.put(Range.closed(61, 70), "D");
|
||||
|
||||
assertThat(map)
|
||||
.isNotEmpty()
|
||||
.containsKeys(0)
|
||||
.contains(MapEntry.entry(34, "F"));
|
||||
assertThat(map).isNotEmpty().containsKeys(0).contains(MapEntry.entry(34, "F"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -109,13 +90,7 @@ public class AssertJGuavaTest {
|
|||
table.put(1, "A", "PRESENT");
|
||||
table.put(1, "B", "ABSENT");
|
||||
|
||||
assertThat(table)
|
||||
.hasRowCount(1)
|
||||
.containsValues("ABSENT")
|
||||
.containsCell(1, "B", "ABSENT");
|
||||
assertThat(table).hasRowCount(1).containsValues("ABSENT").containsCell(1, "B", "ABSENT");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -20,20 +20,14 @@ public class AssertJJava8Test {
|
|||
public void givenOptional_shouldAssert() throws Exception {
|
||||
final Optional<String> givenOptional = Optional.of("something");
|
||||
|
||||
assertThat(givenOptional)
|
||||
.isPresent()
|
||||
.hasValue("something");
|
||||
assertThat(givenOptional).isPresent().hasValue("something");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPredicate_shouldAssert() throws Exception {
|
||||
final Predicate<String> predicate = s -> s.length() > 4;
|
||||
|
||||
assertThat(predicate)
|
||||
.accepts("aaaaa", "bbbbb")
|
||||
.rejects("a", "b")
|
||||
.acceptsAll(asList("aaaaa", "bbbbb"))
|
||||
.rejectsAll(asList("a", "b"));
|
||||
assertThat(predicate).accepts("aaaaa", "bbbbb").rejects("a", "b").acceptsAll(asList("aaaaa", "bbbbb")).rejectsAll(asList("a", "b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -41,92 +35,74 @@ public class AssertJJava8Test {
|
|||
final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
|
||||
final LocalDate todayDate = LocalDate.now();
|
||||
|
||||
assertThat(givenLocalDate)
|
||||
.isBefore(LocalDate.of(2020, 7, 8))
|
||||
.isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
||||
assertThat(givenLocalDate).isBefore(LocalDate.of(2020, 7, 8)).isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
||||
|
||||
assertThat(todayDate)
|
||||
.isAfter(LocalDate.of(1989, 7, 8))
|
||||
.isToday();
|
||||
assertThat(todayDate).isAfter(LocalDate.of(1989, 7, 8)).isToday();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTime_shouldAssert() throws Exception {
|
||||
final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
|
||||
|
||||
assertThat(givenLocalDate)
|
||||
.isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
||||
assertThat(givenLocalDate).isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalTime_shouldAssert() throws Exception {
|
||||
final LocalTime givenLocalTime = LocalTime.of(12, 15);
|
||||
|
||||
assertThat(givenLocalTime)
|
||||
.isAfter(LocalTime.of(1, 0))
|
||||
.hasSameHourAs(LocalTime.of(12, 0));
|
||||
assertThat(givenLocalTime).isAfter(LocalTime.of(1, 0)).hasSameHourAs(LocalTime.of(12, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtracting() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::getYear)
|
||||
.contains(2015);
|
||||
assertThat(givenList).flatExtracting(LocalDate::getYear).contains(2015);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::isLeapYear)
|
||||
.contains(true);
|
||||
assertThat(givenList).flatExtracting(LocalDate::isLeapYear).contains(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtractingClass() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(Object::getClass)
|
||||
.contains(LocalDate.class);
|
||||
assertThat(givenList).flatExtracting(Object::getClass).contains(LocalDate.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth)
|
||||
.contains(2015, 6);
|
||||
assertThat(givenList).flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth).contains(2015, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_shouldSatisfy() throws Exception {
|
||||
final String givenString = "someString";
|
||||
|
||||
assertThat(givenString)
|
||||
.satisfies(s -> {
|
||||
assertThat(s).isNotEmpty();
|
||||
assertThat(s).hasSize(10);
|
||||
});
|
||||
assertThat(givenString).satisfies(s -> {
|
||||
assertThat(s).isNotEmpty();
|
||||
assertThat(s).hasSize(10);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_shouldMatch() throws Exception {
|
||||
final String emptyString = "";
|
||||
|
||||
assertThat(emptyString)
|
||||
.matches(String::isEmpty);
|
||||
assertThat(emptyString).matches(String::isEmpty);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
|
||||
final List<String> givenList = Arrays.asList("");
|
||||
|
||||
assertThat(givenList)
|
||||
.hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
||||
assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,12 +4,12 @@ import com.google.auto.value.AutoValue;
|
|||
|
||||
@AutoValue
|
||||
public abstract class AutoValueMoney {
|
||||
public abstract String getCurrency();
|
||||
public abstract String getCurrency();
|
||||
|
||||
public abstract long getAmount();
|
||||
public abstract long getAmount();
|
||||
|
||||
public static AutoValueMoney create(String currency, long amount) {
|
||||
return new AutoValue_AutoValueMoney(currency, amount);
|
||||
public static AutoValueMoney create(String currency, long amount) {
|
||||
return new AutoValue_AutoValueMoney(currency, amount);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,20 +4,20 @@ import com.google.auto.value.AutoValue;
|
|||
|
||||
@AutoValue
|
||||
public abstract class AutoValueMoneyWithBuilder {
|
||||
public abstract String getCurrency();
|
||||
public abstract String getCurrency();
|
||||
|
||||
public abstract long getAmount();
|
||||
public abstract long getAmount();
|
||||
|
||||
static Builder builder() {
|
||||
return new AutoValue_AutoValueMoneyWithBuilder.Builder();
|
||||
}
|
||||
static Builder builder() {
|
||||
return new AutoValue_AutoValueMoneyWithBuilder.Builder();
|
||||
}
|
||||
|
||||
@AutoValue.Builder
|
||||
abstract static class Builder {
|
||||
abstract Builder setCurrency(String currency);
|
||||
@AutoValue.Builder
|
||||
abstract static class Builder {
|
||||
abstract Builder setCurrency(String currency);
|
||||
|
||||
abstract Builder setAmount(long amount);
|
||||
abstract Builder setAmount(long amount);
|
||||
|
||||
abstract AutoValueMoneyWithBuilder build();
|
||||
}
|
||||
abstract AutoValueMoneyWithBuilder build();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,49 +3,49 @@ package com.baeldung.autovalue;
|
|||
import java.util.Objects;
|
||||
|
||||
public final class Foo {
|
||||
private final String text;
|
||||
private final int number;
|
||||
private final String text;
|
||||
private final int number;
|
||||
|
||||
public Foo(String text, int number) {
|
||||
this.text = text;
|
||||
this.number = number;
|
||||
}
|
||||
public Foo(String text, int number) {
|
||||
this.text = text;
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public int getNumber() {
|
||||
return number;
|
||||
}
|
||||
public int getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(text, number);
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(text, number);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Foo [text=" + text + ", number=" + number + "]";
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Foo [text=" + text + ", number=" + number + "]";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Foo other = (Foo) obj;
|
||||
if (number != other.number)
|
||||
return false;
|
||||
if (text == null) {
|
||||
if (other.text != null)
|
||||
return false;
|
||||
} else if (!text.equals(other.text))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Foo other = (Foo) obj;
|
||||
if (number != other.number)
|
||||
return false;
|
||||
if (text == null) {
|
||||
if (other.text != null)
|
||||
return false;
|
||||
} else if (!text.equals(other.text))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,52 +1,53 @@
|
|||
package com.baeldung.autovalue;
|
||||
|
||||
public final class ImmutableMoney {
|
||||
private final long amount;
|
||||
private final String currency;
|
||||
public ImmutableMoney(long amount, String currency) {
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + (int) (amount ^ (amount >>> 32));
|
||||
result = prime * result
|
||||
+ ((currency == null) ? 0 : currency.hashCode());
|
||||
return result;
|
||||
}
|
||||
private final long amount;
|
||||
private final String currency;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
ImmutableMoney other = (ImmutableMoney) obj;
|
||||
if (amount != other.amount)
|
||||
return false;
|
||||
if (currency == null) {
|
||||
if (other.currency != null)
|
||||
return false;
|
||||
} else if (!currency.equals(other.currency))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
public ImmutableMoney(long amount, String currency) {
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + (int) (amount ^ (amount >>> 32));
|
||||
result = prime * result + ((currency == null) ? 0 : currency.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
ImmutableMoney other = (ImmutableMoney) obj;
|
||||
if (amount != other.amount)
|
||||
return false;
|
||||
if (currency == null) {
|
||||
if (other.currency != null)
|
||||
return false;
|
||||
} else if (!currency.equals(other.currency))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ImmutableMoney [amount=" + amount + ", currency=" + currency
|
||||
+ "]";
|
||||
}
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ImmutableMoney [amount=" + amount + ", currency=" + currency + "]";
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,35 +1,34 @@
|
|||
package com.baeldung.autovalue;
|
||||
|
||||
public class MutableMoney {
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MutableMoney [amount=" + amount + ", currency=" + currency
|
||||
+ "]";
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MutableMoney [amount=" + amount + ", currency=" + currency + "]";
|
||||
}
|
||||
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setAmount(long amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
public void setAmount(long amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public void setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
}
|
||||
public void setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
private long amount;
|
||||
private String currency;
|
||||
private long amount;
|
||||
private String currency;
|
||||
|
||||
public MutableMoney(long amount, String currency) {
|
||||
super();
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
public MutableMoney(long amount, String currency) {
|
||||
super();
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -5,55 +5,59 @@ import static org.junit.Assert.*;
|
|||
import org.junit.Test;
|
||||
|
||||
public class MoneyUnitTest {
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
||||
MutableMoney m1 = new MutableMoney(10000, "USD");
|
||||
MutableMoney m2 = new MutableMoney(10000, "USD");
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
||||
MutableMoney m1 = new MutableMoney(10000, "USD");
|
||||
MutableMoney m2 = new MutableMoney(10000, "USD");
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() {
|
||||
ImmutableMoney m1 = new ImmutableMoney(10000, "USD");
|
||||
ImmutableMoney m2 = new ImmutableMoney(10000, "USD");
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() {
|
||||
ImmutableMoney m1 = new ImmutableMoney(10000, "USD");
|
||||
ImmutableMoney m2 = new ImmutableMoney(10000, "USD");
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoney m = AutoValueMoney.create("USD", 10000);
|
||||
assertEquals(m.getAmount(), 10000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
@Test
|
||||
public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoney m = AutoValueMoney.create("USD", 10000);
|
||||
assertEquals(m.getAmount(), 10000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("USD", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertEquals(m.getAmount(), 5000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
@Test
|
||||
public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("USD", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertEquals(m.getAmount(), 5000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,16 +1,16 @@
|
|||
package com.baeldung.java9.language;
|
||||
|
||||
public interface PrivateInterface {
|
||||
|
||||
|
||||
private static String staticPrivate() {
|
||||
return "static private";
|
||||
}
|
||||
|
||||
|
||||
private String instancePrivate() {
|
||||
return "instance private";
|
||||
}
|
||||
|
||||
public default void check(){
|
||||
|
||||
public default void check() {
|
||||
String result = staticPrivate();
|
||||
if (!result.equals("static private"))
|
||||
throw new AssertionError("Incorrect result for static private interface method");
|
||||
|
|
|
@ -8,37 +8,36 @@ import java.time.Duration;
|
|||
import java.time.Instant;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
|
||||
public class ProcessUtils {
|
||||
|
||||
public static String getClassPath(){
|
||||
public static String getClassPath() {
|
||||
String cp = System.getProperty("java.class.path");
|
||||
System.out.println("ClassPath is "+cp);
|
||||
System.out.println("ClassPath is " + cp);
|
||||
return cp;
|
||||
}
|
||||
|
||||
public static File getJavaCmd() throws IOException{
|
||||
public static File getJavaCmd() throws IOException {
|
||||
String javaHome = System.getProperty("java.home");
|
||||
File javaCmd;
|
||||
if(System.getProperty("os.name").startsWith("Win")){
|
||||
if (System.getProperty("os.name").startsWith("Win")) {
|
||||
javaCmd = new File(javaHome, "bin/java.exe");
|
||||
}else{
|
||||
} else {
|
||||
javaCmd = new File(javaHome, "bin/java");
|
||||
}
|
||||
if(javaCmd.canExecute()){
|
||||
if (javaCmd.canExecute()) {
|
||||
return javaCmd;
|
||||
}else{
|
||||
} else {
|
||||
throw new UnsupportedOperationException(javaCmd.getCanonicalPath() + " is not executable");
|
||||
}
|
||||
}
|
||||
|
||||
public static String getMainClass(){
|
||||
public static String getMainClass() {
|
||||
return System.getProperty("sun.java.command");
|
||||
}
|
||||
|
||||
public static String getSystemProperties(){
|
||||
StringBuilder sb = new StringBuilder();
|
||||
System.getProperties().forEach((s1, s2) -> sb.append(s1 +" - "+ s2) );
|
||||
public static String getSystemProperties() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
System.getProperties().forEach((s1, s2) -> sb.append(s1 + " - " + s2));
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,7 +8,6 @@ public class ServiceMain {
|
|||
ProcessHandle thisProcess = ProcessHandle.current();
|
||||
long pid = thisProcess.getPid();
|
||||
|
||||
|
||||
Optional<String[]> opArgs = Optional.ofNullable(args);
|
||||
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() {
|
||||
assertEquals(4, listOfOptionals.size());
|
||||
|
||||
List<String> filteredList = listOfOptionals.stream()
|
||||
.filter(Optional::isPresent)
|
||||
.map(Optional::get)
|
||||
.collect(Collectors.toList());
|
||||
List<String> filteredList = listOfOptionals.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
|
||||
|
||||
assertEquals(2, filteredList.size());
|
||||
assertEquals("foo", filteredList.get(0));
|
||||
|
@ -33,9 +30,7 @@ public class Java9OptionalsStreamTest {
|
|||
public void filterOutPresentOptionalsWithFlatMap() {
|
||||
assertEquals(4, listOfOptionals.size());
|
||||
|
||||
List<String> filteredList = listOfOptionals.stream()
|
||||
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
|
||||
.collect(Collectors.toList());
|
||||
List<String> filteredList = listOfOptionals.stream().flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()).collect(Collectors.toList());
|
||||
assertEquals(2, filteredList.size());
|
||||
|
||||
assertEquals("foo", filteredList.get(0));
|
||||
|
@ -46,9 +41,7 @@ public class Java9OptionalsStreamTest {
|
|||
public void filterOutPresentOptionalsWithFlatMap2() {
|
||||
assertEquals(4, listOfOptionals.size());
|
||||
|
||||
List<String> filteredList = listOfOptionals.stream()
|
||||
.flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
|
||||
.collect(Collectors.toList());
|
||||
List<String> filteredList = listOfOptionals.stream().flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)).collect(Collectors.toList());
|
||||
assertEquals(2, filteredList.size());
|
||||
|
||||
assertEquals("foo", filteredList.get(0));
|
||||
|
@ -59,9 +52,7 @@ public class Java9OptionalsStreamTest {
|
|||
public void filterOutPresentOptionalsWithJava9() {
|
||||
assertEquals(4, listOfOptionals.size());
|
||||
|
||||
List<String> filteredList = listOfOptionals.stream()
|
||||
.flatMap(Optional::stream)
|
||||
.collect(Collectors.toList());
|
||||
List<String> filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList());
|
||||
|
||||
assertEquals(2, filteredList.size());
|
||||
assertEquals("foo", filteredList.get(0));
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
package com.baeldung.java9;
|
||||
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertSame;
|
||||
|
||||
|
@ -13,7 +13,6 @@ import org.junit.Test;
|
|||
|
||||
public class MultiResultionImageTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void baseMultiResImageTest() {
|
||||
int baseIndex = 1;
|
||||
|
@ -38,10 +37,8 @@ public class MultiResultionImageTest {
|
|||
return 8 * (i + 1);
|
||||
}
|
||||
|
||||
|
||||
private static BufferedImage createImage(int i) {
|
||||
return new BufferedImage(getSize(i), getSize(i),
|
||||
BufferedImage.TYPE_INT_RGB);
|
||||
return new BufferedImage(getSize(i), getSize(i), BufferedImage.TYPE_INT_RGB);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,6 +1,4 @@
|
|||
package com.baeldung.java9.httpclient;
|
||||
|
||||
|
||||
package com.baeldung.java9.httpclient;
|
||||
|
||||
import static java.net.HttpURLConnection.HTTP_OK;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
@ -28,8 +26,8 @@ import org.junit.Test;
|
|||
|
||||
public class SimpleHttpRequestsTest {
|
||||
|
||||
private URI httpURI;
|
||||
|
||||
private URI httpURI;
|
||||
|
||||
@Before
|
||||
public void init() throws URISyntaxException {
|
||||
httpURI = new URI("http://www.baeldung.com/");
|
||||
|
@ -37,26 +35,26 @@ public class SimpleHttpRequestsTest {
|
|||
|
||||
@Test
|
||||
public void quickGet() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.create( httpURI ).GET();
|
||||
HttpRequest request = HttpRequest.create(httpURI).GET();
|
||||
HttpResponse response = request.response();
|
||||
int responseStatusCode = response.statusCode();
|
||||
String responseBody = response.body(HttpResponse.asString());
|
||||
assertTrue("Get response status code is bigger then 400", responseStatusCode < 400);
|
||||
assertTrue("Get response status code is bigger then 400", responseStatusCode < 400);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{
|
||||
public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException {
|
||||
HttpRequest request = HttpRequest.create(httpURI).GET();
|
||||
long before = System.currentTimeMillis();
|
||||
CompletableFuture<HttpResponse> futureResponse = request.responseAsync();
|
||||
futureResponse.thenAccept( response -> {
|
||||
futureResponse.thenAccept(response -> {
|
||||
String responseBody = response.body(HttpResponse.asString());
|
||||
});
|
||||
});
|
||||
HttpResponse resp = futureResponse.get();
|
||||
HttpHeaders hs = resp.headers();
|
||||
assertTrue("There should be more then 1 header.", hs.map().size() >1);
|
||||
assertTrue("There should be more then 1 header.", hs.map().size() > 1);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void postMehtod() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest.Builder requestBuilder = HttpRequest.create(httpURI);
|
||||
|
@ -66,61 +64,63 @@ public class SimpleHttpRequestsTest {
|
|||
int statusCode = response.statusCode();
|
||||
assertTrue("HTTP return code", statusCode == HTTP_OK);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException{
|
||||
public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException {
|
||||
CookieManager cManager = new CookieManager();
|
||||
cManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
|
||||
|
||||
SSLParameters sslParam = new SSLParameters (new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" });
|
||||
|
||||
|
||||
SSLParameters sslParam = new SSLParameters(new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" });
|
||||
|
||||
HttpClient.Builder hcBuilder = HttpClient.create();
|
||||
hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam);
|
||||
HttpClient httpClient = hcBuilder.build();
|
||||
HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://www.facebook.com"));
|
||||
|
||||
|
||||
HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET();
|
||||
HttpResponse response = request.response();
|
||||
int statusCode = response.statusCode();
|
||||
assertTrue("HTTP return code", statusCode == HTTP_OK);
|
||||
}
|
||||
|
||||
SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException{
|
||||
|
||||
SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException {
|
||||
SSLParameters sslP1 = SSLContext.getDefault().getSupportedSSLParameters();
|
||||
String [] proto = sslP1.getApplicationProtocols();
|
||||
String [] cifers = sslP1.getCipherSuites();
|
||||
String[] proto = sslP1.getApplicationProtocols();
|
||||
String[] cifers = sslP1.getCipherSuites();
|
||||
System.out.println(printStringArr(proto));
|
||||
System.out.println(printStringArr(cifers));
|
||||
return sslP1;
|
||||
}
|
||||
|
||||
String printStringArr(String ... args ){
|
||||
if(args == null){
|
||||
|
||||
String printStringArr(String... args) {
|
||||
if (args == null) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String s : args){
|
||||
for (String s : args) {
|
||||
sb.append(s);
|
||||
sb.append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String printHeaders(HttpHeaders h){
|
||||
if(h == null){
|
||||
|
||||
String printHeaders(HttpHeaders h) {
|
||||
if (h == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Map<String, List<String>> hMap = h.map();
|
||||
for(String k : hMap.keySet()){
|
||||
sb.append(k).append(":");
|
||||
List<String> l = hMap.get(k);
|
||||
if( l != null ){
|
||||
l.forEach( s -> { sb.append(s).append(","); } );
|
||||
}
|
||||
sb.append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Map<String, List<String>> hMap = h.map();
|
||||
for (String k : hMap.keySet()) {
|
||||
sb.append(k).append(":");
|
||||
List<String> l = hMap.get(k);
|
||||
if (l != null) {
|
||||
l.forEach(s -> {
|
||||
sb.append(s).append(",");
|
||||
});
|
||||
}
|
||||
sb.append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,7 +7,7 @@ public class TryWithResourcesTest {
|
|||
|
||||
static int closeCount = 0;
|
||||
|
||||
static class MyAutoCloseable implements AutoCloseable{
|
||||
static class MyAutoCloseable implements AutoCloseable {
|
||||
final FinalWrapper finalWrapper = new FinalWrapper();
|
||||
|
||||
public void close() {
|
||||
|
@ -57,7 +57,6 @@ public class TryWithResourcesTest {
|
|||
assertEquals("Expected and Actual does not match", 5, closeCount);
|
||||
}
|
||||
|
||||
|
||||
static class CloseableException extends Exception implements AutoCloseable {
|
||||
@Override
|
||||
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 Stream<String> getStreamAfterTakeWhileOperation() {
|
||||
return Stream
|
||||
.iterate("", s -> s + "s")
|
||||
.takeWhile(s -> s.length() < 10);
|
||||
return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10);
|
||||
}
|
||||
|
||||
public Stream<String> getStreamAfterDropWhileOperation() {
|
||||
return Stream
|
||||
.iterate("", s -> s + "s")
|
||||
.takeWhile(s -> s.length() < 10)
|
||||
.dropWhile(s -> !s.contains("sssss"));
|
||||
return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10).dropWhile(s -> !s.contains("sssss"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -72,25 +67,25 @@ public class StreamFeaturesTest {
|
|||
|
||||
}
|
||||
|
||||
public static class OfNullableTest {
|
||||
public static class OfNullableTest {
|
||||
|
||||
private List<String> collection = Arrays.asList("A", "B", "C");
|
||||
private Map<String, Integer> map = new HashMap<>() {{
|
||||
put("A", 10);
|
||||
put("C", 30);
|
||||
}};
|
||||
private Map<String, Integer> map = new HashMap<>() {
|
||||
{
|
||||
put("A", 10);
|
||||
put("C", 30);
|
||||
}
|
||||
};
|
||||
|
||||
private Stream<Integer> getStreamWithOfNullable() {
|
||||
return collection.stream()
|
||||
.flatMap(s -> Stream.ofNullable(map.get(s)));
|
||||
return collection.stream().flatMap(s -> Stream.ofNullable(map.get(s)));
|
||||
}
|
||||
|
||||
private Stream<Integer> getStream() {
|
||||
return collection.stream()
|
||||
.flatMap(s -> {
|
||||
Integer temp = map.get(s);
|
||||
return temp != null ? Stream.of(temp) : Stream.empty();
|
||||
});
|
||||
return collection.stream().flatMap(s -> {
|
||||
Integer temp = map.get(s);
|
||||
return temp != null ? Stream.of(temp) : Stream.empty();
|
||||
});
|
||||
}
|
||||
|
||||
private List<Integer> testOfNullableFrom(Stream<Integer> stream) {
|
||||
|
@ -107,10 +102,7 @@ public class StreamFeaturesTest {
|
|||
@Test
|
||||
public void testOfNullable() {
|
||||
|
||||
assertEquals(
|
||||
testOfNullableFrom(getStream()),
|
||||
testOfNullableFrom(getStreamWithOfNullable())
|
||||
);
|
||||
assertEquals(testOfNullableFrom(getStream()), testOfNullableFrom(getStreamWithOfNullable()));
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -22,90 +22,89 @@ import static org.junit.Assert.assertTrue;
|
|||
|
||||
public class ProcessApi {
|
||||
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void processInfoExample()throws NoSuchAlgorithmException{
|
||||
public void processInfoExample() throws NoSuchAlgorithmException {
|
||||
ProcessHandle self = ProcessHandle.current();
|
||||
long PID = self.getPid();
|
||||
ProcessHandle.Info procInfo = self.info();
|
||||
Optional<String[]> args = procInfo.arguments();
|
||||
Optional<String> cmd = procInfo.commandLine();
|
||||
Optional<String> cmd = procInfo.commandLine();
|
||||
Optional<Instant> startTime = procInfo.startInstant();
|
||||
Optional<Duration> cpuUsage = procInfo.totalCpuDuration();
|
||||
|
||||
waistCPU();
|
||||
System.out.println("Args "+ args);
|
||||
System.out.println("Command " +cmd.orElse("EmptyCmd"));
|
||||
System.out.println("Start time: "+ startTime.get().toString());
|
||||
System.out.println("Args " + args);
|
||||
System.out.println("Command " + cmd.orElse("EmptyCmd"));
|
||||
System.out.println("Start time: " + startTime.get().toString());
|
||||
System.out.println(cpuUsage.get().toMillis());
|
||||
|
||||
|
||||
Stream<ProcessHandle> allProc = ProcessHandle.current().children();
|
||||
allProc.forEach(p -> {
|
||||
System.out.println("Proc "+ p.getPid());
|
||||
System.out.println("Proc " + p.getPid());
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createAndDestroyProcess() throws IOException, InterruptedException{
|
||||
public void createAndDestroyProcess() throws IOException, InterruptedException {
|
||||
int numberOfChildProcesses = 5;
|
||||
for(int i=0; i < numberOfChildProcesses; i++){
|
||||
for (int i = 0; i < numberOfChildProcesses; i++) {
|
||||
createNewJVM(ServiceMain.class, i).getPid();
|
||||
}
|
||||
|
||||
Stream<ProcessHandle> childProc = ProcessHandle.current().children();
|
||||
assertEquals( childProc.count(), numberOfChildProcesses);
|
||||
|
||||
|
||||
Stream<ProcessHandle> childProc = ProcessHandle.current().children();
|
||||
assertEquals(childProc.count(), numberOfChildProcesses);
|
||||
|
||||
childProc = ProcessHandle.current().children();
|
||||
childProc.forEach(processHandle -> {
|
||||
assertTrue("Process "+ processHandle.getPid() +" should be alive!", processHandle.isAlive());
|
||||
assertTrue("Process " + processHandle.getPid() + " should be alive!", processHandle.isAlive());
|
||||
CompletableFuture<ProcessHandle> onProcExit = processHandle.onExit();
|
||||
onProcExit.thenAccept(procHandle -> {
|
||||
System.out.println("Process with PID "+ procHandle.getPid() + " has stopped");
|
||||
System.out.println("Process with PID " + procHandle.getPid() + " has stopped");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Thread.sleep(10000);
|
||||
|
||||
|
||||
childProc = ProcessHandle.current().children();
|
||||
childProc.forEach(procHandle -> {
|
||||
assertTrue("Could not kill process "+procHandle.getPid(), procHandle.destroy());
|
||||
assertTrue("Could not kill process " + procHandle.getPid(), procHandle.destroy());
|
||||
});
|
||||
|
||||
|
||||
Thread.sleep(5000);
|
||||
|
||||
|
||||
childProc = ProcessHandle.current().children();
|
||||
childProc.forEach(procHandle -> {
|
||||
assertFalse("Process "+ procHandle.getPid() +" should not be alive!", procHandle.isAlive());
|
||||
assertFalse("Process " + procHandle.getPid() + " should not be alive!", procHandle.isAlive());
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
private Process createNewJVM(Class mainClass, int number) throws IOException{
|
||||
private Process createNewJVM(Class mainClass, int number) throws IOException {
|
||||
ArrayList<String> cmdParams = new ArrayList<String>(5);
|
||||
cmdParams.add(ProcessUtils.getJavaCmd().getAbsolutePath());
|
||||
cmdParams.add("-cp");
|
||||
cmdParams.add(ProcessUtils.getClassPath());
|
||||
cmdParams.add(mainClass.getName());
|
||||
cmdParams.add("Service "+ number);
|
||||
cmdParams.add("Service " + number);
|
||||
ProcessBuilder myService = new ProcessBuilder(cmdParams);
|
||||
myService.inheritIO();
|
||||
return myService.start();
|
||||
}
|
||||
|
||||
private void waistCPU() throws NoSuchAlgorithmException{
|
||||
|
||||
private void waistCPU() throws NoSuchAlgorithmException {
|
||||
ArrayList<Integer> randArr = new ArrayList<Integer>(4096);
|
||||
SecureRandom sr = SecureRandom.getInstanceStrong();
|
||||
Duration somecpu = Duration.ofMillis(4200L);
|
||||
Instant end = Instant.now().plus(somecpu);
|
||||
while (Instant.now().isBefore(end)) {
|
||||
//System.out.println(sr.nextInt());
|
||||
randArr.add( sr.nextInt() );
|
||||
// System.out.println(sr.nextInt());
|
||||
randArr.add(sr.nextInt());
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -7,25 +7,24 @@ import com.baeldung.algorithms.slope_one.SlopeOne;
|
|||
|
||||
public class RunAlgorithm {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Run algorithm:");
|
||||
System.out.println("1 - Simulated Annealing");
|
||||
System.out.println("2 - Slope One");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
System.out.println(
|
||||
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||
break;
|
||||
case 2:
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
}
|
||||
in.close();
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Run algorithm:");
|
||||
System.out.println("1 - Simulated Annealing");
|
||||
System.out.println("2 - Slope One");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||
break;
|
||||
case 2:
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
}
|
||||
in.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -5,18 +5,18 @@ import lombok.Data;
|
|||
@Data
|
||||
public class City {
|
||||
|
||||
private int x;
|
||||
private int y;
|
||||
private int x;
|
||||
private int y;
|
||||
|
||||
public City() {
|
||||
this.x = (int) (Math.random() * 500);
|
||||
this.y = (int) (Math.random() * 500);
|
||||
}
|
||||
public City() {
|
||||
this.x = (int) (Math.random() * 500);
|
||||
this.y = (int) (Math.random() * 500);
|
||||
}
|
||||
|
||||
public double distanceToCity(City city) {
|
||||
int x = Math.abs(getX() - city.getX());
|
||||
int y = Math.abs(getY() - city.getY());
|
||||
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
|
||||
}
|
||||
public double distanceToCity(City city) {
|
||||
int x = Math.abs(getX() - city.getX());
|
||||
int y = Math.abs(getY() - city.getY());
|
||||
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -24,7 +24,7 @@ public class SimulatedAnnealing {
|
|||
}
|
||||
t *= coolingRate;
|
||||
} else {
|
||||
continue;
|
||||
continue;
|
||||
}
|
||||
if (i % 100 == 0) {
|
||||
System.out.println("Iteration #" + i);
|
||||
|
|
|
@ -11,26 +11,25 @@ import lombok.Data;
|
|||
|
||||
@Data
|
||||
public class InputData {
|
||||
|
||||
protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"),
|
||||
new Item("Snacks"));
|
||||
|
||||
public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) {
|
||||
Map<User, HashMap<Item, Double>> data = new HashMap<>();
|
||||
HashMap<Item, Double> newUser;
|
||||
Set<Item> newRecommendationSet;
|
||||
for (int i = 0; i < numberOfUsers; i++) {
|
||||
newUser = new HashMap<Item, Double>();
|
||||
newRecommendationSet = new HashSet<>();
|
||||
for (int j = 0; j < 3; j++) {
|
||||
newRecommendationSet.add(items.get((int) (Math.random() * 5)));
|
||||
}
|
||||
for (Item item : newRecommendationSet) {
|
||||
newUser.put(item, Math.random());
|
||||
}
|
||||
data.put(new User("User " + i), newUser);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), new Item("Snacks"));
|
||||
|
||||
public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) {
|
||||
Map<User, HashMap<Item, Double>> data = new HashMap<>();
|
||||
HashMap<Item, Double> newUser;
|
||||
Set<Item> newRecommendationSet;
|
||||
for (int i = 0; i < numberOfUsers; i++) {
|
||||
newUser = new HashMap<Item, Double>();
|
||||
newRecommendationSet = new HashSet<>();
|
||||
for (int j = 0; j < 3; j++) {
|
||||
newRecommendationSet.add(items.get((int) (Math.random() * 5)));
|
||||
}
|
||||
for (Item item : newRecommendationSet) {
|
||||
newUser.put(item, Math.random());
|
||||
}
|
||||
data.put(new User("User " + i), newUser);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -9,5 +9,5 @@ import lombok.NoArgsConstructor;
|
|||
@AllArgsConstructor
|
||||
public class Item {
|
||||
|
||||
private String itemName;
|
||||
private String itemName;
|
||||
}
|
||||
|
|
|
@ -11,114 +11,114 @@ import java.util.Map.Entry;
|
|||
*/
|
||||
public class SlopeOne {
|
||||
|
||||
private static Map<Item, Map<Item, Double>> diff = new HashMap<>();
|
||||
private static Map<Item, Map<Item, Integer>> freq = new HashMap<>();
|
||||
private static Map<User, HashMap<Item, Double>> inputData;
|
||||
private static Map<User, HashMap<Item, Double>> outputData = new HashMap<>();
|
||||
private static Map<Item, Map<Item, Double>> diff = new HashMap<>();
|
||||
private static Map<Item, Map<Item, Integer>> freq = new HashMap<>();
|
||||
private static Map<User, HashMap<Item, Double>> inputData;
|
||||
private static Map<User, HashMap<Item, Double>> outputData = new HashMap<>();
|
||||
|
||||
public static void slopeOne(int numberOfUsers) {
|
||||
inputData = InputData.initializeData(numberOfUsers);
|
||||
System.out.println("Slope One - Before the Prediction\n");
|
||||
buildDifferencesMatrix(inputData);
|
||||
System.out.println("\nSlope One - With Predictions\n");
|
||||
predict(inputData);
|
||||
}
|
||||
public static void slopeOne(int numberOfUsers) {
|
||||
inputData = InputData.initializeData(numberOfUsers);
|
||||
System.out.println("Slope One - Before the Prediction\n");
|
||||
buildDifferencesMatrix(inputData);
|
||||
System.out.println("\nSlope One - With Predictions\n");
|
||||
predict(inputData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Based on the available data, calculate the relationships between the
|
||||
* items and number of occurences
|
||||
*
|
||||
* @param data
|
||||
* existing user data and their items' ratings
|
||||
*/
|
||||
private static void buildDifferencesMatrix(Map<User, HashMap<Item, Double>> data) {
|
||||
for (HashMap<Item, Double> user : data.values()) {
|
||||
for (Entry<Item, Double> e : user.entrySet()) {
|
||||
if (!diff.containsKey(e.getKey())) {
|
||||
diff.put(e.getKey(), new HashMap<Item, Double>());
|
||||
freq.put(e.getKey(), new HashMap<Item, Integer>());
|
||||
}
|
||||
for (Entry<Item, Double> e2 : user.entrySet()) {
|
||||
int oldCount = 0;
|
||||
if (freq.get(e.getKey()).containsKey(e2.getKey())) {
|
||||
oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue();
|
||||
}
|
||||
double oldDiff = 0.0;
|
||||
if (diff.get(e.getKey()).containsKey(e2.getKey())) {
|
||||
oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue();
|
||||
}
|
||||
double observedDiff = e.getValue() - e2.getValue();
|
||||
freq.get(e.getKey()).put(e2.getKey(), oldCount + 1);
|
||||
diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Item j : diff.keySet()) {
|
||||
for (Item i : diff.get(j).keySet()) {
|
||||
double oldValue = diff.get(j).get(i).doubleValue();
|
||||
int count = freq.get(j).get(i).intValue();
|
||||
diff.get(j).put(i, oldValue / count);
|
||||
}
|
||||
}
|
||||
printData(data);
|
||||
}
|
||||
/**
|
||||
* Based on the available data, calculate the relationships between the
|
||||
* items and number of occurences
|
||||
*
|
||||
* @param data
|
||||
* existing user data and their items' ratings
|
||||
*/
|
||||
private static void buildDifferencesMatrix(Map<User, HashMap<Item, Double>> data) {
|
||||
for (HashMap<Item, Double> user : data.values()) {
|
||||
for (Entry<Item, Double> e : user.entrySet()) {
|
||||
if (!diff.containsKey(e.getKey())) {
|
||||
diff.put(e.getKey(), new HashMap<Item, Double>());
|
||||
freq.put(e.getKey(), new HashMap<Item, Integer>());
|
||||
}
|
||||
for (Entry<Item, Double> e2 : user.entrySet()) {
|
||||
int oldCount = 0;
|
||||
if (freq.get(e.getKey()).containsKey(e2.getKey())) {
|
||||
oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue();
|
||||
}
|
||||
double oldDiff = 0.0;
|
||||
if (diff.get(e.getKey()).containsKey(e2.getKey())) {
|
||||
oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue();
|
||||
}
|
||||
double observedDiff = e.getValue() - e2.getValue();
|
||||
freq.get(e.getKey()).put(e2.getKey(), oldCount + 1);
|
||||
diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Item j : diff.keySet()) {
|
||||
for (Item i : diff.get(j).keySet()) {
|
||||
double oldValue = diff.get(j).get(i).doubleValue();
|
||||
int count = freq.get(j).get(i).intValue();
|
||||
diff.get(j).put(i, oldValue / count);
|
||||
}
|
||||
}
|
||||
printData(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Based on existing data predict all missing ratings. If prediction is not
|
||||
* possible, the value will be equal to -1
|
||||
*
|
||||
* @param data
|
||||
* existing user data and their items' ratings
|
||||
*/
|
||||
private static void predict(Map<User, HashMap<Item, Double>> data) {
|
||||
HashMap<Item, Double> uPred = new HashMap<Item, Double>();
|
||||
HashMap<Item, Integer> uFreq = new HashMap<Item, Integer>();
|
||||
for (Item j : diff.keySet()) {
|
||||
uFreq.put(j, 0);
|
||||
uPred.put(j, 0.0);
|
||||
}
|
||||
for (Entry<User, HashMap<Item, Double>> e : data.entrySet()) {
|
||||
for (Item j : e.getValue().keySet()) {
|
||||
for (Item k : diff.keySet()) {
|
||||
try {
|
||||
double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue();
|
||||
double finalValue = predictedValue * freq.get(k).get(j).intValue();
|
||||
uPred.put(k, uPred.get(k) + finalValue);
|
||||
uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue());
|
||||
} catch (NullPointerException e1) {
|
||||
}
|
||||
}
|
||||
}
|
||||
HashMap<Item, Double> clean = new HashMap<Item, Double>();
|
||||
for (Item j : uPred.keySet()) {
|
||||
if (uFreq.get(j) > 0) {
|
||||
clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue());
|
||||
}
|
||||
}
|
||||
for (Item j : InputData.items) {
|
||||
if (e.getValue().containsKey(j)) {
|
||||
clean.put(j, e.getValue().get(j));
|
||||
} else {
|
||||
clean.put(j, -1.0);
|
||||
}
|
||||
}
|
||||
outputData.put(e.getKey(), clean);
|
||||
}
|
||||
printData(outputData);
|
||||
}
|
||||
/**
|
||||
* Based on existing data predict all missing ratings. If prediction is not
|
||||
* possible, the value will be equal to -1
|
||||
*
|
||||
* @param data
|
||||
* existing user data and their items' ratings
|
||||
*/
|
||||
private static void predict(Map<User, HashMap<Item, Double>> data) {
|
||||
HashMap<Item, Double> uPred = new HashMap<Item, Double>();
|
||||
HashMap<Item, Integer> uFreq = new HashMap<Item, Integer>();
|
||||
for (Item j : diff.keySet()) {
|
||||
uFreq.put(j, 0);
|
||||
uPred.put(j, 0.0);
|
||||
}
|
||||
for (Entry<User, HashMap<Item, Double>> e : data.entrySet()) {
|
||||
for (Item j : e.getValue().keySet()) {
|
||||
for (Item k : diff.keySet()) {
|
||||
try {
|
||||
double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue();
|
||||
double finalValue = predictedValue * freq.get(k).get(j).intValue();
|
||||
uPred.put(k, uPred.get(k) + finalValue);
|
||||
uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue());
|
||||
} catch (NullPointerException e1) {
|
||||
}
|
||||
}
|
||||
}
|
||||
HashMap<Item, Double> clean = new HashMap<Item, Double>();
|
||||
for (Item j : uPred.keySet()) {
|
||||
if (uFreq.get(j) > 0) {
|
||||
clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue());
|
||||
}
|
||||
}
|
||||
for (Item j : InputData.items) {
|
||||
if (e.getValue().containsKey(j)) {
|
||||
clean.put(j, e.getValue().get(j));
|
||||
} else {
|
||||
clean.put(j, -1.0);
|
||||
}
|
||||
}
|
||||
outputData.put(e.getKey(), clean);
|
||||
}
|
||||
printData(outputData);
|
||||
}
|
||||
|
||||
private static void printData(Map<User, HashMap<Item, Double>> data) {
|
||||
for (User user : data.keySet()) {
|
||||
System.out.println(user.getUsername() + ":");
|
||||
print(data.get(user));
|
||||
}
|
||||
}
|
||||
private static void printData(Map<User, HashMap<Item, Double>> data) {
|
||||
for (User user : data.keySet()) {
|
||||
System.out.println(user.getUsername() + ":");
|
||||
print(data.get(user));
|
||||
}
|
||||
}
|
||||
|
||||
private static void print(HashMap<Item, Double> hashMap) {
|
||||
NumberFormat formatter = new DecimalFormat("#0.000");
|
||||
for (Item j : hashMap.keySet()) {
|
||||
System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue()));
|
||||
}
|
||||
}
|
||||
private static void print(HashMap<Item, Double> hashMap) {
|
||||
NumberFormat formatter = new DecimalFormat("#0.000");
|
||||
for (Item j : hashMap.keySet()) {
|
||||
System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue()));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -8,7 +8,7 @@ import lombok.NoArgsConstructor;
|
|||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class User {
|
||||
|
||||
private String username;
|
||||
|
||||
private String username;
|
||||
|
||||
}
|
||||
|
|
|
@ -23,8 +23,7 @@ public class LogWithChain {
|
|||
try {
|
||||
howIsManager();
|
||||
} catch (ManagerUpsetException e) {
|
||||
throw new TeamLeadUpsetException(
|
||||
"Team lead is not in good mood", e);
|
||||
throw new TeamLeadUpsetException("Team lead is not in good mood", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -36,9 +35,7 @@ public class LogWithChain {
|
|||
}
|
||||
}
|
||||
|
||||
private static void howIsGirlFriendOfManager()
|
||||
throws GirlFriendOfManagerUpsetException {
|
||||
throw new GirlFriendOfManagerUpsetException(
|
||||
"Girl friend of manager is in bad mood");
|
||||
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -25,8 +25,7 @@ public class LogWithoutChain {
|
|||
howIsManager();
|
||||
} catch (ManagerUpsetException e) {
|
||||
e.printStackTrace();
|
||||
throw new TeamLeadUpsetException(
|
||||
"Team lead is not in good mood");
|
||||
throw new TeamLeadUpsetException("Team lead is not in good mood");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -39,9 +38,7 @@ public class LogWithoutChain {
|
|||
}
|
||||
}
|
||||
|
||||
private static void howIsGirlFriendOfManager()
|
||||
throws GirlFriendOfManagerUpsetException {
|
||||
throw new GirlFriendOfManagerUpsetException(
|
||||
"Girl friend of manager is in bad mood");
|
||||
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||
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;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
|
@ -10,13 +10,11 @@ public class MyLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
|
|||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final int MAX_ENTRIES = 5;
|
||||
|
||||
|
||||
public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
|
||||
super(initialCapacity, loadFactor, accessOrder);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean removeEldestEntry(Map.Entry eldest) {
|
||||
return size() > MAX_ENTRIES;
|
||||
|
|
|
@ -42,136 +42,96 @@ public class Java8CollectorsUnitTest {
|
|||
|
||||
@Test
|
||||
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
||||
final List<String> result = givenList
|
||||
.stream()
|
||||
.collect(toList());
|
||||
final List<String> result = givenList.stream().collect(toList());
|
||||
|
||||
assertThat(result).containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
||||
final Set<String> result = givenList
|
||||
.stream()
|
||||
.collect(toSet());
|
||||
final Set<String> result = givenList.stream().collect(toSet());
|
||||
|
||||
assertThat(result).containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
||||
final List<String> result = givenList
|
||||
.stream()
|
||||
.collect(toCollection(LinkedList::new));
|
||||
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
|
||||
|
||||
assertThat(result)
|
||||
.containsAll(givenList)
|
||||
.isInstanceOf(LinkedList.class);
|
||||
assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
||||
assertThatThrownBy(() -> {
|
||||
givenList
|
||||
.stream()
|
||||
.collect(toCollection(ImmutableList::of));
|
||||
givenList.stream().collect(toCollection(ImmutableList::of));
|
||||
}).isInstanceOf(UnsupportedOperationException.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
||||
final Map<String, Integer> result = givenList
|
||||
.stream()
|
||||
.collect(toMap(Function.identity(), String::length));
|
||||
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
|
||||
|
||||
assertThat(result)
|
||||
.containsEntry("a", 1)
|
||||
.containsEntry("bb", 2)
|
||||
.containsEntry("ccc", 3)
|
||||
.containsEntry("dd", 2);
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
||||
final Map<String, Integer> result = givenList
|
||||
.stream()
|
||||
.collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||
|
||||
assertThat(result)
|
||||
.containsEntry("a", 1)
|
||||
.containsEntry("bb", 2)
|
||||
.containsEntry("ccc", 3)
|
||||
.containsEntry("dd", 2);
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
||||
final List<String> result = givenList
|
||||
.stream()
|
||||
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||
|
||||
assertThat(result)
|
||||
.containsAll(givenList)
|
||||
.isInstanceOf(ImmutableList.class);
|
||||
assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoining_shouldJoin() throws Exception {
|
||||
final String result = givenList
|
||||
.stream()
|
||||
.collect(joining());
|
||||
final String result = givenList.stream().collect(joining());
|
||||
|
||||
assertThat(result).isEqualTo("abbcccdd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
||||
final String result = givenList
|
||||
.stream()
|
||||
.collect(joining(" "));
|
||||
final String result = givenList.stream().collect(joining(" "));
|
||||
|
||||
assertThat(result).isEqualTo("a bb ccc dd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
||||
final String result = givenList
|
||||
.stream()
|
||||
.collect(joining(" ", "PRE-", "-POST"));
|
||||
final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
|
||||
|
||||
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPartitioningBy_shouldPartition() throws Exception {
|
||||
final Map<Boolean, List<String>> result = givenList
|
||||
.stream()
|
||||
.collect(partitioningBy(s -> s.length() > 2));
|
||||
final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
|
||||
|
||||
assertThat(result)
|
||||
.containsKeys(true, false)
|
||||
.satisfies(booleanListMap -> {
|
||||
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||
assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
|
||||
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||
|
||||
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
|
||||
});
|
||||
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCounting_shouldCount() throws Exception {
|
||||
final Long result = givenList
|
||||
.stream()
|
||||
.collect(counting());
|
||||
final Long result = givenList.stream().collect(counting());
|
||||
|
||||
assertThat(result).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSummarizing_shouldSummarize() throws Exception {
|
||||
final DoubleSummaryStatistics result = givenList
|
||||
.stream()
|
||||
.collect(summarizingDouble(String::length));
|
||||
final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
|
||||
|
||||
assertThat(result.getAverage()).isEqualTo(2);
|
||||
assertThat(result.getCount()).isEqualTo(4);
|
||||
|
@ -182,55 +142,37 @@ public class Java8CollectorsUnitTest {
|
|||
|
||||
@Test
|
||||
public void whenAveraging_shouldAverage() throws Exception {
|
||||
final Double result = givenList
|
||||
.stream()
|
||||
.collect(averagingDouble(String::length));
|
||||
final Double result = givenList.stream().collect(averagingDouble(String::length));
|
||||
|
||||
assertThat(result).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSumming_shouldSum() throws Exception {
|
||||
final Double result = givenList
|
||||
.stream()
|
||||
.filter(i -> true)
|
||||
.collect(summingDouble(String::length));
|
||||
final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length));
|
||||
|
||||
assertThat(result).isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
||||
final Optional<String> result = givenList
|
||||
.stream()
|
||||
.collect(maxBy(Comparator.naturalOrder()));
|
||||
final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
|
||||
|
||||
assertThat(result)
|
||||
.isPresent()
|
||||
.hasValue("dd");
|
||||
assertThat(result).isPresent().hasValue("dd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
||||
final Map<Integer, Set<String>> result = givenList
|
||||
.stream()
|
||||
.collect(groupingBy(String::length, toSet()));
|
||||
final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
|
||||
|
||||
assertThat(result)
|
||||
.containsEntry(1, newHashSet("a"))
|
||||
.containsEntry(2, newHashSet("bb", "dd"))
|
||||
.containsEntry(3, newHashSet("ccc"));
|
||||
assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
||||
final ImmutableSet<String> result = givenList
|
||||
.stream()
|
||||
.collect(toImmutableSet());
|
||||
final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
|
||||
|
||||
assertThat(result)
|
||||
.isInstanceOf(ImmutableSet.class)
|
||||
.contains("a", "bb", "ccc", "dd");
|
||||
assertThat(result).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() {
|
||||
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||
|
||||
List<String> result = StreamSupport.stream(iterable.spliterator(), false)
|
||||
.map(String::toUpperCase).collect(Collectors.toList());
|
||||
List<String> result = StreamSupport.stream(iterable.spliterator(), false).map(String::toUpperCase).collect(Collectors.toList());
|
||||
|
||||
assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
|
||||
}
|
||||
|
|
|
@ -201,8 +201,6 @@ public class MapTest {
|
|||
assertEquals("val1", rtnVal);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void whenCallsEqualsOnCollision_thenCorrect() {
|
||||
HashMap<MyKey, String> map = new HashMap<>();
|
||||
|
@ -311,13 +309,7 @@ public class MapTest {
|
|||
|
||||
@Test
|
||||
public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() {
|
||||
TreeMap<Integer, String> map = new TreeMap<>(new Comparator<Integer>() {
|
||||
|
||||
@Override
|
||||
public int compare(Integer o1, Integer o2) {
|
||||
return o2 - o1;
|
||||
}
|
||||
});
|
||||
TreeMap<Integer, String> map = new TreeMap<>(Comparator.reverseOrder());
|
||||
map.put(3, "val");
|
||||
map.put(2, "val");
|
||||
map.put(1, "val");
|
||||
|
@ -335,7 +327,7 @@ public class MapTest {
|
|||
map.put(1, "val");
|
||||
map.put(5, "val");
|
||||
map.put(4, "val");
|
||||
|
||||
|
||||
Integer highestKey = map.lastKey();
|
||||
Integer lowestKey = map.firstKey();
|
||||
Set<Integer> keysLessThan3 = map.headMap(3).keySet();
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
@ -28,11 +27,7 @@ public class Java8FindAnyFindFirstTest {
|
|||
@Test
|
||||
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception {
|
||||
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Optional<Integer> result = list
|
||||
.stream()
|
||||
.parallel()
|
||||
.filter(num -> num < 4)
|
||||
.findAny();
|
||||
Optional<Integer> result = list.stream().parallel().filter(num -> num < 4).findAny();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
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;
|
||||
|
||||
Assert.assertEquals("hello", map.get("greet"));
|
||||
Assert.assertTrue(List.class.isAssignableFrom(map
|
||||
.get("primes")
|
||||
.getClass()));
|
||||
Assert.assertTrue(List.class.isAssignableFrom(map.get("primes").getClass()));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -3,7 +3,7 @@ package com.baeldung.couchbase.async;
|
|||
public interface CouchbaseEntity {
|
||||
|
||||
String getId();
|
||||
|
||||
|
||||
void setId(String id);
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -8,26 +8,27 @@ public class Person implements CouchbaseEntity {
|
|||
private String type;
|
||||
private String name;
|
||||
private String homeTown;
|
||||
|
||||
Person() {}
|
||||
|
||||
|
||||
Person() {
|
||||
}
|
||||
|
||||
public Person(Builder b) {
|
||||
this.id = b.id;
|
||||
this.type = b.type;
|
||||
this.name = b.name;
|
||||
this.homeTown = b.homeTown;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
@ -39,19 +40,19 @@ public class Person implements CouchbaseEntity {
|
|||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
public String getHomeTown() {
|
||||
return homeTown;
|
||||
}
|
||||
|
||||
|
||||
public void setHomeTown(String homeTown) {
|
||||
this.homeTown = homeTown;
|
||||
}
|
||||
|
||||
|
||||
public static class Builder {
|
||||
private String id;
|
||||
private String type;
|
||||
|
@ -61,16 +62,16 @@ public class Person implements CouchbaseEntity {
|
|||
public static Builder newInstance() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
|
||||
public Person build() {
|
||||
return new Person(this);
|
||||
}
|
||||
|
||||
|
||||
public Builder id(String id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public Builder type(String type) {
|
||||
this.type = type;
|
||||
return this;
|
||||
|
|
|
@ -13,9 +13,7 @@ import com.baeldung.couchbase.async.service.BucketService;
|
|||
public class PersonCrudService extends AbstractCrudService<Person> {
|
||||
|
||||
@Autowired
|
||||
public PersonCrudService(
|
||||
@Qualifier("TutorialBucketService") BucketService bucketService,
|
||||
PersonDocumentConverter converter) {
|
||||
public PersonCrudService(@Qualifier("TutorialBucketService") BucketService bucketService, PersonDocumentConverter converter) {
|
||||
super(bucketService, converter);
|
||||
}
|
||||
|
||||
|
|
|
@ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter<Person> {
|
|||
|
||||
@Override
|
||||
public JsonDocument toDocument(Person p) {
|
||||
JsonObject content = JsonObject.empty()
|
||||
.put("type", "Person")
|
||||
.put("name", p.getName())
|
||||
.put("homeTown", p.getHomeTown());
|
||||
JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown());
|
||||
return JsonDocument.create(p.getId(), content);
|
||||
}
|
||||
|
||||
|
|
|
@ -10,19 +10,18 @@ public class RegistrationService {
|
|||
|
||||
@Autowired
|
||||
private PersonCrudService crud;
|
||||
|
||||
|
||||
public void registerNewPerson(String name, String homeTown) {
|
||||
Person person = new Person();
|
||||
person.setName(name);
|
||||
person.setHomeTown(homeTown);
|
||||
crud.create(person);
|
||||
}
|
||||
|
||||
|
||||
public Person findRegistrant(String id) {
|
||||
try{
|
||||
try {
|
||||
return crud.read(id);
|
||||
}
|
||||
catch(CouchbaseException e) {
|
||||
} catch (CouchbaseException e) {
|
||||
return crud.readFromReplica(id);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -11,9 +11,9 @@ public abstract class AbstractBucketService implements BucketService {
|
|||
protected void openBucket() {
|
||||
bucket = clusterService.openBucket(getBucketName(), getBucketPassword());
|
||||
}
|
||||
|
||||
|
||||
protected abstract String getBucketName();
|
||||
|
||||
|
||||
protected abstract String getBucketPassword();
|
||||
|
||||
public AbstractBucketService(ClusterService clusterService) {
|
||||
|
@ -24,4 +24,4 @@ public abstract class AbstractBucketService implements BucketService {
|
|||
public Bucket getBucket() {
|
||||
return bucket;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -40,7 +40,7 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements
|
|||
|
||||
@Override
|
||||
public void create(T t) {
|
||||
if(t.getId() == null) {
|
||||
if (t.getId() == null) {
|
||||
t.setId(UUID.randomUUID().toString());
|
||||
}
|
||||
JsonDocument doc = converter.toDocument(t);
|
||||
|
@ -73,18 +73,15 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements
|
|||
@Override
|
||||
public List<T> readBulk(Iterable<String> ids) {
|
||||
final AsyncBucket asyncBucket = bucket.async();
|
||||
Observable<JsonDocument> asyncOperation = Observable
|
||||
.from(ids)
|
||||
.flatMap(new Func1<String, Observable<JsonDocument>>() {
|
||||
public Observable<JsonDocument> call(String key) {
|
||||
return asyncBucket.get(key);
|
||||
}
|
||||
});
|
||||
Observable<JsonDocument> asyncOperation = Observable.from(ids).flatMap(new Func1<String, Observable<JsonDocument>>() {
|
||||
public Observable<JsonDocument> call(String key) {
|
||||
return asyncBucket.get(key);
|
||||
}
|
||||
});
|
||||
|
||||
final List<T> items = new ArrayList<T>();
|
||||
try {
|
||||
asyncOperation.toBlocking()
|
||||
.forEach(new Action1<JsonDocument>() {
|
||||
asyncOperation.toBlocking().forEach(new Action1<JsonDocument>() {
|
||||
public void call(JsonDocument doc) {
|
||||
T item = converter.fromDocument(doc);
|
||||
items.add(item);
|
||||
|
@ -100,72 +97,42 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements
|
|||
@Override
|
||||
public void createBulk(Iterable<T> items) {
|
||||
final AsyncBucket asyncBucket = bucket.async();
|
||||
Observable
|
||||
.from(items)
|
||||
.flatMap(new Func1<T, Observable<JsonDocument>>() {
|
||||
Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() {
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public Observable<JsonDocument> call(final T t) {
|
||||
if(t.getId() == null) {
|
||||
if (t.getId() == null) {
|
||||
t.setId(UUID.randomUUID().toString());
|
||||
}
|
||||
JsonDocument doc = converter.toDocument(t);
|
||||
return asyncBucket.insert(doc)
|
||||
.retryWhen(RetryBuilder
|
||||
.anyOf(BackpressureException.class)
|
||||
.delay(Delay.exponential(TimeUnit.MILLISECONDS, 100))
|
||||
.max(10)
|
||||
.build());
|
||||
return asyncBucket.insert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
|
||||
}
|
||||
})
|
||||
.last()
|
||||
.toBlocking()
|
||||
.single();
|
||||
}).last().toBlocking().single();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateBulk(Iterable<T> items) {
|
||||
final AsyncBucket asyncBucket = bucket.async();
|
||||
Observable
|
||||
.from(items)
|
||||
.flatMap(new Func1<T, Observable<JsonDocument>>() {
|
||||
Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() {
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public Observable<JsonDocument> call(final T t) {
|
||||
JsonDocument doc = converter.toDocument(t);
|
||||
return asyncBucket.upsert(doc)
|
||||
.retryWhen(RetryBuilder
|
||||
.anyOf(BackpressureException.class)
|
||||
.delay(Delay.exponential(TimeUnit.MILLISECONDS, 100))
|
||||
.max(10)
|
||||
.build());
|
||||
return asyncBucket.upsert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
|
||||
}
|
||||
})
|
||||
.last()
|
||||
.toBlocking()
|
||||
.single();
|
||||
}).last().toBlocking().single();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteBulk(Iterable<String> ids) {
|
||||
final AsyncBucket asyncBucket = bucket.async();
|
||||
Observable
|
||||
.from(ids)
|
||||
.flatMap(new Func1<String, Observable<JsonDocument>>() {
|
||||
Observable.from(ids).flatMap(new Func1<String, Observable<JsonDocument>>() {
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public Observable<JsonDocument> call(String key) {
|
||||
return asyncBucket.remove(key)
|
||||
.retryWhen(RetryBuilder
|
||||
.anyOf(BackpressureException.class)
|
||||
.delay(Delay.exponential(TimeUnit.MILLISECONDS, 100))
|
||||
.max(10)
|
||||
.build());
|
||||
return asyncBucket.remove(key).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
|
||||
}
|
||||
})
|
||||
.last()
|
||||
.toBlocking()
|
||||
.single();
|
||||
}).last().toBlocking().single();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -3,6 +3,6 @@ package com.baeldung.couchbase.async.service;
|
|||
import com.couchbase.client.java.Bucket;
|
||||
|
||||
public interface ClusterService {
|
||||
|
||||
|
||||
Bucket openBucket(String name, String password);
|
||||
}
|
||||
|
|
|
@ -18,7 +18,7 @@ public class ClusterServiceImpl implements ClusterService {
|
|||
|
||||
private Cluster cluster;
|
||||
private Map<String, Bucket> buckets = new ConcurrentHashMap<>();
|
||||
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create();
|
||||
|
@ -27,7 +27,7 @@ public class ClusterServiceImpl implements ClusterService {
|
|||
|
||||
@Override
|
||||
synchronized public Bucket openBucket(String name, String password) {
|
||||
if(!buckets.containsKey(name)) {
|
||||
if (!buckets.containsKey(name)) {
|
||||
Bucket bucket = cluster.openBucket(name, password);
|
||||
buckets.put(name, bucket);
|
||||
}
|
||||
|
|
|
@ -5,6 +5,6 @@ import com.couchbase.client.java.document.JsonDocument;
|
|||
public interface JsonDocumentConverter<T> {
|
||||
|
||||
JsonDocument toDocument(T t);
|
||||
|
||||
|
||||
T fromDocument(JsonDocument doc);
|
||||
}
|
||||
|
|
|
@ -14,40 +14,32 @@ import com.couchbase.client.java.env.CouchbaseEnvironment;
|
|||
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
|
||||
|
||||
public class CodeSnippets {
|
||||
|
||||
|
||||
static Cluster loadClusterWithDefaultEnvironment() {
|
||||
return CouchbaseCluster.create("localhost");
|
||||
}
|
||||
|
||||
static Cluster loadClusterWithCustomEnvironment() {
|
||||
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
|
||||
.connectTimeout(10000)
|
||||
.kvTimeout(3000)
|
||||
.build();
|
||||
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder().connectTimeout(10000).kvTimeout(3000).build();
|
||||
return CouchbaseCluster.create(env, "localhost");
|
||||
}
|
||||
|
||||
|
||||
static Bucket loadDefaultBucketWithBlankPassword(Cluster cluster) {
|
||||
return cluster.openBucket();
|
||||
}
|
||||
|
||||
|
||||
static Bucket loadBaeldungBucket(Cluster cluster) {
|
||||
return cluster.openBucket("baeldung", "");
|
||||
}
|
||||
|
||||
static JsonDocument insertExample(Bucket bucket) {
|
||||
JsonObject content = JsonObject.empty()
|
||||
.put("name", "John Doe")
|
||||
.put("type", "Person")
|
||||
.put("email", "john.doe@mydomain.com")
|
||||
.put("homeTown", "Chicago")
|
||||
;
|
||||
JsonObject content = JsonObject.empty().put("name", "John Doe").put("type", "Person").put("email", "john.doe@mydomain.com").put("homeTown", "Chicago");
|
||||
String id = UUID.randomUUID().toString();
|
||||
JsonDocument document = JsonDocument.create(id, content);
|
||||
JsonDocument inserted = bucket.insert(document);
|
||||
return inserted;
|
||||
}
|
||||
|
||||
|
||||
static JsonDocument retrieveAndUpsertExample(Bucket bucket, String id) {
|
||||
JsonDocument document = bucket.get(id);
|
||||
JsonObject content = document.content();
|
||||
|
@ -55,7 +47,7 @@ public class CodeSnippets {
|
|||
JsonDocument upserted = bucket.upsert(document);
|
||||
return upserted;
|
||||
}
|
||||
|
||||
|
||||
static JsonDocument replaceExample(Bucket bucket, String id) {
|
||||
JsonDocument document = bucket.get(id);
|
||||
JsonObject content = document.content();
|
||||
|
@ -63,30 +55,29 @@ public class CodeSnippets {
|
|||
JsonDocument replaced = bucket.replace(document);
|
||||
return replaced;
|
||||
}
|
||||
|
||||
|
||||
static JsonDocument removeExample(Bucket bucket, String id) {
|
||||
JsonDocument removed = bucket.remove(id);
|
||||
return removed;
|
||||
}
|
||||
|
||||
|
||||
static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) {
|
||||
try{
|
||||
try {
|
||||
return bucket.get(id);
|
||||
}
|
||||
catch(CouchbaseException e) {
|
||||
} catch (CouchbaseException e) {
|
||||
List<JsonDocument> list = bucket.getFromReplica(id, ReplicaMode.FIRST);
|
||||
if(!list.isEmpty()) {
|
||||
if (!list.isEmpty()) {
|
||||
return list.get(0);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
static JsonDocument getLatestReplicaVersion(Bucket bucket, String id) {
|
||||
long maxCasValue = -1;
|
||||
JsonDocument latest = null;
|
||||
for(JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) {
|
||||
if(replica.cas() > maxCasValue) {
|
||||
for (JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) {
|
||||
if (replica.cas() > maxCasValue) {
|
||||
latest = replica;
|
||||
maxCasValue = replica.cas();
|
||||
}
|
||||
|
|
|
@ -6,24 +6,25 @@ public class Person {
|
|||
private String type;
|
||||
private String name;
|
||||
private String homeTown;
|
||||
|
||||
Person() {}
|
||||
|
||||
|
||||
Person() {
|
||||
}
|
||||
|
||||
public Person(Builder b) {
|
||||
this.id = b.id;
|
||||
this.type = b.type;
|
||||
this.name = b.name;
|
||||
this.homeTown = b.homeTown;
|
||||
}
|
||||
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
@ -35,19 +36,19 @@ public class Person {
|
|||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
public String getHomeTown() {
|
||||
return homeTown;
|
||||
}
|
||||
|
||||
|
||||
public void setHomeTown(String homeTown) {
|
||||
this.homeTown = homeTown;
|
||||
}
|
||||
|
||||
|
||||
public static class Builder {
|
||||
private String id;
|
||||
private String type;
|
||||
|
@ -57,16 +58,16 @@ public class Person {
|
|||
public static Builder newInstance() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
|
||||
public Person build() {
|
||||
return new Person(this);
|
||||
}
|
||||
|
||||
|
||||
public Builder id(String id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public Builder type(String type) {
|
||||
this.type = type;
|
||||
return this;
|
||||
|
|
|
@ -16,15 +16,15 @@ import com.couchbase.client.java.document.JsonDocument;
|
|||
|
||||
@Service
|
||||
public class PersonCrudService implements CrudService<Person> {
|
||||
|
||||
|
||||
@Autowired
|
||||
private TutorialBucketService bucketService;
|
||||
|
||||
|
||||
@Autowired
|
||||
private PersonDocumentConverter converter;
|
||||
|
||||
|
||||
private Bucket bucket;
|
||||
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
bucket = bucketService.getBucket();
|
||||
|
@ -32,7 +32,7 @@ public class PersonCrudService implements CrudService<Person> {
|
|||
|
||||
@Override
|
||||
public void create(Person person) {
|
||||
if(person.getId() == null) {
|
||||
if (person.getId() == null) {
|
||||
person.setId(UUID.randomUUID().toString());
|
||||
}
|
||||
JsonDocument document = converter.toDocument(person);
|
||||
|
|
|
@ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter<Person> {
|
|||
|
||||
@Override
|
||||
public JsonDocument toDocument(Person p) {
|
||||
JsonObject content = JsonObject.empty()
|
||||
.put("type", "Person")
|
||||
.put("name", p.getName())
|
||||
.put("homeTown", p.getHomeTown());
|
||||
JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown());
|
||||
return JsonDocument.create(p.getId(), content);
|
||||
}
|
||||
|
||||
|
|
|
@ -10,19 +10,18 @@ public class RegistrationService {
|
|||
|
||||
@Autowired
|
||||
private PersonCrudService crud;
|
||||
|
||||
|
||||
public void registerNewPerson(String name, String homeTown) {
|
||||
Person person = new Person();
|
||||
person.setName(name);
|
||||
person.setHomeTown(homeTown);
|
||||
crud.create(person);
|
||||
}
|
||||
|
||||
|
||||
public Person findRegistrant(String id) {
|
||||
try{
|
||||
try {
|
||||
return crud.read(id);
|
||||
}
|
||||
catch(CouchbaseException e) {
|
||||
} catch (CouchbaseException e) {
|
||||
return crud.readFromReplica(id);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,5 +5,5 @@ import com.couchbase.client.java.Bucket;
|
|||
public interface BucketService {
|
||||
|
||||
Bucket getBucket();
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -7,11 +7,11 @@ import com.couchbase.client.java.Bucket;
|
|||
import com.couchbase.client.java.document.JsonDocument;
|
||||
|
||||
public interface ClusterService {
|
||||
|
||||
|
||||
Bucket openBucket(String name, String password);
|
||||
|
||||
|
||||
List<JsonDocument> getDocuments(Bucket bucket, Iterable<String> keys);
|
||||
|
||||
|
||||
List<JsonDocument> getDocumentsAsync(AsyncBucket bucket, Iterable<String> keys);
|
||||
|
||||
}
|
||||
|
|
|
@ -29,7 +29,7 @@ public class ClusterServiceImpl implements ClusterService {
|
|||
|
||||
private Cluster cluster;
|
||||
private Map<String, Bucket> buckets = new ConcurrentHashMap<>();
|
||||
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create();
|
||||
|
@ -38,7 +38,7 @@ public class ClusterServiceImpl implements ClusterService {
|
|||
|
||||
@Override
|
||||
synchronized public Bucket openBucket(String name, String password) {
|
||||
if(!buckets.containsKey(name)) {
|
||||
if (!buckets.containsKey(name)) {
|
||||
Bucket bucket = cluster.openBucket(name, password);
|
||||
buckets.put(name, bucket);
|
||||
}
|
||||
|
@ -48,9 +48,9 @@ public class ClusterServiceImpl implements ClusterService {
|
|||
@Override
|
||||
public List<JsonDocument> getDocuments(Bucket bucket, Iterable<String> keys) {
|
||||
List<JsonDocument> docs = new ArrayList<>();
|
||||
for(String key : keys) {
|
||||
for (String key : keys) {
|
||||
JsonDocument doc = bucket.get(key);
|
||||
if(doc != null) {
|
||||
if (doc != null) {
|
||||
docs.add(doc);
|
||||
}
|
||||
}
|
||||
|
@ -59,18 +59,15 @@ public class ClusterServiceImpl implements ClusterService {
|
|||
|
||||
@Override
|
||||
public List<JsonDocument> getDocumentsAsync(final AsyncBucket asyncBucket, Iterable<String> keys) {
|
||||
Observable<JsonDocument> asyncBulkGet = Observable
|
||||
.from(keys)
|
||||
.flatMap(new Func1<String, Observable<JsonDocument>>() {
|
||||
public Observable<JsonDocument> call(String key) {
|
||||
return asyncBucket.get(key);
|
||||
}
|
||||
});
|
||||
Observable<JsonDocument> asyncBulkGet = Observable.from(keys).flatMap(new Func1<String, Observable<JsonDocument>>() {
|
||||
public Observable<JsonDocument> call(String key) {
|
||||
return asyncBucket.get(key);
|
||||
}
|
||||
});
|
||||
|
||||
final List<JsonDocument> docs = new ArrayList<>();
|
||||
try {
|
||||
asyncBulkGet.toBlocking()
|
||||
.forEach(new Action1<JsonDocument>() {
|
||||
asyncBulkGet.toBlocking().forEach(new Action1<JsonDocument>() {
|
||||
public void call(JsonDocument doc) {
|
||||
docs.add(doc);
|
||||
}
|
||||
|
|
|
@ -3,14 +3,14 @@ package com.baeldung.couchbase.spring.service;
|
|||
public interface CrudService<T> {
|
||||
|
||||
void create(T t);
|
||||
|
||||
|
||||
T read(String id);
|
||||
|
||||
|
||||
T readFromReplica(String id);
|
||||
|
||||
|
||||
void update(T t);
|
||||
|
||||
|
||||
void delete(String id);
|
||||
|
||||
|
||||
boolean exists(String id);
|
||||
}
|
||||
|
|
|
@ -5,6 +5,6 @@ import com.couchbase.client.java.document.JsonDocument;
|
|||
public interface JsonDocumentConverter<T> {
|
||||
|
||||
JsonDocument toDocument(T t);
|
||||
|
||||
|
||||
T fromDocument(JsonDocument doc);
|
||||
}
|
||||
|
|
|
@ -14,15 +14,15 @@ public class TutorialBucketService implements BucketService {
|
|||
|
||||
@Autowired
|
||||
private ClusterService couchbase;
|
||||
|
||||
|
||||
private Bucket bucket;
|
||||
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
bucket = couchbase.openBucket("baeldung-tutorial", "");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
public Bucket getBucket() {
|
||||
return bucket;
|
||||
}
|
||||
|
|
|
@ -4,6 +4,6 @@ import org.springframework.context.annotation.ComponentScan;
|
|||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages={"com.baeldung.couchbase.async"})
|
||||
@ComponentScan(basePackages = { "com.baeldung.couchbase.async" })
|
||||
public class AsyncIntegrationTestConfig {
|
||||
}
|
||||
|
|
|
@ -29,10 +29,10 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
|
|||
@Autowired
|
||||
@Qualifier("TutorialBucketService")
|
||||
private BucketService bucketService;
|
||||
|
||||
|
||||
@Autowired
|
||||
private PersonDocumentConverter converter;
|
||||
|
||||
|
||||
private Bucket bucket;
|
||||
|
||||
@PostConstruct
|
||||
|
@ -42,182 +42,175 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
|
|||
|
||||
@Test
|
||||
public final void givenRandomPerson_whenCreate_thenPersonPersisted() {
|
||||
//create person
|
||||
// create person
|
||||
Person person = randomPerson();
|
||||
personService.create(person);
|
||||
|
||||
//check results
|
||||
|
||||
// check results
|
||||
assertNotNull(person.getId());
|
||||
assertNotNull(bucket.get(person.getId()));
|
||||
|
||||
//cleanup
|
||||
|
||||
// cleanup
|
||||
bucket.remove(person.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenId_whenRead_thenReturnsPerson() {
|
||||
//create and insert person document
|
||||
// create and insert person document
|
||||
String id = insertRandomPersonDocument().id();
|
||||
|
||||
//read person and check results
|
||||
// read person and check results
|
||||
assertNotNull(personService.read(id));
|
||||
|
||||
//cleanup
|
||||
|
||||
// cleanup
|
||||
bucket.remove(id);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenNewHometown_whenUpdate_thenNewHometownPersisted() {
|
||||
//create and insert person document
|
||||
// create and insert person document
|
||||
JsonDocument doc = insertRandomPersonDocument();
|
||||
|
||||
//update person
|
||||
|
||||
// update person
|
||||
Person expected = converter.fromDocument(doc);
|
||||
String updatedHomeTown = RandomStringUtils.randomAlphabetic(12);
|
||||
expected.setHomeTown(updatedHomeTown);
|
||||
personService.update(expected);
|
||||
|
||||
//check results
|
||||
|
||||
// check results
|
||||
JsonDocument actual = bucket.get(expected.getId());
|
||||
assertNotNull(actual);
|
||||
assertNotNull(actual.content());
|
||||
assertEquals(expected.getHomeTown(), actual.content().getString("homeTown"));
|
||||
|
||||
//cleanup
|
||||
|
||||
// cleanup
|
||||
bucket.remove(expected.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenRandomPerson_whenDelete_thenPersonNotInBucket() {
|
||||
//create and insert person document
|
||||
// create and insert person document
|
||||
String id = insertRandomPersonDocument().id();
|
||||
|
||||
//delete person and check results
|
||||
// delete person and check results
|
||||
personService.delete(id);
|
||||
assertNull(bucket.get(id));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public final void givenIds_whenReadBulk_thenReturnsOnlyPersonsWithMatchingIds() {
|
||||
List<String> ids = new ArrayList<>();
|
||||
|
||||
//add some person documents
|
||||
for(int i=0; i<5; i++) {
|
||||
|
||||
// add some person documents
|
||||
for (int i = 0; i < 5; i++) {
|
||||
ids.add(insertRandomPersonDocument().id());
|
||||
}
|
||||
|
||||
//perform bulk read
|
||||
|
||||
// perform bulk read
|
||||
List<Person> persons = personService.readBulk(ids);
|
||||
|
||||
//check results
|
||||
for(Person person : persons) {
|
||||
|
||||
// check results
|
||||
for (Person person : persons) {
|
||||
assertTrue(ids.contains(person.getId()));
|
||||
}
|
||||
|
||||
//cleanup
|
||||
for(String id : ids) {
|
||||
|
||||
// cleanup
|
||||
for (String id : ids) {
|
||||
bucket.remove(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public final void givenPersons_whenInsertBulk_thenPersonsAreInserted() {
|
||||
|
||||
//create some persons
|
||||
|
||||
// create some persons
|
||||
List<Person> persons = new ArrayList<>();
|
||||
for(int i=0; i<5; i++) {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
persons.add(randomPerson());
|
||||
}
|
||||
|
||||
//perform bulk insert
|
||||
// perform bulk insert
|
||||
personService.createBulk(persons);
|
||||
|
||||
//check results
|
||||
for(Person person : persons) {
|
||||
|
||||
// check results
|
||||
for (Person person : persons) {
|
||||
assertNotNull(bucket.get(person.getId()));
|
||||
}
|
||||
|
||||
//cleanup
|
||||
for(Person person : persons) {
|
||||
|
||||
// cleanup
|
||||
for (Person person : persons) {
|
||||
bucket.remove(person.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenPersons_whenUpdateBulk_thenPersonsAreUpdated() {
|
||||
|
||||
|
||||
List<String> ids = new ArrayList<>();
|
||||
|
||||
//add some person documents
|
||||
for(int i=0; i<5; i++) {
|
||||
|
||||
// add some person documents
|
||||
for (int i = 0; i < 5; i++) {
|
||||
ids.add(insertRandomPersonDocument().id());
|
||||
}
|
||||
|
||||
//load persons from Couchbase
|
||||
// load persons from Couchbase
|
||||
List<Person> persons = new ArrayList<>();
|
||||
for(String id : ids) {
|
||||
for (String id : ids) {
|
||||
persons.add(converter.fromDocument(bucket.get(id)));
|
||||
}
|
||||
|
||||
//modify persons
|
||||
for(Person person : persons) {
|
||||
// modify persons
|
||||
for (Person person : persons) {
|
||||
person.setHomeTown(RandomStringUtils.randomAlphabetic(10));
|
||||
}
|
||||
|
||||
//perform bulk update
|
||||
|
||||
// perform bulk update
|
||||
personService.updateBulk(persons);
|
||||
|
||||
//check results
|
||||
for(Person person : persons) {
|
||||
|
||||
// check results
|
||||
for (Person person : persons) {
|
||||
JsonDocument doc = bucket.get(person.getId());
|
||||
assertEquals(person.getName(), doc.content().getString("name"));
|
||||
assertEquals(person.getHomeTown(), doc.content().getString("homeTown"));
|
||||
}
|
||||
|
||||
//cleanup
|
||||
for(String id : ids) {
|
||||
|
||||
// cleanup
|
||||
for (String id : ids) {
|
||||
bucket.remove(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenIds_whenDeleteBulk_thenPersonsAreDeleted() {
|
||||
|
||||
|
||||
List<String> ids = new ArrayList<>();
|
||||
|
||||
//add some person documents
|
||||
for(int i=0; i<5; i++) {
|
||||
|
||||
// add some person documents
|
||||
for (int i = 0; i < 5; i++) {
|
||||
ids.add(insertRandomPersonDocument().id());
|
||||
}
|
||||
|
||||
//perform bulk delete
|
||||
|
||||
// perform bulk delete
|
||||
personService.deleteBulk(ids);
|
||||
|
||||
//check results
|
||||
for(String id : ids) {
|
||||
|
||||
// check results
|
||||
for (String id : ids) {
|
||||
assertNull(bucket.get(id));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private JsonDocument insertRandomPersonDocument() {
|
||||
Person expected = randomPersonWithId();
|
||||
JsonDocument doc = converter.toDocument(expected);
|
||||
return bucket.insert(doc);
|
||||
return bucket.insert(doc);
|
||||
}
|
||||
|
||||
private Person randomPerson() {
|
||||
return Person.Builder.newInstance()
|
||||
.name(RandomStringUtils.randomAlphabetic(10))
|
||||
.homeTown(RandomStringUtils.randomAlphabetic(10))
|
||||
.build();
|
||||
return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build();
|
||||
}
|
||||
|
||||
private Person randomPersonWithId() {
|
||||
return Person.Builder.newInstance()
|
||||
.id(UUID.randomUUID().toString())
|
||||
.name(RandomStringUtils.randomAlphabetic(10))
|
||||
.homeTown(RandomStringUtils.randomAlphabetic(10))
|
||||
.build();
|
||||
return Person.Builder.newInstance().id(UUID.randomUUID().toString()).name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -22,9 +22,9 @@ public class ClusterServiceIntegrationTest extends AsyncIntegrationTest {
|
|||
|
||||
@Autowired
|
||||
private ClusterService couchbaseService;
|
||||
|
||||
|
||||
private Bucket defaultBucket;
|
||||
|
||||
|
||||
@Test
|
||||
public void whenOpenBucket_thenBucketIsNotNull() throws Exception {
|
||||
defaultBucket = couchbaseService.openBucket("default", "");
|
||||
|
|
|
@ -4,6 +4,6 @@ import org.springframework.context.annotation.ComponentScan;
|
|||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages={"com.baeldung.couchbase.spring"})
|
||||
@ComponentScan(basePackages = { "com.baeldung.couchbase.spring" })
|
||||
public class IntegrationTestConfig {
|
||||
}
|
||||
|
|
|
@ -24,7 +24,7 @@ public class PersonCrudServiceIntegrationTest extends IntegrationTest {
|
|||
@PostConstruct
|
||||
private void init() {
|
||||
clarkKent = personService.read(CLARK_KENT_ID);
|
||||
if(clarkKent == null) {
|
||||
if (clarkKent == null) {
|
||||
clarkKent = buildClarkKent();
|
||||
personService.create(clarkKent);
|
||||
}
|
||||
|
@ -50,7 +50,7 @@ public class PersonCrudServiceIntegrationTest extends IntegrationTest {
|
|||
personService.create(expected);
|
||||
String updatedHomeTown = RandomStringUtils.randomAlphabetic(12);
|
||||
expected.setHomeTown(updatedHomeTown);
|
||||
personService.update(expected);
|
||||
personService.update(expected);
|
||||
Person actual = personService.read(expected.getId());
|
||||
assertNotNull(actual);
|
||||
assertEquals(expected.getHomeTown(), actual.getHomeTown());
|
||||
|
@ -66,17 +66,10 @@ public class PersonCrudServiceIntegrationTest extends IntegrationTest {
|
|||
}
|
||||
|
||||
private Person buildClarkKent() {
|
||||
return Person.Builder.newInstance()
|
||||
.id(CLARK_KENT_ID)
|
||||
.name(CLARK_KENT)
|
||||
.homeTown(SMALLVILLE)
|
||||
.build();
|
||||
return Person.Builder.newInstance().id(CLARK_KENT_ID).name(CLARK_KENT).homeTown(SMALLVILLE).build();
|
||||
}
|
||||
|
||||
private Person randomPerson() {
|
||||
return Person.Builder.newInstance()
|
||||
.name(RandomStringUtils.randomAlphabetic(10))
|
||||
.homeTown(RandomStringUtils.randomAlphabetic(10))
|
||||
.build();
|
||||
return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -21,9 +21,9 @@ public class ClusterServiceIntegrationTest extends IntegrationTest {
|
|||
|
||||
@Autowired
|
||||
private ClusterService couchbaseService;
|
||||
|
||||
|
||||
private Bucket defaultBucket;
|
||||
|
||||
|
||||
@Test
|
||||
public void whenOpenBucket_thenBucketIsNotNull() throws Exception {
|
||||
defaultBucket = couchbaseService.openBucket("default", "");
|
||||
|
|
|
@ -35,9 +35,6 @@ public abstract class MemberRepository extends AbstractEntityRepository<Member,
|
|||
|
||||
public List<Member> findAllOrderedByNameWithQueryDSL() {
|
||||
final QMember member = QMember.member;
|
||||
return jpaQuery()
|
||||
.from(member)
|
||||
.orderBy(member.email.asc())
|
||||
.list(member);
|
||||
return jpaQuery().from(member).orderBy(member.email.asc()).list(member);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -64,7 +64,6 @@ public class MemberRegistration {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
public void register(Member member) throws Exception {
|
||||
log.info("Registering " + member.getName());
|
||||
validateMember(member);
|
||||
|
|
|
@ -41,27 +41,13 @@ import org.junit.runner.RunWith;
|
|||
public class MemberRegistrationTest {
|
||||
@Deployment
|
||||
public static Archive<?> createTestArchive() {
|
||||
File[] files = Maven.resolver().loadPomFromFile("pom.xml")
|
||||
.importRuntimeDependencies().resolve().withTransitivity().asFile();
|
||||
File[] files = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile();
|
||||
|
||||
return ShrinkWrap.create(WebArchive.class, "test.war")
|
||||
.addClasses(
|
||||
EntityManagerProducer.class,
|
||||
Member.class,
|
||||
MemberRegistration.class,
|
||||
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);
|
||||
.addClasses(EntityManagerProducer.class, Member.class, MemberRegistration.class, 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
|
||||
|
|
|
@ -8,7 +8,7 @@ import com.lmax.disruptor.EventHandler;
|
|||
public class MultiEventPrintConsumer implements EventConsumer {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public EventHandler<ValueEvent>[] getEventHandler() {
|
||||
|
|
|
@ -8,7 +8,7 @@ import com.lmax.disruptor.EventHandler;
|
|||
public class SingleEventPrintConsumer implements EventConsumer {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public EventHandler<ValueEvent>[] getEventHandler() {
|
||||
|
|
|
@ -11,16 +11,9 @@ import lombok.Getter;
|
|||
|
||||
@Getter
|
||||
public class BookControllerFeignClientBuilder {
|
||||
private BookClient bookClient = createClient(BookClient.class,
|
||||
"http://localhost:8081/api/books");
|
||||
private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books");
|
||||
|
||||
private static <T> T createClient(Class<T> type, String uri) {
|
||||
return Feign.builder()
|
||||
.client(new OkHttpClient())
|
||||
.encoder(new GsonEncoder())
|
||||
.decoder(new GsonDecoder())
|
||||
.logger(new Slf4jLogger(type))
|
||||
.logLevel(Logger.Level.FULL)
|
||||
.target(type, uri);
|
||||
return Feign.builder().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
|
||||
public void givenBookClient_shouldRunSuccessfully() throws Exception {
|
||||
List<Book> books = bookClient.findAll().stream()
|
||||
.map(BookResource::getBook)
|
||||
.collect(Collectors.toList());
|
||||
List<Book> books = bookClient.findAll().stream().map(BookResource::getBook).collect(Collectors.toList());
|
||||
assertTrue(books.size() > 2);
|
||||
log.info("{}", books);
|
||||
}
|
||||
|
|
|
@ -57,6 +57,12 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -100,6 +106,7 @@
|
|||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<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();
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -11,12 +11,12 @@ import com.datastax.driver.core.utils.UUIDs;
|
|||
|
||||
public class CassandraClient {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(CassandraClient.class);
|
||||
|
||||
|
||||
public static void main(String args[]) {
|
||||
CassandraConnector connector = new CassandraConnector();
|
||||
connector.connect("127.0.0.1", null);
|
||||
Session session = connector.getSession();
|
||||
|
||||
|
||||
KeyspaceRepository sr = new KeyspaceRepository(session);
|
||||
sr.createKeyspace("library", "SimpleStrategy", 1);
|
||||
sr.useKeyspace("library");
|
||||
|
@ -24,21 +24,21 @@ public class CassandraClient {
|
|||
BookRepository br = new BookRepository(session);
|
||||
br.createTable();
|
||||
br.alterTablebooks("publisher", "text");
|
||||
|
||||
|
||||
br.createTableBooksByTitle();
|
||||
|
||||
|
||||
Book book = new Book(UUIDs.timeBased(), "Effective Java", "Joshua Bloch", "Programming");
|
||||
br.insertBookBatch(book);
|
||||
|
||||
|
||||
br.selectAll().forEach(o -> LOG.info("Title in books: " + o.getTitle()));
|
||||
br.selectAllBookByTitle().forEach(o -> LOG.info("Title in booksByTitle: " + o.getTitle()));
|
||||
|
||||
|
||||
br.deletebookByTitle("Effective Java");
|
||||
br.deleteTable("books");
|
||||
br.deleteTable("booksByTitle");
|
||||
|
||||
sr.deleteKeyspace("library");
|
||||
|
||||
|
||||
connector.close();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,14 +16,14 @@ public class Book {
|
|||
|
||||
Book() {
|
||||
}
|
||||
|
||||
|
||||
public Book(UUID id, String title, String author, String subject) {
|
||||
this.id = id;
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.subject = subject;
|
||||
}
|
||||
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
|
|
@ -11,7 +11,7 @@ import com.datastax.driver.core.Session;
|
|||
public class BookRepository {
|
||||
|
||||
private static final String TABLE_NAME = "books";
|
||||
|
||||
|
||||
private static final String TABLE_NAME_BY_TITLE = TABLE_NAME + "ByTitle";
|
||||
|
||||
private Session session;
|
||||
|
@ -29,7 +29,7 @@ public class BookRepository {
|
|||
final String query = sb.toString();
|
||||
session.execute(query);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates the books table.
|
||||
*/
|
||||
|
@ -62,7 +62,7 @@ public class BookRepository {
|
|||
final String query = sb.toString();
|
||||
session.execute(query);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Insert a row in the table booksByTitle.
|
||||
* @param book
|
||||
|
@ -73,19 +73,15 @@ public class BookRepository {
|
|||
final String query = sb.toString();
|
||||
session.execute(query);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Insert a book into two identical tables using a batch query.
|
||||
*
|
||||
* @param book
|
||||
*/
|
||||
public void insertBookBatch(Book book) {
|
||||
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("', '")
|
||||
.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("');")
|
||||
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("', '").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;");
|
||||
|
||||
final String query = sb.toString();
|
||||
|
@ -101,7 +97,7 @@ public class BookRepository {
|
|||
StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME_BY_TITLE).append(" WHERE title = '").append(title).append("';");
|
||||
|
||||
final String query = sb.toString();
|
||||
|
||||
|
||||
ResultSet rs = session.execute(query);
|
||||
|
||||
List<Book> books = new ArrayList<Book>();
|
||||
|
@ -133,7 +129,7 @@ public class BookRepository {
|
|||
}
|
||||
return books;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Select all books from booksByTitle
|
||||
* @return
|
||||
|
|
|
@ -37,4 +37,4 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
</project>
|
|
@ -28,9 +28,8 @@
|
|||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<build>
|
||||
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
|
||||
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>kotlin-maven-plugin</artifactId>
|
||||
|
@ -39,16 +38,50 @@
|
|||
<executions>
|
||||
<execution>
|
||||
<id>compile</id>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
<goals> <goal>compile</goal> </goals>
|
||||
<configuration>
|
||||
<sourceDirs>
|
||||
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
|
||||
<sourceDir>${project.basedir}/src/main/java</sourceDir>
|
||||
</sourceDirs>
|
||||
</configuration>
|
||||
</execution>
|
||||
|
||||
<execution>
|
||||
<id>test-compile</id>
|
||||
<goals>
|
||||
<goal>test-compile</goal>
|
||||
</goals>
|
||||
<goals> <goal>test-compile</goal> </goals>
|
||||
<configuration>
|
||||
<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>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
@ -57,9 +90,10 @@
|
|||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<kotlin-test-junit.version>1.0.4</kotlin-test-junit.version>
|
||||
<kotlin-stdlib.version>1.0.4</kotlin-stdlib.version>
|
||||
<kotlin-maven-plugin.version>1.0.4</kotlin-maven-plugin.version>
|
||||
<kotlin-maven-plugin.version>1.0.6</kotlin-maven-plugin.version>
|
||||
<kotlin-test-junit.version>1.0.6</kotlin-test-junit.version>
|
||||
<kotlin-stdlib.version>1.0.6</kotlin-stdlib.version>
|
||||
<kotlin-maven-plugin.version>1.0.6</kotlin-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -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 {
|
||||
val result = if (catId == "100") "Yes" else "No"
|
||||
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>) {
|
||||
val numbers = arrayOf("first", "second", "third", "fourth")
|
||||
|
||||
var concat = ""
|
||||
for (n in numbers) {
|
||||
concat += n
|
||||
println(n)
|
||||
}
|
||||
|
||||
var sum = 0
|
||||
for (i in 2..9) {
|
||||
sum += i
|
||||
for (i in 2..9 step 2) {
|
||||
println(i)
|
||||
}
|
||||
|
||||
val res = 1.rangeTo(10).map { it * 2 }
|
||||
println(res)
|
||||
|
||||
val firstName = "Tom"
|
||||
val secondName = "Mary"
|
||||
val concatOfNames = "$firstName + $secondName"
|
||||
println("Names: $concatOfNames")
|
||||
val sum = "four: ${2 + 2}"
|
||||
|
||||
val itemManager = ItemManager("cat_id", "db://connection")
|
||||
ItemManager(categoryId = "catId", dbConnection = "db://Connection")
|
||||
val result = "function result: ${itemManager.isFromSpecificCategory("1")}"
|
||||
println(result)
|
||||
|
||||
|
@ -63,4 +75,9 @@ fun main(args: Array<String>) {
|
|||
"Alice" -> println("Hi lady")
|
||||
}
|
||||
|
||||
val items = listOf(1, 2, 3, 4)
|
||||
|
||||
|
||||
val rwList = mutableListOf(1, 2, 3)
|
||||
rwList.add(5)
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue