formatting work

This commit is contained in:
eugenp 2017-01-29 16:03:33 +02:00
parent 44bf48068f
commit 034cde6e20
42 changed files with 455 additions and 700 deletions

View File

@ -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();

View File

@ -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;
} }
} }

View File

@ -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);

View File

@ -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());

View File

@ -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);
} }
} }

View File

@ -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");
} }
} }

View File

@ -20,20 +20,14 @@ public class AssertJJava8Test {
public void givenOptional_shouldAssert() throws Exception { public void givenOptional_shouldAssert() throws Exception {
final Optional<String> givenOptional = Optional.of("something"); final Optional<String> givenOptional = Optional.of("something");
assertThat(givenOptional) assertThat(givenOptional).isPresent().hasValue("something");
.isPresent()
.hasValue("something");
} }
@Test @Test
public void givenPredicate_shouldAssert() throws Exception { public void givenPredicate_shouldAssert() throws Exception {
final Predicate<String> predicate = s -> s.length() > 4; final Predicate<String> predicate = s -> s.length() > 4;
assertThat(predicate) assertThat(predicate).accepts("aaaaa", "bbbbb").rejects("a", "b").acceptsAll(asList("aaaaa", "bbbbb")).rejectsAll(asList("a", "b"));
.accepts("aaaaa", "bbbbb")
.rejects("a", "b")
.acceptsAll(asList("aaaaa", "bbbbb"))
.rejectsAll(asList("a", "b"));
} }
@Test @Test
@ -41,74 +35,58 @@ public class AssertJJava8Test {
final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8); final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
final LocalDate todayDate = LocalDate.now(); final LocalDate todayDate = LocalDate.now();
assertThat(givenLocalDate) assertThat(givenLocalDate).isBefore(LocalDate.of(2020, 7, 8)).isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
.isBefore(LocalDate.of(2020, 7, 8))
.isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
assertThat(todayDate) assertThat(todayDate).isAfter(LocalDate.of(1989, 7, 8)).isToday();
.isAfter(LocalDate.of(1989, 7, 8))
.isToday();
} }
@Test @Test
public void givenLocalDateTime_shouldAssert() throws Exception { public void givenLocalDateTime_shouldAssert() throws Exception {
final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0); final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
assertThat(givenLocalDate) assertThat(givenLocalDate).isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
.isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
} }
@Test @Test
public void givenLocalTime_shouldAssert() throws Exception { public void givenLocalTime_shouldAssert() throws Exception {
final LocalTime givenLocalTime = LocalTime.of(12, 15); final LocalTime givenLocalTime = LocalTime.of(12, 15);
assertThat(givenLocalTime) assertThat(givenLocalTime).isAfter(LocalTime.of(1, 0)).hasSameHourAs(LocalTime.of(12, 0));
.isAfter(LocalTime.of(1, 0))
.hasSameHourAs(LocalTime.of(12, 0));
} }
@Test @Test
public void givenList_shouldAssertFlatExtracting() throws Exception { public void givenList_shouldAssertFlatExtracting() throws Exception {
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
assertThat(givenList) assertThat(givenList).flatExtracting(LocalDate::getYear).contains(2015);
.flatExtracting(LocalDate::getYear)
.contains(2015);
} }
@Test @Test
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception { public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
assertThat(givenList) assertThat(givenList).flatExtracting(LocalDate::isLeapYear).contains(true);
.flatExtracting(LocalDate::isLeapYear)
.contains(true);
} }
@Test @Test
public void givenList_shouldAssertFlatExtractingClass() throws Exception { public void givenList_shouldAssertFlatExtractingClass() throws Exception {
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
assertThat(givenList) assertThat(givenList).flatExtracting(Object::getClass).contains(LocalDate.class);
.flatExtracting(Object::getClass)
.contains(LocalDate.class);
} }
@Test @Test
public void givenList_shouldAssertMultipleFlatExtracting() throws Exception { public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
assertThat(givenList) assertThat(givenList).flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth).contains(2015, 6);
.flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth)
.contains(2015, 6);
} }
@Test @Test
public void givenString_shouldSatisfy() throws Exception { public void givenString_shouldSatisfy() throws Exception {
final String givenString = "someString"; final String givenString = "someString";
assertThat(givenString) assertThat(givenString).satisfies(s -> {
.satisfies(s -> {
assertThat(s).isNotEmpty(); assertThat(s).isNotEmpty();
assertThat(s).hasSize(10); assertThat(s).hasSize(10);
}); });
@ -118,15 +96,13 @@ public class AssertJJava8Test {
public void givenString_shouldMatch() throws Exception { public void givenString_shouldMatch() throws Exception {
final String emptyString = ""; final String emptyString = "";
assertThat(emptyString) assertThat(emptyString).matches(String::isEmpty);
.matches(String::isEmpty);
} }
@Test @Test
public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception { public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
final List<String> givenList = Arrays.asList(""); final List<String> givenList = Arrays.asList("");
assertThat(givenList) assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
.hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
} }
} }

