formatting work
This commit is contained in:
parent
44bf48068f
commit
034cde6e20
|
@ -18,9 +18,7 @@ public class Dijkstra {
|
||||||
while (unsettledNodes.size() != 0) {
|
while (unsettledNodes.size() != 0) {
|
||||||
Node currentNode = getLowestDistanceNode(unsettledNodes);
|
Node currentNode = getLowestDistanceNode(unsettledNodes);
|
||||||
unsettledNodes.remove(currentNode);
|
unsettledNodes.remove(currentNode);
|
||||||
for (Entry<Node, Integer> adjacencyPair : currentNode
|
for (Entry<Node, Integer> adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
|
||||||
.getAdjacentNodes()
|
|
||||||
.entrySet()) {
|
|
||||||
Node adjacentNode = adjacencyPair.getKey();
|
Node adjacentNode = adjacencyPair.getKey();
|
||||||
Integer edgeWeigh = adjacencyPair.getValue();
|
Integer edgeWeigh = adjacencyPair.getValue();
|
||||||
|
|
||||||
|
|
|
@ -55,29 +55,19 @@ public class DijkstraAlgorithmTest {
|
||||||
for (Node node : graph.getNodes()) {
|
for (Node node : graph.getNodes()) {
|
||||||
switch (node.getName()) {
|
switch (node.getName()) {
|
||||||
case "B":
|
case "B":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeB));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeB));
|
|
||||||
break;
|
break;
|
||||||
case "C":
|
case "C":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeC));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeC));
|
|
||||||
break;
|
break;
|
||||||
case "D":
|
case "D":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeD));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeD));
|
|
||||||
break;
|
break;
|
||||||
case "E":
|
case "E":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeE));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeE));
|
|
||||||
break;
|
break;
|
||||||
case "F":
|
case "F":
|
||||||
assertTrue(node
|
assertTrue(node.getShortestPath().equals(shortestPathForNodeF));
|
||||||
.getShortestPath()
|
|
||||||
.equals(shortestPathForNodeF));
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -27,17 +27,12 @@ public class BuilderProcessor extends AbstractProcessor {
|
||||||
|
|
||||||
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
|
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
|
||||||
|
|
||||||
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream()
|
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream().collect(Collectors.partitioningBy(element -> ((ExecutableType) element.asType()).getParameterTypes().size() == 1 && element.getSimpleName().toString().startsWith("set")));
|
||||||
.collect(Collectors.partitioningBy(element ->
|
|
||||||
((ExecutableType) element.asType()).getParameterTypes().size() == 1
|
|
||||||
&& element.getSimpleName().toString().startsWith("set")));
|
|
||||||
|
|
||||||
List<Element> setters = annotatedMethods.get(true);
|
List<Element> setters = annotatedMethods.get(true);
|
||||||
List<Element> otherMethods = annotatedMethods.get(false);
|
List<Element> otherMethods = annotatedMethods.get(false);
|
||||||
|
|
||||||
otherMethods.forEach(element ->
|
otherMethods.forEach(element -> processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@BuilderProperty must be applied to a setXxx method with a single argument", element));
|
||||||
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
|
|
||||||
"@BuilderProperty must be applied to a setXxx method with a single argument", element));
|
|
||||||
|
|
||||||
if (setters.isEmpty()) {
|
if (setters.isEmpty()) {
|
||||||
continue;
|
continue;
|
||||||
|
@ -45,11 +40,7 @@ public class BuilderProcessor extends AbstractProcessor {
|
||||||
|
|
||||||
String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString();
|
String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString();
|
||||||
|
|
||||||
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(
|
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(setter -> setter.getSimpleName().toString(), setter -> ((ExecutableType) setter.asType()).getParameterTypes().get(0).toString()));
|
||||||
setter -> setter.getSimpleName().toString(),
|
|
||||||
setter -> ((ExecutableType) setter.asType())
|
|
||||||
.getParameterTypes().get(0).toString()
|
|
||||||
));
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
writeBuilderFile(className, setterMap);
|
writeBuilderFile(className, setterMap);
|
||||||
|
|
|
@ -9,10 +9,7 @@ public class PersonBuilderTest {
|
||||||
@Test
|
@Test
|
||||||
public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
|
public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
|
||||||
|
|
||||||
Person person = new PersonBuilder()
|
Person person = new PersonBuilder().setAge(25).setName("John").build();
|
||||||
.setAge(25)
|
|
||||||
.setName("John")
|
|
||||||
.build();
|
|
||||||
|
|
||||||
assertEquals(25, person.getAge());
|
assertEquals(25, person.getAge());
|
||||||
assertEquals("John", person.getName());
|
assertEquals("John", person.getName());
|
||||||
|
|
|
@ -38,8 +38,7 @@ public class AssertJCoreTest {
|
||||||
public void whenCheckingForElement_thenContains() throws Exception {
|
public void whenCheckingForElement_thenContains() throws Exception {
|
||||||
List<String> list = Arrays.asList("1", "2", "3");
|
List<String> list = Arrays.asList("1", "2", "3");
|
||||||
|
|
||||||
assertThat(list)
|
assertThat(list).contains("1");
|
||||||
.contains("1");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -50,12 +49,7 @@ public class AssertJCoreTest {
|
||||||
assertThat(list).startsWith("1");
|
assertThat(list).startsWith("1");
|
||||||
assertThat(list).doesNotContainNull();
|
assertThat(list).doesNotContainNull();
|
||||||
|
|
||||||
assertThat(list)
|
assertThat(list).isNotEmpty().contains("1").startsWith("1").doesNotContainNull().containsSequence("2", "3");
|
||||||
.isNotEmpty()
|
|
||||||
.contains("1")
|
|
||||||
.startsWith("1")
|
|
||||||
.doesNotContainNull()
|
|
||||||
.containsSequence("2", "3");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -67,11 +61,7 @@ public class AssertJCoreTest {
|
||||||
public void whenCheckingCharacter_thenIsUnicode() throws Exception {
|
public void whenCheckingCharacter_thenIsUnicode() throws Exception {
|
||||||
char someCharacter = 'c';
|
char someCharacter = 'c';
|
||||||
|
|
||||||
assertThat(someCharacter)
|
assertThat(someCharacter).isNotEqualTo('a').inUnicode().isGreaterThanOrEqualTo('b').isLowerCase();
|
||||||
.isNotEqualTo('a')
|
|
||||||
.inUnicode()
|
|
||||||
.isGreaterThanOrEqualTo('b')
|
|
||||||
.isLowerCase();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -94,11 +84,7 @@ public class AssertJCoreTest {
|
||||||
final File someFile = File.createTempFile("aaa", "bbb");
|
final File someFile = File.createTempFile("aaa", "bbb");
|
||||||
someFile.deleteOnExit();
|
someFile.deleteOnExit();
|
||||||
|
|
||||||
assertThat(someFile)
|
assertThat(someFile).exists().isFile().canRead().canWrite();
|
||||||
.exists()
|
|
||||||
.isFile()
|
|
||||||
.canRead()
|
|
||||||
.canWrite();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -113,20 +99,14 @@ public class AssertJCoreTest {
|
||||||
public void whenGivenMap_then() throws Exception {
|
public void whenGivenMap_then() throws Exception {
|
||||||
Map<Integer, String> map = Maps.newHashMap(2, "a");
|
Map<Integer, String> map = Maps.newHashMap(2, "a");
|
||||||
|
|
||||||
assertThat(map)
|
assertThat(map).isNotEmpty().containsKey(2).doesNotContainKeys(10).contains(entry(2, "a"));
|
||||||
.isNotEmpty()
|
|
||||||
.containsKey(2)
|
|
||||||
.doesNotContainKeys(10)
|
|
||||||
.contains(entry(2, "a"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGivenException_then() throws Exception {
|
public void whenGivenException_then() throws Exception {
|
||||||
Exception ex = new Exception("abc");
|
Exception ex = new Exception("abc");
|
||||||
|
|
||||||
assertThat(ex)
|
assertThat(ex).hasNoCause().hasMessageEndingWith("c");
|
||||||
.hasNoCause()
|
|
||||||
.hasMessageEndingWith("c");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Ignore // IN ORDER TO TEST, REMOVE THIS LINE
|
@Ignore // IN ORDER TO TEST, REMOVE THIS LINE
|
||||||
|
@ -134,8 +114,6 @@ public class AssertJCoreTest {
|
||||||
public void whenRunningAssertion_thenDescribed() throws Exception {
|
public void whenRunningAssertion_thenDescribed() throws Exception {
|
||||||
Person person = new Person("Alex", 34);
|
Person person = new Person("Alex", 34);
|
||||||
|
|
||||||
assertThat(person.getAge())
|
assertThat(person.getAge()).as("%s's age should be equal to 100").isEqualTo(100);
|
||||||
.as("%s's age should be equal to 100")
|
|
||||||
.isEqualTo(100);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -26,9 +26,7 @@ public class AssertJGuavaTest {
|
||||||
final File temp1 = File.createTempFile("bael", "dung1");
|
final File temp1 = File.createTempFile("bael", "dung1");
|
||||||
final File temp2 = File.createTempFile("bael", "dung2");
|
final File temp2 = File.createTempFile("bael", "dung2");
|
||||||
|
|
||||||
assertThat(Files.asByteSource(temp1))
|
assertThat(Files.asByteSource(temp1)).hasSize(0).hasSameContentAs(Files.asByteSource(temp2));
|
||||||
.hasSize(0)
|
|
||||||
.hasSameContentAs(Files.asByteSource(temp2));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -37,11 +35,7 @@ public class AssertJGuavaTest {
|
||||||
mmap.put(1, "one");
|
mmap.put(1, "one");
|
||||||
mmap.put(1, "1");
|
mmap.put(1, "1");
|
||||||
|
|
||||||
assertThat(mmap)
|
assertThat(mmap).hasSize(2).containsKeys(1).contains(entry(1, "one")).contains(entry(1, "1"));
|
||||||
.hasSize(2)
|
|
||||||
.containsKeys(1)
|
|
||||||
.contains(entry(1, "one"))
|
|
||||||
.contains(entry(1, "1"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -62,31 +56,21 @@ public class AssertJGuavaTest {
|
||||||
mmap2.put(1, "one");
|
mmap2.put(1, "one");
|
||||||
mmap2.put(1, "1");
|
mmap2.put(1, "1");
|
||||||
|
|
||||||
assertThat(mmap1)
|
assertThat(mmap1).containsAllEntriesOf(mmap2).containsAllEntriesOf(mmap1_clone).hasSameEntriesAs(mmap1_clone);
|
||||||
.containsAllEntriesOf(mmap2)
|
|
||||||
.containsAllEntriesOf(mmap1_clone)
|
|
||||||
.hasSameEntriesAs(mmap1_clone);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
|
public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
|
||||||
final Optional<String> something = Optional.of("something");
|
final Optional<String> something = Optional.of("something");
|
||||||
|
|
||||||
assertThat(something)
|
assertThat(something).isPresent().extractingValue().isEqualTo("something");
|
||||||
.isPresent()
|
|
||||||
.extractingValue()
|
|
||||||
.isEqualTo("something");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
|
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||||
final Range<String> range = Range.openClosed("a", "g");
|
final Range<String> range = Range.openClosed("a", "g");
|
||||||
|
|
||||||
assertThat(range)
|
assertThat(range).hasOpenedLowerBound().isNotEmpty().hasClosedUpperBound().contains("b");
|
||||||
.hasOpenedLowerBound()
|
|
||||||
.isNotEmpty()
|
|
||||||
.hasClosedUpperBound()
|
|
||||||
.contains("b");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -96,10 +80,7 @@ public class AssertJGuavaTest {
|
||||||
map.put(Range.closed(0, 60), "F");
|
map.put(Range.closed(0, 60), "F");
|
||||||
map.put(Range.closed(61, 70), "D");
|
map.put(Range.closed(61, 70), "D");
|
||||||
|
|
||||||
assertThat(map)
|
assertThat(map).isNotEmpty().containsKeys(0).contains(MapEntry.entry(34, "F"));
|
||||||
.isNotEmpty()
|
|
||||||
.containsKeys(0)
|
|
||||||
.contains(MapEntry.entry(34, "F"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -109,13 +90,7 @@ public class AssertJGuavaTest {
|
||||||
table.put(1, "A", "PRESENT");
|
table.put(1, "A", "PRESENT");
|
||||||
table.put(1, "B", "ABSENT");
|
table.put(1, "B", "ABSENT");
|
||||||
|
|
||||||
assertThat(table)
|
assertThat(table).hasRowCount(1).containsValues("ABSENT").containsCell(1, "B", "ABSENT");
|
||||||
.hasRowCount(1)
|
|
||||||
.containsValues("ABSENT")
|
|
||||||
.containsCell(1, "B", "ABSENT");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -20,20 +20,14 @@ public class AssertJJava8Test {
|
||||||
public void givenOptional_shouldAssert() throws Exception {
|
public void givenOptional_shouldAssert() throws Exception {
|
||||||
final Optional<String> givenOptional = Optional.of("something");
|
final Optional<String> givenOptional = Optional.of("something");
|
||||||
|
|
||||||
assertThat(givenOptional)
|
assertThat(givenOptional).isPresent().hasValue("something");
|
||||||
.isPresent()
|
|
||||||
.hasValue("something");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPredicate_shouldAssert() throws Exception {
|
public void givenPredicate_shouldAssert() throws Exception {
|
||||||
final Predicate<String> predicate = s -> s.length() > 4;
|
final Predicate<String> predicate = s -> s.length() > 4;
|
||||||
|
|
||||||
assertThat(predicate)
|
assertThat(predicate).accepts("aaaaa", "bbbbb").rejects("a", "b").acceptsAll(asList("aaaaa", "bbbbb")).rejectsAll(asList("a", "b"));
|
||||||
.accepts("aaaaa", "bbbbb")
|
|
||||||
.rejects("a", "b")
|
|
||||||
.acceptsAll(asList("aaaaa", "bbbbb"))
|
|
||||||
.rejectsAll(asList("a", "b"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -41,92 +35,74 @@ public class AssertJJava8Test {
|
||||||
final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
|
final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
|
||||||
final LocalDate todayDate = LocalDate.now();
|
final LocalDate todayDate = LocalDate.now();
|
||||||
|
|
||||||
assertThat(givenLocalDate)
|
assertThat(givenLocalDate).isBefore(LocalDate.of(2020, 7, 8)).isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
||||||
.isBefore(LocalDate.of(2020, 7, 8))
|
|
||||||
.isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
|
||||||
|
|
||||||
assertThat(todayDate)
|
assertThat(todayDate).isAfter(LocalDate.of(1989, 7, 8)).isToday();
|
||||||
.isAfter(LocalDate.of(1989, 7, 8))
|
|
||||||
.isToday();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenLocalDateTime_shouldAssert() throws Exception {
|
public void givenLocalDateTime_shouldAssert() throws Exception {
|
||||||
final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
|
final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
|
||||||
|
|
||||||
assertThat(givenLocalDate)
|
assertThat(givenLocalDate).isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
||||||
.isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenLocalTime_shouldAssert() throws Exception {
|
public void givenLocalTime_shouldAssert() throws Exception {
|
||||||
final LocalTime givenLocalTime = LocalTime.of(12, 15);
|
final LocalTime givenLocalTime = LocalTime.of(12, 15);
|
||||||
|
|
||||||
assertThat(givenLocalTime)
|
assertThat(givenLocalTime).isAfter(LocalTime.of(1, 0)).hasSameHourAs(LocalTime.of(12, 0));
|
||||||
.isAfter(LocalTime.of(1, 0))
|
|
||||||
.hasSameHourAs(LocalTime.of(12, 0));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldAssertFlatExtracting() throws Exception {
|
public void givenList_shouldAssertFlatExtracting() throws Exception {
|
||||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).flatExtracting(LocalDate::getYear).contains(2015);
|
||||||
.flatExtracting(LocalDate::getYear)
|
|
||||||
.contains(2015);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
|
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
|
||||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).flatExtracting(LocalDate::isLeapYear).contains(true);
|
||||||
.flatExtracting(LocalDate::isLeapYear)
|
|
||||||
.contains(true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldAssertFlatExtractingClass() throws Exception {
|
public void givenList_shouldAssertFlatExtractingClass() throws Exception {
|
||||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).flatExtracting(Object::getClass).contains(LocalDate.class);
|
||||||
.flatExtracting(Object::getClass)
|
|
||||||
.contains(LocalDate.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
|
public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
|
||||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth).contains(2015, 6);
|
||||||
.flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth)
|
|
||||||
.contains(2015, 6);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_shouldSatisfy() throws Exception {
|
public void givenString_shouldSatisfy() throws Exception {
|
||||||
final String givenString = "someString";
|
final String givenString = "someString";
|
||||||
|
|
||||||
assertThat(givenString)
|
assertThat(givenString).satisfies(s -> {
|
||||||
.satisfies(s -> {
|
assertThat(s).isNotEmpty();
|
||||||
assertThat(s).isNotEmpty();
|
assertThat(s).hasSize(10);
|
||||||
assertThat(s).hasSize(10);
|
});
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenString_shouldMatch() throws Exception {
|
public void givenString_shouldMatch() throws Exception {
|
||||||
final String emptyString = "";
|
final String emptyString = "";
|
||||||
|
|
||||||
assertThat(emptyString)
|
assertThat(emptyString).matches(String::isEmpty);
|
||||||
.matches(String::isEmpty);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
|
public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
|
||||||
final List<String> givenList = Arrays.asList("");
|
final List<String> givenList = Arrays.asList("");
|
||||||
|
|
||||||
assertThat(givenList)
|
assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
||||||
.hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,12 +4,12 @@ import com.google.auto.value.AutoValue;
|
||||||
|
|
||||||
@AutoValue
|
@AutoValue
|
||||||
public abstract class AutoValueMoney {
|
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) {
|
public static AutoValueMoney create(String currency, long amount) {
|
||||||
return new AutoValue_AutoValueMoney(currency, amount);
|
return new AutoValue_AutoValueMoney(currency, amount);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,20 +4,20 @@ import com.google.auto.value.AutoValue;
|
||||||
|
|
||||||
@AutoValue
|
@AutoValue
|
||||||
public abstract class AutoValueMoneyWithBuilder {
|
public abstract class AutoValueMoneyWithBuilder {
|
||||||
public abstract String getCurrency();
|
public abstract String getCurrency();
|
||||||
|
|
||||||
public abstract long getAmount();
|
public abstract long getAmount();
|
||||||
|
|
||||||
static Builder builder() {
|
static Builder builder() {
|
||||||
return new AutoValue_AutoValueMoneyWithBuilder.Builder();
|
return new AutoValue_AutoValueMoneyWithBuilder.Builder();
|
||||||
}
|
}
|
||||||
|
|
||||||
@AutoValue.Builder
|
@AutoValue.Builder
|
||||||
abstract static class Builder {
|
abstract static class Builder {
|
||||||
abstract Builder setCurrency(String currency);
|
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;
|
import java.util.Objects;
|
||||||
|
|
||||||
public final class Foo {
|
public final class Foo {
|
||||||
private final String text;
|
private final String text;
|
||||||
private final int number;
|
private final int number;
|
||||||
|
|
||||||
public Foo(String text, int number) {
|
public Foo(String text, int number) {
|
||||||
this.text = text;
|
this.text = text;
|
||||||
this.number = number;
|
this.number = number;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getText() {
|
public String getText() {
|
||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getNumber() {
|
public int getNumber() {
|
||||||
return number;
|
return number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
return Objects.hash(text, number);
|
return Objects.hash(text, number);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Foo [text=" + text + ", number=" + number + "]";
|
return "Foo [text=" + text + ", number=" + number + "]";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object obj) {
|
public boolean equals(Object obj) {
|
||||||
if (this == obj)
|
if (this == obj)
|
||||||
return true;
|
return true;
|
||||||
if (obj == null)
|
if (obj == null)
|
||||||
return false;
|
return false;
|
||||||
if (getClass() != obj.getClass())
|
if (getClass() != obj.getClass())
|
||||||
return false;
|
return false;
|
||||||
Foo other = (Foo) obj;
|
Foo other = (Foo) obj;
|
||||||
if (number != other.number)
|
if (number != other.number)
|
||||||
return false;
|
return false;
|
||||||
if (text == null) {
|
if (text == null) {
|
||||||
if (other.text != null)
|
if (other.text != null)
|
||||||
return false;
|
return false;
|
||||||
} else if (!text.equals(other.text))
|
} else if (!text.equals(other.text))
|
||||||
return false;
|
return false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,52 +1,53 @@
|
||||||
package com.baeldung.autovalue;
|
package com.baeldung.autovalue;
|
||||||
|
|
||||||
public final class ImmutableMoney {
|
public final class ImmutableMoney {
|
||||||
private final long amount;
|
private final long amount;
|
||||||
private final String currency;
|
private final String currency;
|
||||||
public ImmutableMoney(long amount, String currency) {
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
public ImmutableMoney(long amount, String currency) {
|
||||||
public boolean equals(Object obj) {
|
this.amount = amount;
|
||||||
if (this == obj)
|
this.currency = currency;
|
||||||
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 long getAmount() {
|
@Override
|
||||||
return amount;
|
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() {
|
@Override
|
||||||
return currency;
|
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 long getAmount() {
|
||||||
public String toString() {
|
return amount;
|
||||||
return "ImmutableMoney [amount=" + amount + ", currency=" + currency
|
}
|
||||||
+ "]";
|
|
||||||
}
|
public String getCurrency() {
|
||||||
|
return currency;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "ImmutableMoney [amount=" + amount + ", currency=" + currency + "]";
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,35 +1,34 @@
|
||||||
package com.baeldung.autovalue;
|
package com.baeldung.autovalue;
|
||||||
|
|
||||||
public class MutableMoney {
|
public class MutableMoney {
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "MutableMoney [amount=" + amount + ", currency=" + currency
|
return "MutableMoney [amount=" + amount + ", currency=" + currency + "]";
|
||||||
+ "]";
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public long getAmount() {
|
public long getAmount() {
|
||||||
return amount;
|
return amount;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setAmount(long amount) {
|
public void setAmount(long amount) {
|
||||||
this.amount = amount;
|
this.amount = amount;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getCurrency() {
|
public String getCurrency() {
|
||||||
return currency;
|
return currency;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCurrency(String currency) {
|
public void setCurrency(String currency) {
|
||||||
this.currency = currency;
|
this.currency = currency;
|
||||||
}
|
}
|
||||||
|
|
||||||
private long amount;
|
private long amount;
|
||||||
private String currency;
|
private String currency;
|
||||||
|
|
||||||
public MutableMoney(long amount, String currency) {
|
public MutableMoney(long amount, String currency) {
|
||||||
super();
|
super();
|
||||||
this.amount = amount;
|
this.amount = amount;
|
||||||
this.currency = currency;
|
this.currency = currency;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,55 +5,59 @@ import static org.junit.Assert.*;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class MoneyUnitTest {
|
public class MoneyUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
||||||
MutableMoney m1 = new MutableMoney(10000, "USD");
|
MutableMoney m1 = new MutableMoney(10000, "USD");
|
||||||
MutableMoney m2 = new MutableMoney(10000, "USD");
|
MutableMoney m2 = new MutableMoney(10000, "USD");
|
||||||
assertFalse(m1.equals(m2));
|
assertFalse(m1.equals(m2));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() {
|
public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() {
|
||||||
ImmutableMoney m1 = new ImmutableMoney(10000, "USD");
|
ImmutableMoney m1 = new ImmutableMoney(10000, "USD");
|
||||||
ImmutableMoney m2 = new ImmutableMoney(10000, "USD");
|
ImmutableMoney m2 = new ImmutableMoney(10000, "USD");
|
||||||
assertTrue(m1.equals(m2));
|
assertTrue(m1.equals(m2));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() {
|
public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() {
|
||||||
AutoValueMoney m = AutoValueMoney.create("USD", 10000);
|
AutoValueMoney m = AutoValueMoney.create("USD", 10000);
|
||||||
assertEquals(m.getAmount(), 10000);
|
assertEquals(m.getAmount(), 10000);
|
||||||
assertEquals(m.getCurrency(), "USD");
|
assertEquals(m.getCurrency(), "USD");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() {
|
public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() {
|
||||||
AutoValueMoney m1 = AutoValueMoney.create("USD", 5000);
|
AutoValueMoney m1 = AutoValueMoney.create("USD", 5000);
|
||||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||||
assertTrue(m1.equals(m2));
|
assertTrue(m1.equals(m2));
|
||||||
}
|
}
|
||||||
@Test
|
|
||||||
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
|
@Test
|
||||||
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
|
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
|
||||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
|
||||||
assertFalse(m1.equals(m2));
|
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();
|
@Test
|
||||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() {
|
||||||
assertTrue(m1.equals(m2));
|
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||||
}
|
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||||
@Test
|
assertTrue(m1.equals(m2));
|
||||||
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
|
}
|
||||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
|
||||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
|
@Test
|
||||||
assertFalse(m1.equals(m2));
|
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
|
||||||
}
|
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||||
@Test
|
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
|
||||||
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
|
assertFalse(m1.equals(m2));
|
||||||
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
}
|
||||||
assertEquals(m.getAmount(), 5000);
|
|
||||||
assertEquals(m.getCurrency(), "USD");
|
@Test
|
||||||
}
|
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
|
||||||
|
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||||
|
assertEquals(m.getAmount(), 5000);
|
||||||
|
assertEquals(m.getCurrency(), "USD");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,25 +7,24 @@ import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||||
|
|
||||||
public class RunAlgorithm {
|
public class RunAlgorithm {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
Scanner in = new Scanner(System.in);
|
Scanner in = new Scanner(System.in);
|
||||||
System.out.println("Run algorithm:");
|
System.out.println("Run algorithm:");
|
||||||
System.out.println("1 - Simulated Annealing");
|
System.out.println("1 - Simulated Annealing");
|
||||||
System.out.println("2 - Slope One");
|
System.out.println("2 - Slope One");
|
||||||
int decision = in.nextInt();
|
int decision = in.nextInt();
|
||||||
switch (decision) {
|
switch (decision) {
|
||||||
case 1:
|
case 1:
|
||||||
System.out.println(
|
System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||||
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
break;
|
||||||
break;
|
case 2:
|
||||||
case 2:
|
SlopeOne.slopeOne(3);
|
||||||
SlopeOne.slopeOne(3);
|
break;
|
||||||
break;
|
default:
|
||||||
default:
|
System.out.println("Unknown option");
|
||||||
System.out.println("Unknown option");
|
break;
|
||||||
break;
|
}
|
||||||
}
|
in.close();
|
||||||
in.close();
|
}
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,18 +5,18 @@ import lombok.Data;
|
||||||
@Data
|
@Data
|
||||||
public class City {
|
public class City {
|
||||||
|
|
||||||
private int x;
|
private int x;
|
||||||
private int y;
|
private int y;
|
||||||
|
|
||||||
public City() {
|
public City() {
|
||||||
this.x = (int) (Math.random() * 500);
|
this.x = (int) (Math.random() * 500);
|
||||||
this.y = (int) (Math.random() * 500);
|
this.y = (int) (Math.random() * 500);
|
||||||
}
|
}
|
||||||
|
|
||||||
public double distanceToCity(City city) {
|
public double distanceToCity(City city) {
|
||||||
int x = Math.abs(getX() - city.getX());
|
int x = Math.abs(getX() - city.getX());
|
||||||
int y = Math.abs(getY() - city.getY());
|
int y = Math.abs(getY() - city.getY());
|
||||||
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
|
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -24,7 +24,7 @@ public class SimulatedAnnealing {
|
||||||
}
|
}
|
||||||
t *= coolingRate;
|
t *= coolingRate;
|
||||||
} else {
|
} else {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (i % 100 == 0) {
|
if (i % 100 == 0) {
|
||||||
System.out.println("Iteration #" + i);
|
System.out.println("Iteration #" + i);
|
||||||
|
|
|
@ -11,26 +11,25 @@ import lombok.Data;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class InputData {
|
public class InputData {
|
||||||
|
|
||||||
protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"),
|
|
||||||
new Item("Snacks"));
|
|
||||||
|
|
||||||
public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) {
|
protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), new Item("Snacks"));
|
||||||
Map<User, HashMap<Item, Double>> data = new HashMap<>();
|
|
||||||
HashMap<Item, Double> newUser;
|
public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) {
|
||||||
Set<Item> newRecommendationSet;
|
Map<User, HashMap<Item, Double>> data = new HashMap<>();
|
||||||
for (int i = 0; i < numberOfUsers; i++) {
|
HashMap<Item, Double> newUser;
|
||||||
newUser = new HashMap<Item, Double>();
|
Set<Item> newRecommendationSet;
|
||||||
newRecommendationSet = new HashSet<>();
|
for (int i = 0; i < numberOfUsers; i++) {
|
||||||
for (int j = 0; j < 3; j++) {
|
newUser = new HashMap<Item, Double>();
|
||||||
newRecommendationSet.add(items.get((int) (Math.random() * 5)));
|
newRecommendationSet = new HashSet<>();
|
||||||
}
|
for (int j = 0; j < 3; j++) {
|
||||||
for (Item item : newRecommendationSet) {
|
newRecommendationSet.add(items.get((int) (Math.random() * 5)));
|
||||||
newUser.put(item, Math.random());
|
}
|
||||||
}
|
for (Item item : newRecommendationSet) {
|
||||||
data.put(new User("User " + i), newUser);
|
newUser.put(item, Math.random());
|
||||||
}
|
}
|
||||||
return data;
|
data.put(new User("User " + i), newUser);
|
||||||
}
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,5 +9,5 @@ import lombok.NoArgsConstructor;
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public class Item {
|
public class Item {
|
||||||
|
|
||||||
private String itemName;
|
private String itemName;
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,114 +11,114 @@ import java.util.Map.Entry;
|
||||||
*/
|
*/
|
||||||
public class SlopeOne {
|
public class SlopeOne {
|
||||||
|
|
||||||
private static Map<Item, Map<Item, Double>> diff = 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<Item, Map<Item, Integer>> freq = new HashMap<>();
|
||||||
private static Map<User, HashMap<Item, Double>> inputData;
|
private static Map<User, HashMap<Item, Double>> inputData;
|
||||||
private static Map<User, HashMap<Item, Double>> outputData = new HashMap<>();
|
private static Map<User, HashMap<Item, Double>> outputData = new HashMap<>();
|
||||||
|
|
||||||
public static void slopeOne(int numberOfUsers) {
|
public static void slopeOne(int numberOfUsers) {
|
||||||
inputData = InputData.initializeData(numberOfUsers);
|
inputData = InputData.initializeData(numberOfUsers);
|
||||||
System.out.println("Slope One - Before the Prediction\n");
|
System.out.println("Slope One - Before the Prediction\n");
|
||||||
buildDifferencesMatrix(inputData);
|
buildDifferencesMatrix(inputData);
|
||||||
System.out.println("\nSlope One - With Predictions\n");
|
System.out.println("\nSlope One - With Predictions\n");
|
||||||
predict(inputData);
|
predict(inputData);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Based on the available data, calculate the relationships between the
|
* Based on the available data, calculate the relationships between the
|
||||||
* items and number of occurences
|
* items and number of occurences
|
||||||
*
|
*
|
||||||
* @param data
|
* @param data
|
||||||
* existing user data and their items' ratings
|
* existing user data and their items' ratings
|
||||||
*/
|
*/
|
||||||
private static void buildDifferencesMatrix(Map<User, HashMap<Item, Double>> data) {
|
private static void buildDifferencesMatrix(Map<User, HashMap<Item, Double>> data) {
|
||||||
for (HashMap<Item, Double> user : data.values()) {
|
for (HashMap<Item, Double> user : data.values()) {
|
||||||
for (Entry<Item, Double> e : user.entrySet()) {
|
for (Entry<Item, Double> e : user.entrySet()) {
|
||||||
if (!diff.containsKey(e.getKey())) {
|
if (!diff.containsKey(e.getKey())) {
|
||||||
diff.put(e.getKey(), new HashMap<Item, Double>());
|
diff.put(e.getKey(), new HashMap<Item, Double>());
|
||||||
freq.put(e.getKey(), new HashMap<Item, Integer>());
|
freq.put(e.getKey(), new HashMap<Item, Integer>());
|
||||||
}
|
}
|
||||||
for (Entry<Item, Double> e2 : user.entrySet()) {
|
for (Entry<Item, Double> e2 : user.entrySet()) {
|
||||||
int oldCount = 0;
|
int oldCount = 0;
|
||||||
if (freq.get(e.getKey()).containsKey(e2.getKey())) {
|
if (freq.get(e.getKey()).containsKey(e2.getKey())) {
|
||||||
oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue();
|
oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue();
|
||||||
}
|
}
|
||||||
double oldDiff = 0.0;
|
double oldDiff = 0.0;
|
||||||
if (diff.get(e.getKey()).containsKey(e2.getKey())) {
|
if (diff.get(e.getKey()).containsKey(e2.getKey())) {
|
||||||
oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue();
|
oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue();
|
||||||
}
|
}
|
||||||
double observedDiff = e.getValue() - e2.getValue();
|
double observedDiff = e.getValue() - e2.getValue();
|
||||||
freq.get(e.getKey()).put(e2.getKey(), oldCount + 1);
|
freq.get(e.getKey()).put(e2.getKey(), oldCount + 1);
|
||||||
diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff);
|
diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (Item j : diff.keySet()) {
|
for (Item j : diff.keySet()) {
|
||||||
for (Item i : diff.get(j).keySet()) {
|
for (Item i : diff.get(j).keySet()) {
|
||||||
double oldValue = diff.get(j).get(i).doubleValue();
|
double oldValue = diff.get(j).get(i).doubleValue();
|
||||||
int count = freq.get(j).get(i).intValue();
|
int count = freq.get(j).get(i).intValue();
|
||||||
diff.get(j).put(i, oldValue / count);
|
diff.get(j).put(i, oldValue / count);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
printData(data);
|
printData(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Based on existing data predict all missing ratings. If prediction is not
|
* Based on existing data predict all missing ratings. If prediction is not
|
||||||
* possible, the value will be equal to -1
|
* possible, the value will be equal to -1
|
||||||
*
|
*
|
||||||
* @param data
|
* @param data
|
||||||
* existing user data and their items' ratings
|
* existing user data and their items' ratings
|
||||||
*/
|
*/
|
||||||
private static void predict(Map<User, HashMap<Item, Double>> data) {
|
private static void predict(Map<User, HashMap<Item, Double>> data) {
|
||||||
HashMap<Item, Double> uPred = new HashMap<Item, Double>();
|
HashMap<Item, Double> uPred = new HashMap<Item, Double>();
|
||||||
HashMap<Item, Integer> uFreq = new HashMap<Item, Integer>();
|
HashMap<Item, Integer> uFreq = new HashMap<Item, Integer>();
|
||||||
for (Item j : diff.keySet()) {
|
for (Item j : diff.keySet()) {
|
||||||
uFreq.put(j, 0);
|
uFreq.put(j, 0);
|
||||||
uPred.put(j, 0.0);
|
uPred.put(j, 0.0);
|
||||||
}
|
}
|
||||||
for (Entry<User, HashMap<Item, Double>> e : data.entrySet()) {
|
for (Entry<User, HashMap<Item, Double>> e : data.entrySet()) {
|
||||||
for (Item j : e.getValue().keySet()) {
|
for (Item j : e.getValue().keySet()) {
|
||||||
for (Item k : diff.keySet()) {
|
for (Item k : diff.keySet()) {
|
||||||
try {
|
try {
|
||||||
double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue();
|
double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue();
|
||||||
double finalValue = predictedValue * freq.get(k).get(j).intValue();
|
double finalValue = predictedValue * freq.get(k).get(j).intValue();
|
||||||
uPred.put(k, uPred.get(k) + finalValue);
|
uPred.put(k, uPred.get(k) + finalValue);
|
||||||
uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue());
|
uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue());
|
||||||
} catch (NullPointerException e1) {
|
} catch (NullPointerException e1) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
HashMap<Item, Double> clean = new HashMap<Item, Double>();
|
HashMap<Item, Double> clean = new HashMap<Item, Double>();
|
||||||
for (Item j : uPred.keySet()) {
|
for (Item j : uPred.keySet()) {
|
||||||
if (uFreq.get(j) > 0) {
|
if (uFreq.get(j) > 0) {
|
||||||
clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue());
|
clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (Item j : InputData.items) {
|
for (Item j : InputData.items) {
|
||||||
if (e.getValue().containsKey(j)) {
|
if (e.getValue().containsKey(j)) {
|
||||||
clean.put(j, e.getValue().get(j));
|
clean.put(j, e.getValue().get(j));
|
||||||
} else {
|
} else {
|
||||||
clean.put(j, -1.0);
|
clean.put(j, -1.0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
outputData.put(e.getKey(), clean);
|
outputData.put(e.getKey(), clean);
|
||||||
}
|
}
|
||||||
printData(outputData);
|
printData(outputData);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void printData(Map<User, HashMap<Item, Double>> data) {
|
private static void printData(Map<User, HashMap<Item, Double>> data) {
|
||||||
for (User user : data.keySet()) {
|
for (User user : data.keySet()) {
|
||||||
System.out.println(user.getUsername() + ":");
|
System.out.println(user.getUsername() + ":");
|
||||||
print(data.get(user));
|
print(data.get(user));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void print(HashMap<Item, Double> hashMap) {
|
private static void print(HashMap<Item, Double> hashMap) {
|
||||||
NumberFormat formatter = new DecimalFormat("#0.000");
|
NumberFormat formatter = new DecimalFormat("#0.000");
|
||||||
for (Item j : hashMap.keySet()) {
|
for (Item j : hashMap.keySet()) {
|
||||||
System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue()));
|
System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,7 +8,7 @@ import lombok.NoArgsConstructor;
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public class User {
|
public class User {
|
||||||
|
|
||||||
private String username;
|
private String username;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,8 +23,7 @@ public class LogWithChain {
|
||||||
try {
|
try {
|
||||||
howIsManager();
|
howIsManager();
|
||||||
} catch (ManagerUpsetException e) {
|
} catch (ManagerUpsetException e) {
|
||||||
throw new TeamLeadUpsetException(
|
throw new TeamLeadUpsetException("Team lead is not in good mood", e);
|
||||||
"Team lead is not in good mood", e);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -36,9 +35,7 @@ public class LogWithChain {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void howIsGirlFriendOfManager()
|
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||||
throws GirlFriendOfManagerUpsetException {
|
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
|
||||||
throw new GirlFriendOfManagerUpsetException(
|
|
||||||
"Girl friend of manager is in bad mood");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -25,8 +25,7 @@ public class LogWithoutChain {
|
||||||
howIsManager();
|
howIsManager();
|
||||||
} catch (ManagerUpsetException e) {
|
} catch (ManagerUpsetException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
throw new TeamLeadUpsetException(
|
throw new TeamLeadUpsetException("Team lead is not in good mood");
|
||||||
"Team lead is not in good mood");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -39,9 +38,7 @@ public class LogWithoutChain {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void howIsGirlFriendOfManager()
|
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||||
throws GirlFriendOfManagerUpsetException {
|
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
|
||||||
throw new GirlFriendOfManagerUpsetException(
|
|
||||||
"Girl friend of manager is in bad mood");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,10 +10,7 @@ public class WaitingWorker implements Runnable {
|
||||||
private final CountDownLatch callingThreadBlocker;
|
private final CountDownLatch callingThreadBlocker;
|
||||||
private final CountDownLatch completedThreadCounter;
|
private final CountDownLatch completedThreadCounter;
|
||||||
|
|
||||||
public WaitingWorker(final List<String> outputScraper,
|
public WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
|
||||||
final CountDownLatch readyThreadCounter,
|
|
||||||
final CountDownLatch callingThreadBlocker,
|
|
||||||
CountDownLatch completedThreadCounter) {
|
|
||||||
|
|
||||||
this.outputScraper = outputScraper;
|
this.outputScraper = outputScraper;
|
||||||
this.readyThreadCounter = readyThreadCounter;
|
this.readyThreadCounter = readyThreadCounter;
|
||||||
|
|
|
@ -5,14 +5,14 @@ import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Future;
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
public class SquareCalculator {
|
public class SquareCalculator {
|
||||||
|
|
||||||
private final ExecutorService executor;
|
private final ExecutorService executor;
|
||||||
|
|
||||||
public SquareCalculator(ExecutorService executor) {
|
public SquareCalculator(ExecutorService executor) {
|
||||||
this.executor = executor;
|
this.executor = executor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Future<Integer> calculate(Integer input) {
|
public Future<Integer> calculate(Integer input) {
|
||||||
return executor.submit(new Callable<Integer>() {
|
return executor.submit(new Callable<Integer>() {
|
||||||
@Override
|
@Override
|
||||||
public Integer call() throws Exception {
|
public Integer call() throws Exception {
|
||||||
|
|
|
@ -10,13 +10,11 @@ public class MyLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
|
||||||
*/
|
*/
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
private static final int MAX_ENTRIES = 5;
|
private static final int MAX_ENTRIES = 5;
|
||||||
|
|
||||||
|
|
||||||
public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
|
public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
|
||||||
super(initialCapacity, loadFactor, accessOrder);
|
super(initialCapacity, loadFactor, accessOrder);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean removeEldestEntry(Map.Entry eldest) {
|
protected boolean removeEldestEntry(Map.Entry eldest) {
|
||||||
return size() > MAX_ENTRIES;
|
return size() > MAX_ENTRIES;
|
||||||
|
|
|
@ -42,136 +42,96 @@ public class Java8CollectorsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
||||||
final List<String> result = givenList
|
final List<String> result = givenList.stream().collect(toList());
|
||||||
.stream()
|
|
||||||
.collect(toList());
|
|
||||||
|
|
||||||
assertThat(result).containsAll(givenList);
|
assertThat(result).containsAll(givenList);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
||||||
final Set<String> result = givenList
|
final Set<String> result = givenList.stream().collect(toSet());
|
||||||
.stream()
|
|
||||||
.collect(toSet());
|
|
||||||
|
|
||||||
assertThat(result).containsAll(givenList);
|
assertThat(result).containsAll(givenList);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
||||||
final List<String> result = givenList
|
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
|
||||||
.stream()
|
|
||||||
.collect(toCollection(LinkedList::new));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
|
||||||
.containsAll(givenList)
|
|
||||||
.isInstanceOf(LinkedList.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
||||||
assertThatThrownBy(() -> {
|
assertThatThrownBy(() -> {
|
||||||
givenList
|
givenList.stream().collect(toCollection(ImmutableList::of));
|
||||||
.stream()
|
|
||||||
.collect(toCollection(ImmutableList::of));
|
|
||||||
}).isInstanceOf(UnsupportedOperationException.class);
|
}).isInstanceOf(UnsupportedOperationException.class);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
||||||
final Map<String, Integer> result = givenList
|
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
|
||||||
.stream()
|
|
||||||
.collect(toMap(Function.identity(), String::length));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||||
.containsEntry("a", 1)
|
|
||||||
.containsEntry("bb", 2)
|
|
||||||
.containsEntry("ccc", 3)
|
|
||||||
.containsEntry("dd", 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
||||||
final Map<String, Integer> result = givenList
|
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||||
.stream()
|
|
||||||
.collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||||
.containsEntry("a", 1)
|
|
||||||
.containsEntry("bb", 2)
|
|
||||||
.containsEntry("ccc", 3)
|
|
||||||
.containsEntry("dd", 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
||||||
final List<String> result = givenList
|
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||||
.stream()
|
|
||||||
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
|
||||||
.containsAll(givenList)
|
|
||||||
.isInstanceOf(ImmutableList.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoining_shouldJoin() throws Exception {
|
public void whenJoining_shouldJoin() throws Exception {
|
||||||
final String result = givenList
|
final String result = givenList.stream().collect(joining());
|
||||||
.stream()
|
|
||||||
.collect(joining());
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo("abbcccdd");
|
assertThat(result).isEqualTo("abbcccdd");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
||||||
final String result = givenList
|
final String result = givenList.stream().collect(joining(" "));
|
||||||
.stream()
|
|
||||||
.collect(joining(" "));
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo("a bb ccc dd");
|
assertThat(result).isEqualTo("a bb ccc dd");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
||||||
final String result = givenList
|
final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
|
||||||
.stream()
|
|
||||||
.collect(joining(" ", "PRE-", "-POST"));
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPartitioningBy_shouldPartition() throws Exception {
|
public void whenPartitioningBy_shouldPartition() throws Exception {
|
||||||
final Map<Boolean, List<String>> result = givenList
|
final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
|
||||||
.stream()
|
|
||||||
.collect(partitioningBy(s -> s.length() > 2));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
|
||||||
.containsKeys(true, false)
|
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||||
.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
|
@Test
|
||||||
public void whenCounting_shouldCount() throws Exception {
|
public void whenCounting_shouldCount() throws Exception {
|
||||||
final Long result = givenList
|
final Long result = givenList.stream().collect(counting());
|
||||||
.stream()
|
|
||||||
.collect(counting());
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo(4);
|
assertThat(result).isEqualTo(4);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSummarizing_shouldSummarize() throws Exception {
|
public void whenSummarizing_shouldSummarize() throws Exception {
|
||||||
final DoubleSummaryStatistics result = givenList
|
final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
|
||||||
.stream()
|
|
||||||
.collect(summarizingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result.getAverage()).isEqualTo(2);
|
assertThat(result.getAverage()).isEqualTo(2);
|
||||||
assertThat(result.getCount()).isEqualTo(4);
|
assertThat(result.getCount()).isEqualTo(4);
|
||||||
|
@ -182,55 +142,37 @@ public class Java8CollectorsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAveraging_shouldAverage() throws Exception {
|
public void whenAveraging_shouldAverage() throws Exception {
|
||||||
final Double result = givenList
|
final Double result = givenList.stream().collect(averagingDouble(String::length));
|
||||||
.stream()
|
|
||||||
.collect(averagingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo(2);
|
assertThat(result).isEqualTo(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSumming_shouldSum() throws Exception {
|
public void whenSumming_shouldSum() throws Exception {
|
||||||
final Double result = givenList
|
final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length));
|
||||||
.stream()
|
|
||||||
.filter(i -> true)
|
|
||||||
.collect(summingDouble(String::length));
|
|
||||||
|
|
||||||
assertThat(result).isEqualTo(8);
|
assertThat(result).isEqualTo(8);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
||||||
final Optional<String> result = givenList
|
final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
|
||||||
.stream()
|
|
||||||
.collect(maxBy(Comparator.naturalOrder()));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isPresent().hasValue("dd");
|
||||||
.isPresent()
|
|
||||||
.hasValue("dd");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
||||||
final Map<Integer, Set<String>> result = givenList
|
final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
|
||||||
.stream()
|
|
||||||
.collect(groupingBy(String::length, toSet()));
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
|
||||||
.containsEntry(1, newHashSet("a"))
|
|
||||||
.containsEntry(2, newHashSet("bb", "dd"))
|
|
||||||
.containsEntry(3, newHashSet("ccc"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
||||||
final ImmutableSet<String> result = givenList
|
final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
|
||||||
.stream()
|
|
||||||
.collect(toImmutableSet());
|
|
||||||
|
|
||||||
assertThat(result)
|
assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
|
||||||
.isInstanceOf(ImmutableSet.class)
|
|
||||||
.contains("a", "bb", "ccc", "dd");
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -18,10 +18,7 @@ public class CountdownLatchExampleTest {
|
||||||
// Given
|
// Given
|
||||||
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
|
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
|
||||||
CountDownLatch countDownLatch = new CountDownLatch(5);
|
CountDownLatch countDownLatch = new CountDownLatch(5);
|
||||||
List<Thread> workers = Stream
|
List<Thread> workers = Stream.generate(() -> new Thread(new Worker(outputScraper, countDownLatch))).limit(5).collect(toList());
|
||||||
.generate(() -> new Thread(new Worker(outputScraper, countDownLatch)))
|
|
||||||
.limit(5)
|
|
||||||
.collect(toList());
|
|
||||||
|
|
||||||
// When
|
// When
|
||||||
workers.forEach(Thread::start);
|
workers.forEach(Thread::start);
|
||||||
|
@ -30,15 +27,7 @@ public class CountdownLatchExampleTest {
|
||||||
|
|
||||||
// Then
|
// Then
|
||||||
outputScraper.forEach(Object::toString);
|
outputScraper.forEach(Object::toString);
|
||||||
assertThat(outputScraper)
|
assertThat(outputScraper).containsExactly("Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Latch released");
|
||||||
.containsExactly(
|
|
||||||
"Counted down",
|
|
||||||
"Counted down",
|
|
||||||
"Counted down",
|
|
||||||
"Counted down",
|
|
||||||
"Counted down",
|
|
||||||
"Latch released"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -46,10 +35,7 @@ public class CountdownLatchExampleTest {
|
||||||
// Given
|
// Given
|
||||||
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
|
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
|
||||||
CountDownLatch countDownLatch = new CountDownLatch(5);
|
CountDownLatch countDownLatch = new CountDownLatch(5);
|
||||||
List<Thread> workers = Stream
|
List<Thread> workers = Stream.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch))).limit(5).collect(toList());
|
||||||
.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch)))
|
|
||||||
.limit(5)
|
|
||||||
.collect(toList());
|
|
||||||
|
|
||||||
// When
|
// When
|
||||||
workers.forEach(Thread::start);
|
workers.forEach(Thread::start);
|
||||||
|
@ -66,10 +52,7 @@ public class CountdownLatchExampleTest {
|
||||||
CountDownLatch readyThreadCounter = new CountDownLatch(5);
|
CountDownLatch readyThreadCounter = new CountDownLatch(5);
|
||||||
CountDownLatch callingThreadBlocker = new CountDownLatch(1);
|
CountDownLatch callingThreadBlocker = new CountDownLatch(1);
|
||||||
CountDownLatch completedThreadCounter = new CountDownLatch(5);
|
CountDownLatch completedThreadCounter = new CountDownLatch(5);
|
||||||
List<Thread> workers = Stream
|
List<Thread> workers = Stream.generate(() -> new Thread(new WaitingWorker(outputScraper, readyThreadCounter, callingThreadBlocker, completedThreadCounter))).limit(5).collect(toList());
|
||||||
.generate(() -> new Thread(new WaitingWorker(outputScraper, readyThreadCounter, callingThreadBlocker, completedThreadCounter)))
|
|
||||||
.limit(5)
|
|
||||||
.collect(toList());
|
|
||||||
|
|
||||||
// When
|
// When
|
||||||
workers.forEach(Thread::start);
|
workers.forEach(Thread::start);
|
||||||
|
@ -81,16 +64,7 @@ public class CountdownLatchExampleTest {
|
||||||
|
|
||||||
// Then
|
// Then
|
||||||
outputScraper.forEach(Object::toString);
|
outputScraper.forEach(Object::toString);
|
||||||
assertThat(outputScraper)
|
assertThat(outputScraper).containsExactly("Workers ready", "Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Workers complete");
|
||||||
.containsExactly(
|
|
||||||
"Workers ready",
|
|
||||||
"Counted down",
|
|
||||||
"Counted down",
|
|
||||||
"Counted down",
|
|
||||||
"Counted down",
|
|
||||||
"Counted down",
|
|
||||||
"Workers complete"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -47,9 +47,7 @@ public class ConcurrentMapAggregateStatusTest {
|
||||||
executorService.awaitTermination(1, TimeUnit.MINUTES);
|
executorService.awaitTermination(1, TimeUnit.MINUTES);
|
||||||
|
|
||||||
for (int i = 1; i <= MAX_SIZE; i++) {
|
for (int i = 1; i <= MAX_SIZE; i++) {
|
||||||
assertEquals("map size should be consistently reliable", i, mapSizes
|
assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1).intValue());
|
||||||
.get(i - 1)
|
|
||||||
.intValue());
|
|
||||||
}
|
}
|
||||||
assertEquals(MAX_SIZE, concurrentMap.size());
|
assertEquals(MAX_SIZE, concurrentMap.size());
|
||||||
}
|
}
|
||||||
|
@ -71,9 +69,7 @@ public class ConcurrentMapAggregateStatusTest {
|
||||||
executorService.shutdown();
|
executorService.shutdown();
|
||||||
executorService.awaitTermination(1, TimeUnit.MINUTES);
|
executorService.awaitTermination(1, TimeUnit.MINUTES);
|
||||||
|
|
||||||
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes
|
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1).intValue());
|
||||||
.get(MAX_SIZE - 1)
|
|
||||||
.intValue());
|
|
||||||
assertEquals(MAX_SIZE, concurrentMap.size());
|
assertEquals(MAX_SIZE, concurrentMap.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -36,9 +36,7 @@ public class ConcurrentMapPerformanceTest {
|
||||||
for (int i = 0; i < 4; i++) {
|
for (int i = 0; i < 4; i++) {
|
||||||
executorService.execute(() -> {
|
executorService.execute(() -> {
|
||||||
for (int j = 0; j < 500_000; j++) {
|
for (int j = 0; j < 500_000; j++) {
|
||||||
int value = ThreadLocalRandom
|
int value = ThreadLocalRandom.current().nextInt(10000);
|
||||||
.current()
|
|
||||||
.nextInt(10000);
|
|
||||||
String key = String.valueOf(value);
|
String key = String.valueOf(value);
|
||||||
map.put(key, value);
|
map.put(key, value);
|
||||||
map.get(key);
|
map.get(key);
|
||||||
|
|
|
@ -16,14 +16,8 @@ public class ConcurretMapMemoryConsistencyTest {
|
||||||
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
|
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
|
||||||
Map<String, Integer> map = new ConcurrentHashMap<>();
|
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||||
List<Integer> sumList = parallelSum100(map, 1000);
|
List<Integer> sumList = parallelSum100(map, 1000);
|
||||||
assertEquals(1, sumList
|
assertEquals(1, sumList.stream().distinct().count());
|
||||||
.stream()
|
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
||||||
.distinct()
|
|
||||||
.count());
|
|
||||||
long wrongResultCount = sumList
|
|
||||||
.stream()
|
|
||||||
.filter(num -> num != 100)
|
|
||||||
.count();
|
|
||||||
assertEquals(0, wrongResultCount);
|
assertEquals(0, wrongResultCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -31,14 +25,8 @@ public class ConcurretMapMemoryConsistencyTest {
|
||||||
public void givenHashtable_whenSumParallel_thenCorrect() throws Exception {
|
public void givenHashtable_whenSumParallel_thenCorrect() throws Exception {
|
||||||
Map<String, Integer> map = new Hashtable<>();
|
Map<String, Integer> map = new Hashtable<>();
|
||||||
List<Integer> sumList = parallelSum100(map, 1000);
|
List<Integer> sumList = parallelSum100(map, 1000);
|
||||||
assertEquals(1, sumList
|
assertEquals(1, sumList.stream().distinct().count());
|
||||||
.stream()
|
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
||||||
.distinct()
|
|
||||||
.count());
|
|
||||||
long wrongResultCount = sumList
|
|
||||||
.stream()
|
|
||||||
.filter(num -> num != 100)
|
|
||||||
.count();
|
|
||||||
assertEquals(0, wrongResultCount);
|
assertEquals(0, wrongResultCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -46,14 +34,8 @@ public class ConcurretMapMemoryConsistencyTest {
|
||||||
public void givenHashMap_whenSumParallel_thenError() throws Exception {
|
public void givenHashMap_whenSumParallel_thenError() throws Exception {
|
||||||
Map<String, Integer> map = new HashMap<>();
|
Map<String, Integer> map = new HashMap<>();
|
||||||
List<Integer> sumList = parallelSum100(map, 100);
|
List<Integer> sumList = parallelSum100(map, 100);
|
||||||
assertNotEquals(1, sumList
|
assertNotEquals(1, sumList.stream().distinct().count());
|
||||||
.stream()
|
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
||||||
.distinct()
|
|
||||||
.count());
|
|
||||||
long wrongResultCount = sumList
|
|
||||||
.stream()
|
|
||||||
.filter(num -> num != 100)
|
|
||||||
.count();
|
|
||||||
assertTrue(wrongResultCount > 0);
|
assertTrue(wrongResultCount > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -24,8 +24,7 @@ public class IterableStreamConversionTest {
|
||||||
public void whenConvertedToList_thenCorrect() {
|
public void whenConvertedToList_thenCorrect() {
|
||||||
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||||
|
|
||||||
List<String> result = StreamSupport.stream(iterable.spliterator(), false)
|
List<String> result = StreamSupport.stream(iterable.spliterator(), false).map(String::toUpperCase).collect(Collectors.toList());
|
||||||
.map(String::toUpperCase).collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
|
assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
|
||||||
}
|
}
|
||||||
|
|
|
@ -201,8 +201,6 @@ public class MapTest {
|
||||||
assertEquals("val1", rtnVal);
|
assertEquals("val1", rtnVal);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCallsEqualsOnCollision_thenCorrect() {
|
public void whenCallsEqualsOnCollision_thenCorrect() {
|
||||||
HashMap<MyKey, String> map = new HashMap<>();
|
HashMap<MyKey, String> map = new HashMap<>();
|
||||||
|
@ -329,7 +327,7 @@ public class MapTest {
|
||||||
map.put(1, "val");
|
map.put(1, "val");
|
||||||
map.put(5, "val");
|
map.put(5, "val");
|
||||||
map.put(4, "val");
|
map.put(4, "val");
|
||||||
|
|
||||||
Integer highestKey = map.lastKey();
|
Integer highestKey = map.lastKey();
|
||||||
Integer lowestKey = map.firstKey();
|
Integer lowestKey = map.firstKey();
|
||||||
Set<Integer> keysLessThan3 = map.headMap(3).keySet();
|
Set<Integer> keysLessThan3 = map.headMap(3).keySet();
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.java8;
|
package com.baeldung.java8;
|
||||||
|
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
@ -28,11 +27,7 @@ public class Java8FindAnyFindFirstTest {
|
||||||
@Test
|
@Test
|
||||||
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception {
|
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception {
|
||||||
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
|
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
|
||||||
Optional<Integer> result = list
|
Optional<Integer> result = list.stream().parallel().filter(num -> num < 4).findAny();
|
||||||
.stream()
|
|
||||||
.parallel()
|
|
||||||
.filter(num -> num < 4)
|
|
||||||
.findAny();
|
|
||||||
|
|
||||||
assertTrue(result.isPresent());
|
assertTrue(result.isPresent());
|
||||||
assertThat(result.get(), anyOf(is(1), is(2), is(3)));
|
assertThat(result.get(), anyOf(is(1), is(2), is(3)));
|
||||||
|
|
|
@ -56,9 +56,7 @@ public class NashornTest {
|
||||||
Map<String, Object> map = (Map<String, Object>) obj;
|
Map<String, Object> map = (Map<String, Object>) obj;
|
||||||
|
|
||||||
Assert.assertEquals("hello", map.get("greet"));
|
Assert.assertEquals("hello", map.get("greet"));
|
||||||
Assert.assertTrue(List.class.isAssignableFrom(map
|
Assert.assertTrue(List.class.isAssignableFrom(map.get("primes").getClass()));
|
||||||
.get("primes")
|
|
||||||
.getClass()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -11,16 +11,9 @@ import lombok.Getter;
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
public class BookControllerFeignClientBuilder {
|
public class BookControllerFeignClientBuilder {
|
||||||
private BookClient bookClient = createClient(BookClient.class,
|
private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books");
|
||||||
"http://localhost:8081/api/books");
|
|
||||||
|
|
||||||
private static <T> T createClient(Class<T> type, String uri) {
|
private static <T> T createClient(Class<T> type, String uri) {
|
||||||
return Feign.builder()
|
return Feign.builder().client(new OkHttpClient()).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger(type)).logLevel(Logger.Level.FULL).target(type, uri);
|
||||||
.client(new OkHttpClient())
|
|
||||||
.encoder(new GsonEncoder())
|
|
||||||
.decoder(new GsonDecoder())
|
|
||||||
.logger(new Slf4jLogger(type))
|
|
||||||
.logLevel(Logger.Level.FULL)
|
|
||||||
.target(type, uri);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -31,9 +31,7 @@ public class BookClientTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenBookClient_shouldRunSuccessfully() throws Exception {
|
public void givenBookClient_shouldRunSuccessfully() throws Exception {
|
||||||
List<Book> books = bookClient.findAll().stream()
|
List<Book> books = bookClient.findAll().stream().map(BookResource::getBook).collect(Collectors.toList());
|
||||||
.map(BookResource::getBook)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
assertTrue(books.size() > 2);
|
assertTrue(books.size() > 2);
|
||||||
log.info("{}", books);
|
log.info("{}", books);
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,12 +11,12 @@ import com.datastax.driver.core.utils.UUIDs;
|
||||||
|
|
||||||
public class CassandraClient {
|
public class CassandraClient {
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(CassandraClient.class);
|
private static final Logger LOG = LoggerFactory.getLogger(CassandraClient.class);
|
||||||
|
|
||||||
public static void main(String args[]) {
|
public static void main(String args[]) {
|
||||||
CassandraConnector connector = new CassandraConnector();
|
CassandraConnector connector = new CassandraConnector();
|
||||||
connector.connect("127.0.0.1", null);
|
connector.connect("127.0.0.1", null);
|
||||||
Session session = connector.getSession();
|
Session session = connector.getSession();
|
||||||
|
|
||||||
KeyspaceRepository sr = new KeyspaceRepository(session);
|
KeyspaceRepository sr = new KeyspaceRepository(session);
|
||||||
sr.createKeyspace("library", "SimpleStrategy", 1);
|
sr.createKeyspace("library", "SimpleStrategy", 1);
|
||||||
sr.useKeyspace("library");
|
sr.useKeyspace("library");
|
||||||
|
@ -24,21 +24,21 @@ public class CassandraClient {
|
||||||
BookRepository br = new BookRepository(session);
|
BookRepository br = new BookRepository(session);
|
||||||
br.createTable();
|
br.createTable();
|
||||||
br.alterTablebooks("publisher", "text");
|
br.alterTablebooks("publisher", "text");
|
||||||
|
|
||||||
br.createTableBooksByTitle();
|
br.createTableBooksByTitle();
|
||||||
|
|
||||||
Book book = new Book(UUIDs.timeBased(), "Effective Java", "Joshua Bloch", "Programming");
|
Book book = new Book(UUIDs.timeBased(), "Effective Java", "Joshua Bloch", "Programming");
|
||||||
br.insertBookBatch(book);
|
br.insertBookBatch(book);
|
||||||
|
|
||||||
br.selectAll().forEach(o -> LOG.info("Title in books: " + o.getTitle()));
|
br.selectAll().forEach(o -> LOG.info("Title in books: " + o.getTitle()));
|
||||||
br.selectAllBookByTitle().forEach(o -> LOG.info("Title in booksByTitle: " + o.getTitle()));
|
br.selectAllBookByTitle().forEach(o -> LOG.info("Title in booksByTitle: " + o.getTitle()));
|
||||||
|
|
||||||
br.deletebookByTitle("Effective Java");
|
br.deletebookByTitle("Effective Java");
|
||||||
br.deleteTable("books");
|
br.deleteTable("books");
|
||||||
br.deleteTable("booksByTitle");
|
br.deleteTable("booksByTitle");
|
||||||
|
|
||||||
sr.deleteKeyspace("library");
|
sr.deleteKeyspace("library");
|
||||||
|
|
||||||
connector.close();
|
connector.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,14 +16,14 @@ public class Book {
|
||||||
|
|
||||||
Book() {
|
Book() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public Book(UUID id, String title, String author, String subject) {
|
public Book(UUID id, String title, String author, String subject) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.title = title;
|
this.title = title;
|
||||||
this.author = author;
|
this.author = author;
|
||||||
this.subject = subject;
|
this.subject = subject;
|
||||||
}
|
}
|
||||||
|
|
||||||
public UUID getId() {
|
public UUID getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,7 +11,7 @@ import com.datastax.driver.core.Session;
|
||||||
public class BookRepository {
|
public class BookRepository {
|
||||||
|
|
||||||
private static final String TABLE_NAME = "books";
|
private static final String TABLE_NAME = "books";
|
||||||
|
|
||||||
private static final String TABLE_NAME_BY_TITLE = TABLE_NAME + "ByTitle";
|
private static final String TABLE_NAME_BY_TITLE = TABLE_NAME + "ByTitle";
|
||||||
|
|
||||||
private Session session;
|
private Session session;
|
||||||
|
@ -29,7 +29,7 @@ public class BookRepository {
|
||||||
final String query = sb.toString();
|
final String query = sb.toString();
|
||||||
session.execute(query);
|
session.execute(query);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates the books table.
|
* Creates the books table.
|
||||||
*/
|
*/
|
||||||
|
@ -62,7 +62,7 @@ public class BookRepository {
|
||||||
final String query = sb.toString();
|
final String query = sb.toString();
|
||||||
session.execute(query);
|
session.execute(query);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Insert a row in the table booksByTitle.
|
* Insert a row in the table booksByTitle.
|
||||||
* @param book
|
* @param book
|
||||||
|
@ -73,19 +73,15 @@ public class BookRepository {
|
||||||
final String query = sb.toString();
|
final String query = sb.toString();
|
||||||
session.execute(query);
|
session.execute(query);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Insert a book into two identical tables using a batch query.
|
* Insert a book into two identical tables using a batch query.
|
||||||
*
|
*
|
||||||
* @param book
|
* @param book
|
||||||
*/
|
*/
|
||||||
public void insertBookBatch(Book book) {
|
public void insertBookBatch(Book book) {
|
||||||
StringBuilder sb = new StringBuilder("BEGIN BATCH ")
|
StringBuilder sb = new StringBuilder("BEGIN BATCH ").append("INSERT INTO ").append(TABLE_NAME).append("(id, title, author, subject) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("', '").append(book.getAuthor())
|
||||||
.append("INSERT INTO ").append(TABLE_NAME).append("(id, title, author, subject) ")
|
.append("', '").append(book.getSubject()).append("');").append("INSERT INTO ").append(TABLE_NAME_BY_TITLE).append("(id, title) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("');")
|
||||||
.append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("', '").append(book.getAuthor()).append("', '")
|
|
||||||
.append(book.getSubject()).append("');")
|
|
||||||
.append("INSERT INTO ").append(TABLE_NAME_BY_TITLE).append("(id, title) ")
|
|
||||||
.append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("');")
|
|
||||||
.append("APPLY BATCH;");
|
.append("APPLY BATCH;");
|
||||||
|
|
||||||
final String query = sb.toString();
|
final String query = sb.toString();
|
||||||
|
@ -101,7 +97,7 @@ public class BookRepository {
|
||||||
StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME_BY_TITLE).append(" WHERE title = '").append(title).append("';");
|
StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME_BY_TITLE).append(" WHERE title = '").append(title).append("';");
|
||||||
|
|
||||||
final String query = sb.toString();
|
final String query = sb.toString();
|
||||||
|
|
||||||
ResultSet rs = session.execute(query);
|
ResultSet rs = session.execute(query);
|
||||||
|
|
||||||
List<Book> books = new ArrayList<Book>();
|
List<Book> books = new ArrayList<Book>();
|
||||||
|
@ -133,7 +129,7 @@ public class BookRepository {
|
||||||
}
|
}
|
||||||
return books;
|
return books;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select all books from booksByTitle
|
* Select all books from booksByTitle
|
||||||
* @return
|
* @return
|
||||||
|
|
|
@ -9,7 +9,7 @@ import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
|
||||||
@EnableConfigServer
|
@EnableConfigServer
|
||||||
@EnableEurekaClient
|
@EnableEurekaClient
|
||||||
public class ConfigApplication {
|
public class ConfigApplication {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(ConfigApplication.class, args);
|
SpringApplication.run(ConfigApplication.class, args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,18 +12,12 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
|
||||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
|
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||||
auth.inMemoryAuthentication().withUser("configUser").password("configPassword").roles("SYSTEM");
|
auth.inMemoryAuthentication().withUser("configUser").password("configPassword").roles("SYSTEM");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
http.authorizeRequests()
|
http.authorizeRequests().anyRequest().hasRole("SYSTEM").and().httpBasic().and().csrf().disable();
|
||||||
.anyRequest().hasRole("SYSTEM")
|
|
||||||
.and()
|
|
||||||
.httpBasic()
|
|
||||||
.and()
|
|
||||||
.csrf()
|
|
||||||
.disable();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,11 +5,7 @@ import org.springframework.cloud.netflix.feign.FeignClient;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
|
||||||
@FeignClient(
|
@FeignClient(name = "rest-producer", url = "http://localhost:9090", fallback = GreetingClient.GreetingClientFallback.class)
|
||||||
name = "rest-producer",
|
|
||||||
url = "http://localhost:9090",
|
|
||||||
fallback = GreetingClient.GreetingClientFallback.class
|
|
||||||
)
|
|
||||||
public interface GreetingClient extends GreetingController {
|
public interface GreetingClient extends GreetingController {
|
||||||
@Component
|
@Component
|
||||||
public static class GreetingClientFallback implements GreetingClient {
|
public static class GreetingClientFallback implements GreetingClient {
|
||||||
|
|
Loading…
Reference in New Issue