diff --git a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java b/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java index b82eedbc3f..1d41f46adb 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java @@ -18,9 +18,7 @@ public class Dijkstra { while (unsettledNodes.size() != 0) { Node currentNode = getLowestDistanceNode(unsettledNodes); unsettledNodes.remove(currentNode); - for (Entry adjacencyPair : currentNode - .getAdjacentNodes() - .entrySet()) { + for (Entry adjacencyPair : currentNode.getAdjacentNodes().entrySet()) { Node adjacentNode = adjacencyPair.getKey(); Integer edgeWeigh = adjacencyPair.getValue(); diff --git a/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java b/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java index 86ee62c827..07606bde4b 100644 --- a/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java +++ b/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java @@ -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; } } diff --git a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java index 0883e108e7..18d8f9a8a9 100644 --- a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java +++ b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java @@ -27,17 +27,12 @@ public class BuilderProcessor extends AbstractProcessor { Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); - Map> annotatedMethods = annotatedElements.stream() - .collect(Collectors.partitioningBy(element -> - ((ExecutableType) element.asType()).getParameterTypes().size() == 1 - && element.getSimpleName().toString().startsWith("set"))); + Map> annotatedMethods = annotatedElements.stream().collect(Collectors.partitioningBy(element -> ((ExecutableType) element.asType()).getParameterTypes().size() == 1 && element.getSimpleName().toString().startsWith("set"))); List setters = annotatedMethods.get(true); List 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 setterMap = setters.stream().collect(Collectors.toMap( - setter -> setter.getSimpleName().toString(), - setter -> ((ExecutableType) setter.asType()) - .getParameterTypes().get(0).toString() - )); + Map setterMap = setters.stream().collect(Collectors.toMap(setter -> setter.getSimpleName().toString(), setter -> ((ExecutableType) setter.asType()).getParameterTypes().get(0).toString())); try { writeBuilderFile(className, setterMap); diff --git a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java index 72f9ac8bc7..8d01f8a517 100644 --- a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java +++ b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java @@ -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()); diff --git a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java index fc134ece00..10bb011903 100644 --- a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java +++ b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java @@ -38,8 +38,7 @@ public class AssertJCoreTest { public void whenCheckingForElement_thenContains() throws Exception { List 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 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); } } diff --git a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java index aee803ada1..84aaf46dd1 100644 --- a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java +++ b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java @@ -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 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 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"); } - - - } diff --git a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java index 0cdbd0f7ea..f89defaed1 100644 --- a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java +++ b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java @@ -20,20 +20,14 @@ public class AssertJJava8Test { public void givenOptional_shouldAssert() throws Exception { final Optional givenOptional = Optional.of("something"); - assertThat(givenOptional) - .isPresent() - .hasValue("something"); + assertThat(givenOptional).isPresent().hasValue("something"); } @Test public void givenPredicate_shouldAssert() throws Exception { final Predicate 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 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 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 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 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 givenList = Arrays.asList(""); - assertThat(givenList) - .hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty()); + assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty()); } } diff --git a/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java index ef39f499d1..5da6b48c81 100644 --- a/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java +++ b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java @@ -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); - } + } } diff --git a/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java index a7ac93e45b..8a4dbcd5a5 100644 --- a/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java +++ b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java @@ -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(); + } } diff --git a/autovalue/src/main/java/com/baeldung/autovalue/Foo.java b/autovalue/src/main/java/com/baeldung/autovalue/Foo.java index bb90070f6d..7bc893b044 100644 --- a/autovalue/src/main/java/com/baeldung/autovalue/Foo.java +++ b/autovalue/src/main/java/com/baeldung/autovalue/Foo.java @@ -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; + } } diff --git a/autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java index 04d29b6b09..d715f2047c 100644 --- a/autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java +++ b/autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java @@ -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 + "]"; + } } diff --git a/autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java index 6cf8b75f7d..d04a330a56 100644 --- a/autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java +++ b/autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java @@ -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; + } } diff --git a/autovalue/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java b/autovalue/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java index a9482125a6..f0dffa43a7 100644 --- a/autovalue/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java +++ b/autovalue/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java @@ -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"); + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java index 9394bbdbb8..113ac1cc53 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java +++ b/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java @@ -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(); + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/annealing/City.java b/core-java/src/main/java/com/baeldung/algorithms/annealing/City.java index 0f060c73c2..77e8652df0 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/annealing/City.java +++ b/core-java/src/main/java/com/baeldung/algorithms/annealing/City.java @@ -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)); + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java b/core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java index c02b0b8285..a7dc974e97 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java +++ b/core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java @@ -24,7 +24,7 @@ public class SimulatedAnnealing { } t *= coolingRate; } else { - continue; + continue; } if (i % 100 == 0) { System.out.println("Iteration #" + i); diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/InputData.java b/core-java/src/main/java/com/baeldung/algorithms/slope_one/InputData.java index 548f7ae4da..68a0f11b62 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/slope_one/InputData.java +++ b/core-java/src/main/java/com/baeldung/algorithms/slope_one/InputData.java @@ -11,26 +11,25 @@ import lombok.Data; @Data public class InputData { - - protected static List items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), - new Item("Snacks")); - public static Map> initializeData(int numberOfUsers) { - Map> data = new HashMap<>(); - HashMap newUser; - Set newRecommendationSet; - for (int i = 0; i < numberOfUsers; i++) { - newUser = new HashMap(); - 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 items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), new Item("Snacks")); + + public static Map> initializeData(int numberOfUsers) { + Map> data = new HashMap<>(); + HashMap newUser; + Set newRecommendationSet; + for (int i = 0; i < numberOfUsers; i++) { + newUser = new HashMap(); + 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; + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/Item.java b/core-java/src/main/java/com/baeldung/algorithms/slope_one/Item.java index 818a6d4601..dec1eb9e2c 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/slope_one/Item.java +++ b/core-java/src/main/java/com/baeldung/algorithms/slope_one/Item.java @@ -9,5 +9,5 @@ import lombok.NoArgsConstructor; @AllArgsConstructor public class Item { - private String itemName; + private String itemName; } diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java b/core-java/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java index f11538356a..d5eea279de 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java +++ b/core-java/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java @@ -11,114 +11,114 @@ import java.util.Map.Entry; */ public class SlopeOne { - private static Map> diff = new HashMap<>(); - private static Map> freq = new HashMap<>(); - private static Map> inputData; - private static Map> outputData = new HashMap<>(); + private static Map> diff = new HashMap<>(); + private static Map> freq = new HashMap<>(); + private static Map> inputData; + private static Map> 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> data) { - for (HashMap user : data.values()) { - for (Entry e : user.entrySet()) { - if (!diff.containsKey(e.getKey())) { - diff.put(e.getKey(), new HashMap()); - freq.put(e.getKey(), new HashMap()); - } - for (Entry 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> data) { + for (HashMap user : data.values()) { + for (Entry e : user.entrySet()) { + if (!diff.containsKey(e.getKey())) { + diff.put(e.getKey(), new HashMap()); + freq.put(e.getKey(), new HashMap()); + } + for (Entry 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> data) { - HashMap uPred = new HashMap(); - HashMap uFreq = new HashMap(); - for (Item j : diff.keySet()) { - uFreq.put(j, 0); - uPred.put(j, 0.0); - } - for (Entry> 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 clean = new HashMap(); - 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> data) { + HashMap uPred = new HashMap(); + HashMap uFreq = new HashMap(); + for (Item j : diff.keySet()) { + uFreq.put(j, 0); + uPred.put(j, 0.0); + } + for (Entry> 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 clean = new HashMap(); + 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> data) { - for (User user : data.keySet()) { - System.out.println(user.getUsername() + ":"); - print(data.get(user)); - } - } + private static void printData(Map> data) { + for (User user : data.keySet()) { + System.out.println(user.getUsername() + ":"); + print(data.get(user)); + } + } - private static void print(HashMap 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 hashMap) { + NumberFormat formatter = new DecimalFormat("#0.000"); + for (Item j : hashMap.keySet()) { + System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue())); + } + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/User.java b/core-java/src/main/java/com/baeldung/algorithms/slope_one/User.java index 57f16f6748..32bbe84d17 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/slope_one/User.java +++ b/core-java/src/main/java/com/baeldung/algorithms/slope_one/User.java @@ -8,7 +8,7 @@ import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor public class User { - - private String username; + + private String username; } diff --git a/core-java/src/main/java/com/baeldung/chainedexception/LogWithChain.java b/core-java/src/main/java/com/baeldung/chainedexception/LogWithChain.java index 8542e8c7ac..3d66c2b535 100644 --- a/core-java/src/main/java/com/baeldung/chainedexception/LogWithChain.java +++ b/core-java/src/main/java/com/baeldung/chainedexception/LogWithChain.java @@ -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"); } } diff --git a/core-java/src/main/java/com/baeldung/chainedexception/LogWithoutChain.java b/core-java/src/main/java/com/baeldung/chainedexception/LogWithoutChain.java index a06a324f03..7556e30663 100644 --- a/core-java/src/main/java/com/baeldung/chainedexception/LogWithoutChain.java +++ b/core-java/src/main/java/com/baeldung/chainedexception/LogWithoutChain.java @@ -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"); } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java index 58a2a5f6b4..66be2030e2 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java +++ b/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java @@ -10,10 +10,7 @@ public class WaitingWorker implements Runnable { private final CountDownLatch callingThreadBlocker; private final CountDownLatch completedThreadCounter; - public WaitingWorker(final List outputScraper, - final CountDownLatch readyThreadCounter, - final CountDownLatch callingThreadBlocker, - CountDownLatch completedThreadCounter) { + public WaitingWorker(final List outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) { this.outputScraper = outputScraper; this.readyThreadCounter = readyThreadCounter; diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java index 2cb27025ee..29c4ae53ce 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java +++ b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java @@ -5,14 +5,14 @@ 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 calculate(Integer input) { + + public Future calculate(Integer input) { return executor.submit(new Callable() { @Override public Integer call() throws Exception { diff --git a/core-java/src/main/java/com/baeldung/java/map/MyLinkedHashMap.java b/core-java/src/main/java/com/baeldung/java/map/MyLinkedHashMap.java index e1c0071ed3..1e237580ec 100644 --- a/core-java/src/main/java/com/baeldung/java/map/MyLinkedHashMap.java +++ b/core-java/src/main/java/com/baeldung/java/map/MyLinkedHashMap.java @@ -10,13 +10,11 @@ public class MyLinkedHashMap extends LinkedHashMap { */ 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; diff --git a/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java index 923924cfc2..bad1c32e4a 100644 --- a/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java +++ b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java @@ -42,136 +42,96 @@ public class Java8CollectorsUnitTest { @Test public void whenCollectingToList_shouldCollectToList() throws Exception { - final List result = givenList - .stream() - .collect(toList()); + final List result = givenList.stream().collect(toList()); assertThat(result).containsAll(givenList); } @Test public void whenCollectingToList_shouldCollectToSet() throws Exception { - final Set result = givenList - .stream() - .collect(toSet()); + final Set result = givenList.stream().collect(toSet()); assertThat(result).containsAll(givenList); } @Test public void whenCollectingToCollection_shouldCollectToCollection() throws Exception { - final List result = givenList - .stream() - .collect(toCollection(LinkedList::new)); + final List 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 result = givenList - .stream() - .collect(toMap(Function.identity(), String::length)); + final Map 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 result = givenList - .stream() - .collect(toMap(Function.identity(), String::length, (i1, i2) -> i1)); + final Map 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 result = givenList - .stream() - .collect(collectingAndThen(toList(), ImmutableList::copyOf)); + final List 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> result = givenList - .stream() - .collect(partitioningBy(s -> s.length() > 2)); + final Map> 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 result = givenList - .stream() - .collect(maxBy(Comparator.naturalOrder())); + final Optional 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> result = givenList - .stream() - .collect(groupingBy(String::length, toSet())); + final Map> 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 result = givenList - .stream() - .collect(toImmutableSet()); + final ImmutableSet 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"); } diff --git a/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java b/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java index 2e77042f0b..7bb2d4bb70 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java @@ -18,10 +18,7 @@ public class CountdownLatchExampleTest { // Given List outputScraper = Collections.synchronizedList(new ArrayList<>()); CountDownLatch countDownLatch = new CountDownLatch(5); - List workers = Stream - .generate(() -> new Thread(new Worker(outputScraper, countDownLatch))) - .limit(5) - .collect(toList()); + List workers = Stream.generate(() -> new Thread(new Worker(outputScraper, countDownLatch))).limit(5).collect(toList()); // When workers.forEach(Thread::start); @@ -30,15 +27,7 @@ public class CountdownLatchExampleTest { // Then outputScraper.forEach(Object::toString); - assertThat(outputScraper) - .containsExactly( - "Counted down", - "Counted down", - "Counted down", - "Counted down", - "Counted down", - "Latch released" - ); + assertThat(outputScraper).containsExactly("Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Latch released"); } @Test @@ -46,10 +35,7 @@ public class CountdownLatchExampleTest { // Given List outputScraper = Collections.synchronizedList(new ArrayList<>()); CountDownLatch countDownLatch = new CountDownLatch(5); - List workers = Stream - .generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch))) - .limit(5) - .collect(toList()); + List workers = Stream.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch))).limit(5).collect(toList()); // When workers.forEach(Thread::start); @@ -66,10 +52,7 @@ public class CountdownLatchExampleTest { CountDownLatch readyThreadCounter = new CountDownLatch(5); CountDownLatch callingThreadBlocker = new CountDownLatch(1); CountDownLatch completedThreadCounter = new CountDownLatch(5); - List workers = Stream - .generate(() -> new Thread(new WaitingWorker(outputScraper, readyThreadCounter, callingThreadBlocker, completedThreadCounter))) - .limit(5) - .collect(toList()); + List workers = Stream.generate(() -> new Thread(new WaitingWorker(outputScraper, readyThreadCounter, callingThreadBlocker, completedThreadCounter))).limit(5).collect(toList()); // When workers.forEach(Thread::start); @@ -81,16 +64,7 @@ public class CountdownLatchExampleTest { // Then outputScraper.forEach(Object::toString); - assertThat(outputScraper) - .containsExactly( - "Workers ready", - "Counted down", - "Counted down", - "Counted down", - "Counted down", - "Counted down", - "Workers complete" - ); + assertThat(outputScraper).containsExactly("Workers ready", "Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Workers complete"); } } \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusTest.java index cb43cad24b..73a4cdc0cd 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusTest.java @@ -47,9 +47,7 @@ public class ConcurrentMapAggregateStatusTest { 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("map size should be consistently reliable", i, mapSizes.get(i - 1).intValue()); } assertEquals(MAX_SIZE, concurrentMap.size()); } @@ -71,9 +69,7 @@ public class ConcurrentMapAggregateStatusTest { executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); - assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes - .get(MAX_SIZE - 1) - .intValue()); + assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1).intValue()); assertEquals(MAX_SIZE, concurrentMap.size()); } diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceTest.java index 040434f73b..a0efa89351 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceTest.java @@ -36,9 +36,7 @@ public class ConcurrentMapPerformanceTest { for (int i = 0; i < 4; i++) { executorService.execute(() -> { for (int j = 0; j < 500_000; j++) { - int value = ThreadLocalRandom - .current() - .nextInt(10000); + int value = ThreadLocalRandom.current().nextInt(10000); String key = String.valueOf(value); map.put(key, value); map.get(key); diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyTest.java index 9a6359f187..63a96dd5ee 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyTest.java @@ -16,14 +16,8 @@ public class ConcurretMapMemoryConsistencyTest { public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception { Map map = new ConcurrentHashMap<>(); List sumList = parallelSum100(map, 1000); - assertEquals(1, sumList - .stream() - .distinct() - .count()); - long wrongResultCount = sumList - .stream() - .filter(num -> num != 100) - .count(); + assertEquals(1, sumList.stream().distinct().count()); + long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); assertEquals(0, wrongResultCount); } @@ -31,14 +25,8 @@ public class ConcurretMapMemoryConsistencyTest { public void givenHashtable_whenSumParallel_thenCorrect() throws Exception { Map map = new Hashtable<>(); List sumList = parallelSum100(map, 1000); - assertEquals(1, sumList - .stream() - .distinct() - .count()); - long wrongResultCount = sumList - .stream() - .filter(num -> num != 100) - .count(); + assertEquals(1, sumList.stream().distinct().count()); + long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); assertEquals(0, wrongResultCount); } @@ -46,14 +34,8 @@ public class ConcurretMapMemoryConsistencyTest { public void givenHashMap_whenSumParallel_thenError() throws Exception { Map map = new HashMap<>(); List sumList = parallelSum100(map, 100); - assertNotEquals(1, sumList - .stream() - .distinct() - .count()); - long wrongResultCount = sumList - .stream() - .filter(num -> num != 100) - .count(); + assertNotEquals(1, sumList.stream().distinct().count()); + long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); assertTrue(wrongResultCount > 0); } diff --git a/core-java/src/test/java/com/baeldung/java/conversion/IterableStreamConversionTest.java b/core-java/src/test/java/com/baeldung/java/conversion/IterableStreamConversionTest.java index f52f73558f..e2f6c6a500 100644 --- a/core-java/src/test/java/com/baeldung/java/conversion/IterableStreamConversionTest.java +++ b/core-java/src/test/java/com/baeldung/java/conversion/IterableStreamConversionTest.java @@ -24,8 +24,7 @@ public class IterableStreamConversionTest { public void whenConvertedToList_thenCorrect() { Iterable iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream"); - List result = StreamSupport.stream(iterable.spliterator(), false) - .map(String::toUpperCase).collect(Collectors.toList()); + List result = StreamSupport.stream(iterable.spliterator(), false).map(String::toUpperCase).collect(Collectors.toList()); assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM")); } diff --git a/core-java/src/test/java/com/baeldung/java/map/MapTest.java b/core-java/src/test/java/com/baeldung/java/map/MapTest.java index 4642c4cc4d..ce2710e176 100644 --- a/core-java/src/test/java/com/baeldung/java/map/MapTest.java +++ b/core-java/src/test/java/com/baeldung/java/map/MapTest.java @@ -201,8 +201,6 @@ public class MapTest { assertEquals("val1", rtnVal); } - - @Test public void whenCallsEqualsOnCollision_thenCorrect() { HashMap map = new HashMap<>(); @@ -329,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 keysLessThan3 = map.headMap(3).keySet(); diff --git a/core-java/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstTest.java b/core-java/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstTest.java index 6a2b89963c..87f7eb1018 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstTest.java @@ -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 list = Arrays.asList(1, 2, 3, 4, 5); - Optional result = list - .stream() - .parallel() - .filter(num -> num < 4) - .findAny(); + Optional result = list.stream().parallel().filter(num -> num < 4).findAny(); assertTrue(result.isPresent()); assertThat(result.get(), anyOf(is(1), is(2), is(3))); diff --git a/core-java/src/test/java/com/baeldung/scripting/NashornTest.java b/core-java/src/test/java/com/baeldung/scripting/NashornTest.java index f50db3ad7c..9b6f61361a 100644 --- a/core-java/src/test/java/com/baeldung/scripting/NashornTest.java +++ b/core-java/src/test/java/com/baeldung/scripting/NashornTest.java @@ -56,9 +56,7 @@ public class NashornTest { Map map = (Map) 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 diff --git a/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java b/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java index 9c0c359d88..56cf4071b4 100644 --- a/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java +++ b/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java @@ -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 createClient(Class 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); } } diff --git a/feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java b/feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java index e7e058a336..d7e65a0f4c 100644 --- a/feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java +++ b/feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java @@ -31,9 +31,7 @@ public class BookClientTest { @Test public void givenBookClient_shouldRunSuccessfully() throws Exception { - List books = bookClient.findAll().stream() - .map(BookResource::getBook) - .collect(Collectors.toList()); + List books = bookClient.findAll().stream().map(BookResource::getBook).collect(Collectors.toList()); assertTrue(books.size() > 2); log.info("{}", books); } diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java index c67a2c2ddb..f9b465d908 100644 --- a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java +++ b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/CassandraClient.java @@ -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(); } } diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java index e6c7753eb3..a4edcf6258 100644 --- a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java +++ b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/domain/Book.java @@ -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; } diff --git a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java index 31e2969e01..e6e448f365 100644 --- a/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java +++ b/java-cassandra/src/main/java/com/baeldung/cassandra/java/client/repository/BookRepository.java @@ -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 books = new ArrayList(); @@ -133,7 +129,7 @@ public class BookRepository { } return books; } - + /** * Select all books from booksByTitle * @return diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java index c51819dfe5..847c86f881 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java @@ -9,7 +9,7 @@ import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @EnableConfigServer @EnableEurekaClient public class ConfigApplication { - public static void main(String[] args) { - SpringApplication.run(ConfigApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(ConfigApplication.class, args); + } } diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java index e607144f11..ef1d7b0b78 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java @@ -12,18 +12,12 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{ + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("configUser").password("configPassword").roles("SYSTEM"); } @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .anyRequest().hasRole("SYSTEM") - .and() - .httpBasic() - .and() - .csrf() - .disable(); + http.authorizeRequests().anyRequest().hasRole("SYSTEM").and().httpBasic().and().csrf().disable(); } } diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java index b715e8c052..4fcfb0eeda 100644 --- a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/main/java/com/baeldung/spring/cloud/hystrix/rest/consumer/GreetingClient.java @@ -5,11 +5,7 @@ import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.PathVariable; -@FeignClient( - name = "rest-producer", - url = "http://localhost:9090", - fallback = GreetingClient.GreetingClientFallback.class -) +@FeignClient(name = "rest-producer", url = "http://localhost:9090", fallback = GreetingClient.GreetingClientFallback.class) public interface GreetingClient extends GreetingController { @Component public static class GreetingClientFallback implements GreetingClient {