View File

@ -1,18 +1,20 @@
package com.baeldung.autovalue; package com.baeldung.autovalue;
public final class ImmutableMoney { public final class ImmutableMoney {
private final long amount; private final long amount;
private final String currency; private final String currency;
public ImmutableMoney(long amount, String currency) { public ImmutableMoney(long amount, String currency) {
this.amount = amount; this.amount = amount;
this.currency = currency; this.currency = currency;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + (int) (amount ^ (amount >>> 32)); result = prime * result + (int) (amount ^ (amount >>> 32));
result = prime * result result = prime * result + ((currency == null) ? 0 : currency.hashCode());
+ ((currency == null) ? 0 : currency.hashCode());
return result; return result;
} }
@ -45,8 +47,7 @@ public final class ImmutableMoney {
@Override @Override
public String toString() { public String toString() {
return "ImmutableMoney [amount=" + amount + ", currency=" + currency return "ImmutableMoney [amount=" + amount + ", currency=" + currency + "]";
+ "]";
} }
} }

View File

@ -3,8 +3,7 @@ package com.baeldung.autovalue;
public class MutableMoney { public class MutableMoney {
@Override @Override
public String toString() { public String toString() {
return "MutableMoney [amount=" + amount + ", currency=" + currency return "MutableMoney [amount=" + amount + ", currency=" + currency + "]";
+ "]";
} }
public long getAmount() { public long getAmount() {

View File

@ -32,24 +32,28 @@ public class MoneyUnitTest {
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000); AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
assertTrue(m1.equals(m2)); assertTrue(m1.equals(m2));
} }
@Test @Test
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() { public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000); AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000); AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
assertFalse(m1.equals(m2)); assertFalse(m1.equals(m2));
} }
@Test @Test
public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() { public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() {
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
assertTrue(m1.equals(m2)); assertTrue(m1.equals(m2));
} }
@Test @Test
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() { public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build(); AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
assertFalse(m1.equals(m2)); assertFalse(m1.equals(m2));
} }
@Test @Test
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() { public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();

View File

@ -15,8 +15,7 @@ public class RunAlgorithm {
int decision = in.nextInt(); int decision = in.nextInt();
switch (decision) { switch (decision) {
case 1: case 1:
System.out.println( System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
break; break;
case 2: case 2:
SlopeOne.slopeOne(3); SlopeOne.slopeOne(3);

View File

@ -12,8 +12,7 @@ import lombok.Data;
@Data @Data
public class InputData { public class InputData {
protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), new Item("Snacks"));
new Item("Snacks"));
public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) { public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) {
Map<User, HashMap<Item, Double>> data = new HashMap<>(); Map<User, HashMap<Item, Double>> data = new HashMap<>();

View File

@ -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");
} }
} }

View File

@ -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");
} }
} }

View File

@ -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;

View File

@ -11,12 +11,10 @@ public class MyLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private static final int MAX_ENTRIES = 5; private static final int MAX_ENTRIES = 5;
public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) { public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
super(initialCapacity, loadFactor, accessOrder); super(initialCapacity, loadFactor, accessOrder);
} }
@Override @Override
protected boolean removeEldestEntry(Map.Entry eldest) { protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > MAX_ENTRIES; return size() > MAX_ENTRIES;

View File

@ -42,116 +42,80 @@ public class Java8CollectorsUnitTest {
@Test @Test
public void whenCollectingToList_shouldCollectToList() throws Exception { public void whenCollectingToList_shouldCollectToList() throws Exception {
final List<String> result = givenList final List<String> result = givenList.stream().collect(toList());
.stream()
.collect(toList());
assertThat(result).containsAll(givenList); assertThat(result).containsAll(givenList);
} }
@Test @Test
public void whenCollectingToList_shouldCollectToSet() throws Exception { public void whenCollectingToList_shouldCollectToSet() throws Exception {
final Set<String> result = givenList final Set<String> result = givenList.stream().collect(toSet());
.stream()
.collect(toSet());
assertThat(result).containsAll(givenList); assertThat(result).containsAll(givenList);
} }
@Test @Test
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception { public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
final List<String> result = givenList final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
.stream()
.collect(toCollection(LinkedList::new));
assertThat(result) assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
.containsAll(givenList)
.isInstanceOf(LinkedList.class);
} }
@Test @Test
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception { public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
assertThatThrownBy(() -> { assertThatThrownBy(() -> {
givenList givenList.stream().collect(toCollection(ImmutableList::of));
.stream()
.collect(toCollection(ImmutableList::of));
}).isInstanceOf(UnsupportedOperationException.class); }).isInstanceOf(UnsupportedOperationException.class);
} }
@Test @Test
public void whenCollectingToMap_shouldCollectToMap() throws Exception { public void whenCollectingToMap_shouldCollectToMap() throws Exception {
final Map<String, Integer> result = givenList final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
.stream()
.collect(toMap(Function.identity(), String::length));
assertThat(result) assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
.containsEntry("a", 1)
.containsEntry("bb", 2)
.containsEntry("ccc", 3)
.containsEntry("dd", 2);
} }
@Test @Test
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception { public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
final Map<String, Integer> result = givenList final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
.stream()
.collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
assertThat(result) assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
.containsEntry("a", 1)
.containsEntry("bb", 2)
.containsEntry("ccc", 3)
.containsEntry("dd", 2);
} }
@Test @Test
public void whenCollectingAndThen_shouldCollect() throws Exception { public void whenCollectingAndThen_shouldCollect() throws Exception {
final List<String> result = givenList final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
.stream()
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
assertThat(result) assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
.containsAll(givenList)
.isInstanceOf(ImmutableList.class);
} }
@Test @Test
public void whenJoining_shouldJoin() throws Exception { public void whenJoining_shouldJoin() throws Exception {
final String result = givenList final String result = givenList.stream().collect(joining());
.stream()
.collect(joining());
assertThat(result).isEqualTo("abbcccdd"); assertThat(result).isEqualTo("abbcccdd");
} }
@Test @Test
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception { public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
final String result = givenList final String result = givenList.stream().collect(joining(" "));
.stream()
.collect(joining(" "));
assertThat(result).isEqualTo("a bb ccc dd"); assertThat(result).isEqualTo("a bb ccc dd");
} }
@Test @Test
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception { public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
final String result = givenList final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
.stream()
.collect(joining(" ", "PRE-", "-POST"));
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST"); assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
} }
@Test @Test
public void whenPartitioningBy_shouldPartition() throws Exception { public void whenPartitioningBy_shouldPartition() throws Exception {
final Map<Boolean, List<String>> result = givenList final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
.stream()
.collect(partitioningBy(s -> s.length() > 2));
assertThat(result) assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
.containsKeys(true, false)
.satisfies(booleanListMap -> {
assertThat(booleanListMap.get(true)).contains("ccc"); assertThat(booleanListMap.get(true)).contains("ccc");
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd"); assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
@ -160,18 +124,14 @@ public class Java8CollectorsUnitTest {
@Test @Test
public void whenCounting_shouldCount() throws Exception { public void whenCounting_shouldCount() throws Exception {
final Long result = givenList final Long result = givenList.stream().collect(counting());
.stream()
.collect(counting());
assertThat(result).isEqualTo(4); assertThat(result).isEqualTo(4);
} }
@Test @Test
public void whenSummarizing_shouldSummarize() throws Exception { public void whenSummarizing_shouldSummarize() throws Exception {
final DoubleSummaryStatistics result = givenList final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
.stream()
.collect(summarizingDouble(String::length));
assertThat(result.getAverage()).isEqualTo(2); assertThat(result.getAverage()).isEqualTo(2);
assertThat(result.getCount()).isEqualTo(4); assertThat(result.getCount()).isEqualTo(4);
@ -182,55 +142,37 @@ public class Java8CollectorsUnitTest {
@Test @Test
public void whenAveraging_shouldAverage() throws Exception { public void whenAveraging_shouldAverage() throws Exception {
final Double result = givenList final Double result = givenList.stream().collect(averagingDouble(String::length));
.stream()
.collect(averagingDouble(String::length));
assertThat(result).isEqualTo(2); assertThat(result).isEqualTo(2);
} }
@Test @Test
public void whenSumming_shouldSum() throws Exception { public void whenSumming_shouldSum() throws Exception {
final Double result = givenList final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length));
.stream()
.filter(i -> true)
.collect(summingDouble(String::length));
assertThat(result).isEqualTo(8); assertThat(result).isEqualTo(8);
} }
@Test @Test
public void whenMaxingBy_shouldMaxBy() throws Exception { public void whenMaxingBy_shouldMaxBy() throws Exception {
final Optional<String> result = givenList final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
.stream()
.collect(maxBy(Comparator.naturalOrder()));
assertThat(result) assertThat(result).isPresent().hasValue("dd");
.isPresent()
.hasValue("dd");
} }
@Test @Test
public void whenGroupingBy_shouldGroupBy() throws Exception { public void whenGroupingBy_shouldGroupBy() throws Exception {
final Map<Integer, Set<String>> result = givenList final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
.stream()
.collect(groupingBy(String::length, toSet()));
assertThat(result) assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
.containsEntry(1, newHashSet("a"))
.containsEntry(2, newHashSet("bb", "dd"))
.containsEntry(3, newHashSet("ccc"));
} }
@Test @Test
public void whenCreatingCustomCollector_shouldCollect() throws Exception { public void whenCreatingCustomCollector_shouldCollect() throws Exception {
final ImmutableSet<String> result = givenList final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
.stream()
.collect(toImmutableSet());
assertThat(result) assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
.isInstanceOf(ImmutableSet.class)
.contains("a", "bb", "ccc", "dd");
} }

View File

@ -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"
);
} }
} }

View File

@ -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());
} }

View File

@ -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);

View File

@ -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);
} }

View File

@ -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"));
} }

View File

@ -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<>();

View File

@ -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)));

View File

@ -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

View File

@ -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);
} }
} }

View File

@ -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);
} }

View File

@ -80,12 +80,8 @@ public class BookRepository {
* @param book * @param book
*/ */
public void insertBookBatch(Book book) { public void insertBookBatch(Book book) {
StringBuilder sb = new StringBuilder("BEGIN BATCH ") StringBuilder sb = new StringBuilder("BEGIN BATCH ").append("INSERT INTO ").append(TABLE_NAME).append("(id, title, author, subject) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("', '").append(book.getAuthor())
.append("INSERT INTO ").append(TABLE_NAME).append("(id, title, author, subject) ") .append("', '").append(book.getSubject()).append("');").append("INSERT INTO ").append(TABLE_NAME_BY_TITLE).append("(id, title) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("');")
.append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("', '").append(book.getAuthor()).append("', '")
.append(book.getSubject()).append("');")
.append("INSERT INTO ").append(TABLE_NAME_BY_TITLE).append("(id, title) ")
.append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("');")
.append("APPLY BATCH;"); .append("APPLY BATCH;");
final String query = sb.toString(); final String query = sb.toString();

View File

@ -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();
} }
} }

View File

@ -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 {