From 38989db6c1c37ec68698d1da4679789adba5fafb Mon Sep 17 00:00:00 2001 From: Ganesh Pagade Date: Sat, 29 Jul 2017 00:29:28 +0530 Subject: [PATCH 01/90] code for gRPC --- grpc/pom.xml | 73 +++++++++++++++++++ .../org/baeldung/grpc/client/GrpcClient.java | 28 +++++++ .../org/baeldung/grpc/server/GrpcServer.java | 19 +++++ .../grpc/server/HelloServiceImpl.java | 29 ++++++++ grpc/src/main/proto/HelloService.proto | 16 ++++ 5 files changed, 165 insertions(+) create mode 100644 grpc/pom.xml create mode 100644 grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java create mode 100644 grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java create mode 100644 grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java create mode 100644 grpc/src/main/proto/HelloService.proto diff --git a/grpc/pom.xml b/grpc/pom.xml new file mode 100644 index 000000000000..056db0c3fe58 --- /dev/null +++ b/grpc/pom.xml @@ -0,0 +1,73 @@ + + 4.0.0 + + grpc + grpc-demo + 0.0.1-SNAPSHOT + jar + + grpc-demo + http://maven.apache.org + + + UTF-8 + + + + + io.grpc + grpc-netty + 1.4.0 + + + io.grpc + grpc-protobuf + 1.4.0 + + + io.grpc + grpc-stub + 1.4.0 + + + junit + junit + 4.12 + test + + + + + + kr.motd.maven + os-maven-plugin + 1.5.0.Final + + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + 0.5.0 + + + com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier} + + grpc-java + + io.grpc:protoc-gen-grpc-java:1.4.0:exe:${os.detected.classifier} + + + + + + compile + compile-custom + + + + + + + diff --git a/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java b/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java new file mode 100644 index 000000000000..1a1809387fa4 --- /dev/null +++ b/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java @@ -0,0 +1,28 @@ +package org.baeldung.grpc.client; + +import org.baeldung.grpc.HelloRequest; +import org.baeldung.grpc.HelloResponse; +import org.baeldung.grpc.HelloServiceGrpc; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; + +public class GrpcClient { + public static void main(String[] args) throws InterruptedException { + ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080) + .usePlaintext(true) + .build(); + + HelloServiceGrpc.HelloServiceBlockingStub stub + = HelloServiceGrpc.newBlockingStub(channel); + + HelloResponse helloResponse = stub.hello(HelloRequest.newBuilder() + .setFirstName("Baeldung") + .setLastName("gRPC") + .build()); + + System.out.println("Response received from server:\n" + helloResponse); + + channel.shutdown(); + } +} diff --git a/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java b/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java new file mode 100644 index 000000000000..9f119fe45dd1 --- /dev/null +++ b/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java @@ -0,0 +1,19 @@ +package org.baeldung.grpc.server; + +import java.io.IOException; + +import io.grpc.Server; +import io.grpc.ServerBuilder; + +public class GrpcServer +{ + public static void main(String[] args) throws IOException, InterruptedException { + Server server = ServerBuilder.forPort(8080) + .addService(new HelloServiceImpl()).build(); + + System.out.println("Starting server..."); + server.start(); + System.out.println("Server started!"); + server.awaitTermination(); + } +} diff --git a/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java b/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java new file mode 100644 index 000000000000..b08ad02c9736 --- /dev/null +++ b/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java @@ -0,0 +1,29 @@ +package org.baeldung.grpc.server; + +import org.baeldung.grpc.HelloRequest; +import org.baeldung.grpc.HelloResponse; +import org.baeldung.grpc.HelloServiceGrpc.HelloServiceImplBase; + +import io.grpc.stub.StreamObserver; + +public class HelloServiceImpl extends HelloServiceImplBase { + + @Override + public void hello( + HelloRequest request, StreamObserver responseObserver) { + System.out.println("Request received from client:\n" + request); + + String greeting = new StringBuilder().append("Hello, ") + .append(request.getFirstName()) + .append(" ") + .append(request.getLastName()) + .toString(); + + HelloResponse response = HelloResponse.newBuilder() + .setGreeting(greeting) + .build(); + + responseObserver.onNext(response); + responseObserver.onCompleted(); + } +} diff --git a/grpc/src/main/proto/HelloService.proto b/grpc/src/main/proto/HelloService.proto new file mode 100644 index 000000000000..4f53191ab9b0 --- /dev/null +++ b/grpc/src/main/proto/HelloService.proto @@ -0,0 +1,16 @@ +syntax = "proto3"; +option java_multiple_files = true; +package org.baeldung.grpc; + +message HelloRequest { + string firstName = 1; + string lastName = 2; +} + +message HelloResponse { + string greeting = 1; +} + +service HelloService { + rpc hello(HelloRequest) returns (HelloResponse); +} From 6fcbc9b065e88f65e47c4785d6ae83f22739a2e7 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Tue, 1 Aug 2017 22:31:21 +0100 Subject: [PATCH 02/90] BAEL-1022 - minor fixes --- grpc/pom.xml | 135 +++++++++--------- .../org/baeldung/grpc/server/GrpcServer.java | 5 +- 2 files changed, 70 insertions(+), 70 deletions(-) diff --git a/grpc/pom.xml b/grpc/pom.xml index 056db0c3fe58..074075b5cc9f 100644 --- a/grpc/pom.xml +++ b/grpc/pom.xml @@ -1,73 +1,74 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - grpc - grpc-demo - 0.0.1-SNAPSHOT - jar + grpc + grpc-demo + 0.0.1-SNAPSHOT + jar - grpc-demo - http://maven.apache.org + grpc-demo + http://maven.apache.org - - UTF-8 - + + UTF-8 + 1.5.0 + - - - io.grpc - grpc-netty - 1.4.0 - - - io.grpc - grpc-protobuf - 1.4.0 - - - io.grpc - grpc-stub - 1.4.0 - - - junit - junit - 4.12 - test - - - - - - kr.motd.maven - os-maven-plugin - 1.5.0.Final - - - - - org.xolstice.maven.plugins - protobuf-maven-plugin - 0.5.0 - - - com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier} - - grpc-java - - io.grpc:protoc-gen-grpc-java:1.4.0:exe:${os.detected.classifier} - - - - - - compile - compile-custom - - - - - - + + + io.grpc + grpc-netty + ${io.grpc.version} + + + io.grpc + grpc-protobuf + ${io.grpc.version} + + + io.grpc + grpc-stub + ${io.grpc.version} + + + junit + junit + 4.12 + test + + + + + + kr.motd.maven + os-maven-plugin + 1.5.0.Final + + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + 0.5.0 + + + com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier} + + grpc-java + + io.grpc:protoc-gen-grpc-java:1.4.0:exe:${os.detected.classifier} + + + + + + compile + compile-custom + + + + + + diff --git a/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java b/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java index 9f119fe45dd1..8a2b94e53bf9 100644 --- a/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java +++ b/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java @@ -5,11 +5,10 @@ import io.grpc.Server; import io.grpc.ServerBuilder; -public class GrpcServer -{ +public class GrpcServer { public static void main(String[] args) throws IOException, InterruptedException { Server server = ServerBuilder.forPort(8080) - .addService(new HelloServiceImpl()).build(); + .addService(new HelloServiceImpl()).build(); System.out.println("Starting server..."); server.start(); From b0e05630ea7c7b22dea2ca790e8215192f4b4ab0 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Wed, 2 Aug 2017 00:00:06 +0200 Subject: [PATCH 03/90] rxjava custom operator (#2352) * minor logging fix * spring security sso * use basic auth * use form login * cleanup * cleanup * final cleanup * second client app for sso * spring boot bootstrap * add logic * cleanup * add simple controller * add thymeleaf and security * minor fix * minor fix * add more boot properties * fix live test * fix live test * minor fix * semaphores * fix configuration * kotlin collection * add more collection examples * minor upgrade * cucumber java8 * minor fix * rxjava custom operator --- .../baelding/rxjava/operator/cleanString.java | 39 ++++++ .../baelding/rxjava/operator/toLength.java | 22 ++++ .../rxjava/RxJavaCustomOperatorUnitTest.java | 117 ++++++++++++++++++ 3 files changed, 178 insertions(+) create mode 100644 rxjava/src/main/java/com/baelding/rxjava/operator/cleanString.java create mode 100644 rxjava/src/main/java/com/baelding/rxjava/operator/toLength.java create mode 100644 rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/cleanString.java b/rxjava/src/main/java/com/baelding/rxjava/operator/cleanString.java new file mode 100644 index 000000000000..8ae8d25cd7df --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/cleanString.java @@ -0,0 +1,39 @@ +package com.baelding.rxjava.operator; + +import rx.Observable.Operator; +import rx.Subscriber; + +public class cleanString implements Operator { + + public cleanString() { + super(); + } + + @Override + public Subscriber call(final Subscriber subscriber) { + return new Subscriber(subscriber) { + @Override + public void onCompleted() { + if (!subscriber.isUnsubscribed()) { + subscriber.onCompleted(); + } + } + + @Override + public void onError(Throwable t) { + if (!subscriber.isUnsubscribed()) { + subscriber.onError(t); + } + } + + @Override + public void onNext(String item) { + if (!subscriber.isUnsubscribed()) { + final String result = item.replaceAll("[^A-Za-z0-9]", ""); + subscriber.onNext(result); + } + } + }; + } + +} \ No newline at end of file diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/toLength.java b/rxjava/src/main/java/com/baelding/rxjava/operator/toLength.java new file mode 100644 index 000000000000..47398ddcb8c1 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/toLength.java @@ -0,0 +1,22 @@ +package com.baelding.rxjava.operator; + +import rx.Observable; +import rx.Observable.Transformer; +import rx.functions.Func1; + +public class toLength implements Transformer { + public toLength() { + super(); + } + + @Override + public Observable call(Observable source) { + + return source.map(new Func1() { + @Override + public Integer call(String str) { + return str.length(); + } + }); + } +} \ No newline at end of file diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java new file mode 100644 index 000000000000..0cc458c414c6 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java @@ -0,0 +1,117 @@ +package com.baeldung.rxjava; + +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import rx.Observable; +import rx.Observable.Operator; +import rx.Observable.Transformer; +import rx.Subscriber; +import rx.functions.Func1; + +import com.baelding.rxjava.operator.cleanString; +import com.baelding.rxjava.operator.toLength; + +public class RxJavaCustomOperatorUnitTest { + + @Test + public void whenUseCleanStringOperator_thenSuccess() { + final List list = Arrays.asList("john_1", "tom-3"); + final List results = new ArrayList(); + + final Observable observable = Observable.from(list) + .lift(new cleanString()); + + // when + observable.subscribe(results::add); + + // then + assertThat(results, notNullValue()); + assertThat(results, hasSize(2)); + assertThat(results, hasItems("john1", "tom3")); + } + + @Test + public void whenUseToLengthOperator_thenSuccess() { + final List list = Arrays.asList("john", "tom"); + final List results = new ArrayList(); + + final Observable observable = Observable.from(list) + .compose(new toLength()); + + // when + observable.subscribe(results::add); + + // then + assertThat(results, notNullValue()); + assertThat(results, hasSize(2)); + assertThat(results, hasItems(4, 3)); + } + + @Test + public void whenUseFunctionOperator_thenSuccess() { + final Operator cleanStringFn = subscriber -> { + return new Subscriber(subscriber) { + @Override + public void onCompleted() { + if (!subscriber.isUnsubscribed()) { + subscriber.onCompleted(); + } + } + + @Override + public void onError(Throwable t) { + if (!subscriber.isUnsubscribed()) { + subscriber.onError(t); + } + } + + @Override + public void onNext(String str) { + if (!subscriber.isUnsubscribed()) { + final String result = str.replaceAll("[^A-Za-z0-9]", ""); + subscriber.onNext(result); + } + } + }; + }; + + final List results = new ArrayList(); + Observable.from(Arrays.asList("ap_p-l@e", "or-an?ge")) + .lift(cleanStringFn) + .subscribe(results::add); + + assertThat(results, notNullValue()); + assertThat(results, hasSize(2)); + assertThat(results, hasItems("apple", "orange")); + } + + @Test + public void whenUseFunctionTransformer_thenSuccess() { + final Transformer toLengthFn = source -> { + return source.map(new Func1() { + @Override + public Integer call(String str) { + return str.length(); + } + }); + }; + + final List results = new ArrayList(); + Observable.from(Arrays.asList("apple", "orange")) + .compose(toLengthFn) + .subscribe(results::add); + + assertThat(results, notNullValue()); + assertThat(results, hasSize(2)); + assertThat(results, hasItems(5, 6)); + } +} From 8214c8dd97a38b06959aae00ca678b521c4abef5 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 2 Aug 2017 00:05:37 +0200 Subject: [PATCH 04/90] Refactor --- .../main/java/com/baelding/rxjava/operator/toLength.java | 8 +------- .../baeldung/rxjava/RxJavaCustomOperatorUnitTest.java | 9 +-------- 2 files changed, 2 insertions(+), 15 deletions(-) diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/toLength.java b/rxjava/src/main/java/com/baelding/rxjava/operator/toLength.java index 47398ddcb8c1..fa997b563d88 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/operator/toLength.java +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/toLength.java @@ -11,12 +11,6 @@ public toLength() { @Override public Observable call(Observable source) { - - return source.map(new Func1() { - @Override - public Integer call(String str) { - return str.length(); - } - }); + return source.map(String::length); } } \ No newline at end of file diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java index 0cc458c414c6..99ac0351be5d 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java @@ -96,14 +96,7 @@ public void onNext(String str) { @Test public void whenUseFunctionTransformer_thenSuccess() { - final Transformer toLengthFn = source -> { - return source.map(new Func1() { - @Override - public Integer call(String str) { - return str.length(); - } - }); - }; + final Transformer toLengthFn = source -> source.map(String::length); final List results = new ArrayList(); Observable.from(Arrays.asList("apple", "orange")) From 4ff0768feacf43f622d9e79720c17647a2b18361 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 2 Aug 2017 00:06:14 +0200 Subject: [PATCH 05/90] Refactor --- .../operator/{cleanString.java => CleanString.java} | 4 ++-- .../rxjava/operator/{toLength.java => ToLength.java} | 4 ++-- .../baeldung/rxjava/RxJavaCustomOperatorUnitTest.java | 9 ++++----- 3 files changed, 8 insertions(+), 9 deletions(-) rename rxjava/src/main/java/com/baelding/rxjava/operator/{cleanString.java => CleanString.java} (91%) rename rxjava/src/main/java/com/baelding/rxjava/operator/{toLength.java => ToLength.java} (75%) diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/cleanString.java b/rxjava/src/main/java/com/baelding/rxjava/operator/CleanString.java similarity index 91% rename from rxjava/src/main/java/com/baelding/rxjava/operator/cleanString.java rename to rxjava/src/main/java/com/baelding/rxjava/operator/CleanString.java index 8ae8d25cd7df..9abdd7e07d5e 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/operator/cleanString.java +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/CleanString.java @@ -3,9 +3,9 @@ import rx.Observable.Operator; import rx.Subscriber; -public class cleanString implements Operator { +public class CleanString implements Operator { - public cleanString() { + public CleanString() { super(); } diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/toLength.java b/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java similarity index 75% rename from rxjava/src/main/java/com/baelding/rxjava/operator/toLength.java rename to rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java index fa997b563d88..ea954aa71cc7 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/operator/toLength.java +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java @@ -4,8 +4,8 @@ import rx.Observable.Transformer; import rx.functions.Func1; -public class toLength implements Transformer { - public toLength() { +public class ToLength implements Transformer { + public ToLength() { super(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java index 99ac0351be5d..ca1169486e4e 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java @@ -15,10 +15,9 @@ import rx.Observable.Operator; import rx.Observable.Transformer; import rx.Subscriber; -import rx.functions.Func1; -import com.baelding.rxjava.operator.cleanString; -import com.baelding.rxjava.operator.toLength; +import com.baelding.rxjava.operator.CleanString; +import com.baelding.rxjava.operator.ToLength; public class RxJavaCustomOperatorUnitTest { @@ -28,7 +27,7 @@ public void whenUseCleanStringOperator_thenSuccess() { final List results = new ArrayList(); final Observable observable = Observable.from(list) - .lift(new cleanString()); + .lift(new CleanString()); // when observable.subscribe(results::add); @@ -45,7 +44,7 @@ public void whenUseToLengthOperator_thenSuccess() { final List results = new ArrayList(); final Observable observable = Observable.from(list) - .compose(new toLength()); + .compose(new ToLength()); // when observable.subscribe(results::add); From 5e8022f1f07b2d05f168cccd00161e338f3857ac Mon Sep 17 00:00:00 2001 From: lor6 Date: Wed, 2 Aug 2017 06:29:18 +0300 Subject: [PATCH 06/90] spring template engines (#2326) * spring template engines * formatting --- spring-mvc-simple/pom.xml | 50 +++++++++++++++++-- .../ApplicationConfiguration.java | 2 +- .../FreemarkerConfiguration.java | 29 +++++++++++ .../configuration/GroovyConfiguration.java | 29 +++++++++++ .../configuration/ThymeleafConfiguration.java | 38 ++++++++++++++ .../spring/configuration/WebInitializer.java | 3 ++ .../spring/controller/UserController.java | 44 ++++++++++++++++ .../java/com/baeldung/spring/domain/User.java | 23 +++++++++ .../WEB-INF/views/registration-freemarker.ftl | 15 ++++++ .../WEB-INF/views/registration-groovy.tpl | 18 +++++++ .../WEB-INF/views/registration-thymeleaf.html | 13 +++++ .../webapp/WEB-INF/views/registration.jsp | 18 +++++++ .../src/main/webapp/WEB-INF/web.xml | 19 ------- 13 files changed, 278 insertions(+), 23 deletions(-) create mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java create mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java create mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java create mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java create mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java create mode 100644 spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl create mode 100644 spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl create mode 100644 spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html create mode 100644 spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp delete mode 100644 spring-mvc-simple/src/main/webapp/WEB-INF/web.xml diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 0cfb3e6dee94..14590f3de434 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -15,14 +15,18 @@ - 4.3.4.RELEASE - 2.6 + 4.3.10.RELEASE + 3.1.0 1.2 2.3.1 3.1.0 - 5.3.3.Final + 5.4.1.Final enter-location-of-server 1.3.2 + 1.8 + 3.0.7.RELEASE + 2.4.12 + 2.3.23 @@ -79,6 +83,38 @@ commons-fileupload ${fileupload.version} + + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring4 + ${org.thymeleaf-version} + + + + + org.freemarker + freemarker + ${freemarker.version} + + + org.springframework + spring-context-support + ${springframework.version} + + + + + org.codehaus.groovy + groovy-templates + ${groovy.version} + + @@ -94,6 +130,14 @@ ${deploy-path} + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + springMvcSimple diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java index 9ace968bbe51..b62ccae46513 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java @@ -12,7 +12,7 @@ @Configuration @EnableWebMvc -@ComponentScan(basePackages = "com.baeldung.springmvcforms") +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) class ApplicationConfiguration extends WebMvcConfigurerAdapter { @Override diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java new file mode 100644 index 000000000000..e43238f8a62f --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; +import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) +public class FreemarkerConfiguration { + @Bean + public FreeMarkerConfigurer freemarkerConfig() { + FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); + freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/"); + return freeMarkerConfigurer; + } + + @Bean + public FreeMarkerViewResolver freemarkerViewResolver() { + FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); + resolver.setCache(true); + resolver.setPrefix(""); + resolver.setSuffix(".ftl"); + return resolver; + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java new file mode 100644 index 000000000000..b7a9256fc01d --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer; +import org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) +public class GroovyConfiguration { + + @Bean + public GroovyMarkupConfigurer groovyMarkupConfigurer() { + GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer(); + configurer.setResourceLoaderPath("/WEB-INF/views/"); + return configurer; + } + + @Bean + public GroovyMarkupViewResolver thymeleafViewResolver() { + GroovyMarkupViewResolver viewResolver = new GroovyMarkupViewResolver(); + viewResolver.setSuffix(".tpl"); + return viewResolver; + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java new file mode 100644 index 000000000000..257dbc718afa --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java @@ -0,0 +1,38 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) +public class ThymeleafConfiguration { + @Bean + public SpringTemplateEngine templateEngine() { + SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(thymeleafTemplateResolver()); + return templateEngine; + } + + @Bean + public SpringResourceTemplateResolver thymeleafTemplateResolver() { + SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/views/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } + + @Bean + public ThymeleafViewResolver thymeleafViewResolver() { + ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + return viewResolver; + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java index d6bbf5eabd2b..3e5b416191da 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java @@ -15,6 +15,9 @@ public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(ApplicationConfiguration.class); + //ctx.register(ThymeleafConfiguration.class); + //ctx.register(FreemarkerConfiguration.class); + //ctx.register(GroovyConfiguration.class); ctx.setServletContext(container); // Manage the lifecycle of the root application context diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java new file mode 100644 index 000000000000..55179938fca8 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java @@ -0,0 +1,44 @@ +package com.baeldung.spring.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.spring.domain.User; + +@Controller +public class UserController { + + @GetMapping("/registration") + public String getRegistration(Model model) { + model.addAttribute("user", new User()); + return "registration"; + } + + @GetMapping("/registration-thymeleaf") + public String getRegistrationThymeleaf(Model model) { + model.addAttribute("user", new User()); + return "registration-thymeleaf"; + } + + @GetMapping("/registration-freemarker") + public String getRegistrationFreemarker(Model model) { + model.addAttribute("user", new User()); + return "registration-freemarker"; + } + + @GetMapping("/registration-groovy") + public String getRegistrationGroovy(Model model) { + model.addAttribute("user", new User()); + return "registration-groovy"; + } + + @PostMapping("/register") + @ResponseBody + public void register(User user){ + System.out.println(user.getEmail()); + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java new file mode 100644 index 000000000000..8016f98d8505 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.domain; + +public class User { + private String email; + private String password; + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl new file mode 100644 index 000000000000..8dce9a88c989 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl @@ -0,0 +1,15 @@ +<#import "/spring.ftl" as spring/> + + + +User Registration + + +
+ <@spring.bind path="user" /> + Email:<@spring.formInput "user.email"/>
+ Password:<@spring.formPasswordInput "user.password"/>
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl new file mode 100644 index 000000000000..291077fc2ed1 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl @@ -0,0 +1,18 @@ +yieldUnescaped '' +html(lang:'en') { + head { + meta('http-equiv':'"Content-Type" content="text/html; charset=utf-8"') + title('User Registration') + } + body { + form (id:'userForm', action:'register', method:'post') { + label (for:'email', 'Email') + input (name:'email', type:'text', value:user.email?:'') + label (for:'password', 'Password') + input (name:'password', type:'password', value:user.password?:'') + div (class:'form-actions') { + input (type:'submit', value:'Submit') + } + } + } +} \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html new file mode 100644 index 000000000000..c98f3283c055 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html @@ -0,0 +1,13 @@ + + + +User Registration + + +
+ Email:
+ Password:
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp new file mode 100644 index 000000000000..7c2d9c73b1c2 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp @@ -0,0 +1,18 @@ +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +User Registration + + + + Email: + +
+ Password: + +
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/web.xml b/spring-mvc-simple/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index b6f1065cadea..000000000000 --- a/spring-mvc-simple/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - spring - org.springframework.web.servlet.DispatcherServlet - - contextConfigLocation - classpath*:spring-servlet_RequestMappingHandlerAdapter.xml - - 1 - - - spring - / - - \ No newline at end of file From 43ce43cc363747fdfcb5c23299bfe6b5395341f3 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 2 Aug 2017 15:12:52 +0200 Subject: [PATCH 07/90] Rxjava refactor (#2358) * Refactor * Refactor --- .../{CleanString.java => ToCleanString.java} | 8 ++- .../baelding/rxjava/operator/ToLength.java | 8 ++- ...RxJavaBackpressureLongRunningUnitTest.java | 8 +-- .../rxjava/RxJavaCustomOperatorUnitTest.java | 52 +++++++++---------- 4 files changed, 42 insertions(+), 34 deletions(-) rename rxjava/src/main/java/com/baelding/rxjava/operator/{CleanString.java => ToCleanString.java} (83%) diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/CleanString.java b/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java similarity index 83% rename from rxjava/src/main/java/com/baelding/rxjava/operator/CleanString.java rename to rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java index 9abdd7e07d5e..f6cf9fba6816 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/operator/CleanString.java +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java @@ -3,9 +3,13 @@ import rx.Observable.Operator; import rx.Subscriber; -public class CleanString implements Operator { +public class ToCleanString implements Operator { - public CleanString() { + public static ToCleanString toCleanString() { + return new ToCleanString(); + } + + private ToCleanString() { super(); } diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java b/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java index ea954aa71cc7..006d59de3602 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java @@ -2,10 +2,14 @@ import rx.Observable; import rx.Observable.Transformer; -import rx.functions.Func1; public class ToLength implements Transformer { - public ToLength() { + + public static ToLength toLength() { + return new ToLength(); + } + + private ToLength() { super(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java index 040936a67a74..458091fd1cf5 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java @@ -34,7 +34,7 @@ public void givenColdObservable_shouldNotThrowException() { public void givenHotObservable_whenBackpressureNotDefined_shouldTrowException() { // given TestSubscriber testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); source.observeOn(Schedulers.computation()).subscribe(testSubscriber); @@ -50,7 +50,7 @@ public void givenHotObservable_whenBackpressureNotDefined_shouldTrowException() public void givenHotObservable_whenWindowIsDefined_shouldNotThrowException() { // given TestSubscriber> testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); // when source.window(500).observeOn(Schedulers.computation()).subscribe(testSubscriber); @@ -67,7 +67,7 @@ public void givenHotObservable_whenWindowIsDefined_shouldNotThrowException() { public void givenHotObservable_whenBufferIsDefined_shouldNotThrowException() { // given TestSubscriber> testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); // when source.buffer(1024).observeOn(Schedulers.computation()).subscribe(testSubscriber); @@ -84,7 +84,7 @@ public void givenHotObservable_whenBufferIsDefined_shouldNotThrowException() { public void givenHotObservable_whenSkippingOperationIsDefined_shouldNotThrowException() { // given TestSubscriber testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); // when source.sample(100, TimeUnit.MILLISECONDS) diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java index ca1169486e4e..a49103196cf0 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java @@ -1,5 +1,7 @@ package com.baeldung.rxjava; +import static com.baelding.rxjava.operator.ToCleanString.toCleanString; +import static com.baelding.rxjava.operator.ToLength.toLength; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.notNullValue; @@ -16,7 +18,7 @@ import rx.Observable.Transformer; import rx.Subscriber; -import com.baelding.rxjava.operator.CleanString; +import com.baelding.rxjava.operator.ToCleanString; import com.baelding.rxjava.operator.ToLength; public class RxJavaCustomOperatorUnitTest { @@ -24,10 +26,10 @@ public class RxJavaCustomOperatorUnitTest { @Test public void whenUseCleanStringOperator_thenSuccess() { final List list = Arrays.asList("john_1", "tom-3"); - final List results = new ArrayList(); + final List results = new ArrayList<>(); final Observable observable = Observable.from(list) - .lift(new CleanString()); + .lift(toCleanString()); // when observable.subscribe(results::add); @@ -41,10 +43,10 @@ public void whenUseCleanStringOperator_thenSuccess() { @Test public void whenUseToLengthOperator_thenSuccess() { final List list = Arrays.asList("john", "tom"); - final List results = new ArrayList(); + final List results = new ArrayList<>(); final Observable observable = Observable.from(list) - .compose(new ToLength()); + .compose(toLength()); // when observable.subscribe(results::add); @@ -57,33 +59,31 @@ public void whenUseToLengthOperator_thenSuccess() { @Test public void whenUseFunctionOperator_thenSuccess() { - final Operator cleanStringFn = subscriber -> { - return new Subscriber(subscriber) { - @Override - public void onCompleted() { - if (!subscriber.isUnsubscribed()) { - subscriber.onCompleted(); - } + final Operator cleanStringFn = subscriber -> new Subscriber(subscriber) { + @Override + public void onCompleted() { + if (!subscriber.isUnsubscribed()) { + subscriber.onCompleted(); } + } - @Override - public void onError(Throwable t) { - if (!subscriber.isUnsubscribed()) { - subscriber.onError(t); - } + @Override + public void onError(Throwable t) { + if (!subscriber.isUnsubscribed()) { + subscriber.onError(t); } + } - @Override - public void onNext(String str) { - if (!subscriber.isUnsubscribed()) { - final String result = str.replaceAll("[^A-Za-z0-9]", ""); - subscriber.onNext(result); - } + @Override + public void onNext(String str) { + if (!subscriber.isUnsubscribed()) { + final String result = str.replaceAll("[^A-Za-z0-9]", ""); + subscriber.onNext(result); } - }; + } }; - final List results = new ArrayList(); + final List results = new ArrayList<>(); Observable.from(Arrays.asList("ap_p-l@e", "or-an?ge")) .lift(cleanStringFn) .subscribe(results::add); @@ -97,7 +97,7 @@ public void onNext(String str) { public void whenUseFunctionTransformer_thenSuccess() { final Transformer toLengthFn = source -> source.map(String::length); - final List results = new ArrayList(); + final List results = new ArrayList<>(); Observable.from(Arrays.asList("apple", "orange")) .compose(toLengthFn) .subscribe(results::add); From b6b077b457bf83b9bbc549aebef10fe4b776cae5 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Wed, 2 Aug 2017 15:30:25 +0200 Subject: [PATCH 08/90] minor fix (#2359) * minor logging fix * spring security sso * use basic auth * use form login * cleanup * cleanup * final cleanup * second client app for sso * spring boot bootstrap * add logic * cleanup * add simple controller * add thymeleaf and security * minor fix * minor fix * add more boot properties * fix live test * fix live test * minor fix * semaphores * fix configuration * kotlin collection * add more collection examples * minor upgrade * cucumber java8 * minor fix * rxjava custom operator * minor fix --- spring-rest/src/main/webapp/WEB-INF/web.xml | 4 ++-- .../java/org/baeldung/config/SpringOpenidApplication.java | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/spring-rest/src/main/webapp/WEB-INF/web.xml b/spring-rest/src/main/webapp/WEB-INF/web.xml index a439de8a058a..1b8b767ae36f 100644 --- a/spring-rest/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest/src/main/webapp/WEB-INF/web.xml @@ -19,10 +19,10 @@ org.baeldung.config - + api diff --git a/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java b/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java index 608e8a681972..ed57088c5666 100644 --- a/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java +++ b/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java @@ -2,9 +2,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class SpringOpenidApplication { +public class SpringOpenidApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SpringOpenidApplication.class, args); From f02d11722390db08aba8b687aa5e49dd7e722e3f Mon Sep 17 00:00:00 2001 From: Yasin Date: Wed, 2 Aug 2017 20:57:25 +0530 Subject: [PATCH 09/90] BAEL-887 How to collect a Java Stream to an immutable collection? (#2356) * BAEL-900 Guide to dynamic tests in Junit 5 * BAEL-900 Guide to Dynamic Tests in Junit 5 * Revert "BAEL-900 Guide to Dynamic Tests in Junit 5" This reverts commit d0d45c9067223347da20d0f2c80de391fcade38e. * BAEL-900 Guide to Dynamic Tests in Junit 5 * BAEL-900 Guide to dynamic tests in Junit 5 * removed unnecessary annotation * BAEL-900 unused imports removed * BAEL-900 simplified input generator code * BAEL-252 A Java Client to consume a WebSockets API * BAEL-887 How to collect a Java Stream to an immutable collection? * BAEL-887 How to collect a Java Stream to an immutable collection? --- .../com/baeldung/stream/StreamToImmutableTest.java | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java b/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java index d267bd640681..69b0b6d3ef21 100644 --- a/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java +++ b/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java @@ -7,28 +7,24 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import java.util.HashSet; import java.util.LinkedList; import java.util.List; -import java.util.Set; import java.util.stream.IntStream; import org.junit.Test; import com.baeldung.stream.mycollectors.MyImmutableListCollector; import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; public class StreamToImmutableTest { @Test public void whenUsingCollectingToImmutableSet_thenSuccess() { - Set mutableSet = new HashSet<>(Arrays.asList("a", "b", "c")); - mutableSet.add("test"); - Set immutableSet = mutableSet.stream() - .collect(collectingAndThen(toSet(), ImmutableSet::copyOf)); + List givenList = Arrays.asList("a", "b", "c"); + List result = givenList.stream() + .collect(collectingAndThen(toSet(), ImmutableList::copyOf)); - System.out.println(immutableSet.getClass()); + System.out.println(result.getClass()); } @Test From 8137c203495d67a3afd1e2f902e39ff9c7310b9a Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Wed, 2 Aug 2017 18:42:13 +0100 Subject: [PATCH 10/90] Delegated Properties in Kotlin (#2357) This produces a fake Database representation - working in terms of hardcoded data, a Delegate that loads values from this fake Database, and then a class with fields delegated to the fake database. --- .../com/baeldung/kotlin/delegates/Database.kt | 35 +++++++++++++++++++ .../kotlin/delegates/DatabaseDelegate.kt | 13 +++++++ .../com/baeldung/kotlin/delegates/User.kt | 6 ++++ .../kotlin/delegates/DatabaseDelegatesTest.kt | 26 ++++++++++++++ 4 files changed, 80 insertions(+) create mode 100644 kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt create mode 100644 kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt create mode 100644 kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt create mode 100644 kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt new file mode 100644 index 000000000000..9ea9f027fcb2 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt @@ -0,0 +1,35 @@ +package com.baeldung.kotlin.delegates + +val data = arrayOf>( + mutableMapOf( + "id" to 1, + "name" to "George", + "age" to 4 + ), + mutableMapOf( + "id" to 2, + "name" to "Charlotte", + "age" to 2 + ) +) + +class NoRecordFoundException(id: Int) : Exception("No record found for id $id") { + init { + println("No record found for ID $id") + } +} + +fun queryForValue(field: String, id: Int): Any { + println("Loading record $id from the fake database") + val value = data.firstOrNull { it["id"] == id } + ?.get(field) ?: throw NoRecordFoundException(id) + println("Loaded value $value for field $field of record $id") + return value +} + +fun update(field: String, id: Int, value: Any?) { + println("Updating field $field of record $id to value $value in the fake database") + data.firstOrNull { it["id"] == id } + ?.put(field, value) + ?: throw NoRecordFoundException(id) +} diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt new file mode 100644 index 000000000000..c1c0f8823c3b --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt @@ -0,0 +1,13 @@ +package com.baeldung.kotlin.delegates + +import kotlin.properties.ReadWriteProperty +import kotlin.reflect.KProperty + +class DatabaseDelegate(private val field: String, private val id: Int) : ReadWriteProperty { + override fun getValue(thisRef: R, property: KProperty<*>): T = + queryForValue(field, id) as T + + override fun setValue(thisRef: R, property: KProperty<*>, value: T) { + update(field, id, value) + } +} diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt new file mode 100644 index 000000000000..7788305ea109 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt @@ -0,0 +1,6 @@ +package com.baeldung.kotlin.delegates + +class User(val id: Int) { + var name: String by DatabaseDelegate("name", id) + var age: Int by DatabaseDelegate("age", id) +} diff --git a/kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt b/kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt new file mode 100644 index 000000000000..fc50730dfa45 --- /dev/null +++ b/kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt @@ -0,0 +1,26 @@ +package com.baeldung.kotlin.delegates + +import org.junit.Test +import kotlin.test.assertEquals + +class DatabaseDelegatesTest { + @Test + fun testGetKnownFields() { + val user = User(1) + assertEquals("George", user.name) + assertEquals(4, user.age) + } + + @Test + fun testSetKnownFields() { + val user = User(2) + user.age = 3 + assertEquals(3, user.age) + } + + @Test(expected = NoRecordFoundException::class) + fun testGetKnownField() { + val user = User(3) + user.name + } +} From 8e9c36c98e50520a250ed6dfef386723e568d902 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Thu, 3 Aug 2017 17:39:57 +0200 Subject: [PATCH 11/90] fix spring config (#2364) --- .../src/main/java/org/baeldung/config/Application.java | 5 +++-- .../src/main/java/org/baeldung/config/Application.java | 5 +++-- .../src/main/java/org/baeldung/config/Application.java | 5 +++-- .../src/main/java/org/baeldung/config/Application.java | 3 ++- .../src/main/java/org/baeldung/config/Application.java | 3 ++- .../src/main/java/org/baeldung/config/Application.java | 3 ++- spring-security-core/src/main/java/org/baeldung/app/App.java | 3 ++- 7 files changed, 17 insertions(+), 10 deletions(-) diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java index 4057a85f13f1..c2c59396760f 100644 --- a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java @@ -2,10 +2,11 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.boot.web.support.SpringBootServletInitializer; -@SpringBootApplication +@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) public class Application extends SpringBootServletInitializer { @Override diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java index 4057a85f13f1..c2c59396760f 100644 --- a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java @@ -2,10 +2,11 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.boot.web.support.SpringBootServletInitializer; -@SpringBootApplication +@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) public class Application extends SpringBootServletInitializer { @Override diff --git a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java index 4057a85f13f1..c2c59396760f 100644 --- a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java @@ -2,10 +2,11 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.boot.web.support.SpringBootServletInitializer; -@SpringBootApplication +@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) public class Application extends SpringBootServletInitializer { @Override diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java index bea0194b4032..329b1041437b 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java @@ -2,9 +2,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java index bea0194b4032..329b1041437b 100644 --- a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java @@ -2,9 +2,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java index bea0194b4032..329b1041437b 100644 --- a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java @@ -2,9 +2,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-security-core/src/main/java/org/baeldung/app/App.java b/spring-security-core/src/main/java/org/baeldung/app/App.java index 06c295fcd799..37d8c34c5a4b 100644 --- a/spring-security-core/src/main/java/org/baeldung/app/App.java +++ b/spring-security-core/src/main/java/org/baeldung/app/App.java @@ -3,6 +3,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @@ -10,7 +11,7 @@ @EnableJpaRepositories("org.baeldung.repository") @ComponentScan("org.baeldung") @EntityScan("org.baeldung.entity") -public class App { +public class App extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(App.class, args); } From 71f1a2bc447583a31d84d3c6355e149847bf8799 Mon Sep 17 00:00:00 2001 From: lor6 Date: Thu, 3 Aug 2017 19:47:25 +0300 Subject: [PATCH 12/90] add jade engine example (#2365) * add jade engine example * formatting --- spring-mvc-simple/pom.xml | 8 ++++ .../JadeTemplateConfiguration.java | 39 +++++++++++++++++++ .../spring/configuration/WebInitializer.java | 1 + .../spring/controller/UserController.java | 6 +++ .../WEB-INF/views/registration-jade.jade | 11 ++++++ 5 files changed, 65 insertions(+) create mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java create mode 100644 spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-jade.jade diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 14590f3de434..8a51c0411378 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -27,6 +27,7 @@ 3.0.7.RELEASE 2.4.12 2.3.23 + 1.2.5 @@ -114,6 +115,13 @@ groovy-templates ${groovy.version} + + + + de.neuland-bfi + spring-jade4j + ${jade.version} + diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java new file mode 100644 index 000000000000..10345bac586c --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java @@ -0,0 +1,39 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +import de.neuland.jade4j.JadeConfiguration; +import de.neuland.jade4j.spring.template.SpringTemplateLoader; +import de.neuland.jade4j.spring.view.JadeViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) +public class JadeTemplateConfiguration { + @Bean + public SpringTemplateLoader templateLoader() { + SpringTemplateLoader templateLoader = new SpringTemplateLoader(); + templateLoader.setBasePath("/WEB-INF/views/"); + templateLoader.setSuffix(".jade"); + return templateLoader; + } + + @Bean + public JadeConfiguration jadeConfiguration() { + JadeConfiguration configuration = new JadeConfiguration(); + configuration.setCaching(false); + configuration.setTemplateLoader(templateLoader()); + return configuration; + } + + @Bean + public ViewResolver viewResolver() { + JadeViewResolver viewResolver = new JadeViewResolver(); + viewResolver.setConfiguration(jadeConfiguration()); + return viewResolver; + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java index 3e5b416191da..d57d2c621a48 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java @@ -18,6 +18,7 @@ public void onStartup(ServletContext container) throws ServletException { //ctx.register(ThymeleafConfiguration.class); //ctx.register(FreemarkerConfiguration.class); //ctx.register(GroovyConfiguration.class); + //ctx.register(JadeTemplateConfiguration.class); ctx.setServletContext(container); // Manage the lifecycle of the root application context diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java index 55179938fca8..b402a376c061 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java @@ -35,6 +35,12 @@ public String getRegistrationGroovy(Model model) { return "registration-groovy"; } + @GetMapping("/registration-jade") + public String getRegistrationJade(Model model) { + model.addAttribute("user", new User()); + return "registration-jade"; + } + @PostMapping("/register") @ResponseBody public void register(User user){ diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-jade.jade b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-jade.jade new file mode 100644 index 000000000000..44b6293ff09a --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-jade.jade @@ -0,0 +1,11 @@ +doctype html +html + head + title User Registration + body + form(action="register" method="post" ) + label(for="email") Emailaaaaaaaa: + input(type="text" name="email") + label(for="password") Password: + input(type="password" name="password") + input(type="submit" value="Submit") \ No newline at end of file From dc78aac622d01bfe2b6824835f3f637479e6c70b Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Fri, 4 Aug 2017 10:26:18 +0100 Subject: [PATCH 13/90] BAEL-884 Spring Security in JEE App (#2362) * added updated example codes * updated example code StringToCharStream * deleted StringToCharStream.java locally * removed redundant file * added code for apache commons collection SetUtils * refactored example code * added example code for bytebuddy * added example code for PCollections * update pom * refactored tests for PCollections * spring security xml config * spring security xml config --- jee7/.gitignore | 5 ++++ jee7/pom.xml | 3 +++ .../main/webapp/WEB-INF/spring/security.xml | 23 ++++++++++++++++ jee7/src/main/webapp/WEB-INF/web.xml | 27 +++++++++++++++++++ jee7/src/main/webapp/index.jsp | 18 +++++++++++++ jee7/src/main/webapp/secure.jsp | 24 +++++++++++++++++ 6 files changed, 100 insertions(+) create mode 100644 jee7/.gitignore create mode 100644 jee7/src/main/webapp/WEB-INF/spring/security.xml create mode 100644 jee7/src/main/webapp/index.jsp create mode 100644 jee7/src/main/webapp/secure.jsp diff --git a/jee7/.gitignore b/jee7/.gitignore new file mode 100644 index 000000000000..067348b3f408 --- /dev/null +++ b/jee7/.gitignore @@ -0,0 +1,5 @@ + +/classes/ +/.idea/ +/target/ +/jee7.iml diff --git a/jee7/pom.xml b/jee7/pom.xml index b5e0d80b6cb5..6858a05d17e3 100644 --- a/jee7/pom.xml +++ b/jee7/pom.xml @@ -6,8 +6,10 @@ com.baeldung jee7 1.0-SNAPSHOT + war JavaEE 7 Arquillian Archetype Sample + com.baeldung parent-modules @@ -174,6 +176,7 @@ maven-war-plugin ${maven-war-plugin.version} + webapp false diff --git a/jee7/src/main/webapp/WEB-INF/spring/security.xml b/jee7/src/main/webapp/WEB-INF/spring/security.xml new file mode 100644 index 000000000000..777cd9461fa3 --- /dev/null +++ b/jee7/src/main/webapp/WEB-INF/spring/security.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee7/src/main/webapp/WEB-INF/web.xml b/jee7/src/main/webapp/WEB-INF/web.xml index 11bd87cf9926..1bcbb96e240b 100644 --- a/jee7/src/main/webapp/WEB-INF/web.xml +++ b/jee7/src/main/webapp/WEB-INF/web.xml @@ -32,6 +32,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + index.jsf welcome.jsf diff --git a/jee7/src/main/webapp/index.jsp b/jee7/src/main/webapp/index.jsp new file mode 100644 index 000000000000..66a47eb7ce37 --- /dev/null +++ b/jee7/src/main/webapp/index.jsp @@ -0,0 +1,18 @@ +<%-- + Created by IntelliJ IDEA. + User: smatt + Date: 02/08/2017 + Time: 07:03 AM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Index Page + + + Non-secured Index Page +
+ Login + + diff --git a/jee7/src/main/webapp/secure.jsp b/jee7/src/main/webapp/secure.jsp new file mode 100644 index 000000000000..0cadd2cd4f0e --- /dev/null +++ b/jee7/src/main/webapp/secure.jsp @@ -0,0 +1,24 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %> + + + + + Home Page + + +

Home Page

+ +

+ Hello
+ Roles: +

+ +
+ + +
+ + \ No newline at end of file From b5835c574fdfb16547add22d747f8243fcc79e03 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Fri, 4 Aug 2017 11:05:54 +0100 Subject: [PATCH 14/90] Updated PR for BAEL-884 (#2372) * added updated example codes * updated example code StringToCharStream * deleted StringToCharStream.java locally * removed redundant file * added code for apache commons collection SetUtils * refactored example code * added example code for bytebuddy * added example code for PCollections * update pom * refactored tests for PCollections * spring security xml config * spring security xml config * remove redundant comment --- jee7/src/main/webapp/index.jsp | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/jee7/src/main/webapp/index.jsp b/jee7/src/main/webapp/index.jsp index 66a47eb7ce37..93fef9713dce 100644 --- a/jee7/src/main/webapp/index.jsp +++ b/jee7/src/main/webapp/index.jsp @@ -1,10 +1,3 @@ -<%-- - Created by IntelliJ IDEA. - User: smatt - Date: 02/08/2017 - Time: 07:03 AM - To change this template use File | Settings | File Templates. ---%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> @@ -15,4 +8,4 @@
Login - + \ No newline at end of file From 6a9e13cc03901909a3c35fb26711685d3b97bd7d Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Fri, 4 Aug 2017 19:52:00 +0100 Subject: [PATCH 15/90] BAEL-892: Example of Sealed Classes (#2373) --- .../main/kotlin/com/baeldung/kotlin/Sealed.kt | 19 +++++ .../kotlin/com/baeldung/kotlin/SealedTest.kt | 84 +++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt create mode 100644 kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt new file mode 100644 index 000000000000..96e54716b3b9 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt @@ -0,0 +1,19 @@ +package com.baeldung.kotlin + +sealed class Result { + abstract fun map(func: (S) -> R) : Result + abstract fun mapFailure(func: (F) -> R) : Result + abstract fun get() : S? +} + +data class Success(val success: S) : Result() { + override fun map(func: (S) -> R) : Result = Success(func(success)) + override fun mapFailure(func: (F) -> R): Result = Success(success) + override fun get(): S? = success +} + +data class Failure(val failure: F) : Result() { + override fun map(func: (S) -> R) : Result = Failure(failure) + override fun mapFailure(func: (F) -> R): Result = Failure(func(failure)) + override fun get(): S? = null +} diff --git a/kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt b/kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt new file mode 100644 index 000000000000..8c7509f6532f --- /dev/null +++ b/kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt @@ -0,0 +1,84 @@ +package com.baeldung.kotlin + +import org.junit.Assert +import org.junit.Test + +class SealedTest { + fun divide(a: Int, b: Int) : Result = when (b) { + 0 -> Failure("Division by zero") + else -> Success(a.toFloat() / b) + } + + @Test + fun testSuccess() { + val result = divide(10, 5) + Assert.assertEquals(Success(2.0f), result) + } + + @Test + fun testError() { + val result = divide(10, 0) + Assert.assertEquals(Failure("Division by zero"), result) + } + + @Test + fun testMatchOnSuccess() { + val result = divide(10, 5) + when (result) { + is Success -> { + // Expected + } + is Failure -> Assert.fail("Expected Success") + } + } + + @Test + fun testMatchOnError() { + val result = divide(10, 0) + when (result) { + is Failure -> { + // Expected + } + } + } + + @Test + fun testGetSuccess() { + val result = divide(10, 5) + Assert.assertEquals(2.0f, result.get()) + } + + @Test + fun testGetError() { + val result = divide(10, 0) + Assert.assertNull(result.get()) + } + + @Test + fun testMapOnSuccess() { + val result = divide(10, 5) + .map { "Result: $it" } + Assert.assertEquals(Success("Result: 2.0"), result) + } + + @Test + fun testMapOnError() { + val result = divide(10, 0) + .map { "Result: $it" } + Assert.assertEquals(Failure("Division by zero"), result) + } + + @Test + fun testMapFailureOnSuccess() { + val result = divide(10, 5) + .mapFailure { "Failure: $it" } + Assert.assertEquals(Success(2.0f), result) + } + + @Test + fun testMapFailureOnError() { + val result = divide(10, 0) + .mapFailure { "Failure: $it" } + Assert.assertEquals(Failure("Failure: Division by zero"), result) + } +} From 891b4eb2484d69f34b620509ca7dbbbad803f7fb Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 5 Aug 2017 14:11:45 +0200 Subject: [PATCH 16/90] Remove jooq module (#2375) * Remove jooq module * Refactor --- jooq/README.md | 3 - jooq/pom.xml | 25 ------ .../test/java/com/baeldung/jool/JOOLTest.java | 90 +++++++++---------- pom.xml | 1 - 4 files changed, 45 insertions(+), 74 deletions(-) delete mode 100644 jooq/README.md delete mode 100644 jooq/pom.xml rename jooq/src/test/java/com/baeldung/JOOLUnitTest.java => libraries/src/test/java/com/baeldung/jool/JOOLTest.java (64%) diff --git a/jooq/README.md b/jooq/README.md deleted file mode 100644 index 2f09cab46bf6..000000000000 --- a/jooq/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles - -- [Introduction to jOOL](http://www.baeldung.com/jool) diff --git a/jooq/pom.xml b/jooq/pom.xml deleted file mode 100644 index 667640d08598..000000000000 --- a/jooq/pom.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - - 4.0.0 - - jooq - - - - org.jooq - jool - ${jool.version} - - - - - 0.9.12 - - - \ No newline at end of file diff --git a/jooq/src/test/java/com/baeldung/JOOLUnitTest.java b/libraries/src/test/java/com/baeldung/jool/JOOLTest.java similarity index 64% rename from jooq/src/test/java/com/baeldung/JOOLUnitTest.java rename to libraries/src/test/java/com/baeldung/jool/JOOLTest.java index 17873db50ab2..ba20e153fda3 100644 --- a/jooq/src/test/java/com/baeldung/JOOLUnitTest.java +++ b/libraries/src/test/java/com/baeldung/jool/JOOLTest.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.jool; import org.jooq.lambda.Seq; import org.jooq.lambda.Unchecked; @@ -13,6 +13,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -20,7 +21,7 @@ import static junit.framework.TestCase.assertEquals; import static org.jooq.lambda.tuple.Tuple.tuple; -public class JOOLUnitTest { +public class JOOLTest { @Test public void givenSeq_whenCheckContains_shouldReturnTrue() { List concat = Seq.of(1, 2, 3).concat(Seq.of(4, 5, 6)).toList(); @@ -54,58 +55,58 @@ public void givenStreams_whenJoin_shouldHaveElementsFromTwoStreams() { @Test public void givenSeq_whenJoin_shouldHaveElementsFromBothSeq() { assertEquals( - Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2)) + Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(), + Arrays.asList(tuple(1, 1), tuple(2, 2)) ); assertEquals( - Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null)) + Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), + Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null)) ); assertEquals( - Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3)) + Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), + Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3)) ); assertEquals( - Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), - Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B")) + Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), + Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B")) ); } @Test public void givenSeq_whenManipulateSeq_seqShouldHaveNewElementsInIt() { assertEquals( - Seq.of(1, 2, 3).cycle().limit(9).toList(), - Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3) + Seq.of(1, 2, 3).cycle().limit(9).toList(), + Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3) ); assertEquals( - Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), - tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)) + Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), + tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)) ); assertEquals( - Seq.of(1, 2, 3, 4).intersperse(0).toList(), - Arrays.asList(1, 0, 2, 0, 3, 0, 4) + Seq.of(1, 2, 3, 4).intersperse(0).toList(), + Arrays.asList(1, 0, 2, 0, 3, 0, 4) ); assertEquals( - Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), - 5 + Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), + 5 ); assertEquals( - Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), - tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) + Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), + tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) ); assertEquals( - Seq.of(1, 2, 3, 4).reverse().toList(), - Arrays.asList(4, 3, 2, 1) + Seq.of(1, 2, 3, 4).reverse().toList(), + Arrays.asList(4, 3, 2, 1) ); } @@ -117,20 +118,20 @@ public void givenSeq_whenGroupByAndFold_shouldReturnProperSeq() { expectedAfterGroupBy.put(0, Arrays.asList(2, 4)); assertEquals( - Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), - expectedAfterGroupBy + Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), + expectedAfterGroupBy ); assertEquals( - Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), - "!abc" + Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), + "!abc" ); assertEquals( - Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), - "abc!" + Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), + "abc!" ); } @@ -138,13 +139,13 @@ public void givenSeq_whenGroupByAndFold_shouldReturnProperSeq() { public void givenSeq_whenUsingSeqWhile_shouldBehaveAsWhileLoop() { assertEquals( - Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), - Arrays.asList(3, 4, 5) + Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), + Arrays.asList(3, 4, 5) ); assertEquals( - Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), - Arrays.asList(3, 4, 5) + Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), + Arrays.asList(3, 4, 5) ); } @@ -152,19 +153,19 @@ public void givenSeq_whenUsingSeqWhile_shouldBehaveAsWhileLoop() { public void givenSeq_whenZip_shouldHaveZippedSeq() { assertEquals( - Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), - Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c")) + Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), + Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c")) ); assertEquals( - Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), - Arrays.asList("1:a", "2:b", "3:c") + Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), + Arrays.asList("1:a", "2:b", "3:c") ); assertEquals( - Seq.of("a", "b", "c").zipWithIndex().toList(), - Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L)) + Seq.of("a", "b", "c").zipWithIndex().toList(), + Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L)) ); } @@ -187,8 +188,8 @@ public void givenOperationThatThrowsCheckedException_whenExecuteAndNeedToWrapChe //then assertEquals( - collect, - Arrays.asList(1, 1, 1) + collect, + Arrays.asList(1, 1, 1) ); } @@ -197,13 +198,13 @@ public void givenOperationThatThrowsCheckedException_whenExecuteAndNeedToWrapChe public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() { //when List collect = Stream.of("a", "b", "c") - .map(Unchecked.function(elem -> methodThatThrowsChecked(elem))) - .collect(Collectors.toList()); + .map(Unchecked.function(this::methodThatThrowsChecked)) + .collect(Collectors.toList()); //then assertEquals( - collect, - Arrays.asList(1, 1, 1) + collect, + Arrays.asList(1, 1, 1) ); } @@ -236,5 +237,4 @@ public void givenSeqOfTuples_whenTransformToLowerNumberOfTuples_shouldHaveProper Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer")) ); } - } diff --git a/pom.xml b/pom.xml index 3feba96d5a0d..82dccf832d75 100644 --- a/pom.xml +++ b/pom.xml @@ -83,7 +83,6 @@ jjwt - jooq jpa-storedprocedure jsf json-path From 7114e3965bb4755d8d561a6775bce0418b3401f2 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Sat, 5 Aug 2017 14:48:10 +0200 Subject: [PATCH 17/90] fix spring config (#2374) * fix spring config * fix spring config --- spring-mvc-email/pom.xml | 11 ++++---- .../java/com/baeldung/spring/Application.java | 3 ++- spring-security-mvc-ldap/pom.xml | 2 +- .../org/baeldung/SampleLDAPApplication.java | 22 +++++++++------ spring-security-rest-custom/pom.xml | 27 +++++-------------- 5 files changed, 30 insertions(+), 35 deletions(-) diff --git a/spring-mvc-email/pom.xml b/spring-mvc-email/pom.xml index c40abdb4bfc7..92280548788c 100644 --- a/spring-mvc-email/pom.xml +++ b/spring-mvc-email/pom.xml @@ -21,16 +21,17 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-tomcat + provided + org.springframework.boot spring-boot-starter-mail - + - - org.apache.tomcat.embed - tomcat-embed-jasper - javax.servlet jstl diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java b/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java index f146ee1d04ec..bc5d6b31515a 100644 --- a/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java @@ -2,10 +2,11 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); } diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index f2b6b766eba8..e6452ea70b50 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -57,7 +57,7 @@
- 1.5.7 + 1.5.5 diff --git a/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java b/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java index 4bcb25504604..5936aa30ef18 100644 --- a/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java +++ b/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java @@ -1,8 +1,9 @@ package org.baeldung; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @@ -11,17 +12,22 @@ * class to run up a Jetty Server (on http://localhost:8080) * */ -@EnableAutoConfiguration -@ComponentScan("org.baeldung") -public class SampleLDAPApplication extends WebMvcConfigurerAdapter { +@SpringBootApplication +public class SampleLDAPApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SampleLDAPApplication.class, args); } - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/login").setViewName("login"); + @Bean + public WebMvcConfigurerAdapter adapter() { + return new WebMvcConfigurerAdapter() { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/login") + .setViewName("login"); + } + }; } } \ No newline at end of file diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index c329bd1cb8f9..77a58a56d88b 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -33,12 +33,6 @@ org.springframework spring-core - - - commons-logging - commons-logging - - org.springframework @@ -79,6 +73,12 @@ spring-oxm + + commons-logging + commons-logging + ${commons-logging.version} + + @@ -105,24 +105,11 @@ org.apache.httpcomponents httpcore - ${httpcore.version} - - - commons-logging - commons-logging - - org.apache.httpcomponents httpclient - - - commons-logging - commons-logging - - @@ -213,7 +200,7 @@ 19.0 3.5 - + 1.2 4.4.5 4.5.2 From f913859c6f9434cbd89748055cb8505fa6ca4846 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 5 Aug 2017 16:13:22 +0300 Subject: [PATCH 18/90] package fixes --- .../java/com/baeldung/hashcode/application/Application.java | 5 +++-- .../src/main/java/com/baeldung/hashcode/entities/User.java | 2 +- .../com/baeldung/hashcode/application/ApplicationTest.java | 2 +- .../test/java/com/baeldung/hashcode/entities/UserTest.java | 4 ++-- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/hashcode/application/Application.java b/core-java/src/main/java/com/baeldung/hashcode/application/Application.java index 08c670c82f78..8e6125045e98 100644 --- a/core-java/src/main/java/com/baeldung/hashcode/application/Application.java +++ b/core-java/src/main/java/com/baeldung/hashcode/application/Application.java @@ -1,9 +1,10 @@ -package com.baeldung.application; +package com.baeldung.hashcode.application; -import com.baeldung.entities.User; import java.util.HashMap; import java.util.Map; +import com.baeldung.hashcode.entities.User; + public class Application { public static void main(String[] args) { diff --git a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java index a976233562dc..c1c5a82d316c 100644 --- a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java +++ b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java @@ -1,4 +1,4 @@ -package com.baeldung.entities; +package com.baeldung.hashcode.entities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java index dcd853f451d9..70abd69fad8c 100644 --- a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.application; +package com.baeldung.hashcode.application; import org.junit.After; import org.junit.Before; diff --git a/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java index 01f6085d7eac..e356b4beef44 100644 --- a/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java +++ b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java @@ -1,4 +1,4 @@ -package com.baeldung.entities; +package com.baeldung.hashcode.entities; import org.junit.After; import org.junit.Assert; @@ -23,7 +23,7 @@ public void tearDownUserInstances() { } @Test - public void equals_EqualUserInstance_TrueAssertion(){ + public void equals_EqualUserInstance_TrueAssertion() { Assert.assertTrue(user.equals(comparisonUser)); } From 4d8f92e58753a71683e8d14d68784f86907601a9 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 5 Aug 2017 16:14:20 +0300 Subject: [PATCH 19/90] formatting cleanup --- .../cyclicbarrier/CyclicBarrierDemo.java | 12 ++--- .../diningphilosophers/Philosopher.java | 3 +- .../executorservice/ExecutorServiceDemo.java | 26 +++++------ .../concurrent/future/FutureDemo.java | 46 +++++++++---------- .../threadfactory/BaeldungThreadFactory.java | 26 +++++------ .../concurrent/threadfactory/Task.java | 10 ++-- .../filesystem/jndi/LookupFSJNDI.java | 13 +++--- .../com/baeldung/hashcode/entities/User.java | 11 +++-- .../baeldung/jmx/JMXTutorialMainlauncher.java | 1 - .../java/com/baeldung/socket/EchoClient.java | 3 +- .../com/baeldung/stream/InfiniteStreams.java | 1 - .../com/baeldung/string/StringHelper.java | 9 +--- .../baeldung/stringtokenizer/MyTokenizer.java | 6 +-- .../CustomTemporalAdjuster.java | 12 ++--- .../com/baeldung/transferqueue/Consumer.java | 1 - .../accumulator/LongAccumulatorUnitTest.java | 12 ++--- .../hashcode/application/ApplicationTest.java | 2 +- .../LambdaExceptionWrappersUnitTest.java | 1 - .../list/listoflist/ListOfListsUnitTest.java | 24 ++++------ .../CoreThreadPoolIntegrationTest.java | 1 - 20 files changed, 96 insertions(+), 124 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java index 977dae4fdbd8..758bdecd0c66 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java @@ -15,14 +15,12 @@ public class CyclicBarrierDemo { private int NUM_PARTIAL_RESULTS; private int NUM_WORKERS; - private void runSimulation(int numWorkers, int numberOfPartialResults) { NUM_PARTIAL_RESULTS = numberOfPartialResults; NUM_WORKERS = numWorkers; cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread()); - System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " - + NUM_PARTIAL_RESULTS + " partial results each"); + System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " + NUM_PARTIAL_RESULTS + " partial results each"); for (int i = 0; i < NUM_WORKERS; i++) { Thread worker = new Thread(new NumberCruncherThread()); worker.setName("Thread " + i); @@ -38,8 +36,7 @@ public void run() { List partialResult = new ArrayList<>(); for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) { Integer num = random.nextInt(10); - System.out.println(thisThreadName - + ": Crunching some numbers! Final result - " + num); + System.out.println(thisThreadName + ": Crunching some numbers! Final result - " + num); partialResult.add(num); } partialResults.add(partialResult); @@ -57,13 +54,12 @@ class AggregatorThread implements Runnable { @Override public void run() { String thisThreadName = Thread.currentThread().getName(); - System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS - + " workers, having " + NUM_PARTIAL_RESULTS + " results each."); + System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS + " workers, having " + NUM_PARTIAL_RESULTS + " results each."); int sum = 0; for (List threadResult : partialResults) { System.out.print("Adding "); for (Integer partialResult : threadResult) { - System.out.print(partialResult+" "); + System.out.print(partialResult + " "); sum += partialResult; } System.out.println(); diff --git a/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java b/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java index c5672706ad2e..4de420900aec 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java +++ b/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java @@ -15,7 +15,8 @@ private void doAction(String action) throws InterruptedException { Thread.sleep(((int) (Math.random() * 100))); } - @Override public void run() { + @Override + public void run() { try { while (true) { doAction(System.nanoTime() + ": Thinking"); // thinking diff --git a/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java b/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java index ae2b279d9a91..83a9fb669288 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java @@ -6,22 +6,22 @@ public class ExecutorServiceDemo { - ExecutorService executor = Executors.newFixedThreadPool(10); + ExecutorService executor = Executors.newFixedThreadPool(10); - public void execute() { + public void execute() { - executor.submit(() -> { - new Task(); - }); + executor.submit(() -> { + new Task(); + }); - executor.shutdown(); - executor.shutdownNow(); - try { - executor.awaitTermination(20l, TimeUnit.NANOSECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } + executor.shutdown(); + executor.shutdownNow(); + try { + executor.awaitTermination(20l, TimeUnit.NANOSECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } - } + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java b/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java index 7cb611be0fca..4794d5cb61bc 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java @@ -9,36 +9,36 @@ public class FutureDemo { - public String invoke() { + public String invoke() { - String str = null; + String str = null; - ExecutorService executorService = Executors.newFixedThreadPool(10); + ExecutorService executorService = Executors.newFixedThreadPool(10); - Future future = executorService.submit(() -> { - // Task - Thread.sleep(10000l); - return "Hellow world"; - }); + Future future = executorService.submit(() -> { + // Task + Thread.sleep(10000l); + return "Hellow world"; + }); - future.cancel(false); + future.cancel(false); - try { - future.get(20, TimeUnit.SECONDS); - } catch (InterruptedException | ExecutionException | TimeoutException e1) { - e1.printStackTrace(); - } + try { + future.get(20, TimeUnit.SECONDS); + } catch (InterruptedException | ExecutionException | TimeoutException e1) { + e1.printStackTrace(); + } - if (future.isDone() && !future.isCancelled()) { - try { - str = future.get(); - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - } - } + if (future.isDone() && !future.isCancelled()) { + try { + str = future.get(); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + } - return str; + return str; - } + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java index 8744027e40f4..f708804cae54 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java +++ b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java @@ -4,20 +4,20 @@ public class BaeldungThreadFactory implements ThreadFactory { - private int threadId; - private String name; + private int threadId; + private String name; - public BaeldungThreadFactory(String name) { - threadId = 1; - this.name = name; - } + public BaeldungThreadFactory(String name) { + threadId = 1; + this.name = name; + } - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r, name + "-Thread_" + threadId); - System.out.println("created new thread with id : " + threadId + " and name : " + t.getName()); - threadId++; - return t; - } + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r, name + "-Thread_" + threadId); + System.out.println("created new thread with id : " + threadId + " and name : " + t.getName()); + threadId++; + return t; + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java index 04ba62d457bf..a69623c66737 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java +++ b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java @@ -2,9 +2,9 @@ public class Task implements Runnable { - @Override - public void run() { - // task details - } - + @Override + public void run() { + // task details + } + } diff --git a/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java b/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java index 4afce56e3973..7e6bb5d3b21a 100644 --- a/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java +++ b/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java @@ -14,26 +14,25 @@ public LookupFSJNDI() throws NamingException { super(); init(); } - + private void init() throws NamingException { Hashtable env = new Hashtable(); - - env.put (Context.INITIAL_CONTEXT_FACTORY, - "com.sun.jndi.fscontext.RefFSContextFactory"); + + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); // URI to namespace (actual directory) env.put(Context.PROVIDER_URL, "file:./src/test/resources"); - + ctx = new InitialContext(env); } public InitialContext getCtx() { return ctx; } - + public File getFile(String fileName) { File file; try { - file = (File)getCtx().lookup(fileName); + file = (File) getCtx().lookup(fileName); } catch (NamingException e) { file = null; } diff --git a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java index c1c5a82d316c..c46c3de65a3e 100644 --- a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java +++ b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java @@ -18,13 +18,16 @@ public User(long id, String name, String email) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null) return false; - if (this.getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null) + return false; + if (this.getClass() != o.getClass()) + return false; User user = (User) o; return id != user.id && (!name.equals(user.name) && !email.equals(user.email)); } - + @Override public int hashCode() { int hash = 7; diff --git a/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java b/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java index 220b9a8ec632..21044f82c4c0 100644 --- a/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java +++ b/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java @@ -10,7 +10,6 @@ public class JMXTutorialMainlauncher { private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class); - public static void main(String[] args) { // TODO Auto-generated method stub diff --git a/core-java/src/main/java/com/baeldung/socket/EchoClient.java b/core-java/src/main/java/com/baeldung/socket/EchoClient.java index cf5c25327658..fa3901d5da6d 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoClient.java @@ -8,9 +8,8 @@ public class EchoClient { - private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class); - + private Socket clientSocket; private PrintWriter out; private BufferedReader in; diff --git a/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java index ae00fc7cb4c8..d79a7c3ecbcf 100644 --- a/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java +++ b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java @@ -1,6 +1,5 @@ package com.baeldung.stream; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java/src/main/java/com/baeldung/string/StringHelper.java b/core-java/src/main/java/com/baeldung/string/StringHelper.java index dac0d1272e9a..a9cc71d36ad3 100644 --- a/core-java/src/main/java/com/baeldung/string/StringHelper.java +++ b/core-java/src/main/java/com/baeldung/string/StringHelper.java @@ -12,15 +12,10 @@ static String removeLastCharRegex(String s) { } static String removeLastCharOptional(String s) { - return Optional.ofNullable(s) - .filter(str -> str.length() != 0) - .map(str -> str.substring(0, str.length() - 1)) - .orElse(s); + return Optional.ofNullable(s).filter(str -> str.length() != 0).map(str -> str.substring(0, str.length() - 1)).orElse(s); } static String removeLastCharRegexOptional(String s) { - return Optional.ofNullable(s) - .map(str -> str.replaceAll(".$", "")) - .orElse(s); + return Optional.ofNullable(s).map(str -> str.replaceAll(".$", "")).orElse(s); } } diff --git a/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java b/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java index 130218acc269..21164a976c78 100644 --- a/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java +++ b/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java @@ -25,11 +25,7 @@ public List getTokens(String str) { } public List getTokensWithCollection(String str) { - return Collections - .list(new StringTokenizer(str, ",")) - .stream() - .map(token -> (String) token) - .collect(Collectors.toList()); + return Collections.list(new StringTokenizer(str, ",")).stream().map(token -> (String) token).collect(Collectors.toList()); } public List getTokensFromFile(String path, String delim) { diff --git a/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java b/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java index bfb6681f7c55..5631616ea800 100644 --- a/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java +++ b/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java @@ -11,12 +11,12 @@ public class CustomTemporalAdjuster implements TemporalAdjuster { @Override public Temporal adjustInto(Temporal temporal) { switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) { - case FRIDAY: - return temporal.plus(3, ChronoUnit.DAYS); - case SATURDAY: - return temporal.plus(2, ChronoUnit.DAYS); - default: - return temporal.plus(1, ChronoUnit.DAYS); + case FRIDAY: + return temporal.plus(3, ChronoUnit.DAYS); + case SATURDAY: + return temporal.plus(2, ChronoUnit.DAYS); + default: + return temporal.plus(1, ChronoUnit.DAYS); } } } diff --git a/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java b/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java index 69d7ff239091..a5f70d9df54e 100644 --- a/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java +++ b/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java @@ -9,7 +9,6 @@ public class Consumer implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(Consumer.class); - private final TransferQueue transferQueue; private final String name; private final int numberOfMessagesToConsume; diff --git a/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java index 2f1abef64e47..8cddf3124528 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java @@ -15,28 +15,24 @@ public class LongAccumulatorUnitTest { @Test public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException { - //given + // given ExecutorService executorService = Executors.newFixedThreadPool(8); LongBinaryOperator sum = Long::sum; LongAccumulator accumulator = new LongAccumulator(sum, 0L); int numberOfThreads = 4; int numberOfIncrements = 100; - //when - Runnable accumulateAction = () -> IntStream - .rangeClosed(0, numberOfIncrements) - .forEach(accumulator::accumulate); + // when + Runnable accumulateAction = () -> IntStream.rangeClosed(0, numberOfIncrements).forEach(accumulator::accumulate); for (int i = 0; i < numberOfThreads; i++) { executorService.execute(accumulateAction); } - - //then + // then executorService.awaitTermination(500, TimeUnit.MILLISECONDS); executorService.shutdown(); assertEquals(accumulator.get(), 20200); - } } diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java index 70abd69fad8c..bf7a24347dd3 100644 --- a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java @@ -24,7 +24,7 @@ public void tearDownByteArrayOutputStream() throws Exception { @Test public void main_NoInputState_TextPrintedToConsole() throws Exception { - Application.main(new String[]{}); + Application.main(new String[] {}); assertEquals("User found in the collection", outContent.toString()); } } \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java b/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java index 0fd6f7dfe8c5..fe102660439b 100644 --- a/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java @@ -15,7 +15,6 @@ public class LambdaExceptionWrappersUnitTest { private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersUnitTest.class); - private List integers; @Before diff --git a/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java b/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java index 7a23afa12fd2..5327e5f4f06a 100644 --- a/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java +++ b/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java @@ -29,12 +29,9 @@ public void init() { @Test public void givenListOfLists_thenCheckNames() { - assertEquals("Pen 1", ((Pen) listOfLists.get(0) - .get(0)).getName()); - assertEquals("Pencil 1", ((Pencil) listOfLists.get(1) - .get(0)).getName()); - assertEquals("Rubber 1", ((Rubber) listOfLists.get(2) - .get(0)).getName()); + assertEquals("Pen 1", ((Pen) listOfLists.get(0).get(0)).getName()); + assertEquals("Pencil 1", ((Pencil) listOfLists.get(1).get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(2).get(0)).getName()); } @SuppressWarnings("unchecked") @@ -43,11 +40,9 @@ public void givenListOfLists_whenRemovingElements_thenCheckNames() { ((ArrayList) listOfLists.get(1)).remove(0); listOfLists.remove(1); - assertEquals("Rubber 1", ((Rubber) listOfLists.get(1) - .get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(1).get(0)).getName()); listOfLists.remove(0); - assertEquals("Rubber 1", ((Rubber) listOfLists.get(0) - .get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(0).get(0)).getName()); } @Test @@ -67,11 +62,8 @@ public void givenThreeList_whenCombineIntoOneList_thenCheckList() { list.add(pencils); list.add(rubbers); - assertEquals("Pen 1", ((Pen) list.get(0) - .get(0)).getName()); - assertEquals("Pencil 1", ((Pencil) list.get(1) - .get(0)).getName()); - assertEquals("Rubber 1", ((Rubber) list.get(2) - .get(0)).getName()); + assertEquals("Pen 1", ((Pen) list.get(0).get(0)).getName()); + assertEquals("Pencil 1", ((Pencil) list.get(1).get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) list.get(2).get(0)).getName()); } } diff --git a/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java index 9d8d3c884ba5..5fb85bb2c4b1 100644 --- a/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java @@ -13,7 +13,6 @@ public class CoreThreadPoolIntegrationTest { private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class); - @Test(timeout = 1000) public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException { From 67448de055fde89b7be1b7cd77a5a38df5ba7a8e Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 5 Aug 2017 16:32:00 +0300 Subject: [PATCH 20/90] enabling jee7 in the main build --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 82dccf832d75..8401a2f159eb 100644 --- a/pom.xml +++ b/pom.xml @@ -80,7 +80,7 @@ javax-servlets javaxval jaxb - + jee7 jjwt jpa-storedprocedure From ae827f312222cc4e5ba97cd13fe2eecfe421e859 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 5 Aug 2017 22:07:50 +0200 Subject: [PATCH 21/90] Refactor hashcode() samples (#2377) --- core-java/hashcode/pom.xml | 39 ------------------- .../com/baeldung/application/Application.java | 23 ----------- .../main/java/com/baeldung/entities/User.java | 38 ------------------ .../baeldung/application/ApplicationTest.java | 30 -------------- .../java/com/baeldung/entities/UserTest.java | 34 ---------------- .../hashcode/application/Application.java | 24 ------------ .../hashcode/application/ApplicationTest.java | 30 +++++++------- 7 files changed, 15 insertions(+), 203 deletions(-) delete mode 100644 core-java/hashcode/pom.xml delete mode 100644 core-java/hashcode/src/main/java/com/baeldung/application/Application.java delete mode 100644 core-java/hashcode/src/main/java/com/baeldung/entities/User.java delete mode 100644 core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java delete mode 100644 core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java delete mode 100644 core-java/src/main/java/com/baeldung/hashcode/application/Application.java diff --git a/core-java/hashcode/pom.xml b/core-java/hashcode/pom.xml deleted file mode 100644 index 393aa69153e9..000000000000 --- a/core-java/hashcode/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - com.baeldung.hashcode - hashcode - 1.0 - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - - - - junit - junit - 4.12 - test - - - org.slf4j - slf4j-api - 1.7.25 - - - org.slf4j - slf4j-simple - 1.7.25 - - - \ No newline at end of file diff --git a/core-java/hashcode/src/main/java/com/baeldung/application/Application.java b/core-java/hashcode/src/main/java/com/baeldung/application/Application.java deleted file mode 100644 index 08c670c82f78..000000000000 --- a/core-java/hashcode/src/main/java/com/baeldung/application/Application.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.application; - -import com.baeldung.entities.User; -import java.util.HashMap; -import java.util.Map; - -public class Application { - - public static void main(String[] args) { - Map users = new HashMap<>(); - User user1 = new User(1L, "John", "john@domain.com"); - User user2 = new User(2L, "Jennifer", "jennifer@domain.com"); - User user3 = new User(3L, "Mary", "mary@domain.com"); - - users.put(user1, user1); - users.put(user2, user2); - users.put(user3, user3); - - if (users.containsKey(user1)) { - System.out.print("User found in the collection"); - } - } -} diff --git a/core-java/hashcode/src/main/java/com/baeldung/entities/User.java b/core-java/hashcode/src/main/java/com/baeldung/entities/User.java deleted file mode 100644 index a976233562dc..000000000000 --- a/core-java/hashcode/src/main/java/com/baeldung/entities/User.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.entities; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class User { - - private final Logger logger = LoggerFactory.getLogger(User.class); - private long id; - private String name; - private String email; - - public User(long id, String name, String email) { - this.id = id; - this.name = name; - this.email = email; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null) return false; - if (this.getClass() != o.getClass()) return false; - User user = (User) o; - return id != user.id && (!name.equals(user.name) && !email.equals(user.email)); - } - - @Override - public int hashCode() { - int hash = 7; - hash = 31 * hash + (int) id; - hash = 31 * hash + (name == null ? 0 : name.hashCode()); - hash = 31 * hash + (email == null ? 0 : email.hashCode()); - logger.info("hashCode() method called - Computed hash: " + hash); - return hash; - } - // getters and setters here -} diff --git a/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java b/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java deleted file mode 100644 index dcd853f451d9..000000000000 --- a/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.application; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import static org.junit.Assert.assertEquals; - -public class ApplicationTest { - - private ByteArrayOutputStream outContent; - - @Before - public void setUpPrintStreamInstance() throws Exception { - this.outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - } - - @After - public void tearDownByteArrayOutputStream() throws Exception { - outContent = null; - } - - @Test - public void main_NoInputState_TextPrintedToConsole() throws Exception { - Application.main(new String[]{}); - assertEquals("User found in the collection", outContent.toString()); - } -} \ No newline at end of file diff --git a/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java b/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java deleted file mode 100644 index 01f6085d7eac..000000000000 --- a/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.entities; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class UserTest { - - private User user; - private User comparisonUser; - - @Before - public void setUpUserInstances() { - this.user = new User(1L, "test", "test@domain.com"); - this.comparisonUser = this.user; - } - - @After - public void tearDownUserInstances() { - user = null; - comparisonUser = null; - } - - @Test - public void equals_EqualUserInstance_TrueAssertion(){ - Assert.assertTrue(user.equals(comparisonUser)); - } - - @Test - public void hashCode_UserHash_TrueAssertion() { - Assert.assertEquals(1792276941, user.hashCode()); - } -} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/hashcode/application/Application.java b/core-java/src/main/java/com/baeldung/hashcode/application/Application.java deleted file mode 100644 index 8e6125045e98..000000000000 --- a/core-java/src/main/java/com/baeldung/hashcode/application/Application.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.hashcode.application; - -import java.util.HashMap; -import java.util.Map; - -import com.baeldung.hashcode.entities.User; - -public class Application { - - public static void main(String[] args) { - Map users = new HashMap<>(); - User user1 = new User(1L, "John", "john@domain.com"); - User user2 = new User(2L, "Jennifer", "jennifer@domain.com"); - User user3 = new User(3L, "Mary", "mary@domain.com"); - - users.put(user1, user1); - users.put(user2, user2); - users.put(user3, user3); - - if (users.containsKey(user1)) { - System.out.print("User found in the collection"); - } - } -} diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java index bf7a24347dd3..04e32e5fa066 100644 --- a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java @@ -1,30 +1,30 @@ package com.baeldung.hashcode.application; +import com.baeldung.hashcode.entities.User; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import java.util.HashMap; +import java.util.Map; + import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class ApplicationTest { - private ByteArrayOutputStream outContent; - - @Before - public void setUpPrintStreamInstance() throws Exception { - this.outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - } - - @After - public void tearDownByteArrayOutputStream() throws Exception { - outContent = null; - } - @Test public void main_NoInputState_TextPrintedToConsole() throws Exception { - Application.main(new String[] {}); - assertEquals("User found in the collection", outContent.toString()); + Map users = new HashMap<>(); + User user1 = new User(1L, "John", "john@domain.com"); + User user2 = new User(2L, "Jennifer", "jennifer@domain.com"); + User user3 = new User(3L, "Mary", "mary@domain.com"); + + users.put(user1, user1); + users.put(user2, user2); + users.put(user3, user3); + + assertTrue(users.containsKey(user1)); } } \ No newline at end of file From 40b3cc7d2b1549c67f19610cac156772dbd7f69a Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Sun, 6 Aug 2017 02:01:55 +0530 Subject: [PATCH 22/90] Bootique module (#2376) * moving jmh into libraries module * refactoring jmh * Update pom.xml * manual algorightm * with BM result * fix for space issue * Fixed indentation * change as per suggestion * vavr either * adding unit test and othe rutilities * adding concurrent module * concurrent package description * concurrent package description * Update EitherUnitTest.java * introducing lambda expression * jooby project * jooby project * reducing employee bean content * bootique module * bootique * bootique --- bootique/config.yml | 11 ++++ bootique/dependency-reduced-pom.xml | 50 ++++++++++++++ bootique/pom.xml | 66 +++++++++++++++++++ .../main/java/com/baeldung/bootique/App.java | 42 ++++++++++++ .../bootique/module/ModuleBinder.java | 15 +++++ .../bootique/module/ModuleProvider.java | 14 ++++ .../bootique/router/IndexController.java | 14 ++++ .../bootique/router/SaveController.java | 20 ++++++ .../bootique/service/HelloService.java | 7 ++ .../service/impl/HelloServiceImpl.java | 12 ++++ .../services/io.bootique.BQModuleProvider | 1 + .../java/com/baeldung/bootique/AppTest.java | 29 ++++++++ 12 files changed, 281 insertions(+) create mode 100644 bootique/config.yml create mode 100644 bootique/dependency-reduced-pom.xml create mode 100644 bootique/pom.xml create mode 100644 bootique/src/main/java/com/baeldung/bootique/App.java create mode 100644 bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java create mode 100644 bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java create mode 100644 bootique/src/main/java/com/baeldung/bootique/router/IndexController.java create mode 100644 bootique/src/main/java/com/baeldung/bootique/router/SaveController.java create mode 100644 bootique/src/main/java/com/baeldung/bootique/service/HelloService.java create mode 100644 bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java create mode 100644 bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider create mode 100644 bootique/src/test/java/com/baeldung/bootique/AppTest.java diff --git a/bootique/config.yml b/bootique/config.yml new file mode 100644 index 000000000000..269b4ab867f0 --- /dev/null +++ b/bootique/config.yml @@ -0,0 +1,11 @@ +log: + level: warn + appenders: + - type: file + logFormat: '%c{20}: %m%n' + file: /home/logger.log + +jetty: + context: /hello + connector: + port: 10001 diff --git a/bootique/dependency-reduced-pom.xml b/bootique/dependency-reduced-pom.xml new file mode 100644 index 000000000000..ed18f4e42a40 --- /dev/null +++ b/bootique/dependency-reduced-pom.xml @@ -0,0 +1,50 @@ + + + + bootique-parent + io.bootique.parent + 0.12 + + 4.0.0 + com.baeldung.bootique + bootique + bootique + 1.0-SNAPSHOT + http://maven.apache.org + + + + maven-shade-plugin + + + + + + io.bootique + bootique-test + 0.23 + test + + + junit + junit + 3.8.1 + test + + + + + + io.bootique.bom + bootique-bom + 0.23 + pom + import + + + + + com.baeldung.bootique.App + + + diff --git a/bootique/pom.xml b/bootique/pom.xml new file mode 100644 index 000000000000..28b716e10403 --- /dev/null +++ b/bootique/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + com.baeldung.bootique + bootique + jar + 1.0-SNAPSHOT + bootique + http://maven.apache.org + + + com.baeldung.bootique.App + + + + io.bootique.parent + bootique-parent + 0.12 + + + + + + io.bootique.bom + bootique-bom + 0.23 + pom + import + + + + + + + io.bootique.jersey + bootique-jersey + compile + + + io.bootique.logback + bootique-logback + compile + + + io.bootique + bootique-test + test + + + junit + junit + 4.12 + test + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + + \ No newline at end of file diff --git a/bootique/src/main/java/com/baeldung/bootique/App.java b/bootique/src/main/java/com/baeldung/bootique/App.java new file mode 100644 index 000000000000..2fd03bd6c30e --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/App.java @@ -0,0 +1,42 @@ +package com.baeldung.bootique; + +import java.util.function.Supplier; + +import com.baeldung.bootique.module.ModuleBinder; +import com.baeldung.bootique.router.IndexController; +import com.baeldung.bootique.router.SaveController; +import com.google.inject.Module; + +import io.bootique.Bootique; +import io.bootique.jersey.JerseyModule; +import io.bootique.log.BootLogger; + +public class App { + + public static void main(String[] args) { + Module module = binder -> JerseyModule.extend(binder).addResource(IndexController.class) + .addResource(SaveController.class); + Bootique.app(args).module(module).module(ModuleBinder.class).bootLogger(new BootLogger() { + @Override + public void trace(Supplier arg0) { + // ... + } + + @Override + public void stdout(String arg0) { + // ... + } + + @Override + public void stderr(String arg0, Throwable arg1) { + // ... + } + + @Override + public void stderr(String arg0) { + // ... + } + }).autoLoadModules().exec(); + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java b/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java new file mode 100644 index 000000000000..8c6fbb9642bc --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java @@ -0,0 +1,15 @@ +package com.baeldung.bootique.module; + +import com.baeldung.bootique.service.HelloService; +import com.baeldung.bootique.service.impl.HelloServiceImpl; +import com.google.inject.Binder; +import com.google.inject.Module; + +public class ModuleBinder implements Module { + + @Override + public void configure(Binder binder) { + binder.bind(HelloService.class).to(HelloServiceImpl.class); + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java b/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java new file mode 100644 index 000000000000..8de866fcfbf0 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java @@ -0,0 +1,14 @@ +package com.baeldung.bootique.module; + +import com.google.inject.Module; + +import io.bootique.BQModuleProvider; + +public class ModuleProvider implements BQModuleProvider { + + @Override + public Module module() { + return new ModuleBinder(); + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java b/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java new file mode 100644 index 000000000000..4bb80277a117 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java @@ -0,0 +1,14 @@ +package com.baeldung.bootique.router; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/") +public class IndexController { + + @GET + public String index() { + return "Hello, baeldung!"; + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java b/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java new file mode 100644 index 000000000000..0610b9d91348 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java @@ -0,0 +1,20 @@ +package com.baeldung.bootique.router; + +import javax.ws.rs.POST; +import javax.ws.rs.Path; + +import com.baeldung.bootique.service.HelloService; +import com.google.inject.Inject; + +@Path("/save") +public class SaveController { + + @Inject + HelloService helloService; + + @POST + public String save() { + return "Data Saved!"; + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/service/HelloService.java b/bootique/src/main/java/com/baeldung/bootique/service/HelloService.java new file mode 100644 index 000000000000..74c0401cc303 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/service/HelloService.java @@ -0,0 +1,7 @@ +package com.baeldung.bootique.service; + +public interface HelloService { + + boolean save(); + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java b/bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java new file mode 100644 index 000000000000..d2c0b5b838f1 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java @@ -0,0 +1,12 @@ +package com.baeldung.bootique.service.impl; + +import com.baeldung.bootique.service.HelloService; + +public class HelloServiceImpl implements HelloService { + + @Override + public boolean save() { + return true; + } + +} diff --git a/bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider b/bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider new file mode 100644 index 000000000000..714cf3a2dff4 --- /dev/null +++ b/bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider @@ -0,0 +1 @@ +com.baeldung.bootique.module.ModuleProvider \ No newline at end of file diff --git a/bootique/src/test/java/com/baeldung/bootique/AppTest.java b/bootique/src/test/java/com/baeldung/bootique/AppTest.java new file mode 100644 index 000000000000..0793e2f13c97 --- /dev/null +++ b/bootique/src/test/java/com/baeldung/bootique/AppTest.java @@ -0,0 +1,29 @@ +package com.baeldung.bootique; + +import static org.junit.Assert.assertEquals; + +import org.junit.Rule; +import org.junit.Test; + +import com.baeldung.bootique.service.HelloService; + +import io.bootique.BQRuntime; +import io.bootique.test.junit.BQDaemonTestFactory; +import io.bootique.test.junit.BQTestFactory; + +public class AppTest { + + @Rule + public BQTestFactory bqTestFactory = new BQTestFactory(); + + @Rule + public BQDaemonTestFactory bqDaemonTestFactory = new BQDaemonTestFactory(); + + @Test + public void givenService_expectBoolen() { + BQRuntime runtime = bqTestFactory.app("--server").autoLoadModules().createRuntime(); + HelloService service = runtime.getInstance(HelloService.class); + assertEquals(true, service.save()); + } + +} From b6e59c2ae7113bc31ae82d07571e2f9a87a70d86 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 6 Aug 2017 13:23:19 +0200 Subject: [PATCH 23/90] Refactor bootique (#2380) --- .../main/java/com/baeldung/bootique/App.java | 55 +++++++++---------- .../bootique/module/ModuleBinder.java | 8 +-- .../bootique/module/ModuleProvider.java | 9 ++- .../bootique/router/IndexController.java | 10 ++-- .../bootique/router/SaveController.java | 22 ++++---- .../java/com/baeldung/bootique/AppTest.java | 30 +++++----- .../hashcode/application/ApplicationTest.java | 6 +- pom.xml | 1 + 8 files changed, 67 insertions(+), 74 deletions(-) diff --git a/bootique/src/main/java/com/baeldung/bootique/App.java b/bootique/src/main/java/com/baeldung/bootique/App.java index 2fd03bd6c30e..cc1b90ce7da3 100644 --- a/bootique/src/main/java/com/baeldung/bootique/App.java +++ b/bootique/src/main/java/com/baeldung/bootique/App.java @@ -1,42 +1,41 @@ package com.baeldung.bootique; -import java.util.function.Supplier; - import com.baeldung.bootique.module.ModuleBinder; import com.baeldung.bootique.router.IndexController; import com.baeldung.bootique.router.SaveController; import com.google.inject.Module; - import io.bootique.Bootique; import io.bootique.jersey.JerseyModule; import io.bootique.log.BootLogger; +import java.util.function.Supplier; + public class App { - public static void main(String[] args) { - Module module = binder -> JerseyModule.extend(binder).addResource(IndexController.class) - .addResource(SaveController.class); - Bootique.app(args).module(module).module(ModuleBinder.class).bootLogger(new BootLogger() { - @Override - public void trace(Supplier arg0) { - // ... - } - - @Override - public void stdout(String arg0) { - // ... - } - - @Override - public void stderr(String arg0, Throwable arg1) { - // ... - } - - @Override - public void stderr(String arg0) { - // ... - } - }).autoLoadModules().exec(); - } + public static void main(String[] args) { + Module module = binder -> JerseyModule.extend(binder).addResource(IndexController.class) + .addResource(SaveController.class); + Bootique.app(args).module(module).module(ModuleBinder.class).bootLogger(new BootLogger() { + @Override + public void trace(Supplier arg0) { + // ... + } + + @Override + public void stdout(String arg0) { + // ... + } + + @Override + public void stderr(String arg0, Throwable arg1) { + // ... + } + + @Override + public void stderr(String arg0) { + // ... + } + }).autoLoadModules().exec(); + } } diff --git a/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java b/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java index 8c6fbb9642bc..8811d48652c4 100644 --- a/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java +++ b/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java @@ -7,9 +7,9 @@ public class ModuleBinder implements Module { - @Override - public void configure(Binder binder) { - binder.bind(HelloService.class).to(HelloServiceImpl.class); - } + @Override + public void configure(Binder binder) { + binder.bind(HelloService.class).to(HelloServiceImpl.class); + } } diff --git a/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java b/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java index 8de866fcfbf0..cf78177e6d8c 100644 --- a/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java +++ b/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java @@ -1,14 +1,13 @@ package com.baeldung.bootique.module; import com.google.inject.Module; - import io.bootique.BQModuleProvider; public class ModuleProvider implements BQModuleProvider { - @Override - public Module module() { - return new ModuleBinder(); - } + @Override + public Module module() { + return new ModuleBinder(); + } } diff --git a/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java b/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java index 4bb80277a117..6e3b31df412d 100644 --- a/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java +++ b/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java @@ -5,10 +5,10 @@ @Path("/") public class IndexController { - - @GET - public String index() { - return "Hello, baeldung!"; - } + + @GET + public String index() { + return "Hello, baeldung!"; + } } diff --git a/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java b/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java index 0610b9d91348..f38f59708c01 100644 --- a/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java +++ b/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java @@ -1,20 +1,20 @@ package com.baeldung.bootique.router; -import javax.ws.rs.POST; -import javax.ws.rs.Path; - import com.baeldung.bootique.service.HelloService; import com.google.inject.Inject; +import javax.ws.rs.POST; +import javax.ws.rs.Path; + @Path("/save") public class SaveController { - @Inject - HelloService helloService; - - @POST - public String save() { - return "Data Saved!"; - } - + @Inject + HelloService helloService; + + @POST + public String save() { + return "Data Saved!"; + } + } diff --git a/bootique/src/test/java/com/baeldung/bootique/AppTest.java b/bootique/src/test/java/com/baeldung/bootique/AppTest.java index 0793e2f13c97..8856780ed431 100644 --- a/bootique/src/test/java/com/baeldung/bootique/AppTest.java +++ b/bootique/src/test/java/com/baeldung/bootique/AppTest.java @@ -1,29 +1,27 @@ package com.baeldung.bootique; -import static org.junit.Assert.assertEquals; - -import org.junit.Rule; -import org.junit.Test; - import com.baeldung.bootique.service.HelloService; - import io.bootique.BQRuntime; import io.bootique.test.junit.BQDaemonTestFactory; import io.bootique.test.junit.BQTestFactory; +import org.junit.Rule; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; public class AppTest { - @Rule - public BQTestFactory bqTestFactory = new BQTestFactory(); + @Rule + public BQTestFactory bqTestFactory = new BQTestFactory(); - @Rule - public BQDaemonTestFactory bqDaemonTestFactory = new BQDaemonTestFactory(); + @Rule + public BQDaemonTestFactory bqDaemonTestFactory = new BQDaemonTestFactory(); - @Test - public void givenService_expectBoolen() { - BQRuntime runtime = bqTestFactory.app("--server").autoLoadModules().createRuntime(); - HelloService service = runtime.getInstance(HelloService.class); - assertEquals(true, service.save()); - } + @Test + public void givenService_expectBoolen() { + BQRuntime runtime = bqTestFactory.app("--server").autoLoadModules().createRuntime(); + HelloService service = runtime.getInstance(HelloService.class); + assertEquals(true, service.save()); + } } diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java index 04e32e5fa066..60950fae7a7a 100644 --- a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java @@ -1,15 +1,11 @@ package com.baeldung.hashcode.application; import com.baeldung.hashcode.entities.User; -import org.junit.After; -import org.junit.Before; import org.junit.Test; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; + import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ApplicationTest { diff --git a/pom.xml b/pom.xml index 8401a2f159eb..f33d63bc48d9 100644 --- a/pom.xml +++ b/pom.xml @@ -38,6 +38,7 @@ apache-thrift autovalue axon + bootique cdi From 5383b2b01b857635b421d29216431fbedda1b5bb Mon Sep 17 00:00:00 2001 From: chrisoberle Date: Sun, 6 Aug 2017 16:31:55 -0400 Subject: [PATCH 24/90] add valueswithdefaults example (#2369) * add values with defaults example * add additional examples * remove unused imports --- .../ValuesWithDefaultsApp.java | 75 +++++++++++++++++++ .../resources/valueswithdefaults.properties | 0 2 files changed, 75 insertions(+) create mode 100644 spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java create mode 100644 spring-core/src/main/resources/valueswithdefaults.properties diff --git a/spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java b/spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java new file mode 100644 index 000000000000..d2cda19ae678 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java @@ -0,0 +1,75 @@ +package com.baeldung.valuewithdefaults; + +import java.util.Arrays; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.util.Assert; + +import com.google.common.collect.Lists; +import com.google.common.primitives.Ints; + +/** + * Demonstrates setting defaults for @Value annotation. Note that there are no properties + * defined in the specified property source. We also assume that the user here + * does not have a system property named some.key. + * + */ +@Configuration +@PropertySource(name = "myProperties", value = "valueswithdefaults.properties") +public class ValuesWithDefaultsApp { + + @Value("${some.key:my default value}") + private String stringWithDefaultValue; + + @Value("${some.key:}") + private String stringWithBlankDefaultValue; + + @Value("${some.key:true}") + private boolean booleanWithDefaultValue; + + @Value("${some.key:42}") + private int intWithDefaultValue; + + @Value("${some.key:one,two,three}") + private String[] stringArrayWithDefaults; + + @Value("${some.key:1,2,3}") + private int[] intArrayWithDefaults; + + @Value("#{systemProperties['some.key'] ?: 'my default system property value'}") + private String spelWithDefaultValue; + + + public static void main(String[] args) { + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesWithDefaultsApp.class); + } + + @PostConstruct + public void afterInitialize() { + // strings + Assert.isTrue(stringWithDefaultValue.equals("my default value")); + Assert.isTrue(stringWithBlankDefaultValue.equals("")); + + // other primitives + Assert.isTrue(booleanWithDefaultValue); + Assert.isTrue(intWithDefaultValue == 42); + + // arrays + List stringListValues = Lists.newArrayList("one", "two", "three"); + Assert.isTrue(Arrays.asList(stringArrayWithDefaults).containsAll(stringListValues)); + + List intListValues = Lists.newArrayList(1, 2, 3); + Assert.isTrue(Ints.asList(intArrayWithDefaults).containsAll(intListValues)); + + // SpEL + Assert.isTrue(spelWithDefaultValue.equals("my default system property value")); + + } +} diff --git a/spring-core/src/main/resources/valueswithdefaults.properties b/spring-core/src/main/resources/valueswithdefaults.properties new file mode 100644 index 000000000000..e69de29bb2d1 From ddee04fca6640fdcb6fd8fb74c1437405ff75849 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sun, 6 Aug 2017 21:53:30 -0500 Subject: [PATCH 25/90] BAEL-644: RSS with Rome (#2385) * BAEL-886: Updated README * BAEL-917 Testing with Google Truth Updated README * BAEL-936: adding akka-streams module to parent * BAEL-936: Update README * BAEL-918: Update README * BAEL-980: Update README * BAEL-967: Update README * BAEL-509: Using @GetMapping instead of @RequestMapping with method=GET * BAEL-1005: Update README * BAEL-509: Security and WebSockets (README) * BAEL-861: Intro to Awaitility (README) * BAEL-1010: Guide to the HyperLogLog Algorithm (README) * BAEL-907: Guide to Apache Commons CircularFifoQueue (README) * BAEL-644: Quick Guide to RSS with Rome --- libraries/pom.xml | 6 ++ .../com/baeldung/rome/RSSRomeExample.java | 76 +++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java diff --git a/libraries/pom.xml b/libraries/pom.xml index efdf20423a1f..87971fb26ed9 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -181,6 +181,11 @@ jetty-servlet ${jetty.version} + + rome + rome + ${rome.version} + io.specto hoverfly-java @@ -497,5 +502,6 @@ 1.6.0 1.7.1 2.1.2 + 1.0 diff --git a/libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java b/libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java new file mode 100644 index 000000000000..66a9e0ebce89 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java @@ -0,0 +1,76 @@ +package com.baeldung.rome; + +import com.sun.syndication.feed.synd.*; +import com.sun.syndication.io.FeedException; +import com.sun.syndication.io.SyndFeedInput; +import com.sun.syndication.io.SyndFeedOutput; +import com.sun.syndication.io.XmlReader; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class RSSRomeExample { + + public static void main(String[] args) throws IOException, FeedException { + SyndFeed feed = createFeed(); + addEntryToFeed(feed); + publishFeed(feed); + readFeed(); + } + + private static SyndFeed createFeed() { + SyndFeed feed = new SyndFeedImpl(); + feed.setFeedType("rss_1.0"); + feed.setTitle("Test title"); + feed.setLink("http://www.somelink.com"); + feed.setDescription("Basic description"); + + return feed; + } + + private static void addEntryToFeed(SyndFeed feed) { + SyndEntry entry = new SyndEntryImpl(); + entry.setTitle("Entry title"); + entry.setLink("http://www.somelink.com/entry1"); + + addDescriptionToEntry(entry); + addCategoryToEntry(entry); + + feed.setEntries(Arrays.asList(entry)); + } + + private static void addDescriptionToEntry(SyndEntry entry) { + SyndContent description = new SyndContentImpl(); + description.setType("text/html"); + description.setValue("First entry"); + + entry.setDescription(description); + } + + private static void addCategoryToEntry(SyndEntry entry) { + List categories = new ArrayList<>(); + SyndCategory category = new SyndCategoryImpl(); + category.setName("Sophisticated category"); + categories.add(category); + + entry.setCategories(categories); + } + + private static void publishFeed(SyndFeed feed) throws IOException, FeedException { + Writer writer = new FileWriter("xyz.txt"); + SyndFeedOutput syndFeedOutput = new SyndFeedOutput(); + syndFeedOutput.output(feed, writer); + writer.close(); + } + + private static SyndFeed readFeed() throws IOException, FeedException { + URL feedSource = new URL("http://rssblog.whatisrss.com/feed/"); + SyndFeedInput input = new SyndFeedInput(); + return input.build(new XmlReader(feedSource)); + } +} \ No newline at end of file From a1388b643b6327cd5b6d32be40eb9d11f2b42d20 Mon Sep 17 00:00:00 2001 From: Mansi Date: Mon, 7 Aug 2017 12:16:40 +0530 Subject: [PATCH 26/90] BAEL-378 A Guide to Activiti with Java (#2245) * Example Code For Evaluation Article This is an example code for the evaluation article on "Different Types of Bean Injection in Spring" * Added unit tests * Minor changes to application context * Removed code committed for evaluation article * BAEL-944 Demonstrating the problems with new Url pattern matching in Spring 5 * BAEL-944 Demonstrating the problems with new Url pattern matching in Spring 5 * BAEL-944 Exploring the Spring MVC URL Matching Improvements * BAEL-944 Exploring the Spring MVC URL Matching Improvements * BAEL-944 Exploring the Spring MVC URL Matching Improvements * BAEL-944 Code Formatting and solving build issue * BAEL-944 Resolving build issue due to change in Spring version * BAEL-944 Resolving build issue * BAEL-944 Formatting code * BAEL-944 Moving tests to correct package * BAEL-944 Moving tests to correct package * BAEL-944 Replacing @RequestMapping by @GetMapping * BAEL-944 Remove unnecessary attribute name, "value" in annotations * BAEL-79 Intro to Activiti with Spring * BAEL-79 Intro to Activiti with Spring * BAEL-79 Adding activiti module to the parent modules * BAEL-79 Using latest version * BAEL-79 Update Spring boot version that works with Activiti * BAEL-79 Replace RequestMapping with GetMapping * BAEL-79 Use Java 8 Syntax * BAEL-79 Formatting * BAEL-79 changed module name * BAEL-378 A Guide to Activiti with Java * BAEL-79 Fixed unit tests * BAEL-79 Simplified the process * BAEL-79 Fix test cases --- .../ActivitiController.java | 7 +- .../servicetasks/SendEmailServiceTask.java | 12 ++ .../resources/processes/my-process.bpmn20.xml | 65 ++------ .../ActivitiControllerIntegrationTest.java | 14 +- .../ProcessEngineCreationTests.java | 64 ++++++++ .../ProcessExecutionTests.java | 97 ++++++++++++ .../src/test/resources/activiti.cfg.xml | 16 ++ .../src/test/resources/my.activiti.cfg.xml | 26 +++ .../activiti/test/vacationRequest.bpmn20.xml | 149 ++++++++++++++++++ 9 files changed, 388 insertions(+), 62 deletions(-) create mode 100644 spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java create mode 100644 spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java create mode 100644 spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java create mode 100644 spring-activiti/src/test/resources/activiti.cfg.xml create mode 100644 spring-activiti/src/test/resources/my.activiti.cfg.xml create mode 100644 spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java index fd184556c479..96b551c03ce9 100644 --- a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java @@ -42,16 +42,11 @@ public List getTasks(@PathVariable String processInstanceId) } @GetMapping("/complete-task-A/{processInstanceId}") - public TaskRepresentation completeTaskA(@PathVariable String processInstanceId) { + public void completeTaskA(@PathVariable String processInstanceId) { Task task = taskService.createTaskQuery() .processInstanceId(processInstanceId) .singleResult(); taskService.complete(task.getId()); logger.info("Task completed"); - task = taskService.createTaskQuery() - .processInstanceId(processInstanceId) - .singleResult(); - - return new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId()); } } diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java b/spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java new file mode 100644 index 000000000000..c11b48f37add --- /dev/null +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java @@ -0,0 +1,12 @@ +package com.example.activitiwithspring.servicetasks; + +import org.activiti.engine.delegate.DelegateExecution; +import org.activiti.engine.delegate.JavaDelegate; + +public class SendEmailServiceTask implements JavaDelegate { + + public void execute(DelegateExecution execution) { + //logic to sent email confirmation + } + +} diff --git a/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml b/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml index 3ced8d6b7cdb..6f151af458a2 100644 --- a/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml +++ b/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml @@ -1,66 +1,35 @@ - - + + - - - - - - - + + + - + - + - + - + - - + + - - - - - - - - - - + + + - - - + + + diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java index baca58f6ffad..65fd33bfc6ea 100644 --- a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java @@ -106,14 +106,12 @@ public void givenProcess_whenCompleteTaskA_thenReceivedNextTask() throws Excepti .get(0); logger.info("process instance = " + pi.getId()); - String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/complete-task-A/" + pi.getId())) - .andReturn() - .getResponse() - .getContentAsString(); - - ObjectMapper mapper = new ObjectMapper(); - TaskRepresentation task = mapper.readValue(responseBody, TaskRepresentation.class); - assertEquals("B", task.getName()); + this.mockMvc.perform(MockMvcRequestBuilders.get("/complete-task-A/" + pi.getId())) + .andReturn() + .getResponse() + .getContentAsString(); + List list = runtimeService.createProcessInstanceQuery().list(); + assertEquals(0, list.size()); } } diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java new file mode 100644 index 000000000000..7f07191cde72 --- /dev/null +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java @@ -0,0 +1,64 @@ +package com.example.activitiwithspring; + +import org.activiti.engine.ProcessEngine; +import org.activiti.engine.ProcessEngineConfiguration; +import org.activiti.engine.ProcessEngines; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import org.junit.Test; + +public class ProcessEngineCreationTests { + + @Test + public void givenXMLConfig_whenGetDefault_thenGotProcessEngine() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + assertNotNull(processEngine); + assertEquals("root", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenXMLConfig_whenCreateDefaultConfiguration_thenGotProcessEngine() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createProcessEngineConfigurationFromResourceDefault(); + ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("root", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenDifferentNameXMLConfig_whenGetProcessEngineConfig_thenGotResult() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource("my.activiti.cfg.xml"); + ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("baeldung", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenDifferentBeanNameInXMLConfig_whenGetProcessEngineConfig_thenGotResult() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration + .createProcessEngineConfigurationFromResource("my.activiti.cfg.xml", "myProcessEngineConfiguration"); + ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("baeldung", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenNoXMLConfig_whenCreateInMemProcessEngineConfig_thenCreated() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration(); + ProcessEngine processEngine = processEngineConfiguration + .setJdbcUrl("jdbc:h2:mem:my-own-in-mem-db;DB_CLOSE_DELAY=1000") + .buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenNoXMLConfig_whenCreateProcessEngineConfig_thenCreated() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration(); + ProcessEngine processEngine = processEngineConfiguration + .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE) + .setJdbcUrl("jdbc:h2:mem:my-own-db;DB_CLOSE_DELAY=1000") + .buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } +} diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java new file mode 100644 index 000000000000..cae28d5281f6 --- /dev/null +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java @@ -0,0 +1,97 @@ +package com.example.activitiwithspring; + + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.activiti.engine.ActivitiException; +import org.activiti.engine.ProcessEngine; +import org.activiti.engine.ProcessEngines; +import org.activiti.engine.RepositoryService; +import org.activiti.engine.RuntimeService; +import org.activiti.engine.TaskService; +import org.activiti.engine.runtime.ProcessInstance; +import org.activiti.engine.task.Task; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class ProcessExecutionTests { + + @Test + public void givenBPMN_whenDeployProcess_thenDeployed() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + Long count = repositoryService.createProcessDefinitionQuery().count(); + assertTrue(count >= 1); + } + + @Test + public void givenProcessDefinition_whenStartProcessInstance_thenProcessRunning() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + + Map variables = new HashMap(); + variables.put("employeeName", "Kermit"); + variables.put("numberOfDays", new Integer(4)); + variables.put("vacationMotivation", "I'm really tired!"); + + RuntimeService runtimeService = processEngine.getRuntimeService(); + ProcessInstance processInstance = runtimeService + .startProcessInstanceByKey("vacationRequest", variables); + + Long count = runtimeService.createProcessInstanceQuery().count(); + assertTrue(count >= 1); + } + + @Test + public void givenProcessInstance_whenCompleteTask_thenProcessExecutionContinues() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + + Map variables = new HashMap(); + variables.put("employeeName", "Kermit"); + variables.put("numberOfDays", new Integer(4)); + variables.put("vacationMotivation", "I'm really tired!"); + + RuntimeService runtimeService = processEngine.getRuntimeService(); + ProcessInstance processInstance = runtimeService + .startProcessInstanceByKey("vacationRequest", variables); + + TaskService taskService = processEngine.getTaskService(); + List tasks = taskService.createTaskQuery().taskCandidateGroup("management").list(); + + Task task = tasks.get(0); + + Map taskVariables = new HashMap(); + taskVariables.put("vacationApproved", "false"); + taskVariables.put("comments", "We have a tight deadline!"); + taskService.complete(task.getId(), taskVariables); + + Task currentTask = taskService.createTaskQuery().taskName("Modify vacation request").singleResult(); + assertNotNull(currentTask); + } + + @Test(expected = ActivitiException.class) + public void givenProcessDefinition_whenSuspend_thenNoProcessInstanceCreated() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + + RuntimeService runtimeService = processEngine.getRuntimeService(); + repositoryService.suspendProcessDefinitionByKey("vacationRequest"); + runtimeService.startProcessInstanceByKey("vacationRequest"); + } +} diff --git a/spring-activiti/src/test/resources/activiti.cfg.xml b/spring-activiti/src/test/resources/activiti.cfg.xml new file mode 100644 index 000000000000..1ee117d936cb --- /dev/null +++ b/spring-activiti/src/test/resources/activiti.cfg.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + diff --git a/spring-activiti/src/test/resources/my.activiti.cfg.xml b/spring-activiti/src/test/resources/my.activiti.cfg.xml new file mode 100644 index 000000000000..07e4206dad94 --- /dev/null +++ b/spring-activiti/src/test/resources/my.activiti.cfg.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml b/spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml new file mode 100644 index 000000000000..354c6333851a --- /dev/null +++ b/spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml @@ -0,0 +1,149 @@ + + + + + + + + + + + + + ${employeeName} would like to take ${numberOfDays} day(s) of vacation (Motivation: ${reason}). + + + + + + + + + + management + + + + + + + + + + Your manager has disapproved your vacation request for ${numberOfDays} days. + Reason: ${comments} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From d11d9ad8b190a2657a6d725c95273f01f1bbb159 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Mon, 7 Aug 2017 14:31:28 +0200 Subject: [PATCH 27/90] fix spring config (#2386) * fix spring config * fix spring config * fix spring config --- patterns/intercepting-filter/pom.xml | 1 - .../org/baeldung/config/UiApplication.java | 14 ++----------- .../org/baeldung/config/UiSecurityConfig.java | 20 +++++++++++++++++++ .../org/baeldung/config/UiApplication.java | 15 ++------------ .../org/baeldung/config/UiSecurityConfig.java | 20 +++++++++++++++++++ .../org/baeldung/config/UiApplication.java | 3 ++- 6 files changed, 46 insertions(+), 27 deletions(-) create mode 100644 spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java create mode 100644 spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java diff --git a/patterns/intercepting-filter/pom.xml b/patterns/intercepting-filter/pom.xml index 550409b64368..5b7eb48a8606 100644 --- a/patterns/intercepting-filter/pom.xml +++ b/patterns/intercepting-filter/pom.xml @@ -22,7 +22,6 @@ org.slf4j slf4j-api ${slf4j.version} - provided diff --git a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java index 5ef699d26431..c0ad5eb69088 100644 --- a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java @@ -3,24 +3,14 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.context.request.RequestContextListener; @EnableOAuth2Sso @SpringBootApplication -public class UiApplication extends WebSecurityConfigurerAdapter { +public class UiApplication extends SpringBootServletInitializer { - @Override - public void configure(HttpSecurity http) throws Exception { - http.antMatcher("/**") - .authorizeRequests() - .antMatchers("/", "/login**") - .permitAll() - .anyRequest() - .authenticated(); - } @Bean public RequestContextListener requestContextListener() { diff --git a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java new file mode 100644 index 000000000000..5dbe9ada34e6 --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class UiSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/", "/login**") + .permitAll() + .anyRequest() + .authenticated(); + } + +} diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java index 5ef699d26431..6e29879cb3a7 100644 --- a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java @@ -3,24 +3,13 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.context.request.RequestContextListener; @EnableOAuth2Sso @SpringBootApplication -public class UiApplication extends WebSecurityConfigurerAdapter { - - @Override - public void configure(HttpSecurity http) throws Exception { - http.antMatcher("/**") - .authorizeRequests() - .antMatchers("/", "/login**") - .permitAll() - .anyRequest() - .authenticated(); - } +public class UiApplication extends SpringBootServletInitializer { @Bean public RequestContextListener requestContextListener() { diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java new file mode 100644 index 000000000000..5dbe9ada34e6 --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class UiSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/", "/login**") + .permitAll() + .anyRequest() + .authenticated(); + } + +} diff --git a/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java index 625e5439ee2f..b8eda2596087 100644 --- a/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java @@ -2,11 +2,12 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @EnableZuulProxy @SpringBootApplication -public class UiApplication { +public class UiApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(UiApplication.class, args); From 2263b24c9fb80b41636219319feff15b506cf4cc Mon Sep 17 00:00:00 2001 From: Roman Seleznov Date: Mon, 7 Aug 2017 21:19:41 +0100 Subject: [PATCH 28/90] BAEL-764 Renaming Modules as per the review (#2371) * Create pom.xml Initial import * First submit * Second submit * Different Types of Bean Injection in Spring * Different Types of Bean Injection in Spring * Added spring-core-di into the main build * Revert "Create pom.xml" This reverts commit 1bdc5443125df19575605f41ab28c9e8b6c69a32. * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot Make executable jars for property-exp-default project and use mvn exec:java to run property-exp-default project * BAEL-764 Automatic Property Expansion with Spring Boot Rename modules as per code reivew --- spring-boot-property-exp/pom.xml | 4 ++-- .../pom.xml | 0 .../propertyexpansion/SpringBootPropertyExpansionApp.java | 0 .../propertyexpansion/components/PropertyLoggerBean.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/banner.txt | 0 .../build.gradle | 0 .../gradle.properties | 0 .../pom.xml | 0 .../settings.gradle | 0 .../propertyexpansion/SpringBootPropertyExpansionApp.java | 0 .../propertyexpansion/components/PropertyLoggerBean.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/banner.txt | 0 14 files changed, 2 insertions(+), 2 deletions(-) rename spring-boot-property-exp/{property-exp-custom => property-exp-custom-config}/pom.xml (100%) rename spring-boot-property-exp/{property-exp-custom => property-exp-custom-config}/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java (100%) rename spring-boot-property-exp/{property-exp-custom => property-exp-custom-config}/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java (100%) rename spring-boot-property-exp/{property-exp-custom => property-exp-custom-config}/src/main/resources/application.properties (100%) rename spring-boot-property-exp/{property-exp-custom => property-exp-custom-config}/src/main/resources/banner.txt (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/build.gradle (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/gradle.properties (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/pom.xml (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/settings.gradle (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/src/main/resources/application.properties (100%) rename spring-boot-property-exp/{property-exp-default => property-exp-default-config}/src/main/resources/banner.txt (100%) diff --git a/spring-boot-property-exp/pom.xml b/spring-boot-property-exp/pom.xml index f554bb5b9913..0c54d57db1e4 100644 --- a/spring-boot-property-exp/pom.xml +++ b/spring-boot-property-exp/pom.xml @@ -24,8 +24,8 @@ - property-exp-default - property-exp-custom + property-exp-default-config + property-exp-custom-config diff --git a/spring-boot-property-exp/property-exp-custom/pom.xml b/spring-boot-property-exp/property-exp-custom-config/pom.xml similarity index 100% rename from spring-boot-property-exp/property-exp-custom/pom.xml rename to spring-boot-property-exp/property-exp-custom-config/pom.xml diff --git a/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java b/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java rename to spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java diff --git a/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java b/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java rename to spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java diff --git a/spring-boot-property-exp/property-exp-custom/src/main/resources/application.properties b/spring-boot-property-exp/property-exp-custom-config/src/main/resources/application.properties similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/resources/application.properties rename to spring-boot-property-exp/property-exp-custom-config/src/main/resources/application.properties diff --git a/spring-boot-property-exp/property-exp-custom/src/main/resources/banner.txt b/spring-boot-property-exp/property-exp-custom-config/src/main/resources/banner.txt similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/resources/banner.txt rename to spring-boot-property-exp/property-exp-custom-config/src/main/resources/banner.txt diff --git a/spring-boot-property-exp/property-exp-default/build.gradle b/spring-boot-property-exp/property-exp-default-config/build.gradle similarity index 100% rename from spring-boot-property-exp/property-exp-default/build.gradle rename to spring-boot-property-exp/property-exp-default-config/build.gradle diff --git a/spring-boot-property-exp/property-exp-default/gradle.properties b/spring-boot-property-exp/property-exp-default-config/gradle.properties similarity index 100% rename from spring-boot-property-exp/property-exp-default/gradle.properties rename to spring-boot-property-exp/property-exp-default-config/gradle.properties diff --git a/spring-boot-property-exp/property-exp-default/pom.xml b/spring-boot-property-exp/property-exp-default-config/pom.xml similarity index 100% rename from spring-boot-property-exp/property-exp-default/pom.xml rename to spring-boot-property-exp/property-exp-default-config/pom.xml diff --git a/spring-boot-property-exp/property-exp-default/settings.gradle b/spring-boot-property-exp/property-exp-default-config/settings.gradle similarity index 100% rename from spring-boot-property-exp/property-exp-default/settings.gradle rename to spring-boot-property-exp/property-exp-default-config/settings.gradle diff --git a/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java b/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java rename to spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java diff --git a/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java b/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java rename to spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java diff --git a/spring-boot-property-exp/property-exp-default/src/main/resources/application.properties b/spring-boot-property-exp/property-exp-default-config/src/main/resources/application.properties similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/resources/application.properties rename to spring-boot-property-exp/property-exp-default-config/src/main/resources/application.properties diff --git a/spring-boot-property-exp/property-exp-default/src/main/resources/banner.txt b/spring-boot-property-exp/property-exp-default-config/src/main/resources/banner.txt similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/resources/banner.txt rename to spring-boot-property-exp/property-exp-default-config/src/main/resources/banner.txt From 1824320f95fda5a87347803fb9c1297feff4a2a6 Mon Sep 17 00:00:00 2001 From: cleversonzanon Date: Mon, 7 Aug 2017 18:14:57 -0300 Subject: [PATCH 29/90] [BAEL-1066] Implementing Singleton pattern in Java (#2361) * Different Types of Bean Injection in Spring code * Dataclasses in Kotlin * Revert "Different Types of Bean Injection in Spring code" This reverts commit 4b747726b93a9f6bf76d6518792fc77e0d5c2fc9. * Destructuring Declarations in Kotlin * Corrections on Destructuring Declarations in Kotlin * Implementing Singleton pattern in Java * [BAEL-1066] Implementing Singleton pattern in Java * Singleton Implementation changes. --- .../singleton/ClassSingleton.java | 28 ++++++++++++++++ .../singleton/EnumSingleton.java | 26 +++++++++++++++ .../designpatterns/singleton/Sandbox.java | 32 +++++++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java new file mode 100644 index 000000000000..0fc86e30a793 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java @@ -0,0 +1,28 @@ +package com.baeldung.designpatterns.singleton; + +public class ClassSingleton { + + private static ClassSingleton INSTANCE; + private String info = "Initial class info"; + + private ClassSingleton(){ + } + + public static ClassSingleton getInstance(){ + if(INSTANCE == null){ + INSTANCE = new ClassSingleton(); + } + + return INSTANCE; + } + + // getters and setters + + public String getInfo() { + return info; + } + + public void setInfo(String info) { + this.info = info; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java new file mode 100644 index 000000000000..f75484477ba2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java @@ -0,0 +1,26 @@ +package com.baeldung.designpatterns.singleton; + +public enum EnumSingleton { + + INSTANCE("Initial enum info"); //Name of the single instance + + private String info; + + private EnumSingleton(String info) { + this.info = info; + } + + public EnumSingleton getInstance(){ + return INSTANCE; + } + + //getters and setters + + public String getInfo() { + return info; + } + + public void setInfo(String info) { + this.info = info; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java new file mode 100644 index 000000000000..f8ca2ffa7813 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java @@ -0,0 +1,32 @@ +package com.baeldung.designpatterns.singleton; + +public class Sandbox { + + public static void main(String[] args) { + + //Class singleton + + ClassSingleton classSingleton1 = ClassSingleton.getInstance(); + //OurSingleton object1 = new OurSingleton(); // The constructor OurSingleton() is not visible + + System.out.println(classSingleton1.getInfo()); //Initial class info + + ClassSingleton classSingleton2 = ClassSingleton.getInstance(); + classSingleton2.setInfo("New class info"); + + System.out.println(classSingleton1.getInfo()); //New class info + System.out.println(classSingleton2.getInfo()); //New class info + + //Enum singleton + + EnumSingleton enumSingleton1 = EnumSingleton.INSTANCE.getInstance(); + + System.out.println(enumSingleton1.getInfo()); //Initial enum info + + EnumSingleton enumSingleton2 = EnumSingleton.INSTANCE.getInstance(); + enumSingleton2.setInfo("New enum info"); + + System.out.println(enumSingleton1.getInfo()); //New enum info + System.out.println(enumSingleton2.getInfo()); //New enum info + } +} From 53433a06d899571a22d08405208b441e439b9e01 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Mon, 7 Aug 2017 17:45:03 -0500 Subject: [PATCH 30/90] README updates (#2389) * BAEL-886: Updated README * BAEL-917 Testing with Google Truth Updated README * BAEL-936: adding akka-streams module to parent * BAEL-936: Update README * BAEL-918: Update README * BAEL-980: Update README * BAEL-967: Update README * BAEL-509: Using @GetMapping instead of @RequestMapping with method=GET * BAEL-1005: Update README * BAEL-509: Security and WebSockets (README) * BAEL-861: Intro to Awaitility (README) * BAEL-1010: Guide to the HyperLogLog Algorithm (README) * BAEL-907: Guide to Apache Commons CircularFifoQueue (README) * BAEL-1086: README update * BAEL-644: README update --- libraries/README.md | 1 + spring-core/README.md | 1 + 2 files changed, 2 insertions(+) diff --git a/libraries/README.md b/libraries/README.md index 86baa39045bd..0e586281185f 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -28,6 +28,7 @@ - [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) - [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph) - [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) +- [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/spring-core/README.md b/spring-core/README.md index 380b3138fe9a..b0d0b8408c26 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -6,3 +6,4 @@ - [Constructor Injection in Spring with Lombok](http://www.baeldung.com/spring-injection-lombok) - [A Quick Guide to Spring @Value](http://www.baeldung.com/spring-value-annotation) - [Spring YAML Configuration](http://www.baeldung.com/spring-yaml) +- [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults) From 415b80d03f554f6535a4b74172ddf8daffc39ed8 Mon Sep 17 00:00:00 2001 From: ramansahasi Date: Tue, 8 Aug 2017 23:26:53 +0530 Subject: [PATCH 31/90] BAEL-1072 - Difference between Proxy, Decorator, Adapter, and Bridge Patterns (#2390) * Structural Design Patterns Difference between several types of structural design patterns * Structural Design Pattern Difference between several types of structural design patterns * Structural Design Patterns Difference between several types of structural design patterns * Structural Design Patterns Difference between several types of structural design patterns --- core-java/pom.xml | 6 ++- .../adapter/AdapterPatternDriver.java | 13 +++++ .../adapter/LuxuryCarsSpeed.java | 15 ++++++ .../adapter/LuxuryCarsSpeedAdapter.java | 7 +++ .../adapter/LuxuryCarsSpeedAdapterImpl.java | 26 ++++++++++ .../baeldung/designpatterns/bridge/Blue.java | 12 +++++ .../bridge/BridgePatternDriver.java | 14 +++++ .../baeldung/designpatterns/bridge/Color.java | 5 ++ .../baeldung/designpatterns/bridge/Red.java | 12 +++++ .../baeldung/designpatterns/bridge/Shape.java | 11 ++++ .../designpatterns/bridge/Square.java | 16 ++++++ .../designpatterns/bridge/Triangle.java | 16 ++++++ .../decorator/BubbleLights.java | 16 ++++++ .../decorator/ChristmasTree.java | 5 ++ .../decorator/ChristmasTreeImpl.java | 10 ++++ .../decorator/DecoratorPatternDriver.java | 20 +++++++ .../designpatterns/decorator/Garland.java | 16 ++++++ .../decorator/TreeDecorator.java | 15 ++++++ .../designpatterns/proxy/ExpensiveObject.java | 5 ++ .../proxy/ExpensiveObjectImpl.java | 20 +++++++ .../proxy/ExpensiveObjectProxy.java | 13 +++++ .../proxy/ProxyPatternDriver.java | 9 ++++ .../designpatterns/util/LogerUtil.java | 35 +++++++++++++ .../resources/log4jstructuraldp.properties | 9 ++++ .../AdapterPatternIntegrationTest.java | 20 +++++++ .../BridgePatternIntegrationTest.java | 52 +++++++++++++++++++ .../DecoratorPatternIntegrationTest.java | 28 ++++++++++ .../ProxyPatternIntegrationTest.java | 44 ++++++++++++++++ .../designpatterns/TestAppenderDP.java | 29 +++++++++++ 29 files changed, 498 insertions(+), 1 deletion(-) create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java create mode 100644 core-java/src/main/resources/log4jstructuraldp.properties create mode 100644 core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java create mode 100644 core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java create mode 100644 core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java create mode 100644 core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java create mode 100644 core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java diff --git a/core-java/pom.xml b/core-java/pom.xml index 73b1c22ed843..422965a0ed9e 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -80,7 +80,11 @@ - + + log4j + log4j + 1.2.17 + org.slf4j slf4j-api diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java new file mode 100644 index 000000000000..0d69d0e7ec65 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java @@ -0,0 +1,13 @@ +package com.baeldung.designpatterns.adapter; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class AdapterPatternDriver { + + public static void main(String args[]) { + LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl(); + LOG.info("Bugatti Veyron Super Sport's top speed is " + luxuryCars.bugattiVeyronInKMPH() + " Kmph."); + LOG.info("McLaren F1 top speed is " + luxuryCars.mcLarenInKMPH() + " Kmph."); + LOG.info("Aston Martin One-77 top speed is " + luxuryCars.astonMartinInKMPH() + " Kmph."); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java new file mode 100644 index 000000000000..278329b994d0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.adapter; + +public class LuxuryCarsSpeed { + public double bugattiVeyronInMPH() { + return 268; + } + + public double mcLarenInMPH() { + return 241; + } + + public double astonMartinInMPH() { + return 220; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java new file mode 100644 index 000000000000..84f7be2729dd --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java @@ -0,0 +1,7 @@ +package com.baeldung.designpatterns.adapter; + +public interface LuxuryCarsSpeedAdapter { + public double bugattiVeyronInKMPH(); + public double mcLarenInKMPH(); + public double astonMartinInKMPH(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java new file mode 100644 index 000000000000..2767b78e38df --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java @@ -0,0 +1,26 @@ +package com.baeldung.designpatterns.adapter; + +public class LuxuryCarsSpeedAdapterImpl extends LuxuryCarsSpeed implements LuxuryCarsSpeedAdapter { + + @Override + public double bugattiVeyronInKMPH() { + double mph = super.bugattiVeyronInMPH(); + return convertMPHtoKMPH(mph); + } + + @Override + public double mcLarenInKMPH() { + double mph = super.mcLarenInMPH(); + return convertMPHtoKMPH(mph); + } + + @Override + public double astonMartinInKMPH() { + double mph = super.astonMartinInMPH(); + return convertMPHtoKMPH(mph); + } + + private double convertMPHtoKMPH(double mph) { + return mph * 1.60934; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java new file mode 100644 index 000000000000..97a4a9508cf6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java @@ -0,0 +1,12 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Blue implements Color { + + @Override + public void fillColor() { + LOG.info("Color : Blue"); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java new file mode 100644 index 000000000000..921deadcac32 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java @@ -0,0 +1,14 @@ +package com.baeldung.designpatterns.bridge; + +public class BridgePatternDriver { + + public static void main(String[] args) { + //a square with red color + Shape square = new Square(new Red()); + square.drawShape(); + + //a triangle with blue color + Shape triangle = new Triangle(new Blue()); + triangle.drawShape(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java new file mode 100644 index 000000000000..91d2b016096b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.bridge; + +public interface Color { + public void fillColor(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java new file mode 100644 index 000000000000..8c22a94f002d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java @@ -0,0 +1,12 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Red implements Color { + + @Override + public void fillColor() { + LOG.info("Color : Red"); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java new file mode 100644 index 000000000000..c4daf7a821d0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java @@ -0,0 +1,11 @@ +package com.baeldung.designpatterns.bridge; + +public abstract class Shape { + protected Color color; + + public Shape(Color color) { + this.color = color; + } + + abstract public void drawShape(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java new file mode 100644 index 000000000000..6b377197ebf2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Square extends Shape { + + public Square(Color color) { + super(color); + } + + @Override + public void drawShape() { + LOG.info("Square drawn. "); + color.fillColor(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java new file mode 100644 index 000000000000..900e78cf2b7b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Triangle extends Shape { + + public Triangle(Color color) { + super(color); + } + + @Override + public void drawShape() { + LOG.info("Triangle drawn. "); + color.fillColor(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java new file mode 100644 index 000000000000..881add8b2110 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.decorator; + +public class BubbleLights extends TreeDecorator { + + public BubbleLights(ChristmasTree tree) { + super(tree); + } + + public String decorate() { + return super.decorate() + decorateWithBubbleLights(); + } + + private String decorateWithBubbleLights() { + return " with Bubble Lights"; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java new file mode 100644 index 000000000000..80a0865567b7 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.decorator; + +public interface ChristmasTree { + public String decorate(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java new file mode 100644 index 000000000000..9241fd59db05 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.decorator; + +public class ChristmasTreeImpl implements ChristmasTree { + + @Override + public String decorate() { + return "Christmas tree"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java new file mode 100644 index 000000000000..f70991da6bf2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java @@ -0,0 +1,20 @@ +package com.baeldung.designpatterns.decorator; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class DecoratorPatternDriver { + + public static void main(String[] args) { + //christmas tree with just one Garland + ChristmasTree tree1 = new Garland(new ChristmasTreeImpl()); + LOG.info(tree1.decorate()); + + //christmas tree with two Garlands and one Bubble lights + ChristmasTree tree2 = new BubbleLights(new Garland( + new Garland(new ChristmasTreeImpl())) + ); + LOG.info(tree2.decorate()); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java new file mode 100644 index 000000000000..d2efd6e4519e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.decorator; + +public class Garland extends TreeDecorator { + + public Garland(ChristmasTree tree) { + super(tree); + } + + public String decorate() { + return super.decorate() + decorateWithGarland(); + } + + private String decorateWithGarland() { + return " with Garland"; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java new file mode 100644 index 000000000000..5427d2ac7edf --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.decorator; + +public abstract class TreeDecorator implements ChristmasTree { + private ChristmasTree tree; + + public TreeDecorator(ChristmasTree tree) { + this.tree = tree; + } + + @Override + public String decorate() { + return tree.decorate(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java new file mode 100644 index 000000000000..96a6bfb8780b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.proxy; + +public interface ExpensiveObject { + public void process(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java new file mode 100644 index 000000000000..7014d3811cbe --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java @@ -0,0 +1,20 @@ +package com.baeldung.designpatterns.proxy; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG;; + +public class ExpensiveObjectImpl implements ExpensiveObject { + + public ExpensiveObjectImpl() { + heavyInitialConfiguration(); + } + + @Override + public void process() { + LOG.info("processing complete."); + } + + private void heavyInitialConfiguration() { + LOG.info("Loading initial configuration..."); + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java new file mode 100644 index 000000000000..f36e688c90d0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java @@ -0,0 +1,13 @@ +package com.baeldung.designpatterns.proxy; + +public class ExpensiveObjectProxy implements ExpensiveObject{ + private static ExpensiveObject object; + + @Override + public void process() { + if(object == null) { + object = new ExpensiveObjectImpl(); + } + object.process(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java new file mode 100644 index 000000000000..088b069e284e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java @@ -0,0 +1,9 @@ +package com.baeldung.designpatterns.proxy; + +public class ProxyPatternDriver { + public static void main(String[] args) { + ExpensiveObject object = new ExpensiveObjectProxy(); + object.process(); + object.process(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java b/core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java new file mode 100644 index 000000000000..f7b6e4f3e900 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java @@ -0,0 +1,35 @@ +package com.baeldung.designpatterns.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Properties; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; + +public class LogerUtil { + + public final static Logger LOG = Logger.getLogger("GLOBAL"); + + static { + configuration(); + } + + private static void configuration() { + Properties props = new Properties(); + try { + props.load( + new BufferedReader( + new InputStreamReader( + LogerUtil.class.getResourceAsStream("/log4jstructuraldp.properties") + ) + ) + ); + } catch (IOException e) { + System.out.println("log4jstructuraldp.properties file not configured properly"); + System.exit(0); + } + PropertyConfigurator.configure(props); + } +} diff --git a/core-java/src/main/resources/log4jstructuraldp.properties b/core-java/src/main/resources/log4jstructuraldp.properties new file mode 100644 index 000000000000..5bc2bfe4b9ee --- /dev/null +++ b/core-java/src/main/resources/log4jstructuraldp.properties @@ -0,0 +1,9 @@ + +# Root logger +log4j.rootLogger=INFO, file, stdout + +# Write to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java new file mode 100644 index 000000000000..fb483a8a6868 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java @@ -0,0 +1,20 @@ +package com.baeldung.designpatterns; + + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapter; +import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapterImpl; + +public class AdapterPatternIntegrationTest { + @Test + public void givenLuxuryCarsAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() { + LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl(); + assertEquals(luxuryCars.bugattiVeyronInKMPH(), 431.30312, 0.00001); + assertEquals(luxuryCars.mcLarenInKMPH(), 387.85094, 0.00001); + assertEquals(luxuryCars.astonMartinInKMPH(), 354.0548, 0.00001); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java new file mode 100644 index 000000000000..56a7a704f214 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.designpatterns; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.apache.log4j.spi.LoggingEvent; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.designpatterns.bridge.Blue; +import com.baeldung.designpatterns.bridge.Red; +import com.baeldung.designpatterns.bridge.Shape; +import com.baeldung.designpatterns.bridge.Square; +import com.baeldung.designpatterns.bridge.Triangle; + +public class BridgePatternIntegrationTest { + public static TestAppenderDP appender; + + @Before + public void setUp() { + appender = new TestAppenderDP(); + LOG.addAppender(appender); + } + + @Test + public void whenBridgePatternInvoked_thenConfigSuccess() { + //a square with red color + Shape square = new Square(new Red()); + square.drawShape(); + + //a triangle with blue color + Shape triangle = new Triangle(new Blue()); + triangle.drawShape(); + + final List log = appender.getLog(); + + assertThat((String) log.get(0).getMessage(), is("Square drawn. ")); + assertThat((String) log.get(1).getMessage(), is("Color : Red")); + assertThat((String) log.get(2).getMessage(), is("Triangle drawn. ")); + assertThat((String) log.get(3).getMessage(), is("Color : Blue")); + } + + @After + public void tearDown() { + LOG.removeAppender(appender); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java new file mode 100644 index 000000000000..b3b3f988f17c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java @@ -0,0 +1,28 @@ +package com.baeldung.designpatterns; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.designpatterns.decorator.BubbleLights; +import com.baeldung.designpatterns.decorator.ChristmasTree; +import com.baeldung.designpatterns.decorator.ChristmasTreeImpl; +import com.baeldung.designpatterns.decorator.Garland; + +public class DecoratorPatternIntegrationTest { + private ChristmasTree tree; + + @Test + public void givenDecoratorPattern_WhenDecoratorsInjectedAtRuntime_thenConfigSuccess() { + //christmas tree with just one Garland + tree = new Garland(new ChristmasTreeImpl()); + assertEquals(tree.decorate(), "Christmas tree with Garland"); + + //christmas tree with two Garlands and one Bubble lights + tree = new BubbleLights(new Garland( + new Garland(new ChristmasTreeImpl())) + ); + assertEquals(tree.decorate(), "Christmas tree with Garland with Garland with Bubble Lights"); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java new file mode 100644 index 000000000000..7fa95b31d71e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java @@ -0,0 +1,44 @@ +package com.baeldung.designpatterns; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.apache.log4j.spi.LoggingEvent; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.designpatterns.proxy.ExpensiveObject; +import com.baeldung.designpatterns.proxy.ExpensiveObjectProxy; + +public class ProxyPatternIntegrationTest { + public static TestAppenderDP appender; + + @Before + public void setUp() { + appender = new TestAppenderDP(); + LOG.addAppender(appender); + } + + @Test + public void givenExpensiveObjectProxy_WhenObjectInitialized_thenInitializedOnlyOnce() { + ExpensiveObject object = new ExpensiveObjectProxy(); + object.process(); + object.process(); + + final List log = appender.getLog(); + + assertThat((String) log.get(0).getMessage(), is("Loading initial configuration...")); + assertThat((String) log.get(1).getMessage(), is("processing complete.")); + assertThat((String) log.get(2).getMessage(), is("processing complete.")); + } + + @After + public void tearDown() { + LOG.removeAppender(appender); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java b/core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java new file mode 100644 index 000000000000..613c26fa1378 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java @@ -0,0 +1,29 @@ +package com.baeldung.designpatterns; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; + +public class TestAppenderDP extends AppenderSkeleton { + private final List log = new ArrayList(); + + @Override + public boolean requiresLayout() { + return false; + } + + @Override + protected void append(final LoggingEvent loggingEvent) { + log.add(loggingEvent); + } + + @Override + public void close() { + } + + public List getLog() { + return new ArrayList(log); + } +} \ No newline at end of file From 2036138ed17fc71fea05f52e9e8e7130825fbf7c Mon Sep 17 00:00:00 2001 From: Eric Goebelbecker Date: Wed, 9 Aug 2017 02:19:15 -0400 Subject: [PATCH 32/90] BAEL-1044 - Introduction to NoException (#2394) * BAEL-1044 - Introduction to NoException * BAEL-1044 - Introduction to NoException --- noexception/README.md | 2 + noexception/pom.xml | 23 +++++++ .../noexception/CustomExceptionHandler.java | 24 +++++++ .../noexception/NoExceptionUnitTest.java | 63 +++++++++++++++++++ pom.xml | 1 + 5 files changed, 113 insertions(+) create mode 100644 noexception/README.md create mode 100644 noexception/pom.xml create mode 100644 noexception/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java create mode 100644 noexception/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java diff --git a/noexception/README.md b/noexception/README.md new file mode 100644 index 000000000000..d840191369ac --- /dev/null +++ b/noexception/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception) diff --git a/noexception/pom.xml b/noexception/pom.xml new file mode 100644 index 000000000000..64c0591fda19 --- /dev/null +++ b/noexception/pom.xml @@ -0,0 +1,23 @@ + + 4.0.0 + + com.baeldung + noexception + 1.0 + noexception + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.machinezoo.noexception + noexception + 1.1.0 + + + diff --git a/noexception/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java b/noexception/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java new file mode 100644 index 000000000000..59e13efaa056 --- /dev/null +++ b/noexception/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java @@ -0,0 +1,24 @@ +package com.baeldung.noexception; + +import com.machinezoo.noexception.ExceptionHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CustomExceptionHandler extends ExceptionHandler { + + private Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class); + + @Override + public boolean handle(Throwable throwable) { + + if (throwable.getClass() + .isAssignableFrom(RuntimeException.class) + || throwable.getClass() + .isAssignableFrom(Error.class)) { + return false; + } else { + logger.error("Caught Exception ", throwable); + return true; + } + } +} diff --git a/noexception/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java b/noexception/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java new file mode 100644 index 000000000000..690ea4352010 --- /dev/null +++ b/noexception/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.noexception; + +import com.machinezoo.noexception.Exceptions; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NoExceptionUnitTest { + + private static Logger logger = LoggerFactory.getLogger(NoExceptionUnitTest.class); + + @Test + public void whenStdExceptionHandling_thenCatchAndLog() { + try { + System.out.println("Result is " + Integer.parseInt("foobar")); + } catch (Throwable exception) { + logger.error("Caught exception:", exception); + } + } + + @Test + public void whenDefaultNoException_thenCatchAndLog() { + + Exceptions.log().run(() -> System.out.println("Result is " + Integer.parseInt("foobar"))); + } + + @Test + public void givenLogger_whenDefaultNoException_thenCatchAndLogWithClassName() { + System.out.println("Result is " + Exceptions.log(logger).get(() -> +Integer.parseInt("foobar")).orElse(-1)); + } + + @Test + public void givenLoggerAndMessage_whenDefaultNoException_thenCatchAndLogWithClassNameAndMessage() { + System.out.println("Result is " + Exceptions.log(logger, "Something went wrong:").get(() -> +Integer.parseInt("foobar")).orElse(-1)); + } + + @Test + public void givenDefaultValue_whenDefaultNoException_thenCatchAndLogPrintDefault() { + System.out.println("Result is " + Exceptions.log(logger, "Something went wrong:").get(() -> +Integer.parseInt("foobar")).orElse(-1)); + } + + @Test(expected = Error.class) + public void givenCustomHandler_whenError_thenRethrowError() { + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); + customExceptionHandler.run(() -> throwError()); + } + + @Test + public void givenCustomHandler_whenException_thenCatchAndLog() { + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); + customExceptionHandler.run(() -> throwException()); + } + + private static void throwError() { + throw new Error("This is very bad."); + } + + private static void throwException() { + String testString = "foo"; + testString.charAt(5); + } + +} diff --git a/pom.xml b/pom.xml index f33d63bc48d9..8b3df8de0d8e 100644 --- a/pom.xml +++ b/pom.xml @@ -106,6 +106,7 @@ mockito2 mocks mustache + noexception orika From 69f3e1175ace4edf9e2cfb5526060f431bfeead1 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Wed, 9 Aug 2017 15:30:02 +0200 Subject: [PATCH 33/90] minor fix (#2398) * fix spring config * fix spring config * fix spring config * minor fix --- apache-velocity/src/main/webapp/WEB-INF/velocity.properties | 2 +- spring-jpa/pom.xml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/apache-velocity/src/main/webapp/WEB-INF/velocity.properties b/apache-velocity/src/main/webapp/WEB-INF/velocity.properties index 00e0b7e41040..97b19f4cb7e7 100644 --- a/apache-velocity/src/main/webapp/WEB-INF/velocity.properties +++ b/apache-velocity/src/main/webapp/WEB-INF/velocity.properties @@ -1,4 +1,4 @@ resource.loader=webapp webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader -webapp.resource.loader.path = . +webapp.resource.loader.path = webapp.resource.loader.cache = true \ No newline at end of file diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index 1a1e6b31527a..6a67d44b48eb 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -102,6 +102,7 @@ javax.servlet servlet-api + provided ${javax.servlet.servlet-api.version} From b5478f7e9a7d8a0b29040f58572b346e8527c85f Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 9 Aug 2017 15:32:08 +0200 Subject: [PATCH 34/90] Build opt 9 08 2017 (#2397) * pCollections * Reformat * Refactor metrics * Refactor hoverfly --- .../java/com/baeldung/hll/HLLUnitTest.java | 18 ++++++------ ...t.java => HoverflyApiIntegrationTest.java} | 2 +- .../pcollections/PCollectionsUnitTest.java | 29 ++++++++++++------- .../metrics/servo/AtlasObserverLiveTest.java | 3 -- ...t.java => MetricAnnotationManualTest.java} | 5 +--- ...est.java => MetricObserverManualTest.java} | 12 ++++---- ...rTest.java => MetricPollerManualTest.java} | 15 ++++++---- .../metrics/servo/MetricTestBase.java | 10 ++++--- .../metrics/servo/MetricTypeTest.java | 28 +++++++++++++----- 9 files changed, 72 insertions(+), 50 deletions(-) rename libraries/src/test/java/com/baeldung/hoverfly/{HoverflyApiTest.java => HoverflyApiIntegrationTest.java} (99%) rename metrics/src/test/java/com/baeldung/metrics/servo/{MetricAnnotationTest.java => MetricAnnotationManualTest.java} (95%) rename metrics/src/test/java/com/baeldung/metrics/servo/{MetricObserverTest.java => MetricObserverManualTest.java} (86%) rename metrics/src/test/java/com/baeldung/metrics/servo/{MetricPollerTest.java => MetricPollerManualTest.java} (74%) diff --git a/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java b/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java index 8d09c99f0f1e..e208add3c860 100644 --- a/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java +++ b/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java @@ -23,9 +23,9 @@ public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardina //when LongStream.range(0, numberOfElements).forEach(element -> { - long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); - hll.addRaw(hashedValue); - } + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + hll.addRaw(hashedValue); + } ); //then @@ -44,15 +44,15 @@ public void givenTwoHLLs_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCar //when LongStream.range(0, numberOfElements).forEach(element -> { - long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); - firstHll.addRaw(hashedValue); - } + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + firstHll.addRaw(hashedValue); + } ); LongStream.range(numberOfElements, numberOfElements * 2).forEach(element -> { - long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); - secondHLL.addRaw(hashedValue); - } + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + secondHLL.addRaw(hashedValue); + } ); //then diff --git a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java similarity index 99% rename from libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java rename to libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java index bdaf4d7bd999..167aef5ec6d5 100644 --- a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java +++ b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java @@ -31,7 +31,7 @@ import io.specto.hoverfly.junit.core.SimulationSource; import io.specto.hoverfly.junit.rule.HoverflyRule; -public class HoverflyApiTest { +public class HoverflyApiIntegrationTest { private static final SimulationSource source = dsl( service("http://www.baeldung.com") diff --git a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java index 23f9abf2f31e..acc7718ea8fc 100644 --- a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java @@ -1,7 +1,12 @@ package com.baeldung.pcollections; import org.junit.Test; -import org.pcollections.*; +import org.pcollections.HashPMap; +import org.pcollections.HashTreePMap; +import org.pcollections.HashTreePSet; +import org.pcollections.MapPSet; +import org.pcollections.PVector; +import org.pcollections.TreePVector; import java.util.Arrays; import java.util.HashMap; @@ -27,7 +32,7 @@ public void givenKeyValue_whenSingleton_thenCreateNonEmptyHashPMap() { @Test public void givenExistingHashMap_whenFrom_thenCreateHashPMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("mkey1", "mval1"); map.put("mkey2", "mval2"); @@ -41,7 +46,7 @@ public void whenHashPMapMethods_thenPerformOperations() { HashPMap pmap = HashTreePMap.empty(); HashPMap pmap0 = pmap.plus("key1", "value1"); - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("key2", "val2"); map.put("key3", "val3"); @@ -57,22 +62,24 @@ public void whenHashPMapMethods_thenPerformOperations() { @Test public void whenTreePVectorMethods_thenPerformOperations() { - TreePVector pVector = TreePVector.empty(); + TreePVector pVector = TreePVector.empty(); + + TreePVector pV1 = pVector.plus("e1"); + TreePVector pV2 = pV1.plusAll(Arrays.asList("e2", "e3", "e4")); - TreePVector pV1 = pVector.plus("e1"); - TreePVector pV2 = pV1.plusAll(Arrays.asList("e2", "e3", "e4")); assertEquals(1, pV1.size()); assertEquals(4, pV2.size()); - TreePVector pV3 = pV2.minus("e1"); - TreePVector pV4 = pV3.minusAll(Arrays.asList("e2", "e3", "e4")); + TreePVector pV3 = pV2.minus("e1"); + TreePVector pV4 = pV3.minusAll(Arrays.asList("e2", "e3", "e4")); + assertEquals(pV3.size(), 3); assertEquals(pV4.size(), 0); - TreePVector pSub = pV2.subList(0, 2); + TreePVector pSub = pV2.subList(0, 2); assertTrue(pSub.contains("e1") && pSub.contains("e2")); - TreePVector pVW = (TreePVector) pV2.with(0, "e10"); + PVector pVW = pV2.with(0, "e10"); assertEquals(pVW.get(0), "e10"); } @@ -80,7 +87,7 @@ public void whenTreePVectorMethods_thenPerformOperations() { public void whenMapPSetMethods_thenPerformOperations() { MapPSet pSet = HashTreePSet.empty() - .plusAll(Arrays.asList("e1","e2","e3","e4")); + .plusAll(Arrays.asList("e1", "e2", "e3", "e4")); assertEquals(pSet.size(), 4); MapPSet pSet1 = pSet.minus("e4"); diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java index cc2d3aa39318..134c3c91cf16 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java @@ -27,9 +27,6 @@ import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; -/** - * @author aiet - */ public class AtlasObserverLiveTest { private final String atlasUri = "http://localhost:7101/api/v1"; diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationManualTest.java similarity index 95% rename from metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationTest.java rename to metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationManualTest.java index 3d6a73912f57..2f908531f6b2 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationManualTest.java @@ -22,10 +22,7 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -/** - * @author aiet - */ -public class MetricAnnotationTest extends MetricTestBase { +public class MetricAnnotationManualTest extends MetricTestBase { @Monitor(name = "integerCounter", type = DataSourceType.COUNTER, description = "Total number of update operations.") private final AtomicInteger updateCount = new AtomicInteger(0); diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverManualTest.java similarity index 86% rename from metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverTest.java rename to metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverManualTest.java index 14d3c2646fc9..3bb421b3ef98 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverManualTest.java @@ -13,14 +13,16 @@ import static com.netflix.servo.annotations.DataSourceType.GAUGE; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -/** - * @author aiet - */ -public class MetricObserverTest extends MetricTestBase { +public class MetricObserverManualTest extends MetricTestBase { @Test public void givenMetrics_whenRegister_thenMonitored() throws InterruptedException { diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerManualTest.java similarity index 74% rename from metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerTest.java rename to metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerManualTest.java index 4a9a77efde40..318170fb1f2d 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerManualTest.java @@ -1,20 +1,23 @@ package com.baeldung.metrics.servo; import com.netflix.servo.Metric; -import com.netflix.servo.publish.*; +import com.netflix.servo.publish.BasicMetricFilter; +import com.netflix.servo.publish.JvmMetricPoller; +import com.netflix.servo.publish.MemoryMetricObserver; +import com.netflix.servo.publish.PollRunnable; +import com.netflix.servo.publish.PollScheduler; import org.junit.Test; import java.util.List; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.toList; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; -/** - * @author aiet - */ -public class MetricPollerTest { +public class MetricPollerManualTest { @Test public void givenJvmPoller_whenMonitor_thenDataCollected() throws Exception { diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTestBase.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTestBase.java index 86a9d201e8a5..42f3c72e9744 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTestBase.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTestBase.java @@ -1,14 +1,16 @@ package com.baeldung.metrics.servo; -import com.netflix.servo.publish.*; +import com.netflix.servo.publish.BasicMetricFilter; +import com.netflix.servo.publish.MemoryMetricObserver; +import com.netflix.servo.publish.MetricFilter; +import com.netflix.servo.publish.MonitorRegistryMetricPoller; +import com.netflix.servo.publish.PollRunnable; +import com.netflix.servo.publish.PollScheduler; import org.junit.After; import org.junit.Before; import static java.util.concurrent.TimeUnit.SECONDS; -/** - * @author aiet - */ abstract class MetricTestBase { MemoryMetricObserver observer; diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java index 68ba23244d1b..99009f8d840e 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java @@ -1,6 +1,21 @@ package com.baeldung.metrics.servo; -import com.netflix.servo.monitor.*; +import com.netflix.servo.monitor.BasicCounter; +import com.netflix.servo.monitor.BasicGauge; +import com.netflix.servo.monitor.BasicInformational; +import com.netflix.servo.monitor.BasicTimer; +import com.netflix.servo.monitor.BucketConfig; +import com.netflix.servo.monitor.BucketTimer; +import com.netflix.servo.monitor.Counter; +import com.netflix.servo.monitor.Gauge; +import com.netflix.servo.monitor.MaxGauge; +import com.netflix.servo.monitor.Monitor; +import com.netflix.servo.monitor.MonitorConfig; +import com.netflix.servo.monitor.Monitors; +import com.netflix.servo.monitor.PeakRateCounter; +import com.netflix.servo.monitor.StatsTimer; +import com.netflix.servo.monitor.StepCounter; +import com.netflix.servo.monitor.Stopwatch; import com.netflix.servo.stats.StatsConfig; import org.junit.Ignore; import org.junit.Test; @@ -9,13 +24,12 @@ import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.toMap; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasEntry; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -/** - * Unit test for simple App. - */ public class MetricTypeTest { @Test @@ -113,7 +127,7 @@ public void givenBucketTimer_whenRecord_thenStatsCalculated() throws Exception { BucketTimer timer = new BucketTimer(MonitorConfig .builder("test") .build(), new BucketConfig.Builder() - .withBuckets(new long[] { 2L, 5L }) + .withBuckets(new long[]{2L, 5L}) .withTimeUnit(SECONDS) .build(), SECONDS); timer.record(3); @@ -150,7 +164,7 @@ public void givenStatsTimer_whenExecuteTask_thenStatsCalculated() throws Excepti .builder("test") .build(), new StatsConfig.Builder() .withComputeFrequencyMillis(2000) - .withPercentiles(new double[] { 99.0, 95.0, 90.0 }) + .withPercentiles(new double[]{99.0, 95.0, 90.0}) .withPublishMax(true) .withPublishMin(true) .withPublishCount(true) From 1a001a5a6834a57f332c0a34e023757a367fee27 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 9 Aug 2017 15:58:00 +0200 Subject: [PATCH 35/90] Activiti test as integration (#2399) --- ...ProcessEngineCreationIntegrationTest.java} | 17 +++++----- ...a => ProcessExecutionIntegrationTest.java} | 33 ++++++++++--------- 2 files changed, 26 insertions(+), 24 deletions(-) rename spring-activiti/src/test/java/com/example/activitiwithspring/{ProcessEngineCreationTests.java => ProcessEngineCreationIntegrationTest.java} (85%) rename spring-activiti/src/test/java/com/example/activitiwithspring/{ProcessExecutionTests.java => ProcessExecutionIntegrationTest.java} (85%) diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationIntegrationTest.java similarity index 85% rename from spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java rename to spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationIntegrationTest.java index 7f07191cde72..00afd14590a7 100644 --- a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationIntegrationTest.java @@ -3,11 +3,12 @@ import org.activiti.engine.ProcessEngine; import org.activiti.engine.ProcessEngineConfiguration; import org.activiti.engine.ProcessEngines; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import org.junit.Test; -public class ProcessEngineCreationTests { +public class ProcessEngineCreationIntegrationTest { @Test public void givenXMLConfig_whenGetDefault_thenGotProcessEngine() { @@ -35,7 +36,7 @@ public void givenDifferentNameXMLConfig_whenGetProcessEngineConfig_thenGotResult @Test public void givenDifferentBeanNameInXMLConfig_whenGetProcessEngineConfig_thenGotResult() { ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration - .createProcessEngineConfigurationFromResource("my.activiti.cfg.xml", "myProcessEngineConfiguration"); + .createProcessEngineConfigurationFromResource("my.activiti.cfg.xml", "myProcessEngineConfiguration"); ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); assertNotNull(processEngine); assertEquals("baeldung", processEngine.getProcessEngineConfiguration().getJdbcUsername()); @@ -45,8 +46,8 @@ public void givenDifferentBeanNameInXMLConfig_whenGetProcessEngineConfig_thenGot public void givenNoXMLConfig_whenCreateInMemProcessEngineConfig_thenCreated() { ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration(); ProcessEngine processEngine = processEngineConfiguration - .setJdbcUrl("jdbc:h2:mem:my-own-in-mem-db;DB_CLOSE_DELAY=1000") - .buildProcessEngine(); + .setJdbcUrl("jdbc:h2:mem:my-own-in-mem-db;DB_CLOSE_DELAY=1000") + .buildProcessEngine(); assertNotNull(processEngine); assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername()); } @@ -55,9 +56,9 @@ public void givenNoXMLConfig_whenCreateInMemProcessEngineConfig_thenCreated() { public void givenNoXMLConfig_whenCreateProcessEngineConfig_thenCreated() { ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration(); ProcessEngine processEngine = processEngineConfiguration - .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE) - .setJdbcUrl("jdbc:h2:mem:my-own-db;DB_CLOSE_DELAY=1000") - .buildProcessEngine(); + .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE) + .setJdbcUrl("jdbc:h2:mem:my-own-db;DB_CLOSE_DELAY=1000") + .buildProcessEngine(); assertNotNull(processEngine); assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername()); } diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionIntegrationTest.java similarity index 85% rename from spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java rename to spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionIntegrationTest.java index cae28d5281f6..9c35ea413bcd 100644 --- a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionIntegrationTest.java @@ -1,10 +1,6 @@ package com.example.activitiwithspring; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.activiti.engine.ActivitiException; import org.activiti.engine.ProcessEngine; import org.activiti.engine.ProcessEngines; @@ -13,19 +9,24 @@ import org.activiti.engine.TaskService; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; +import org.junit.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import org.junit.Test; -public class ProcessExecutionTests { +public class ProcessExecutionIntegrationTest { @Test public void givenBPMN_whenDeployProcess_thenDeployed() { ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); RepositoryService repositoryService = processEngine.getRepositoryService(); repositoryService.createDeployment() - .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") - .deploy(); + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); Long count = repositoryService.createProcessDefinitionQuery().count(); assertTrue(count >= 1); } @@ -35,8 +36,8 @@ public void givenProcessDefinition_whenStartProcessInstance_thenProcessRunning() ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); RepositoryService repositoryService = processEngine.getRepositoryService(); repositoryService.createDeployment() - .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") - .deploy(); + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); Map variables = new HashMap(); variables.put("employeeName", "Kermit"); @@ -45,7 +46,7 @@ public void givenProcessDefinition_whenStartProcessInstance_thenProcessRunning() RuntimeService runtimeService = processEngine.getRuntimeService(); ProcessInstance processInstance = runtimeService - .startProcessInstanceByKey("vacationRequest", variables); + .startProcessInstanceByKey("vacationRequest", variables); Long count = runtimeService.createProcessInstanceQuery().count(); assertTrue(count >= 1); @@ -56,8 +57,8 @@ public void givenProcessInstance_whenCompleteTask_thenProcessExecutionContinues( ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); RepositoryService repositoryService = processEngine.getRepositoryService(); repositoryService.createDeployment() - .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") - .deploy(); + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); Map variables = new HashMap(); variables.put("employeeName", "Kermit"); @@ -66,7 +67,7 @@ public void givenProcessInstance_whenCompleteTask_thenProcessExecutionContinues( RuntimeService runtimeService = processEngine.getRuntimeService(); ProcessInstance processInstance = runtimeService - .startProcessInstanceByKey("vacationRequest", variables); + .startProcessInstanceByKey("vacationRequest", variables); TaskService taskService = processEngine.getTaskService(); List tasks = taskService.createTaskQuery().taskCandidateGroup("management").list(); @@ -87,8 +88,8 @@ public void givenProcessDefinition_whenSuspend_thenNoProcessInstanceCreated() { ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); RepositoryService repositoryService = processEngine.getRepositoryService(); repositoryService.createDeployment() - .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") - .deploy(); + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); RuntimeService runtimeService = processEngine.getRuntimeService(); repositoryService.suspendProcessDefinitionByKey("vacationRequest"); From ca70e9f9fbf1d4186f4028538c61e181333fded6 Mon Sep 17 00:00:00 2001 From: Nikhil Khatwani Date: Thu, 10 Aug 2017 02:49:03 +0530 Subject: [PATCH 36/90] Changes for BAEL-332 (#2396) --- .../controller/redirect/RedirectController.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java b/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java index 472c0c8bf5da..59868593a350 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java @@ -1,11 +1,15 @@ package org.baeldung.web.controller.redirect; +import javax.servlet.http.HttpServletRequest; + +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.View; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.RedirectView; @@ -49,4 +53,16 @@ public ModelAndView redirection(final ModelMap model, @ModelAttribute("flashAttr model.addAttribute("redirectionAttribute", flashAttribute); return new ModelAndView("redirection", model); } + + @RequestMapping(value = "/redirectPostToPost", method = RequestMethod.POST) + public ModelAndView redirectPostToPost(HttpServletRequest request) { + request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT); + return new ModelAndView("redirect:/redirectedPostToPost"); + } + + @RequestMapping(value = "/redirectedPostToPost", method = RequestMethod.POST) + public ModelAndView redirectedPostToPost() { + return new ModelAndView("redirection"); + } + } \ No newline at end of file From 71ef6b2a431d8395b41ffa1387ff650a4f0b35ae Mon Sep 17 00:00:00 2001 From: Mohamed Sanaulla Date: Thu, 10 Aug 2017 04:02:17 +0300 Subject: [PATCH 37/90] code for Java 9 Objects API (#2408) --- .../language/Java9ObjectsAPIUnitTest.java | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java new file mode 100644 index 000000000000..a174e519ab9c --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.java9.language; + +import org.junit.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +import static org.hamcrest.Matchers.*; +import static org.hamcrest.MatcherAssert.assertThat; + +public class Java9ObjectsAPIUnitTest { + + @Test + public void givenNullObject_whenRequireNonNullElse_thenElse(){ + assertThat(Objects.requireNonNullElse(null, Collections.EMPTY_LIST), + is(Collections.EMPTY_LIST)); + } + + @Test + public void givenObject_whenRequireNonNullElse_thenObject(){ + assertThat(Objects.requireNonNullElse(List.of("item1", "item2"), + Collections.EMPTY_LIST), is(List.of("item1", "item2"))); + } + + @Test + public void givenObject_whenRequireNonNullElseGet_thenObject(){ + assertThat(Objects.requireNonNullElseGet(null, List::of), + is(List.of())); + } + + @Test + public void givenNumber_whenInvokeCheckIndex_thenNumber(){ + int length = 5; + + assertThat(Objects.checkIndex(4, length), is(4)); + + try{ + Objects.checkIndex(5, length); + }catch(Exception ex){ + assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); + } + } + + @Test + public void givenSubRange_whenCheckFromToIndex_thenNumber(){ + int length = 6; + + assertThat(Objects.checkFromToIndex(2,length,length), is(2)); + + try{ + Objects.checkFromToIndex(2,7,length); + }catch(Exception ex){ + assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); + } + } + + @Test + public void giveSubRange_whenCheckFromIndexSize_thenNumber(){ + int length = 6; + + assertThat(Objects.checkFromToIndex(2,5,length), is(2)); + + try{ + Objects.checkFromToIndex(2,6,length); + }catch(Exception ex){ + assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); + } + } + + +} From 146b633bacef437ea51c1d9ed0bc3526b53505b3 Mon Sep 17 00:00:00 2001 From: Makoto Go Date: Thu, 10 Aug 2017 08:27:27 -0500 Subject: [PATCH 38/90] New artifacts for BAEL-1081. (#2392) * New artifacts for BAEL-1081. * Consolidate code to new package. --- junit5/pom.xml | 8 +- .../param/InvalidPersonParameterResolver.java | 50 ++++++ .../test/java/com/baeldung/param/Person.java | 43 ++++++ .../com/baeldung/param/PersonValidator.java | 142 ++++++++++++++++++ .../baeldung/param/PersonValidatorTest.java | 102 +++++++++++++ .../param/ValidPersonParameterResolver.java | 50 ++++++ 6 files changed, 391 insertions(+), 4 deletions(-) create mode 100644 junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java create mode 100644 junit5/src/test/java/com/baeldung/param/Person.java create mode 100644 junit5/src/test/java/com/baeldung/param/PersonValidator.java create mode 100644 junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java create mode 100644 junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java diff --git a/junit5/pom.xml b/junit5/pom.xml index 2316b034e923..1fa4818447db 100644 --- a/junit5/pom.xml +++ b/junit5/pom.xml @@ -3,7 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung + junit5 1.0-SNAPSHOT @@ -19,9 +19,9 @@ UTF-8 1.8 - 5.0.0-M5 - 1.0.0-M5 - 4.12.0-M5 + 5.0.0-RC2 + 1.0.0-RC2 + 4.12.0-RC2 2.8.2 1.4.196 diff --git a/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java b/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java new file mode 100644 index 000000000000..67bd47a44a27 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java @@ -0,0 +1,50 @@ +package com.baeldung.param; + +import java.util.Random; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +public class InvalidPersonParameterResolver implements ParameterResolver { + + /** + * The "bad" (invalid) data for testing purposes has to go somewhere, right? + */ + public static Person[] INVALID_PERSONS = { + new Person().setId(1L).setLastName("Ad_ams").setFirstName("Jill,"), + new Person().setId(2L).setLastName(",Baker").setFirstName(""), + new Person().setId(3L).setLastName(null).setFirstName(null), + new Person().setId(4L).setLastName("Daniel&").setFirstName("{Joseph}"), + new Person().setId(5L).setLastName("").setFirstName("English, Jane"), + new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */, + // TODO: ADD MORE DATA HERE + }; + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + Object ret = null; + // + // Return a random, valid Person object if Person.class is the type of Parameter + /// to be resolved. Otherwise return null. + if (parameterContext.getParameter().getType() == Person.class) { + ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)]; + } + return ret; + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + boolean ret = false; + // + // If the Parameter.type == Person.class, then we support it, otherwise, get outta here! + if (parameterContext.getParameter().getType() == Person.class) { + ret = true; + } + return ret; + } + +} diff --git a/junit5/src/test/java/com/baeldung/param/Person.java b/junit5/src/test/java/com/baeldung/param/Person.java new file mode 100644 index 000000000000..65333b5e565d --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/Person.java @@ -0,0 +1,43 @@ +package com.baeldung.param; + +/** + * Very simple Person entity. + * Use the Fluent-style interface to set properties. + * + * @author J Steven Perry + * + */ +public class Person { + + private Long id; + private String lastName; + private String firstName; + + public Long getId() { + return id; + } + + public Person setId(Long id) { + this.id = id; + return this; + } + + public String getLastName() { + return lastName; + } + + public Person setLastName(String lastName) { + this.lastName = lastName; + return this; + } + + public String getFirstName() { + return firstName; + } + + public Person setFirstName(String firstName) { + this.firstName = firstName; + return this; + } + +} diff --git a/junit5/src/test/java/com/baeldung/param/PersonValidator.java b/junit5/src/test/java/com/baeldung/param/PersonValidator.java new file mode 100644 index 000000000000..0219169aab5a --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/PersonValidator.java @@ -0,0 +1,142 @@ +package com.baeldung.param; + +import java.util.Arrays; + +/** + * Somewhat contrived validation class to illustrate unit test + * concepts. + * + * @author J Steven Perry + * + */ +public class PersonValidator { + + /** + * Contrived checked exception to illustrate one possible + * way to handle validation errors (via a checked exception). + * + * @author J Steven Perry + * + */ + public static class ValidationException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -134518049431883102L; + + // Probably should implement some more constructors, but don't want + /// to tarnish the lesson... + + /** + * The one and only way to create this checked exception. + * + * @param message + * The message accompanying the exception. Should be meaningful. + */ + public ValidationException(String message) { + super(message); + + } + + } + + private static final String[] ILLEGAL_NAME_CHARACTERS = { + ",", + "_", + "{", + "}", + "!" + }; + + /** + * Validate the first name of the specified Person object. + * + * @param person + * The Person object to validate. + * + * @return - returns true if the specified Person is valid + * + * @throws ValidationException + * - this Exception is thrown if any kind of validation error occurs. + */ + public static boolean validateFirstName(Person person) throws ValidationException { + boolean ret = true; + // The validation rules go here. + // Naive: use simple ifs + if (person == null) { + throw new ValidationException("Person is null (not allowed)!"); + } + if (person.getFirstName() == null) { + throw new ValidationException("Person FirstName is null (not allowed)!"); + } + if (person.getFirstName().isEmpty()) { + throw new ValidationException("Person FirstName is an empty String (not allowed)!"); + } + if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) { + throw new ValidationException( + "Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: " + + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + + "!"); + } + return ret; + } + + /** + * Validate the last name of the specified Person object. Looks the same as first + * name? Look closer. Just kidding. It's the same. But real world code can (and will) diverge. + * + * @param person + * The Person object to validate. + * + * @return - returns true if the specified Person is valid + * + * @throws ValidationException + * - this Exception is thrown if any kind of validation error occurs. + */ + public static boolean validateLastName(Person person) throws ValidationException { + boolean ret = true; + // The validation rules go here. + // Naive: use simple ifs + if (person == null) { + throw new ValidationException("Person is null (not allowed)!"); + } + if (person.getFirstName() == null) { + throw new ValidationException("Person FirstName is null (not allowed)!"); + } + if (person.getFirstName().isEmpty()) { + throw new ValidationException("Person FirstName is an empty String (not allowed)!"); + } + if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) { + throw new ValidationException( + "Person LastName (" + person.getLastName() + ") may not contain any of the following characters: " + + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + + "!"); + } + return ret; + } + + /** + * Validates the specified name. If it contains any of the illegalCharacters, + * this method returns false (indicating the name is illegal). Otherwise it returns true. + * + * @param candidate + * The candidate String to validate + * + * @param illegalCharacters + * The characters the String is not allowed to have + * + * @return - boolean - true if the name is valid, false otherwise. + */ + private static boolean isStringValid(String candidate, String[] illegalCharacters) { + boolean ret = true; + for (String illegalChar : illegalCharacters) { + if (candidate.contains(illegalChar)) { + ret = false; + break; + } + } + return ret; + } + +} diff --git a/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java b/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java new file mode 100644 index 000000000000..09ab03b811c9 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java @@ -0,0 +1,102 @@ +package com.baeldung.param; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@DisplayName("Testing PersonValidator") +public class PersonValidatorTest { + + /** + * Nested class, uses ExtendWith + * {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver} + * to feed Test methods with "good" data. + */ + @Nested + @DisplayName("When using Valid data") + @ExtendWith(ValidPersonParameterResolver.class) + public class ValidData { + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * A valid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are valid") + public void validateFirstName(Person person) { + try { + assertTrue(PersonValidator.validateFirstName(person)); + } catch (PersonValidator.ValidationException e) { + fail("Exception not expected: " + e.getLocalizedMessage()); + } + } + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * A valid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All last names are valid") + public void validateLastName(Person person) { + try { + assertTrue(PersonValidator.validateLastName(person)); + } catch (PersonValidator.ValidationException e) { + fail("Exception not expected: " + e.getLocalizedMessage()); + } + } + + } + + /** + * Nested class, uses ExtendWith + * {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver} + * to feed Test methods with "bad" data. + */ + @Nested + @DisplayName("When using Invalid data") + @ExtendWith(InvalidPersonParameterResolver.class) + public class InvalidData { + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * An invalid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are invalid") + public void validateFirstName(Person person) { + assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateFirstName(person)); + } + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * An invalid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are invalid") + public void validateLastName(Person person) { + assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateLastName(person)); + } + + } + +} diff --git a/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java b/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java new file mode 100644 index 000000000000..abb97586eb94 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java @@ -0,0 +1,50 @@ +package com.baeldung.param; + +import java.util.Random; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +public class ValidPersonParameterResolver implements ParameterResolver { + + /** + * The "good" (valid) data for testing purposes has to go somewhere, right? + */ + public static Person[] VALID_PERSONS = { + new Person().setId(1L).setLastName("Adams").setFirstName("Jill"), + new Person().setId(2L).setLastName("Baker").setFirstName("James"), + new Person().setId(3L).setLastName("Carter").setFirstName("Samanta"), + new Person().setId(4L).setLastName("Daniels").setFirstName("Joseph"), + new Person().setId(5L).setLastName("English").setFirstName("Jane"), + new Person().setId(6L).setLastName("Fontana").setFirstName("Enrique"), + // TODO: ADD MORE DATA HERE + }; + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + Object ret = null; + // + // Return a random, valid Person object if Person.class is the type of Parameter + /// to be resolved. Otherwise return null. + if (parameterContext.getParameter().getType() == Person.class) { + ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)]; + } + return ret; + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + boolean ret = false; + // + // If the Parameter.type == Person.class, then we support it, otherwise, get outta here! + if (parameterContext.getParameter().getType() == Person.class) { + ret = true; + } + return ret; + } + +} From c3de3dbfa9d1ed6ab552f4e4a55cf29d05364aac Mon Sep 17 00:00:00 2001 From: Ahmed Tawila Date: Thu, 10 Aug 2017 16:58:22 +0300 Subject: [PATCH 39/90] BAEL 1035 - Introduction to Eclipse Collections (#2395) * Evaluation article: Different Types of Bean Injection in Spring * added tests & changed configuration to Java-based config * removed xml config files * rename unit tests * BAEL-972 - Apache Commons Text * remove code from evaluation article * remove code from evaluation article * BAEL-972 - Apache Commons Text - added another example * BAEL-972 - Apache Commons Text - just indentation * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java - fix problems * BAEL-1033 Introduction to StreamUtils * BAEL-1033 Introduction to StreamUtils * BAEL-1033 Introduction to StreamUtils * fix formatting * BAEL-1033 minor refactor * BAEL-1035 Introduction to Eclipse Collections * format * BAEL-1035 Introduction to Eclipse Collections --- libraries/pom.xml | 8 ++- .../ConvertContainerToAnother.java | 20 ++++++ .../baeldung/eclipsecollections/Student.java | 20 ++++++ .../AllSatisfyPatternTest.java | 34 +++++++++++ .../AnySatisfyPatternTest.java | 34 +++++++++++ .../CollectPatternTest.java | 22 +++++++ .../ConvertContainerToAnotherTest.java | 20 ++++++ .../eclipsecollections/DetectPatternTest.java | 34 +++++++++++ .../ForEachPatternTest.java | 32 ++++++++++ .../InjectIntoPatternTest.java | 23 +++++++ .../eclipsecollections/LazyIterationTest.java | 26 ++++++++ .../PartitionPatternTest.java | 61 +++++++++++++++++++ .../eclipsecollections/RejectPatternTest.java | 38 ++++++++++++ .../eclipsecollections/SelectPatternTest.java | 52 ++++++++++++++++ 14 files changed, 423 insertions(+), 1 deletion(-) create mode 100644 libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java create mode 100644 libraries/src/main/java/com/baeldung/eclipsecollections/Student.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index 87971fb26ed9..8f28a23d75d8 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -462,6 +462,11 @@ pcollections ${pcollections.version} + + org.eclipse.collections + eclipse-collections + ${eclipse-collections.version} + 0.7.0 @@ -503,5 +508,6 @@ 1.7.1 2.1.2 1.0 + 8.2.0 - + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java b/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java new file mode 100644 index 000000000000..069baeab9f58 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java @@ -0,0 +1,20 @@ +package com.baeldung.eclipsecollections; + +import java.util.List; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.set.mutable.UnifiedSet; + +public class ConvertContainerToAnother { + + @SuppressWarnings("rawtypes") + public static List convertToList() { + UnifiedSet cars = new UnifiedSet<>(); + + cars.add("Toyota"); + cars.add("Mercedes"); + cars.add("Volkswagen"); + + return cars.toList(); + } +} diff --git a/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java b/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java new file mode 100644 index 000000000000..2c634a28d9c1 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java @@ -0,0 +1,20 @@ +package com.baeldung.eclipsecollections; + +public class Student { + + private String firstName; + private String lastName; + + public Student(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public String getFirstName() { + return this.firstName; + } + + public String getLastName() { + return this.lastName; + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java new file mode 100644 index 000000000000..1ea10317c7db --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java @@ -0,0 +1,34 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertTrue; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class AllSatisfyPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = new FastList<>(); + list.add(1); + list.add(8); + list.add(5); + list.add(41); + list.add(31); + list.add(17); + list.add(23); + list.add(38); + } + + @Test + public void whenAnySatisfiesCondition_thenCorrect() { + boolean result = list.allSatisfy(Predicates.greaterThan(0)); + + assertTrue(result); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java new file mode 100644 index 000000000000..58f8ad40af41 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java @@ -0,0 +1,34 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertTrue; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class AnySatisfyPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = new FastList<>(); + list.add(1); + list.add(8); + list.add(5); + list.add(41); + list.add(31); + list.add(17); + list.add(23); + list.add(38); + } + + @Test + public void whenAnySatisfiesCondition_thenCorrect() { + boolean result = list.anySatisfy(Predicates.greaterThan(30)); + + assertTrue(result); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java new file mode 100644 index 000000000000..51591cd08c09 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java @@ -0,0 +1,22 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.list.mutable.FastList; +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +public class CollectPatternTest { + + @Test + public void whenCollect_thenCorrect() { + Student student1 = new Student("John", "Hopkins"); + Student student2 = new Student("George", "Adams"); + + MutableList students = FastList.newListWith(student1, student2); + + MutableList lastNames = students.collect(Student::getLastName); + + assertEquals(lastNames.get(0), "Hopkins"); + assertEquals(lastNames.get(1), "Adams"); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java new file mode 100644 index 000000000000..b538abfa6eb0 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java @@ -0,0 +1,20 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertTrue; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.junit.Test; + +public class ConvertContainerToAnotherTest { + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void whenConvertContainerToAnother_thenCorrect() { + MutableList cars = (MutableList) ConvertContainerToAnother.convertToList(); + + assertTrue(cars.anySatisfy(Predicates.equal("Toyota"))); + assertTrue(cars.anySatisfy(Predicates.equal("Mercedes"))); + assertTrue(cars.anySatisfy(Predicates.equal("Volkswagen"))); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java new file mode 100644 index 000000000000..fc643f2840ba --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java @@ -0,0 +1,34 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class DetectPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = new FastList<>(); + list.add(1); + list.add(8); + list.add(5); + list.add(41); + list.add(31); + list.add(17); + list.add(23); + list.add(38); + } + + @Test + public void whenDetect_thenCorrect() { + Integer result = list.detect(Predicates.greaterThan(30)); + + assertEquals((int) result, 41); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java new file mode 100644 index 000000000000..e8d93a2af65a --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java @@ -0,0 +1,32 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.block.procedure.Procedure; +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.map.mutable.UnifiedMap; +import org.eclipse.collections.impl.tuple.Tuples; +import static org.junit.Assert.assertEquals; + +import java.util.Map; + +import org.junit.Test; + +public class ForEachPatternTest { + + @SuppressWarnings("unchecked") + @Test + public void whenInstantiateAndChangeValues_thenCorrect() { + Pair pair1 = Tuples.pair(1, "One"); + Pair pair2 = Tuples.pair(2, "Two"); + Pair pair3 = Tuples.pair(3, "Three"); + + UnifiedMap map = UnifiedMap.newMapWith(pair1, pair2, pair3); + + for (int i = 0; i < map.size(); i++) { + map.put(i + 1, "New Value"); + } + + for (int i = 0; i < map.size(); i++) { + assertEquals("New Value", map.get(i + 1)); + } + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java new file mode 100644 index 000000000000..bcd34021b1a7 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java @@ -0,0 +1,23 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.eclipse.collections.impl.factory.Lists; +import org.junit.Test; + +public class InjectIntoPatternTest { + + @Test + public void whenInjectInto_thenCorrect() { + List list = Lists.mutable.of(1, 2, 3, 4); + int result = 5; + for (int i = 0; i < list.size(); i++) { + Integer v = list.get(i); + result = result + v.intValue(); + } + + assertEquals(15, result); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java new file mode 100644 index 000000000000..8fe1286d4112 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.LazyIterable; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.factory.Lists; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class LazyIterationTest { + + @Test + public void whenLazyIteration_thenCorrect() { + Student student1 = new Student("John", "Hopkins"); + Student student2 = new Student("George", "Adams"); + Student student3 = new Student("Jennifer", "Rodriguez"); + + MutableList students = Lists.mutable.with(student1, student2, student3); + LazyIterable lazyStudents = students.asLazy(); + LazyIterable lastNames = lazyStudents.collect(Student::getLastName); + + assertTrue(lastNames.anySatisfy(Predicates.equal("Hopkins"))); + assertTrue(lastNames.anySatisfy(Predicates.equal("Adams"))); + assertTrue(lastNames.anySatisfy(Predicates.equal("Rodriguez"))); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java new file mode 100644 index 000000000000..3e528298240e --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java @@ -0,0 +1,61 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.eclipse.collections.api.block.predicate.Predicate; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.partition.list.PartitionMutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class PartitionPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = new FastList<>(); + list.add(1); + list.add(8); + list.add(5); + list.add(41); + list.add(31); + list.add(17); + list.add(23); + list.add(38); + } + + @SuppressWarnings({ "unused" }) + @Test + public void whenAnySatisfiesCondition_thenCorrect() { + MutableList numbers = list; + PartitionMutableList partitionedFolks = numbers.partition(new Predicate() { + + /** + * + */ + private static final long serialVersionUID = -1551138743683678406L; + + public boolean accept(Integer each) { + return each > 30; + } + }); + MutableList greaterThanThirty = partitionedFolks.getSelected() + .sortThis(); + MutableList smallerThanThirty = partitionedFolks.getRejected() + .sortThis(); + + assertEquals(1, (int) smallerThanThirty.getFirst()); + assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(5))); + assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(8))); + assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(17))); + assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(23))); + + assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(31))); + assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(38))); + assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(41))); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java new file mode 100644 index 000000000000..044a8203d631 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java @@ -0,0 +1,38 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; + +public class RejectPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = new FastList<>(); + list.add(1); + list.add(8); + list.add(5); + list.add(41); + list.add(31); + list.add(17); + list.add(23); + list.add(38); + } + + @Test + public void whenReject_thenCorrect() { + MutableList notGreaterThanThirty = list.reject(Predicates.greaterThan(30)) + .sortThis(); + + assertEquals(1, (int) notGreaterThanThirty.getFirst()); + assertEquals(5, (int) notGreaterThanThirty.get(1)); + assertEquals(8, (int) notGreaterThanThirty.get(2)); + assertEquals(17, (int) notGreaterThanThirty.get(3)); + assertEquals(23, (int) notGreaterThanThirty.getLast()); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java new file mode 100644 index 000000000000..20c94f602801 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java @@ -0,0 +1,52 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; + +public class SelectPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = new FastList<>(); + list.add(1); + list.add(8); + list.add(5); + list.add(41); + list.add(31); + list.add(17); + list.add(23); + list.add(38); + } + + @Test + public void givenListwhenSelect_thenCorrect() { + MutableList greaterThanThirty = list.select(Predicates.greaterThan(30)) + .sortThis(); + + assertEquals(31, (int) greaterThanThirty.getFirst()); + assertEquals(38, (int) greaterThanThirty.get(1)); + assertEquals(41, (int) greaterThanThirty.getLast()); + } + + @SuppressWarnings("rawtypes") + public MutableList selectUsingLambda() { + return list.select(each -> each > 30) + .sortThis(); + } + + @SuppressWarnings("unchecked") + @Test + public void givenListwhenSelectUsingLambda_thenCorrect() { + MutableList greaterThanThirty = selectUsingLambda(); + + assertEquals(31, (int) greaterThanThirty.getFirst()); + assertEquals(38, (int) greaterThanThirty.get(1)); + assertEquals(41, (int) greaterThanThirty.getLast()); + } +} From accb430f5e76d3223f3ee1fb00c92c008669c30f Mon Sep 17 00:00:00 2001 From: Mohamed Sanaulla Date: Thu, 10 Aug 2017 20:45:43 +0300 Subject: [PATCH 40/90] java 9 objects api sample (#2413) --- .../baeldung/java9/process/ServiceMain.java | 2 +- .../language/Java9ObjectsAPIUnitTest.java | 46 ++++++++++--------- 2 files changed, 26 insertions(+), 22 deletions(-) diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java index 299f74e8771c..5dc00dba25bf 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java @@ -6,7 +6,7 @@ public class ServiceMain { public static void main(String[] args) throws InterruptedException { ProcessHandle thisProcess = ProcessHandle.current(); - long pid = thisProcess.getPid(); + long pid = thisProcess.pid(); Optional opArgs = Optional.ofNullable(args); String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command")); diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java index a174e519ab9c..93abe4e185e5 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java @@ -10,7 +10,7 @@ import static org.hamcrest.MatcherAssert.assertThat; public class Java9ObjectsAPIUnitTest { - + @Test public void givenNullObject_whenRequireNonNullElse_thenElse(){ assertThat(Objects.requireNonNullElse(null, Collections.EMPTY_LIST), @@ -23,6 +23,11 @@ public void givenObject_whenRequireNonNullElse_thenObject(){ Collections.EMPTY_LIST), is(List.of("item1", "item2"))); } + @Test(expected = NullPointerException.class) + public void givenNull_whenRequireNonNullElse_thenException(){ + Objects.requireNonNullElse(null, null); + } + @Test public void givenObject_whenRequireNonNullElseGet_thenObject(){ assertThat(Objects.requireNonNullElseGet(null, List::of), @@ -32,40 +37,39 @@ public void givenObject_whenRequireNonNullElseGet_thenObject(){ @Test public void givenNumber_whenInvokeCheckIndex_thenNumber(){ int length = 5; - assertThat(Objects.checkIndex(4, length), is(4)); + } - try{ - Objects.checkIndex(5, length); - }catch(Exception ex){ - assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); - } + @Test(expected = IndexOutOfBoundsException.class) + public void givenOutOfRangeNumber_whenInvokeCheckIndex_thenException(){ + int length = 5; + Objects.checkIndex(5, length); } + @Test public void givenSubRange_whenCheckFromToIndex_thenNumber(){ int length = 6; - assertThat(Objects.checkFromToIndex(2,length,length), is(2)); + } - try{ - Objects.checkFromToIndex(2,7,length); - }catch(Exception ex){ - assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); - } + @Test(expected = IndexOutOfBoundsException.class) + public void givenInvalidSubRange_whenCheckFromToIndex_thenException(){ + int length = 6; + Objects.checkFromToIndex(2,7,length); } + @Test - public void giveSubRange_whenCheckFromIndexSize_thenNumber(){ + public void givenSubRange_whenCheckFromIndexSize_thenNumber(){ int length = 6; + assertThat(Objects.checkFromIndexSize(2,3,length), is(2)); + } - assertThat(Objects.checkFromToIndex(2,5,length), is(2)); - - try{ - Objects.checkFromToIndex(2,6,length); - }catch(Exception ex){ - assertThat(ex, instanceOf(IndexOutOfBoundsException.class)); - } + @Test(expected = IndexOutOfBoundsException.class) + public void givenInvalidSubRange_whenCheckFromIndexSize_thenException(){ + int length = 6; + Objects.checkFromIndexSize(2, 6, length); } From 69d8c107515a4eaa8bf5c4828e435a74abc0249e Mon Sep 17 00:00:00 2001 From: Eric Goebelbecker Date: Thu, 10 Aug 2017 13:59:38 -0400 Subject: [PATCH 41/90] BAEL-1044 - Introduction to NoException (#2412) * BAEL-1044 - Introduction to NoException * BAEL-1044 - Introduction to NoException * BAEL-1044 - Introduction to NoException * BAEL-1044 - Introduction to NoException * BAEL-1044 - Introduction to NoException * Update pom.xml Add missing --- libraries/README.md | 2 + libraries/pom.xml | 7 ++- .../noexception/CustomExceptionHandler.java | 24 +++++++ .../noexception/NoExceptionUnitTest.java | 62 +++++++++++++++++++ 4 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java create mode 100644 libraries/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java diff --git a/libraries/README.md b/libraries/README.md index 0e586281185f..88075af3903d 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -29,6 +29,8 @@ - [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph) - [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) - [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) +- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception) + The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index 8f28a23d75d8..490302ca290c 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -462,6 +462,11 @@ pcollections ${pcollections.version} + + com.machinezoo.noexception + noexception + 1.1.0 + org.eclipse.collections eclipse-collections @@ -510,4 +515,4 @@ 1.0 8.2.0 - \ No newline at end of file + diff --git a/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java b/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java new file mode 100644 index 000000000000..59e13efaa056 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java @@ -0,0 +1,24 @@ +package com.baeldung.noexception; + +import com.machinezoo.noexception.ExceptionHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CustomExceptionHandler extends ExceptionHandler { + + private Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class); + + @Override + public boolean handle(Throwable throwable) { + + if (throwable.getClass() + .isAssignableFrom(RuntimeException.class) + || throwable.getClass() + .isAssignableFrom(Error.class)) { + return false; + } else { + logger.error("Caught Exception ", throwable); + return true; + } + } +} diff --git a/libraries/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java b/libraries/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java new file mode 100644 index 000000000000..b7619202fe20 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.noexception; + +import com.machinezoo.noexception.Exceptions; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NoExceptionUnitTest { + + private static Logger logger = LoggerFactory.getLogger(NoExceptionUnitTest.class); + + @Test + public void whenStdExceptionHandling_thenCatchAndLog() { + try { + System.out.println("Result is " + Integer.parseInt("foobar")); + } catch (Throwable exception) { + logger.error("Caught exception:", exception); + } + } + + @Test + public void whenDefaultNoException_thenCatchAndLog() { + Exceptions.log().run(() -> System.out.println("Result is " + Integer.parseInt("foobar"))); + } + + @Test + public void givenLogger_whenDefaultNoException_thenCatchAndLogWithClassName() { + Exceptions.log(logger).run(() -> System.out.println("Result is " + Integer.parseInt("foobar"))); + } + + @Test + public void givenLoggerAndMessage_whenDefaultNoException_thenCatchAndLogWithMessage() { + Exceptions.log(logger, "Something went wrong:").run(() -> System.out.println("Result is " + Integer.parseInt("foobar"))); + } + + @Test + public void givenDefaultValue_whenDefaultNoException_thenCatchAndLogPrintDefault() { + System.out.println("Result is " + Exceptions.log(logger, "Something went wrong:").get(() -> Integer.parseInt("foobar")).orElse(-1)); + } + + @Test(expected = Error.class) + public void givenCustomHandler_whenError_thenRethrowError() { + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); + customExceptionHandler.run(() -> throwError()); + } + + @Test + public void givenCustomHandler_whenException_thenCatchAndLog() { + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); + customExceptionHandler.run(() -> throwException()); + } + + private static void throwError() { + throw new Error("This is very bad."); + } + + private static void throwException() { + String testString = "foo"; + testString.charAt(5); + } + +} From 127dd7323d801a78bed8adf057e41e6a916c7616 Mon Sep 17 00:00:00 2001 From: Parth Karia Date: Fri, 11 Aug 2017 20:39:36 +0530 Subject: [PATCH 42/90] BAEL-243 Spring Batch using Partitioner (#2419) * BAEL-1004 changes in variable names * BAEL-243 Spring Batch using Partitioner --- .../CustomMultiResourcePartitioner.java | 77 ++++++++ .../SpringbatchPartitionConfig.java | 169 ++++++++++++++++++ .../SpringbatchPartitionerApp.java | 28 +++ .../resources/input/partitioner/record1.csv | 4 + .../resources/input/partitioner/record2.csv | 4 + .../resources/input/partitioner/record3.csv | 4 + .../resources/input/partitioner/record4.csv | 4 + .../resources/input/partitioner/record5.csv | 4 + .../src/main/resources/output/output1.xml | 21 +++ .../src/main/resources/output/output2.xml | 21 +++ .../src/main/resources/output/output3.xml | 21 +++ .../src/main/resources/output/output4.xml | 21 +++ .../src/main/resources/output/output5.xml | 21 +++ 13 files changed, 399 insertions(+) create mode 100644 spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java create mode 100644 spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java create mode 100644 spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java create mode 100644 spring-batch/src/main/resources/input/partitioner/record1.csv create mode 100644 spring-batch/src/main/resources/input/partitioner/record2.csv create mode 100644 spring-batch/src/main/resources/input/partitioner/record3.csv create mode 100644 spring-batch/src/main/resources/input/partitioner/record4.csv create mode 100644 spring-batch/src/main/resources/input/partitioner/record5.csv create mode 100644 spring-batch/src/main/resources/output/output1.xml create mode 100644 spring-batch/src/main/resources/output/output2.xml create mode 100644 spring-batch/src/main/resources/output/output3.xml create mode 100644 spring-batch/src/main/resources/output/output4.xml create mode 100644 spring-batch/src/main/resources/output/output5.xml diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java new file mode 100644 index 000000000000..4cae69efbd5a --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java @@ -0,0 +1,77 @@ +/* + * Copyright 2006-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.baeldung.spring_batch_intro.partitioner; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.batch.core.partition.support.Partitioner; +import org.springframework.batch.item.ExecutionContext; +import org.springframework.core.io.Resource; +import org.springframework.util.Assert; + +public class CustomMultiResourcePartitioner implements Partitioner { + + private static final String DEFAULT_KEY_NAME = "fileName"; + + private static final String PARTITION_KEY = "partition"; + + private Resource[] resources = new Resource[0]; + + private String keyName = DEFAULT_KEY_NAME; + + /** + * The resources to assign to each partition. In Spring configuration you + * can use a pattern to select multiple resources. + * @param resources the resources to use + */ + public void setResources(Resource[] resources) { + this.resources = resources; + } + + /** + * The name of the key for the file name in each {@link ExecutionContext}. + * Defaults to "fileName". + * @param keyName the value of the key + */ + public void setKeyName(String keyName) { + this.keyName = keyName; + } + + /** + * Assign the filename of each of the injected resources to an + * {@link ExecutionContext}. + * + * @see Partitioner#partition(int) + */ + @Override + public Map partition(int gridSize) { + Map map = new HashMap(gridSize); + int i = 0, k = 1; + for (Resource resource : resources) { + ExecutionContext context = new ExecutionContext(); + Assert.state(resource.exists(), "Resource does not exist: " + resource); + context.putString(keyName, resource.getFilename()); + context.putString("opFileName", "output" + k++ + ".xml"); + + map.put(PARTITION_KEY + i, context); + i++; + } + return map; + } + +} diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java new file mode 100644 index 000000000000..fe8339a8b4b6 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java @@ -0,0 +1,169 @@ +package org.baeldung.spring_batch_intro.partitioner; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.text.ParseException; + +import javax.sql.DataSource; + +import org.baeldung.spring_batch_intro.model.Transaction; +import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.Step; +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepScope; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.batch.core.launch.support.SimpleJobLauncher; +import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; +import org.springframework.batch.item.UnexpectedInputException; +import org.springframework.batch.item.file.FlatFileItemReader; +import org.springframework.batch.item.file.mapping.DefaultLineMapper; +import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; +import org.springframework.batch.item.xml.StaxEventItemWriter; +import org.springframework.batch.support.transaction.ResourcelessTransactionManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.core.task.TaskExecutor; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.oxm.Marshaller; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.transaction.PlatformTransactionManager; + +@Configuration +@EnableBatchProcessing +public class SpringbatchPartitionConfig { + + @Autowired + ResourcePatternResolver resoursePatternResolver; + + @Autowired + private JobBuilderFactory jobs; + + @Autowired + private StepBuilderFactory steps; + + @Bean(name = "partitionerJob") + public Job partitionerJob() throws UnexpectedInputException, MalformedURLException, ParseException { + return jobs.get("partitionerJob") + .start(partitionStep()) + .build(); + } + + @Bean + public Step partitionStep() throws UnexpectedInputException, MalformedURLException, ParseException { + return steps.get("partitionStep") + .partitioner("slaveStep", partitioner()) + .step(slaveStep()) + .taskExecutor(taskExecutor()) + .build(); + } + + @Bean + public Step slaveStep() throws UnexpectedInputException, MalformedURLException, ParseException { + return steps.get("slaveStep") + . chunk(1) + .reader(itemReader(null)) + .writer(itemWriter(marshaller(), null)) + .build(); + } + + @Bean + public CustomMultiResourcePartitioner partitioner() { + CustomMultiResourcePartitioner partitioner = new CustomMultiResourcePartitioner(); + Resource[] resources; + try { + resources = resoursePatternResolver.getResources("file:src/main/resources/input/partitioner/*.csv"); + } catch (IOException e) { + throw new RuntimeException("I/O problems when resolving the input file pattern.", e); + } + partitioner.setResources(resources); + return partitioner; + } + + @Bean + @StepScope + public FlatFileItemReader itemReader(@Value("#{stepExecutionContext[fileName]}") String filename) throws UnexpectedInputException, ParseException { + FlatFileItemReader reader = new FlatFileItemReader(); + DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); + String[] tokens = { "username", "userid", "transactiondate", "amount" }; + tokenizer.setNames(tokens); + reader.setResource(new ClassPathResource("input/partitioner/" + filename)); + DefaultLineMapper lineMapper = new DefaultLineMapper(); + lineMapper.setLineTokenizer(tokenizer); + lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); + reader.setLinesToSkip(1); + reader.setLineMapper(lineMapper); + return reader; + } + + @Bean(destroyMethod = "") + @StepScope + public StaxEventItemWriter itemWriter(Marshaller marshaller, @Value("#{stepExecutionContext[opFileName]}") String filename) throws MalformedURLException { + StaxEventItemWriter itemWriter = new StaxEventItemWriter<>(); + itemWriter.setMarshaller(marshaller); + itemWriter.setRootTagName("transactionRecord"); + itemWriter.setResource(new FileSystemResource("src/main/resources/output/" + filename)); + return itemWriter; + } + + @Bean + public Marshaller marshaller() { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); + marshaller.setClassesToBeBound(new Class[] { Transaction.class }); + return marshaller; + } + + @Bean + public TaskExecutor taskExecutor() { + ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); + taskExecutor.setMaxPoolSize(5); + taskExecutor.setCorePoolSize(5); + taskExecutor.setQueueCapacity(5); + taskExecutor.afterPropertiesSet(); + return taskExecutor; + } + + private JobRepository getJobRepository() throws Exception { + JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); + factory.setDataSource(dataSource()); + factory.setTransactionManager(getTransactionManager()); + // JobRepositoryFactoryBean's methods Throws Generic Exception, + // it would have been better to have a specific one + factory.afterPropertiesSet(); + return (JobRepository) factory.getObject(); + } + + private DataSource dataSource() { + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); + EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL) + .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql") + .addScript("classpath:org/springframework/batch/core/schema-h2.sql") + .build(); + return db; + } + + private PlatformTransactionManager getTransactionManager() { + return new ResourcelessTransactionManager(); + } + + public JobLauncher getJobLauncher() throws Exception { + SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); + // SimpleJobLauncher's methods Throws Generic Exception, + // it would have been better to have a specific one + jobLauncher.setJobRepository(getJobRepository()); + jobLauncher.afterPropertiesSet(); + return jobLauncher; + } +} diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java new file mode 100644 index 000000000000..1d6d92296933 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java @@ -0,0 +1,28 @@ +package org.baeldung.spring_batch_intro.partitioner; + +import org.springframework.batch.core.Job; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.JobParameters; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class SpringbatchPartitionerApp { + public static void main(final String[] args) { + // Spring Java config + final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.register(SpringbatchPartitionConfig.class); + context.refresh(); + + final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); + final Job job = (Job) context.getBean("partitionerJob"); + System.out.println("Starting the batch job"); + try { + final JobExecution execution = jobLauncher.run(job, new JobParameters()); + System.out.println("Job Status : " + execution.getStatus()); + System.out.println("Job succeeded"); + } catch (final Exception e) { + e.printStackTrace(); + System.out.println("Job failed"); + } + } +} \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record1.csv b/spring-batch/src/main/resources/input/partitioner/record1.csv new file mode 100644 index 000000000000..e554becb2ab4 --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record1.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record2.csv b/spring-batch/src/main/resources/input/partitioner/record2.csv new file mode 100644 index 000000000000..e554becb2ab4 --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record2.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record3.csv b/spring-batch/src/main/resources/input/partitioner/record3.csv new file mode 100644 index 000000000000..e554becb2ab4 --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record3.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record4.csv b/spring-batch/src/main/resources/input/partitioner/record4.csv new file mode 100644 index 000000000000..e554becb2ab4 --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record4.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record5.csv b/spring-batch/src/main/resources/input/partitioner/record5.csv new file mode 100644 index 000000000000..e554becb2ab4 --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record5.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output1.xml b/spring-batch/src/main/resources/output/output1.xml new file mode 100644 index 000000000000..194b86081375 --- /dev/null +++ b/spring-batch/src/main/resources/output/output1.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output2.xml b/spring-batch/src/main/resources/output/output2.xml new file mode 100644 index 000000000000..194b86081375 --- /dev/null +++ b/spring-batch/src/main/resources/output/output2.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output3.xml b/spring-batch/src/main/resources/output/output3.xml new file mode 100644 index 000000000000..194b86081375 --- /dev/null +++ b/spring-batch/src/main/resources/output/output3.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output4.xml b/spring-batch/src/main/resources/output/output4.xml new file mode 100644 index 000000000000..194b86081375 --- /dev/null +++ b/spring-batch/src/main/resources/output/output4.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output5.xml b/spring-batch/src/main/resources/output/output5.xml new file mode 100644 index 000000000000..194b86081375 --- /dev/null +++ b/spring-batch/src/main/resources/output/output5.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file From dc3589a7a0548e0d6d1a1158fabd0f6af9bd4b2e Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Fri, 11 Aug 2017 22:02:08 +0200 Subject: [PATCH 43/90] fix spring-boot module (#2422) * fix spring config * fix spring config * fix spring config * minor fix * fix spring-boot module --- spring-boot/pom.xml | 8 ++++---- .../baeldung/servlets/props/PropertySourcesLoader.java | 2 +- .../utils/{Application.java => UtilsApplication.java} | 4 ++-- spring-boot/src/main/webapp/WEB-INF/context.xml | 4 ++-- spring-boot/src/main/webapp/WEB-INF/dispatcher.xml | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) rename spring-boot/src/main/java/com/baeldung/utils/{Application.java => UtilsApplication.java} (83%) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 2a1de00039d3..3fafa6ade234 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -52,7 +52,7 @@ test - + io.dropwizard.metrics @@ -253,8 +253,8 @@ - org.baeldung.boot.DemoApplication - 4.3.4.RELEASE + 4.3.4.RELEASE 2.2.1 3.1.1 3.3.7-1 diff --git a/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java b/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java index 56a6751326c7..aa70bac7775f 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java @@ -9,7 +9,7 @@ import org.springframework.core.env.ConfigurableEnvironment; @Configuration -@ComponentScan(basePackages = { "com.baeldung.*" }) +@ComponentScan(basePackages = { "com.baeldung.servlets.*" }) @PropertySource("classpath:custom.properties") public class PropertySourcesLoader { private static final Logger log = LoggerFactory.getLogger(PropertySourcesLoader.class); diff --git a/spring-boot/src/main/java/com/baeldung/utils/Application.java b/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java similarity index 83% rename from spring-boot/src/main/java/com/baeldung/utils/Application.java rename to spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java index 9d5d75bce2ab..b63ada9eee3e 100644 --- a/spring-boot/src/main/java/com/baeldung/utils/Application.java +++ b/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java @@ -10,11 +10,11 @@ @SpringBootApplication(exclude=MySQLAutoconfiguration.class) @ComponentScan(basePackages="com.baeldung.utils") -public class Application { +public class UtilsApplication { @RolesAllowed("*") public static void main(String[] args) { - SpringApplication.run(Application.class, args); + SpringApplication.run(UtilsApplication.class, args); } } diff --git a/spring-boot/src/main/webapp/WEB-INF/context.xml b/spring-boot/src/main/webapp/WEB-INF/context.xml index 263bed443016..32f11f78f6c5 100644 --- a/spring-boot/src/main/webapp/WEB-INF/context.xml +++ b/spring-boot/src/main/webapp/WEB-INF/context.xml @@ -6,7 +6,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> - + - + \ No newline at end of file diff --git a/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml b/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml index ade8e66777bf..54e62921be70 100644 --- a/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml +++ b/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml @@ -7,7 +7,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> - + From a4132df3e541db2825134cbd81222b43c7c74525 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Sat, 12 Aug 2017 07:49:55 +0200 Subject: [PATCH 44/90] fix pom (#2423) * fix spring config * fix spring config * fix spring config * minor fix * fix spring-boot module * fix pom --- spring-boot/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 3fafa6ade234..0cf7df86cd7d 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -253,8 +253,8 @@ - 4.3.4.RELEASE + org.baeldung.boot.DemoApplication + 4.3.4.RELEASE 2.2.1 3.1.1 3.3.7-1 From 310e89e4f04402700be4a5fa4686a9c7914ec6f6 Mon Sep 17 00:00:00 2001 From: Ahmed Tawila Date: Sat, 12 Aug 2017 07:59:15 +0200 Subject: [PATCH 45/90] BAEL-1035 Introduction to Eclipse Collections (#2421) * Evaluation article: Different Types of Bean Injection in Spring * added tests & changed configuration to Java-based config * removed xml config files * rename unit tests * BAEL-972 - Apache Commons Text * remove code from evaluation article * remove code from evaluation article * BAEL-972 - Apache Commons Text - added another example * BAEL-972 - Apache Commons Text - just indentation * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java - fix problems * BAEL-1033 Introduction to StreamUtils * BAEL-1033 Introduction to StreamUtils * BAEL-1033 Introduction to StreamUtils * fix formatting * BAEL-1033 minor refactor * BAEL-1035 Introduction to Eclipse Collections * format * BAEL-1035 Introduction to Eclipse Collections * BAEL-1035 Introduction to Eclipse Collections --- libraries/pom.xml | 2 +- .../baeldung/eclipsecollections/Student.java | 26 ++++++++++++ .../CollectPatternTest.java | 4 +- .../eclipsecollections/FlatCollectTest.java | 42 +++++++++++++++++++ .../PartitionPatternTest.java | 1 - .../baeldung/eclipsecollections/ZipTest.java | 22 ++++++++++ .../eclipsecollections/ZipWithIndexTest.java | 22 ++++++++++ 7 files changed, 115 insertions(+), 4 deletions(-) create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java create mode 100644 libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index 490302ca290c..a16a4de59dfc 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -515,4 +515,4 @@ 1.0 8.2.0 - + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java b/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java index 2c634a28d9c1..cf6c06cec076 100644 --- a/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java +++ b/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java @@ -1,15 +1,25 @@ package com.baeldung.eclipsecollections; +import java.util.List; + public class Student { private String firstName; private String lastName; + private List addresses; public Student(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } + public Student(String firstName, String lastName, List addresses) { + super(); + this.firstName = firstName; + this.lastName = lastName; + this.addresses = addresses; + } + public String getFirstName() { return this.firstName; } @@ -17,4 +27,20 @@ public String getFirstName() { public String getLastName() { return this.lastName; } + + public List getAddresses() { + return addresses; + } + + public void setAddresses(List addresses) { + this.addresses = addresses; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java index 51591cd08c09..5fb63794a16a 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java @@ -16,7 +16,7 @@ public void whenCollect_thenCorrect() { MutableList lastNames = students.collect(Student::getLastName); - assertEquals(lastNames.get(0), "Hopkins"); - assertEquals(lastNames.get(1), "Adams"); + assertEquals("Hopkins", lastNames.get(0)); + assertEquals("Adams", lastNames.get(1)); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java new file mode 100644 index 000000000000..3d1453e557f8 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java @@ -0,0 +1,42 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.list.mutable.FastList; +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; + +public class FlatCollectTest { + + MutableList addresses1; + MutableList addresses2; + MutableList addresses3; + MutableList addresses4; + + MutableList students; + + @Before + public void setup() { + String address1 = "73 Pacific St., Forest Hills, NY 11375"; + String address2 = "93 Bayport Ave., South Richmond Hill, NY 11419"; + String address3 = "548 Market St, San Francisco, CA 94104"; + String address4 = "8605 Santa Monica Blvd, West Hollywood, CA 90069"; + + this.addresses1 = FastList.newListWith(address1, address2); + this.addresses2 = FastList.newListWith(address3, address4); + Student student1 = new Student("John", "Hopkins", addresses1); + Student student2 = new Student("George", "Adams", addresses2); + this.addresses2 = FastList.newListWith(address3, address4); + this.students = FastList.newListWith(student1, student2); + } + + @Test + public void whenFlatCollect_thenCorrect() { + MutableList addresses = students.flatCollect(Student::getAddresses); + + assertEquals("73 Pacific St., Forest Hills, NY 11375", addresses.get(0)); + assertEquals("93 Bayport Ave., South Richmond Hill, NY 11419", addresses.get(1)); + assertEquals("548 Market St, San Francisco, CA 94104", addresses.get(2)); + assertEquals("8605 Santa Monica Blvd, West Hollywood, CA 90069", addresses.get(3)); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java index 3e528298240e..4d9619817b2c 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java @@ -28,7 +28,6 @@ public void getList() { list.add(38); } - @SuppressWarnings({ "unused" }) @Test public void whenAnySatisfiesCondition_thenCorrect() { MutableList numbers = list; diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java new file mode 100644 index 000000000000..9dfab8f32d91 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java @@ -0,0 +1,22 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.factory.Lists; +import org.eclipse.collections.impl.tuple.Tuples; +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +public class ZipTest { + + @Test + public void whenZip_thenCorrect() { + MutableList numbers = Lists.mutable.with("1", "2", "3", "Ignored"); + MutableList cars = Lists.mutable.with("Porsche", "Volvo", "Toyota"); + MutableList> pairs = numbers.zip(cars); + + assertEquals(Tuples.pair("1", "Porsche"), pairs.get(0)); + assertEquals(Tuples.pair("2", "Volvo"), pairs.get(1)); + assertEquals(Tuples.pair("3", "Toyota"), pairs.get(2)); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java new file mode 100644 index 000000000000..3e8fe9b410e9 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java @@ -0,0 +1,22 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertEquals; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.eclipse.collections.impl.tuple.Tuples; +import org.junit.Test; + +public class ZipWithIndexTest { + + @Test + public void whenZip_thenCorrect() { + MutableList cars = FastList.newListWith("Porsche", "Volvo", "Toyota"); + MutableList> pairs = cars.zipWithIndex(); + + assertEquals(Tuples.pair("Porsche", 0), pairs.get(0)); + assertEquals(Tuples.pair("Volvo", 1), pairs.get(1)); + assertEquals(Tuples.pair("Toyota", 2), pairs.get(2)); + } +} From 9b2e8ec9f9868e490d3cf9e92ef18dfa99aa6f2f Mon Sep 17 00:00:00 2001 From: Ahmed Tawila Date: Sat, 12 Aug 2017 18:42:04 +0200 Subject: [PATCH 46/90] BAEL-1035 Introduction to Eclipse Collections (#2425) * Evaluation article: Different Types of Bean Injection in Spring * added tests & changed configuration to Java-based config * removed xml config files * rename unit tests * BAEL-972 - Apache Commons Text * remove code from evaluation article * remove code from evaluation article * BAEL-972 - Apache Commons Text - added another example * BAEL-972 - Apache Commons Text - just indentation * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java * BAEL-994 - TemporalAdjuster in Java - fix problems * BAEL-1033 Introduction to StreamUtils * BAEL-1033 Introduction to StreamUtils * BAEL-1033 Introduction to StreamUtils * fix formatting * BAEL-1033 minor refactor * BAEL-1035 Introduction to Eclipse Collections * format * BAEL-1035 Introduction to Eclipse Collections * BAEL-1035 Introduction to Eclipse Collections * BAEL-1035 Introduction to Eclipse Collections * cleanup * cleanup --- .../AllSatisfyPatternTest.java | 10 +------ .../AnySatisfyPatternTest.java | 10 +------ .../CollectPatternTest.java | 7 +++-- .../ConvertContainerToAnotherTest.java | 12 ++++---- .../eclipsecollections/DetectPatternTest.java | 16 +++-------- .../eclipsecollections/FlatCollectTest.java | 18 ++++++++---- .../ForEachPatternTest.java | 7 ++--- .../eclipsecollections/LazyIterationTest.java | 8 ++---- .../PartitionPatternTest.java | 28 ++++--------------- .../eclipsecollections/RejectPatternTest.java | 23 +++++---------- .../eclipsecollections/SelectPatternTest.java | 22 ++++----------- .../baeldung/eclipsecollections/ZipTest.java | 20 ++++++++++--- .../eclipsecollections/ZipWithIndexTest.java | 21 ++++++++++---- 13 files changed, 84 insertions(+), 118 deletions(-) diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java index 1ea10317c7db..ee369fc75b12 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java @@ -14,15 +14,7 @@ public class AllSatisfyPatternTest { @Before public void getList() { - this.list = new FastList<>(); - list.add(1); - list.add(8); - list.add(5); - list.add(41); - list.add(31); - list.add(17); - list.add(23); - list.add(38); + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); } @Test diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java index 58f8ad40af41..a3314ebee6a7 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java @@ -14,15 +14,7 @@ public class AnySatisfyPatternTest { @Before public void getList() { - this.list = new FastList<>(); - list.add(1); - list.add(8); - list.add(5); - list.add(41); - list.add(31); - list.add(17); - list.add(23); - list.add(38); + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); } @Test diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java index 5fb63794a16a..ee384c2f9d61 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java @@ -2,7 +2,8 @@ import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.list.mutable.FastList; -import static org.junit.Assert.assertEquals; + +import org.assertj.core.api.Assertions; import org.junit.Test; public class CollectPatternTest { @@ -16,7 +17,7 @@ public void whenCollect_thenCorrect() { MutableList lastNames = students.collect(Student::getLastName); - assertEquals("Hopkins", lastNames.get(0)); - assertEquals("Adams", lastNames.get(1)); + Assertions.assertThat(lastNames) + .containsExactly("Hopkins", "Adams"); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java index b538abfa6eb0..4655431872f9 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java @@ -1,9 +1,8 @@ package com.baeldung.eclipsecollections; -import static org.junit.Assert.assertTrue; - +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; import org.junit.Test; public class ConvertContainerToAnotherTest { @@ -12,9 +11,8 @@ public class ConvertContainerToAnotherTest { @Test public void whenConvertContainerToAnother_thenCorrect() { MutableList cars = (MutableList) ConvertContainerToAnother.convertToList(); - - assertTrue(cars.anySatisfy(Predicates.equal("Toyota"))); - assertTrue(cars.anySatisfy(Predicates.equal("Mercedes"))); - assertTrue(cars.anySatisfy(Predicates.equal("Volkswagen"))); + + Assertions.assertThat(cars) + .containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes")); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java index fc643f2840ba..c5b5e1c4128b 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java @@ -1,10 +1,9 @@ package com.baeldung.eclipsecollections; +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.block.factory.Predicates; import org.eclipse.collections.impl.list.mutable.FastList; -import static org.junit.Assert.assertEquals; - import org.junit.Before; import org.junit.Test; @@ -14,21 +13,14 @@ public class DetectPatternTest { @Before public void getList() { - this.list = new FastList<>(); - list.add(1); - list.add(8); - list.add(5); - list.add(41); - list.add(31); - list.add(17); - list.add(23); - list.add(38); + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); } @Test public void whenDetect_thenCorrect() { Integer result = list.detect(Predicates.greaterThan(30)); - assertEquals((int) result, 41); + Assertions.assertThat(result) + .isEqualTo(41); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java index 3d1453e557f8..021c72e91ea6 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java @@ -1,8 +1,12 @@ package com.baeldung.eclipsecollections; +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.list.mutable.FastList; -import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + import org.junit.Before; import org.junit.Test; @@ -13,6 +17,7 @@ public class FlatCollectTest { MutableList addresses3; MutableList addresses4; + List expectedAddresses; MutableList students; @Before @@ -28,15 +33,18 @@ public void setup() { Student student2 = new Student("George", "Adams", addresses2); this.addresses2 = FastList.newListWith(address3, address4); this.students = FastList.newListWith(student1, student2); + this.expectedAddresses = new ArrayList<>(); + this.expectedAddresses.add("73 Pacific St., Forest Hills, NY 11375"); + this.expectedAddresses.add("93 Bayport Ave., South Richmond Hill, NY 11419"); + this.expectedAddresses.add("548 Market St, San Francisco, CA 94104"); + this.expectedAddresses.add("8605 Santa Monica Blvd, West Hollywood, CA 90069"); } @Test public void whenFlatCollect_thenCorrect() { MutableList addresses = students.flatCollect(Student::getAddresses); - assertEquals("73 Pacific St., Forest Hills, NY 11375", addresses.get(0)); - assertEquals("93 Bayport Ave., South Richmond Hill, NY 11419", addresses.get(1)); - assertEquals("548 Market St, San Francisco, CA 94104", addresses.get(2)); - assertEquals("8605 Santa Monica Blvd, West Hollywood, CA 90069", addresses.get(3)); + Assertions.assertThat(addresses) + .containsExactlyElementsOf(this.expectedAddresses); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java index e8d93a2af65a..8cea575222dc 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java @@ -1,13 +1,10 @@ package com.baeldung.eclipsecollections; -import org.eclipse.collections.api.block.procedure.Procedure; +import static org.junit.Assert.assertEquals; + import org.eclipse.collections.api.tuple.Pair; import org.eclipse.collections.impl.map.mutable.UnifiedMap; import org.eclipse.collections.impl.tuple.Tuples; -import static org.junit.Assert.assertEquals; - -import java.util.Map; - import org.junit.Test; public class ForEachPatternTest { diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java index 8fe1286d4112..9c216ecc87fb 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java @@ -1,10 +1,9 @@ package com.baeldung.eclipsecollections; +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.LazyIterable; import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.block.factory.Predicates; import org.eclipse.collections.impl.factory.Lists; -import static org.junit.Assert.assertTrue; import org.junit.Test; public class LazyIterationTest { @@ -19,8 +18,7 @@ public void whenLazyIteration_thenCorrect() { LazyIterable lazyStudents = students.asLazy(); LazyIterable lastNames = lazyStudents.collect(Student::getLastName); - assertTrue(lastNames.anySatisfy(Predicates.equal("Hopkins"))); - assertTrue(lastNames.anySatisfy(Predicates.equal("Adams"))); - assertTrue(lastNames.anySatisfy(Predicates.equal("Rodriguez"))); + Assertions.assertThat(lastNames) + .containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez")); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java index 4d9619817b2c..c055413cd9ed 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java @@ -1,12 +1,9 @@ package com.baeldung.eclipsecollections; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.block.predicate.Predicate; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.api.partition.list.PartitionMutableList; -import org.eclipse.collections.impl.block.factory.Predicates; import org.eclipse.collections.impl.list.mutable.FastList; import org.junit.Before; import org.junit.Test; @@ -17,15 +14,7 @@ public class PartitionPatternTest { @Before public void getList() { - this.list = new FastList<>(); - list.add(1); - list.add(8); - list.add(5); - list.add(41); - list.add(31); - list.add(17); - list.add(23); - list.add(38); + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); } @Test @@ -47,14 +36,9 @@ public boolean accept(Integer each) { MutableList smallerThanThirty = partitionedFolks.getRejected() .sortThis(); - assertEquals(1, (int) smallerThanThirty.getFirst()); - assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(5))); - assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(8))); - assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(17))); - assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(23))); - - assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(31))); - assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(38))); - assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(41))); + Assertions.assertThat(smallerThanThirty) + .containsExactly(1, 5, 8, 17, 23); + Assertions.assertThat(greaterThanThirty) + .containsExactly(31, 38, 41); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java index 044a8203d631..1666c863332d 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java @@ -1,27 +1,21 @@ package com.baeldung.eclipsecollections; +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.block.factory.Predicates; import org.eclipse.collections.impl.list.mutable.FastList; -import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; public class RejectPatternTest { MutableList list; + MutableList expectedList; @Before - public void getList() { - this.list = new FastList<>(); - list.add(1); - list.add(8); - list.add(5); - list.add(41); - list.add(31); - list.add(17); - list.add(23); - list.add(38); + public void setup() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + this.expectedList = FastList.newListWith(1, 5, 8, 17, 23); } @Test @@ -29,10 +23,7 @@ public void whenReject_thenCorrect() { MutableList notGreaterThanThirty = list.reject(Predicates.greaterThan(30)) .sortThis(); - assertEquals(1, (int) notGreaterThanThirty.getFirst()); - assertEquals(5, (int) notGreaterThanThirty.get(1)); - assertEquals(8, (int) notGreaterThanThirty.get(2)); - assertEquals(17, (int) notGreaterThanThirty.get(3)); - assertEquals(23, (int) notGreaterThanThirty.getLast()); + Assertions.assertThat(notGreaterThanThirty) + .containsExactlyElementsOf(this.expectedList); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java index 20c94f602801..d79c864fc529 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java @@ -1,9 +1,9 @@ package com.baeldung.eclipsecollections; +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.block.factory.Predicates; import org.eclipse.collections.impl.list.mutable.FastList; -import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; @@ -13,15 +13,7 @@ public class SelectPatternTest { @Before public void getList() { - this.list = new FastList<>(); - list.add(1); - list.add(8); - list.add(5); - list.add(41); - list.add(31); - list.add(17); - list.add(23); - list.add(38); + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); } @Test @@ -29,9 +21,8 @@ public void givenListwhenSelect_thenCorrect() { MutableList greaterThanThirty = list.select(Predicates.greaterThan(30)) .sortThis(); - assertEquals(31, (int) greaterThanThirty.getFirst()); - assertEquals(38, (int) greaterThanThirty.get(1)); - assertEquals(41, (int) greaterThanThirty.getLast()); + Assertions.assertThat(greaterThanThirty) + .containsExactly(31, 38, 41); } @SuppressWarnings("rawtypes") @@ -45,8 +36,7 @@ public MutableList selectUsingLambda() { public void givenListwhenSelectUsingLambda_thenCorrect() { MutableList greaterThanThirty = selectUsingLambda(); - assertEquals(31, (int) greaterThanThirty.getFirst()); - assertEquals(38, (int) greaterThanThirty.get(1)); - assertEquals(41, (int) greaterThanThirty.getLast()); + Assertions.assertThat(greaterThanThirty) + .containsExactly(31, 38, 41); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java index 9dfab8f32d91..29f0c23954bc 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java @@ -4,19 +4,31 @@ import org.eclipse.collections.api.tuple.Pair; import org.eclipse.collections.impl.factory.Lists; import org.eclipse.collections.impl.tuple.Tuples; -import static org.junit.Assert.assertEquals; + +import org.assertj.core.api.Assertions; +import org.junit.Before; import org.junit.Test; public class ZipTest { + MutableList> expectedPairs; + + @SuppressWarnings("unchecked") + @Before + public void setup() { + Pair pair1 = Tuples.pair("1", "Porsche"); + Pair pair2 = Tuples.pair("2", "Volvo"); + Pair pair3 = Tuples.pair("3", "Toyota"); + expectedPairs = Lists.mutable.of(pair1, pair2, pair3); + } + @Test public void whenZip_thenCorrect() { MutableList numbers = Lists.mutable.with("1", "2", "3", "Ignored"); MutableList cars = Lists.mutable.with("Porsche", "Volvo", "Toyota"); MutableList> pairs = numbers.zip(cars); - assertEquals(Tuples.pair("1", "Porsche"), pairs.get(0)); - assertEquals(Tuples.pair("2", "Volvo"), pairs.get(1)); - assertEquals(Tuples.pair("3", "Toyota"), pairs.get(2)); + Assertions.assertThat(pairs) + .containsExactlyElementsOf(this.expectedPairs); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java index 3e8fe9b410e9..a2d8be44ec5f 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java @@ -1,22 +1,33 @@ package com.baeldung.eclipsecollections; -import static org.junit.Assert.assertEquals; - +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.factory.Lists; import org.eclipse.collections.impl.list.mutable.FastList; import org.eclipse.collections.impl.tuple.Tuples; +import org.junit.Before; import org.junit.Test; public class ZipWithIndexTest { + MutableList> expectedPairs; + + @SuppressWarnings("unchecked") + @Before + public void setup() { + Pair pair1 = Tuples.pair("Porsche", 0); + Pair pair2 = Tuples.pair("Volvo", 1); + Pair pair3 = Tuples.pair("Toyota", 2); + expectedPairs = Lists.mutable.of(pair1, pair2, pair3); + } + @Test public void whenZip_thenCorrect() { MutableList cars = FastList.newListWith("Porsche", "Volvo", "Toyota"); MutableList> pairs = cars.zipWithIndex(); - assertEquals(Tuples.pair("Porsche", 0), pairs.get(0)); - assertEquals(Tuples.pair("Volvo", 1), pairs.get(1)); - assertEquals(Tuples.pair("Toyota", 2), pairs.get(2)); + Assertions.assertThat(pairs) + .containsExactlyElementsOf(this.expectedPairs); } } From e13204ca96a30cc5db83cd248288d16d95c9ef4a Mon Sep 17 00:00:00 2001 From: Alejandro Gervasio Date: Sat, 12 Aug 2017 23:02:09 -0300 Subject: [PATCH 47/90] Introduction to EJB JNDI Lookup on WildFly Application Server - Alejandro Gervasio | alejandro.gervasio@gmail.com (#2417) * Initial Commit * jboss-ejb-client.properties file * Updated jboss-ejb-client.properties file --- .../resources/jboss-ejb-client.properties | 8 ++-- .../application/TextApplication.java | 42 +++++++++++++++++++ .../resources/jboss-ejb-client.properties | 8 ++++ .../application/TextApplicationTest.java | 31 ++++++++++++++ .../baeldung/ejbmodule/TextProcessorBean.java | 10 +++++ .../ejbmodule/TextProcessorRemote.java | 9 ++++ .../ejbmodule/TextProcessorBeanTest.java | 12 ++++++ 7 files changed, 116 insertions(+), 4 deletions(-) create mode 100644 ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java create mode 100644 ejb/ejbclient/src/main/resources/jboss-ejb-client.properties create mode 100644 ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java create mode 100644 ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java create mode 100644 ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java create mode 100644 ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java diff --git a/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties b/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties index a01a675e4406..67533b78258e 100755 --- a/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties +++ b/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties @@ -1,8 +1,8 @@ +endpoint.name=client-endpoint +remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false remote.connections=default remote.connection.default.host=127.0.0.1 remote.connection.default.port=8080 remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false -remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false -remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER} -remote.connection.default.username=testUser -remote.connection.default.password=admin1234! +remote.connection.default.username=myusername +remote.connection.default.password=mypassword \ No newline at end of file diff --git a/ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java b/ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java new file mode 100644 index 000000000000..b65c21100d8f --- /dev/null +++ b/ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java @@ -0,0 +1,42 @@ +package com.baeldung.ejbclient.application; + +import com.baeldung.ejbmodule.TextProcessorBean; +import com.baeldung.ejbmodule.TextProcessorRemote; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import java.util.Properties; + +public class TextApplication { + + public static void main(String[] args) throws NamingException { + TextProcessorRemote textProcessor = EJBFactory.createTextProcessorBeanFromJNDI("ejb:"); + System.out.print(textProcessor.processText("sample text")); + } + + private static class EJBFactory { + + private static TextProcessorRemote createTextProcessorBeanFromJNDI(String namespace) throws NamingException { + return lookupTextProcessorBean(namespace); + } + + private static TextProcessorRemote lookupTextProcessorBean(String namespace) throws NamingException { + Context ctx = createInitialContext(); + final String appName = ""; + final String moduleName = "EJBModule"; + final String distinctName = ""; + final String beanName = TextProcessorBean.class.getSimpleName(); + final String viewClassName = TextProcessorRemote.class.getName(); + return (TextProcessorRemote) ctx.lookup(namespace + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName); + } + + private static Context createInitialContext() throws NamingException { + Properties jndiProperties = new Properties(); + jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"); + jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); + jndiProperties.put(Context.PROVIDER_URL, "http-remoting://localhost:8080"); + jndiProperties.put("jboss.naming.client.ejb.context", true); + return new InitialContext(jndiProperties); + } + } +} diff --git a/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties b/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties new file mode 100644 index 000000000000..67533b78258e --- /dev/null +++ b/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties @@ -0,0 +1,8 @@ +endpoint.name=client-endpoint +remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false +remote.connections=default +remote.connection.default.host=127.0.0.1 +remote.connection.default.port=8080 +remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false +remote.connection.default.username=myusername +remote.connection.default.password=mypassword \ No newline at end of file diff --git a/ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java b/ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java new file mode 100644 index 000000000000..947c72d0b06c --- /dev/null +++ b/ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.ejbclient.application; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import javax.naming.NamingException; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import static org.junit.Assert.*; + +public class TextApplicationTest { + + private static ByteArrayOutputStream outContent; + + @BeforeClass + public static void setUpPrintStreamInstance() { + outContent = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outContent)); + } + + @AfterClass + public static void tearDownByteArrayOutputStream() { + outContent = null; + } + + @Test + public void givenInputString_whenCompareTtoStringPrintedToConsole_thenSuccessful() throws NamingException { + TextApplication.main(new String[]{}); + assertEquals("SAMPLE TEXT", outContent.toString()); + } +} \ No newline at end of file diff --git a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java b/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java new file mode 100644 index 000000000000..dc0db5fc53bb --- /dev/null +++ b/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java @@ -0,0 +1,10 @@ +package com.baeldung.ejbmodule; + +import javax.ejb.Stateless; + +@Stateless +public class TextProcessorBean implements TextProcessorRemote { + public String processText(String text) { + return text.toUpperCase(); + } +} diff --git a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java b/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java new file mode 100644 index 000000000000..680d8f4e1063 --- /dev/null +++ b/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java @@ -0,0 +1,9 @@ +package com.baeldung.ejbmodule; + +import javax.ejb.Remote; + +@Remote +public interface TextProcessorRemote { + + String processText(String text); +} \ No newline at end of file diff --git a/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java b/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java new file mode 100644 index 000000000000..d8693420d42f --- /dev/null +++ b/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java @@ -0,0 +1,12 @@ +package com.baeldung.ejbmodule; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class TextProcessorBeanTest { + @Test + public void givenInputString_whenComparedToStringParsedByBean_thenSuccessful() { + TextProcessorBean textProcessor = new TextProcessorBean(); + assertEquals("TEST", textProcessor.processText("test")); + } +} \ No newline at end of file From 299432df1178fccc62772ef60a6116ec68153d51 Mon Sep 17 00:00:00 2001 From: Mohamed Sanaulla Date: Sun, 13 Aug 2017 21:06:42 +0300 Subject: [PATCH 48/90] updating Java9ObjectsAPIUnitTest (#2430) * updating Java9ObjectsAPIUnitTest * some more changes to test --- .../language/Java9ObjectsAPIUnitTest.java | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java index 93abe4e185e5..93579019a171 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java @@ -10,17 +10,27 @@ import static org.hamcrest.MatcherAssert.assertThat; public class Java9ObjectsAPIUnitTest { - + + private List aMethodReturningNullList(){ + return null; + } + @Test public void givenNullObject_whenRequireNonNullElse_thenElse(){ - assertThat(Objects.requireNonNullElse(null, Collections.EMPTY_LIST), - is(Collections.EMPTY_LIST)); + List aList = Objects.requireNonNullElse( + aMethodReturningNullList(), Collections.EMPTY_LIST); + assertThat(aList, is(Collections.EMPTY_LIST)); + } + + private List aMethodReturningNonNullList(){ + return List.of("item1", "item2"); } @Test public void givenObject_whenRequireNonNullElse_thenObject(){ - assertThat(Objects.requireNonNullElse(List.of("item1", "item2"), - Collections.EMPTY_LIST), is(List.of("item1", "item2"))); + List aList = Objects.requireNonNullElse( + aMethodReturningNonNullList(), Collections.EMPTY_LIST); + assertThat(aList, is(List.of("item1", "item2"))); } @Test(expected = NullPointerException.class) @@ -30,8 +40,8 @@ public void givenNull_whenRequireNonNullElse_thenException(){ @Test public void givenObject_whenRequireNonNullElseGet_thenObject(){ - assertThat(Objects.requireNonNullElseGet(null, List::of), - is(List.of())); + List aList = Objects.requireNonNullElseGet(null, List::of); + assertThat(aList, is(List.of())); } @Test From 290e759d4ae6599d690c56a11c20f49cd8408162 Mon Sep 17 00:00:00 2001 From: deep20jain Date: Mon, 14 Aug 2017 07:41:49 +0530 Subject: [PATCH 49/90] BAEL1053 - deep20jain@gmail.com - Broadcasting and Multicasting in Java (#2368) * Adding code for java broadcasting and multicasting * Changing multicast ip * Adding code to iterate thorugh all network interfaces * Formatting again and fixing bug * Applying formatting rules on all classes * Fixing formatting --- .../udp/broadcast/BroadcastingClient.java | 85 +++++++++++++++++++ .../udp/broadcast/BroadcastingEchoServer.java | 44 ++++++++++ .../udp/multicast/MulticastEchoServer.java | 41 +++++++++ .../udp/multicast/MulticastingClient.java | 53 ++++++++++++ .../broadcast/BroadcastIntegrationTest.java | 39 +++++++++ .../multicast/MulticastIntegrationTest.java | 39 +++++++++ 6 files changed, 301 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java create mode 100644 core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java create mode 100644 core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java create mode 100644 core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java create mode 100644 core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java create mode 100644 core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java b/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java new file mode 100644 index 000000000000..3162ff0b1e62 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java @@ -0,0 +1,85 @@ +package com.baeldung.java.networking.udp.broadcast; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.stream.Collectors; + +public class BroadcastingClient { + private DatagramSocket socket; + private InetAddress address; + private int expectedServerCount; + private byte[] buf; + + public BroadcastingClient(int expectedServerCount) throws Exception { + this.expectedServerCount = expectedServerCount; + this.address = InetAddress.getByName("255.255.255.255"); + } + + public int discoverServers(String msg) throws IOException { + initializeSocketForBroadcasting(); + copyMessageOnBuffer(msg); + + // When we want to broadcast not just to local network, call listAllBroadcastAddresses() and execute broadcastPacket for each value. + broadcastPacket(address); + + return receivePackets(); + } + + List listAllBroadcastAddresses() throws SocketException { + List broadcastList = new ArrayList<>(); + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + while (interfaces.hasMoreElements()) { + NetworkInterface networkInterface = interfaces.nextElement(); + + if (networkInterface.isLoopback() || !networkInterface.isUp()) { + continue; + } + + broadcastList.addAll(networkInterface.getInterfaceAddresses() + .stream() + .filter(address -> address.getBroadcast() != null) + .map(address -> address.getBroadcast()) + .collect(Collectors.toList())); + } + return broadcastList; + } + + private void initializeSocketForBroadcasting() throws SocketException { + socket = new DatagramSocket(); + socket.setBroadcast(true); + } + + private void copyMessageOnBuffer(String msg) { + buf = msg.getBytes(); + } + + private void broadcastPacket(InetAddress address) throws IOException { + DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); + socket.send(packet); + } + + private int receivePackets() throws IOException { + int serversDiscovered = 0; + while (serversDiscovered != expectedServerCount) { + receivePacket(); + serversDiscovered++; + } + return serversDiscovered; + } + + private void receivePacket() throws IOException { + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + } + + public void close() { + socket.close(); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java b/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java new file mode 100644 index 000000000000..afc50e1f40ce --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java @@ -0,0 +1,44 @@ +package com.baeldung.java.networking.udp.broadcast; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.InetSocketAddress; + +public class BroadcastingEchoServer extends Thread { + + protected DatagramSocket socket = null; + protected boolean running; + protected byte[] buf = new byte[256]; + + public BroadcastingEchoServer() throws IOException { + socket = new DatagramSocket(null); + socket.setReuseAddress(true); + socket.bind(new InetSocketAddress(4445)); + } + + public void run() { + running = true; + + while (running) { + try { + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + InetAddress address = packet.getAddress(); + int port = packet.getPort(); + packet = new DatagramPacket(buf, buf.length, address, port); + String received = new String(packet.getData(), 0, packet.getLength()); + if (received.equals("end")) { + running = false; + continue; + } + socket.send(packet); + } catch (IOException e) { + e.printStackTrace(); + running = false; + } + } + socket.close(); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java b/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java new file mode 100644 index 000000000000..cae5c27d95e1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java @@ -0,0 +1,41 @@ +package com.baeldung.java.networking.udp.multicast; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.MulticastSocket; + +public class MulticastEchoServer extends Thread { + + protected MulticastSocket socket = null; + protected byte[] buf = new byte[256]; + protected InetAddress group = null; + + public MulticastEchoServer() throws IOException { + socket = new MulticastSocket(4446); + socket.setReuseAddress(true); + group = InetAddress.getByName("230.0.0.0"); + socket.joinGroup(group); + } + + public void run() { + try { + while (true) { + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + InetAddress address = packet.getAddress(); + int port = packet.getPort(); + packet = new DatagramPacket(buf, buf.length, address, port); + String received = new String(packet.getData(), 0, packet.getLength()); + if (received.equals("end")) { + break; + } + socket.send(packet); + } + socket.leaveGroup(group); + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java b/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java new file mode 100644 index 000000000000..4e425055fecc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java @@ -0,0 +1,53 @@ +package com.baeldung.java.networking.udp.multicast; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +public class MulticastingClient { + private DatagramSocket socket; + private InetAddress group; + private int expectedServerCount; + private byte[] buf; + + public MulticastingClient(int expectedServerCount) throws Exception { + this.expectedServerCount = expectedServerCount; + this.socket = new DatagramSocket(); + this.group = InetAddress.getByName("230.0.0.0"); + } + + public int discoverServers(String msg) throws IOException { + copyMessageOnBuffer(msg); + multicastPacket(); + + return receivePackets(); + } + + private void copyMessageOnBuffer(String msg) { + buf = msg.getBytes(); + } + + private void multicastPacket() throws IOException { + DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446); + socket.send(packet); + } + + private int receivePackets() throws IOException { + int serversDiscovered = 0; + while (serversDiscovered != expectedServerCount) { + receivePacket(); + serversDiscovered++; + } + return serversDiscovered; + } + + private void receivePacket() throws IOException { + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + } + + public void close() { + socket.close(); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java new file mode 100644 index 000000000000..e3ffbcc0523f --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.java.networking.udp.broadcast; + +import org.junit.After; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +public class BroadcastIntegrationTest { + private BroadcastingClient client; + + @Test + public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception { + int expectedServers = 4; + initializeForExpectedServers(expectedServers); + + int serversDiscovered = client.discoverServers("hello server"); + assertEquals(expectedServers, serversDiscovered); + } + + private void initializeForExpectedServers(int expectedServers) throws Exception { + for (int i = 0; i < expectedServers; i++) { + new BroadcastingEchoServer().start(); + } + + client = new BroadcastingClient(expectedServers); + } + + @After + public void tearDown() throws IOException { + stopEchoServer(); + client.close(); + } + + private void stopEchoServer() throws IOException { + client.discoverServers("end"); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java new file mode 100644 index 000000000000..26c0704b01ce --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.java.networking.udp.multicast; + +import org.junit.After; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +public class MulticastIntegrationTest { + private MulticastingClient client; + + @Test + public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception { + int expectedServers = 4; + initializeForExpectedServers(expectedServers); + + int serversDiscovered = client.discoverServers("hello server"); + assertEquals(expectedServers, serversDiscovered); + } + + private void initializeForExpectedServers(int expectedServers) throws Exception { + for (int i = 0; i < expectedServers; i++) { + new MulticastEchoServer().start(); + } + + client = new MulticastingClient(expectedServers); + } + + @After + public void tearDown() throws IOException { + stopEchoServer(); + client.close(); + } + + private void stopEchoServer() throws IOException { + client.discoverServers("end"); + } +} From 87cdf5d9dd2891eb97c08b96cc3b96e632186c52 Mon Sep 17 00:00:00 2001 From: mokhan Date: Mon, 14 Aug 2017 11:51:46 +0530 Subject: [PATCH 50/90] Spring Data Ldap --- spring-ldap/pom.xml | 246 +++++++++--------- .../baeldung/ldap/data/repository/User.java | 55 ++++ .../ldap/data/repository/UserRepository.java | 17 ++ .../ldap/data/service/LdapClient.java | 83 ++++++ .../ldap/data/service/UserService.java | 66 +++++ .../baeldung/ldap/javaconfig/AppConfig.java | 2 + .../ldap/client/LdapDataRepositoryTest.java | 68 +++++ .../baeldung/ldap/javaconfig/TestConfig.java | 2 + 8 files changed, 422 insertions(+), 117 deletions(-) create mode 100644 spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java create mode 100644 spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java create mode 100644 spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java create mode 100644 spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java create mode 100644 spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java diff --git a/spring-ldap/pom.xml b/spring-ldap/pom.xml index 16d4879f10f3..f000b07a0961 100644 --- a/spring-ldap/pom.xml +++ b/spring-ldap/pom.xml @@ -1,131 +1,143 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - com.baeldung - spring-ldap - 0.1-SNAPSHOT - jar + com.baeldung + spring-ldap + 0.1-SNAPSHOT + jar - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - 2.3.1.RELEASE - 4.3.6.RELEASE - 1.5.5 - 0.9.15 - + + 2.3.1.RELEASE + 4.3.6.RELEASE + 1.5.5 + 0.9.15 + - - spring-ldap - + + spring-ldap + - + - - org.springframework.ldap - spring-ldap-core - ${spring-ldap.version} - - - commons-logging - commons-logging - - - + + org.springframework.ldap + spring-ldap-core + ${spring-ldap.version} + + + commons-logging + commons-logging + + + - - org.springframework - spring-context - ${spring-context.version} - + + org.springframework + spring-context + ${spring-context.version} + - - - org.springframework.ldap - spring-ldap-test - ${spring-ldap.version} - test - - - commons-logging - commons-logging - - - + + + org.springframework.ldap + spring-ldap-test + ${spring-ldap.version} + test + + + commons-logging + commons-logging + + + - - - org.apache.directory.server - apacheds-core - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-core-entry - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-protocol-shared - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-protocol-ldap - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-server-jndi - ${apacheds.version} - test - - - org.apache.directory.shared - shared-ldap - ${shared-ldap.version} - test - + + + org.apache.directory.server + apacheds-core + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-core-entry + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-protocol-shared + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-protocol-ldap + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-server-jndi + ${apacheds.version} + test + + + org.apache.directory.shared + shared-ldap + ${shared-ldap.version} + test + - - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*IntegrationTest.java - - - **/*LiveTest.java - - - - - - - - - + + + org.springframework.data + spring-data-ldap + 1.0.6.RELEASE + + + org.springframework.data + spring-data-jpa + 1.11.6.RELEASE + + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + **/*LiveTest.java + + + + + + + + + \ No newline at end of file diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java new file mode 100644 index 000000000000..726fa53b0268 --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java @@ -0,0 +1,55 @@ +package com.baeldung.ldap.data.repository; + +import javax.naming.Name; + +import org.springframework.ldap.odm.annotations.Attribute; +import org.springframework.ldap.odm.annotations.Entry; +import org.springframework.ldap.odm.annotations.Id; + +@Entry(base = "ou=users", objectClasses = { "person", "inetOrgPerson", "top" }) +public class User { + + @Id + private Name id; + + private @Attribute(name = "cn") String username; + private @Attribute(name = "sn") String password; + + public User() { + } + + public User(String username, String password) { + this.username = username; + this.password = password; + } + + public Name getId() { + return id; + } + + public void setId(Name id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String toString() { + return username; + } + +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java new file mode 100644 index 000000000000..9140616eee7c --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.ldap.data.repository; + +import java.util.List; + +import org.springframework.data.ldap.repository.LdapRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends LdapRepository { + + public User findByUsername(String username); + + public User findByUsernameAndPassword(String username, String password); + + public List findByUsernameLikeIgnoreCase(String username); + +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java new file mode 100644 index 000000000000..753c5f6c34ff --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java @@ -0,0 +1,83 @@ +package com.baeldung.ldap.data.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.ldap.core.*; +import org.springframework.ldap.support.LdapNameBuilder; + +import javax.naming.Name; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.List; + +public class LdapClient { + + @Autowired + private Environment env; + + @Autowired + private ContextSource contextSource; + + @Autowired + private LdapTemplate ldapTemplate; + + public void authenticate(final String username, final String password) { + contextSource.getContext("cn=" + username + ",ou=users," + env.getRequiredProperty("ldap.partitionSuffix"), password); + } + + public List search(final String username) { + return ldapTemplate.search( + "ou=users", + "cn=" + username, + (AttributesMapper) attrs -> (String) attrs + .get("cn") + .get()); + } + + public void create(final String username, final String password) { + Name dn = LdapNameBuilder + .newInstance() + .add("ou", "users") + .add("cn", username) + .build(); + DirContextAdapter context = new DirContextAdapter(dn); + + context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); + context.setAttributeValue("cn", username); + context.setAttributeValue("sn", username); + context.setAttributeValue("userPassword", digestSHA(password)); + + ldapTemplate.bind(context); + } + + public void modify(final String username, final String password) { + Name dn = LdapNameBuilder + .newInstance() + .add("ou", "users") + .add("cn", username) + .build(); + DirContextOperations context = ldapTemplate.lookupContext(dn); + + context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); + context.setAttributeValue("cn", username); + context.setAttributeValue("sn", username); + context.setAttributeValue("userPassword", digestSHA(password)); + + ldapTemplate.modifyAttributes(context); + } + + private String digestSHA(final String password) { + String base64; + try { + MessageDigest digest = MessageDigest.getInstance("SHA"); + digest.update(password.getBytes()); + base64 = Base64 + .getEncoder() + .encodeToString(digest.digest()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return "{SHA}" + base64; + } +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java new file mode 100644 index 000000000000..39d4df1cd67c --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java @@ -0,0 +1,66 @@ +package com.baeldung.ldap.data.service; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.stereotype.Service; + +import com.baeldung.ldap.data.repository.User; +import com.baeldung.ldap.data.repository.UserRepository; + +@Service +public class UserService { + + @Autowired + private UserRepository userRepository; + + public Boolean authenticate(final String username, final String password) { + User user = userRepository.findByUsernameAndPassword(username, password); + return user != null ? true : false; + } + + public List search(final String username) { + List userList = userRepository.findByUsernameLikeIgnoreCase(username); + List users = null; + if (null != userList) { + users = new ArrayList(); + for (User user : userList) { + users.add(user.getUsername()); + } + } + return users; + + } + + public void create(final String username, final String password) { + User newUser = new User(username,digestSHA(password)); + newUser.setId(LdapUtils.emptyLdapName()); + userRepository.save(newUser); + + } + + public void modify(final String username, final String password) { + User user = userRepository.findByUsername(username); + user.setPassword(password); + userRepository.save(user); + + } + + private String digestSHA(final String password) { + String base64; + try { + MessageDigest digest = MessageDigest.getInstance("SHA"); + digest.update(password.getBytes()); + base64 = Base64.getEncoder() + .encodeToString(digest.digest()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return "{SHA}" + base64; + } +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java index 8572e5d1be61..9330da7ab764 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java @@ -7,6 +7,7 @@ import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; +import org.springframework.data.ldap.repository.config.EnableLdapRepositories; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; @@ -16,6 +17,7 @@ @PropertySource("classpath:application.properties") @ComponentScan(basePackages = { "com.baeldung.ldap.*" }) @Profile("default") +@EnableLdapRepositories(basePackages="com.baeldung.ldap.**") public class AppConfig { @Autowired diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java new file mode 100644 index 000000000000..8460fb3eb93b --- /dev/null +++ b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java @@ -0,0 +1,68 @@ +package com.baeldung.ldap.client; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.hamcrest.Matchers; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.ldap.data.service.UserService; +import com.baeldung.ldap.javaconfig.TestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ActiveProfiles("testlive") +@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +public class LdapDataRepositoryTest { + + private static final String USER2 = "TEST02"; + private static final String USER3 = "TEST03"; + private static final String USER4 = "TEST04"; + + private static final String USER2_PWD = "TEST02"; + private static final String USER3_PWD = "TEST03"; + private static final String USER4_PWD = "TEST04"; + + private static final String SEARCH_STRING = "TEST*"; + + @Autowired + private UserService userService; + + @Test + public void givenLdapClient_whenCorrectCredentials_thenSuccessfulLogin() { + Boolean isValid = userService.authenticate(USER3, USER3_PWD); + assertEquals(true, isValid); + } + + @Test + public void givenLdapClient_whenIncorrectCredentials_thenFailedLogin() { + Boolean isValid = userService.authenticate(USER3, USER2_PWD); + assertEquals(false, isValid); + } + + @Test + public void givenLdapClient_whenCorrectSearchFilter_thenEntriesReturned() { + List userList = userService.search(SEARCH_STRING); + assertThat(userList, Matchers.containsInAnyOrder(USER2, USER3)); + } + + @Test + public void givenLdapClientNotExists_whenDataProvided_thenNewUserCreated() { + userService.create(USER4, USER4_PWD); + userService.authenticate(USER4, USER4_PWD); + } + + @Test + public void givenLdapClientExists_whenDataProvided_thenExistingUserModified() { + userService.modify(USER2, USER3_PWD); + userService.authenticate(USER2, USER3_PWD); + } + +} diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java index e2968e977c82..0752262159bf 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java @@ -8,6 +8,7 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; +import org.springframework.data.ldap.repository.config.EnableLdapRepositories; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.ldap.test.TestContextSourceFactoryBean; @@ -17,6 +18,7 @@ @Configuration @PropertySource("classpath:test_application.properties") @ComponentScan(basePackages = { "com.baeldung.ldap.*" }) +@EnableLdapRepositories(basePackages="com.baeldung.ldap.**") @Profile("testlive") public class TestConfig { @Autowired From 43357b0809a079381c9980149236dc22af4ce19a Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 14 Aug 2017 11:00:51 +0200 Subject: [PATCH 51/90] Partitioner Refactor (#2434) * Refactor Batch * Refactor Batch --- .../{spring_batch_intro => batch}/App.java | 2 +- .../SpringBatchConfig.java | 20 +++---- .../SpringConfig.java | 2 +- .../model/Transaction.java | 2 +- .../CustomMultiResourcePartitioner.java | 2 +- .../SpringbatchPartitionConfig.java | 57 +++++++++---------- .../SpringbatchPartitionerApp.java | 2 +- .../service/CustomItemProcessor.java | 4 +- .../service/RecordFieldSetMapper.java | 4 +- .../src/main/resources/spring-batch-intro.xml | 6 +- 10 files changed, 49 insertions(+), 52 deletions(-) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/App.java (96%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/SpringBatchConfig.java (85%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/SpringConfig.java (98%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/model/Transaction.java (96%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/partitioner/CustomMultiResourcePartitioner.java (97%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/partitioner/SpringbatchPartitionConfig.java (84%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/partitioner/SpringbatchPartitionerApp.java (95%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/service/CustomItemProcessor.java (71%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/service/RecordFieldSetMapper.java (91%) diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch/src/main/java/org/baeldung/batch/App.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java rename to spring-batch/src/main/java/org/baeldung/batch/App.java index 2ce4dae6e698..cea4e8d486b9 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java +++ b/spring-batch/src/main/java/org/baeldung/batch/App.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro; +package org.baeldung.batch; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java similarity index 85% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java rename to spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java index 9973005c7c21..7b19935cc84f 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java +++ b/spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java @@ -1,11 +1,8 @@ -package org.baeldung.spring_batch_intro; +package org.baeldung.batch; -import java.net.MalformedURLException; -import java.text.ParseException; - -import org.baeldung.spring_batch_intro.model.Transaction; -import org.baeldung.spring_batch_intro.service.CustomItemProcessor; -import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper; +import org.baeldung.batch.model.Transaction; +import org.baeldung.batch.service.CustomItemProcessor; +import org.baeldung.batch.service.RecordFieldSetMapper; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; @@ -26,6 +23,9 @@ import org.springframework.oxm.Marshaller; import org.springframework.oxm.jaxb.Jaxb2Marshaller; +import java.net.MalformedURLException; +import java.text.ParseException; + public class SpringBatchConfig { @Autowired private JobBuilderFactory jobs; @@ -43,7 +43,7 @@ public class SpringBatchConfig { public ItemReader itemReader() throws UnexpectedInputException, ParseException { FlatFileItemReader reader = new FlatFileItemReader(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); - String[] tokens = { "username", "userid", "transactiondate", "amount" }; + String[] tokens = {"username", "userid", "transactiondate", "amount"}; tokenizer.setNames(tokens); reader.setResource(inputCsv); DefaultLineMapper lineMapper = new DefaultLineMapper(); @@ -71,13 +71,13 @@ public ItemWriter itemWriter(Marshaller marshaller) throws Malforme @Bean public Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); - marshaller.setClassesToBeBound(new Class[] { Transaction.class }); + marshaller.setClassesToBeBound(Transaction.class); return marshaller; } @Bean protected Step step1(ItemReader reader, ItemProcessor processor, ItemWriter writer) { - return steps.get("step1"). chunk(10).reader(reader).processor(processor).writer(writer).build(); + return steps.get("step1").chunk(10).reader(reader).processor(processor).writer(writer).build(); } @Bean(name = "firstBatchJob") diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java b/spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java similarity index 98% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java rename to spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java index ed7d302047bf..35abcb2d16e9 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java +++ b/spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro; +package org.baeldung.batch; import java.net.MalformedURLException; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java b/spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java rename to spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java index 3b2b9610f2cb..0ce3a413ab80 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java +++ b/spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro.model; +package org.baeldung.batch.model; import java.util.Date; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java b/spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java similarity index 97% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java rename to spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java index 4cae69efbd5a..667e013c3594 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java +++ b/spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.baeldung.spring_batch_intro.partitioner; +package org.baeldung.batch.partitioner; import java.util.HashMap; import java.util.Map; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java similarity index 84% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java rename to spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java index fe8339a8b4b6..ad3aee4a2e57 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java +++ b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java @@ -1,13 +1,7 @@ -package org.baeldung.spring_batch_intro.partitioner; +package org.baeldung.batch.partitioner; -import java.io.IOException; -import java.net.MalformedURLException; -import java.text.ParseException; - -import javax.sql.DataSource; - -import org.baeldung.spring_batch_intro.model.Transaction; -import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper; +import org.baeldung.batch.model.Transaction; +import org.baeldung.batch.service.RecordFieldSetMapper; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; @@ -33,7 +27,6 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.task.TaskExecutor; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.oxm.Marshaller; @@ -41,6 +34,11 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.transaction.PlatformTransactionManager; +import javax.sql.DataSource; +import java.io.IOException; +import java.net.MalformedURLException; +import java.text.ParseException; + @Configuration @EnableBatchProcessing public class SpringbatchPartitionConfig { @@ -57,26 +55,26 @@ public class SpringbatchPartitionConfig { @Bean(name = "partitionerJob") public Job partitionerJob() throws UnexpectedInputException, MalformedURLException, ParseException { return jobs.get("partitionerJob") - .start(partitionStep()) - .build(); + .start(partitionStep()) + .build(); } @Bean public Step partitionStep() throws UnexpectedInputException, MalformedURLException, ParseException { return steps.get("partitionStep") - .partitioner("slaveStep", partitioner()) - .step(slaveStep()) - .taskExecutor(taskExecutor()) - .build(); + .partitioner("slaveStep", partitioner()) + .step(slaveStep()) + .taskExecutor(taskExecutor()) + .build(); } @Bean public Step slaveStep() throws UnexpectedInputException, MalformedURLException, ParseException { return steps.get("slaveStep") - . chunk(1) - .reader(itemReader(null)) - .writer(itemWriter(marshaller(), null)) - .build(); + .chunk(1) + .reader(itemReader(null)) + .writer(itemWriter(marshaller(), null)) + .build(); } @Bean @@ -95,12 +93,12 @@ public CustomMultiResourcePartitioner partitioner() { @Bean @StepScope public FlatFileItemReader itemReader(@Value("#{stepExecutionContext[fileName]}") String filename) throws UnexpectedInputException, ParseException { - FlatFileItemReader reader = new FlatFileItemReader(); + FlatFileItemReader reader = new FlatFileItemReader<>(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); - String[] tokens = { "username", "userid", "transactiondate", "amount" }; + String[] tokens = {"username", "userid", "transactiondate", "amount"}; tokenizer.setNames(tokens); reader.setResource(new ClassPathResource("input/partitioner/" + filename)); - DefaultLineMapper lineMapper = new DefaultLineMapper(); + DefaultLineMapper lineMapper = new DefaultLineMapper<>(); lineMapper.setLineTokenizer(tokenizer); lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); reader.setLinesToSkip(1); @@ -121,7 +119,7 @@ public StaxEventItemWriter itemWriter(Marshaller marshaller, @Value @Bean public Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); - marshaller.setClassesToBeBound(new Class[] { Transaction.class }); + marshaller.setClassesToBeBound(Transaction.class); return marshaller; } @@ -142,16 +140,15 @@ private JobRepository getJobRepository() throws Exception { // JobRepositoryFactoryBean's methods Throws Generic Exception, // it would have been better to have a specific one factory.afterPropertiesSet(); - return (JobRepository) factory.getObject(); + return factory.getObject(); } private DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); - EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL) - .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql") - .addScript("classpath:org/springframework/batch/core/schema-h2.sql") - .build(); - return db; + return builder.setType(EmbeddedDatabaseType.HSQL) + .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql") + .addScript("classpath:org/springframework/batch/core/schema-h2.sql") + .build(); } private PlatformTransactionManager getTransactionManager() { diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java similarity index 95% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java rename to spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java index 1d6d92296933..e56afc591cee 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java +++ b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro.partitioner; +package org.baeldung.batch.partitioner; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java b/spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java similarity index 71% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java rename to spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java index ebee1d2802b6..8ca7892fec18 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java +++ b/spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java @@ -1,6 +1,6 @@ -package org.baeldung.spring_batch_intro.service; +package org.baeldung.batch.service; -import org.baeldung.spring_batch_intro.model.Transaction; +import org.baeldung.batch.model.Transaction; import org.springframework.batch.item.ItemProcessor; public class CustomItemProcessor implements ItemProcessor { diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java b/spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java similarity index 91% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java rename to spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java index 94f9e7d94e9f..fa6f0870aa57 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java +++ b/spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java @@ -1,9 +1,9 @@ -package org.baeldung.spring_batch_intro.service; +package org.baeldung.batch.service; import java.text.ParseException; import java.text.SimpleDateFormat; -import org.baeldung.spring_batch_intro.model.Transaction; +import org.baeldung.batch.model.Transaction; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.transform.FieldSet; import org.springframework.validation.BindException; diff --git a/spring-batch/src/main/resources/spring-batch-intro.xml b/spring-batch/src/main/resources/spring-batch-intro.xml index 93606d232f54..0f76dd50ffb9 100644 --- a/spring-batch/src/main/resources/spring-batch-intro.xml +++ b/spring-batch/src/main/resources/spring-batch-intro.xml @@ -22,14 +22,14 @@ + class="org.baeldung.batch.service.RecordFieldSetMapper" /> - + @@ -40,7 +40,7 @@ - org.baeldung.spring_batch_intro.model.Transaction + org.baeldung.batch.model.Transaction From 8d9a7b0ecff611b751f103537b20b78ae1c5464d Mon Sep 17 00:00:00 2001 From: Roman Seleznov Date: Mon, 14 Aug 2017 14:12:29 +0100 Subject: [PATCH 52/90] BAEL-764 Automatic Property Expansion with Spring Boot (#2435) * Create pom.xml Initial import * First submit * Second submit * Different Types of Bean Injection in Spring * Different Types of Bean Injection in Spring * Added spring-core-di into the main build * Revert "Create pom.xml" This reverts commit 1bdc5443125df19575605f41ab28c9e8b6c69a32. * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot Make executable jars for property-exp-default project and use mvn exec:java to run property-exp-default project * BAEL-764 Automatic Property Expansion with Spring Boot Rename modules as per code reivew * BAEL-764 Automatic Property Expansion with Spring Boot Updated README.md as per code review * BAEL-764 Automatic Property Expansion with Spring Boot Updated README.md as per code review * BAEL-764 Automatic Property Expansion with Spring Boot Updated README.md as per code review * BAEL-764 Automatic Property Expansion with Spring Boot Updated README.md as per code review --- spring-boot-property-exp/README.md | 18 +++++++++++++++++- .../property-exp-custom-config/pom.xml | 2 +- .../property-exp-default-config/pom.xml | 2 +- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/spring-boot-property-exp/README.md b/spring-boot-property-exp/README.md index 5b2552ade78f..8a598e7a0545 100644 --- a/spring-boot-property-exp/README.md +++ b/spring-boot-property-exp/README.md @@ -1,2 +1,18 @@ ## The Module Holds Sources for the Following Articles - - [Automatic Property Expansion with Spring Boot] (http://www.baeldung.com/property-expansion-spring-boot) \ No newline at end of file + - [Automatic Property Expansion with Spring Boot](http://www.baeldung.com/property-expansion-spring-boot) + +### Module property-exp-default-config + This module contains both a standard Maven Spring Boot build and the Gradle build which is Maven compatible. + + In order to execute the Maven example, run the following command: + + `mvn spring-boot:run` + + To execute the Gradle example: + +`gradle bootRun` + + ### Module property-exp-custom-config + This project is not using the standard Spring Boot parent and is configured manually. Run the following command: + + `mvn exec:java` \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-custom-config/pom.xml b/spring-boot-property-exp/property-exp-custom-config/pom.xml index cfce323eabb4..7822b31cf270 100644 --- a/spring-boot-property-exp/property-exp-custom-config/pom.xml +++ b/spring-boot-property-exp/property-exp-custom-config/pom.xml @@ -9,7 +9,7 @@ 4.0.0 com.baeldung - property-exp-custom + property-exp-custom-config 0.0.1-SNAPSHOT jar diff --git a/spring-boot-property-exp/property-exp-default-config/pom.xml b/spring-boot-property-exp/property-exp-default-config/pom.xml index 2544800e6a1e..0625916d328c 100644 --- a/spring-boot-property-exp/property-exp-default-config/pom.xml +++ b/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -11,7 +11,7 @@ com.baeldung - property-exp-default + property-exp-default-config 0.0.1-SNAPSHOT jar From 99eee4df2cd1a0dbf9e4011864bf16f1d90b35be Mon Sep 17 00:00:00 2001 From: baljeet20 Date: Mon, 14 Aug 2017 22:38:01 +0530 Subject: [PATCH 53/90] BAEL-1077 Guide to volatile keyword (#2433) * review changes * BAEL-1024 Removed the proxy reference * BAEL-1024 Renamed methods * BAEL-1077 Guide to volatile keyword --- .../volatilekeyword/SharedObject.java | 13 +++ .../SharedObjectManualTest.java | 99 +++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java create mode 100644 core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java b/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java new file mode 100644 index 000000000000..3f24df5059b2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.volatilekeyword; + + +public class SharedObject { + private volatile int count=0; + + public void increamentCount(){ + count++; + } + public int getCount(){ + return count; + } +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java b/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java new file mode 100644 index 000000000000..260a7c060bdc --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java @@ -0,0 +1,99 @@ +package com.baeldung.concurrent.volatilekeyword; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static junit.framework.Assert.assertEquals; + +public class SharedObjectManualTest { + + SharedObject sharedObject; + int valueReadByThread2; + int valueReadByThread3; + + @Before + public void setUp(){ + sharedObject = new SharedObject(); + } + + @Test + public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { + Thread writer = new Thread(){ + public void run(){ + sharedObject.increamentCount(); + } + }; + writer.start(); + + + Thread readerOne = new Thread(){ + public void run(){ + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + valueReadByThread2= sharedObject.getCount(); + } + }; + readerOne.start(); + + Thread readerTwo = new Thread(){ + public void run(){ + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + valueReadByThread3=sharedObject.getCount(); + } + }; + readerTwo.start(); + + assertEquals(1,valueReadByThread2); + assertEquals(1,valueReadByThread3); + + } + + @Test + public void whenTwoThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { + Thread writerOne = new Thread(){ + public void run(){ + sharedObject.increamentCount(); + } + }; + writerOne.start(); + Thread.sleep(100); + + Thread writerTwo = new Thread(){ + public void run(){ + sharedObject.increamentCount(); + } + }; + writerTwo.start(); + Thread.sleep(100); + + Thread readerOne = new Thread(){ + public void run(){ + valueReadByThread2= sharedObject.getCount(); + } + }; + readerOne.start(); + + Thread readerTwo = new Thread(){ + public void run(){ + valueReadByThread3=sharedObject.getCount(); + } + }; + readerTwo.start(); + + assertEquals(2,valueReadByThread2); + assertEquals(2,valueReadByThread3); + + } + @After + public void cleanup(){ + sharedObject = null; + } +} From 58469d79bf11cb7349e220588d7472a499108acd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Ju=C3=A1rez?= Date: Mon, 14 Aug 2017 12:45:30 -0500 Subject: [PATCH 54/90] BAEL-864 Difference between URL and URI (#2438) --- .../uriurl/URIvsURLUnitTest.java | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java new file mode 100644 index 000000000000..ed36951f73c2 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java @@ -0,0 +1,78 @@ +package com.baeldung.javanetworking.uriurl; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import org.apache.commons.io.IOUtils; +import static org.junit.Assert.*; +import org.junit.Test; + +public class URIvsURLUnitTest { + + @Test + public void whenCreatingURIs_thenSameInfo() throws URISyntaxException { + URI firstURI = new URI("somescheme://theuser:thepassword@someauthority:80/some/path?thequery#somefragment"); + URI secondURI = new URI("somescheme", "theuser:thepassword", "someuthority", 80, "/some/path", "thequery", "somefragment"); + + assertEquals(firstURI.getScheme(), secondURI.getScheme()); + assertEquals(firstURI.getPath(), secondURI.getPath()); + } + + @Test + public void whenCreatingURLs_thenSameInfo() throws MalformedURLException { + URL firstURL = new URL("http://theuser:thepassword@somehost:80/path/to/file?thequery#somefragment"); + URL secondURL = new URL("http", "somehost", 80, "/path/to/file"); + + assertEquals(firstURL.getHost(), secondURL.getHost()); + assertEquals(firstURL.getPath(), secondURL.getPath()); + } + + @Test + public void whenCreatingURI_thenCorrect() { + URI uri = URI.create("urn:isbn:1234567890"); + + assertNotNull(uri); + } + + @Test(expected = MalformedURLException.class) + public void whenCreatingURLs_thenException() throws MalformedURLException { + URL theURL = new URL("otherprotocol://somehost/path/to/file"); + + assertNotNull(theURL); + } + + @Test + public void givenObjects_whenConverting_thenCorrect() throws MalformedURLException, URISyntaxException { + String aURIString = "http://somehost:80/path?thequery"; + URI uri = new URI(aURIString); + URL url = new URL(aURIString); + + URL toURL = uri.toURL(); + URI toURI = url.toURI(); + + assertNotNull(url); + assertNotNull(uri); + assertEquals(toURL.toString(), toURI.toString()); + } + + @Test(expected = MalformedURLException.class) + public void givenURI_whenConvertingToURL_thenException() throws MalformedURLException, URISyntaxException { + URI uri = new URI("somescheme://someauthority/path?thequery"); + + URL url = uri.toURL(); + + assertNotNull(url); + } + + @Test + public void givenURL_whenGettingContents_thenCorrect() throws MalformedURLException, IOException { + URL url = new URL("http://courses.baeldung.com"); + + String contents = IOUtils.toString(url.openStream()); + + assertTrue(contents.contains("")); + } + +} From 0de69c346c87c2f628cfe93dc6688312cb8db580 Mon Sep 17 00:00:00 2001 From: lor6 Date: Mon, 14 Aug 2017 20:46:16 +0300 Subject: [PATCH 55/90] add dependency management (#2382) --- spring-boot-bootstrap/pom.xml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 697a139eb511..9da37a32617a 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -17,6 +17,25 @@ 1.5.3.RELEASE + + UTF-8 From dc9ecc143df547e16725fbad678fe75211f8f423 Mon Sep 17 00:00:00 2001 From: Nikhil Khatwani Date: Mon, 14 Aug 2017 23:59:36 +0530 Subject: [PATCH 56/90] Added test cases for BAEL-897 (#2436) --- .../test/JacksonDeserializationUnitTest.java | 40 ++++++++++++++++++- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java index 45d957b90bcd..035ff8ca9cf9 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java @@ -1,19 +1,23 @@ package com.baeldung.jackson.test; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import java.io.IOException; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +import org.junit.Test; import com.baeldung.jackson.deserialization.ItemDeserializer; import com.baeldung.jackson.dtos.Item; import com.baeldung.jackson.dtos.ItemWithSerializer; import com.baeldung.jackson.dtos.MyDto; import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreUnknown; -import org.junit.Test; - import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; @@ -21,6 +25,7 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import com.fasterxml.jackson.databind.module.SimpleModule; @@ -165,4 +170,35 @@ public final void givenDeserializerIsOnClass_whenDeserializingCustomRepresentati assertThat(readValue, notNullValue()); } + @Test + public void whenDeserialisingZonedDateTimeWithDefaults_thenTimeZoneIsNotPreserved() throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + // construct a new instance of ZonedDateTime + ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); + String converted = objectMapper.writeValueAsString(now); + // restore an instance of ZonedDateTime from String + ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); + System.out.println("serialized: " + now); + System.out.println("restored: " + restored); + assertThat(now, is(not(restored))); + } + + @Test + public void whenDeserialisingZonedDateTimeWithFeaturesDisabled_thenTimeZoneIsPreserved() throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); + // construct a new instance of ZonedDateTime + ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); + String converted = objectMapper.writeValueAsString(now); + // restore an instance of ZonedDateTime from String + ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); + System.out.println("serialized: " + now); + System.out.println("restored: " + restored); + assertThat(now, is(restored)); + } + } From bcc122b7247753923d34e593665c84af3aa8c3a4 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 14 Aug 2017 21:46:04 +0200 Subject: [PATCH 57/90] Refactor Batch (#2439) --- spring-ldap/pom.xml | 256 +++++++++--------- .../ldap/data/repository/UserRepository.java | 6 +- .../ldap/data/service/LdapClient.java | 14 +- .../ldap/data/service/UserService.java | 31 +-- .../baeldung/ldap/javaconfig/AppConfig.java | 7 +- spring-ldap/src/main/resources/logback.xml | 8 +- .../ldap/client/LdapClientLiveTest.java | 7 +- .../ldap/client/LdapDataRepositoryTest.java | 15 +- .../baeldung/ldap/javaconfig/TestConfig.java | 7 +- 9 files changed, 174 insertions(+), 177 deletions(-) diff --git a/spring-ldap/pom.xml b/spring-ldap/pom.xml index f000b07a0961..05baf8c66d88 100644 --- a/spring-ldap/pom.xml +++ b/spring-ldap/pom.xml @@ -1,143 +1,143 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - com.baeldung - spring-ldap - 0.1-SNAPSHOT - jar + com.baeldung + spring-ldap + 0.1-SNAPSHOT + jar - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - 2.3.1.RELEASE - 4.3.6.RELEASE - 1.5.5 - 0.9.15 - + + 2.3.1.RELEASE + 4.3.6.RELEASE + 1.5.5 + 0.9.15 + - - spring-ldap - + + spring-ldap + - + - - org.springframework.ldap - spring-ldap-core - ${spring-ldap.version} - - - commons-logging - commons-logging - - - + + org.springframework.ldap + spring-ldap-core + ${spring-ldap.version} + + + commons-logging + commons-logging + + + - - org.springframework - spring-context - ${spring-context.version} - + + org.springframework + spring-context + ${spring-context.version} + - - - org.springframework.ldap - spring-ldap-test - ${spring-ldap.version} - test - - - commons-logging - commons-logging - - - + + + org.springframework.ldap + spring-ldap-test + ${spring-ldap.version} + test + + + commons-logging + commons-logging + + + - - - org.apache.directory.server - apacheds-core - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-core-entry - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-protocol-shared - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-protocol-ldap - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-server-jndi - ${apacheds.version} - test - - - org.apache.directory.shared - shared-ldap - ${shared-ldap.version} - test - + + + org.apache.directory.server + apacheds-core + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-core-entry + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-protocol-shared + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-protocol-ldap + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-server-jndi + ${apacheds.version} + test + + + org.apache.directory.shared + shared-ldap + ${shared-ldap.version} + test + - - - org.springframework.data - spring-data-ldap - 1.0.6.RELEASE - - - org.springframework.data - spring-data-jpa - 1.11.6.RELEASE - - + + + org.springframework.data + spring-data-ldap + 1.0.6.RELEASE + + + org.springframework.data + spring-data-jpa + 1.11.6.RELEASE + + - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*IntegrationTest.java - - - **/*LiveTest.java - - - - - - - - - + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + **/*LiveTest.java + + + + + + + + + \ No newline at end of file diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java index 9140616eee7c..12dc0f7f1438 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java @@ -8,10 +8,10 @@ @Repository public interface UserRepository extends LdapRepository { - public User findByUsername(String username); + User findByUsername(String username); - public User findByUsernameAndPassword(String username, String password); + User findByUsernameAndPassword(String username, String password); - public List findByUsernameLikeIgnoreCase(String username); + List findByUsernameLikeIgnoreCase(String username); } diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java index 753c5f6c34ff..1b04edb35b5a 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java @@ -2,7 +2,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.ldap.core.*; +import org.springframework.ldap.core.AttributesMapper; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DirContextOperations; +import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.support.LdapNameBuilder; import javax.naming.Name; @@ -31,8 +35,8 @@ public List search(final String username) { "ou=users", "cn=" + username, (AttributesMapper) attrs -> (String) attrs - .get("cn") - .get()); + .get("cn") + .get()); } public void create(final String username, final String password) { @@ -43,7 +47,7 @@ public void create(final String username, final String password) { .build(); DirContextAdapter context = new DirContextAdapter(dn); - context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); + context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"}); context.setAttributeValue("cn", username); context.setAttributeValue("sn", username); context.setAttributeValue("userPassword", digestSHA(password)); @@ -59,7 +63,7 @@ public void modify(final String username, final String password) { .build(); DirContextOperations context = ldapTemplate.lookupContext(dn); - context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); + context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"}); context.setAttributeValue("cn", username); context.setAttributeValue("sn", username); context.setAttributeValue("userPassword", digestSHA(password)); diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java index 39d4df1cd67c..54954e3c9d4c 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java @@ -1,17 +1,17 @@ package com.baeldung.ldap.data.service; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Base64; -import java.util.List; - +import com.baeldung.ldap.data.repository.User; +import com.baeldung.ldap.data.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ldap.support.LdapUtils; import org.springframework.stereotype.Service; -import com.baeldung.ldap.data.repository.User; -import com.baeldung.ldap.data.repository.UserRepository; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; @Service public class UserService { @@ -21,20 +21,18 @@ public class UserService { public Boolean authenticate(final String username, final String password) { User user = userRepository.findByUsernameAndPassword(username, password); - return user != null ? true : false; + return user != null; } public List search(final String username) { List userList = userRepository.findByUsernameLikeIgnoreCase(username); - List users = null; - if (null != userList) { - users = new ArrayList(); - for (User user : userList) { - users.add(user.getUsername()); - } + if (userList == null) { + return Collections.emptyList(); } - return users; + return userList.stream() + .map(User::getUsername) + .collect(Collectors.toList()); } public void create(final String username, final String password) { @@ -48,7 +46,6 @@ public void modify(final String username, final String password) { User user = userRepository.findByUsername(username); user.setPassword(password); userRepository.save(user); - } private String digestSHA(final String password) { diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java index 9330da7ab764..fb3000b2bda8 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java @@ -1,5 +1,6 @@ package com.baeldung.ldap.javaconfig; +import com.baeldung.ldap.client.LdapClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -11,13 +12,11 @@ import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; -import com.baeldung.ldap.client.LdapClient; - @Configuration @PropertySource("classpath:application.properties") -@ComponentScan(basePackages = { "com.baeldung.ldap.*" }) +@ComponentScan(basePackages = {"com.baeldung.ldap.*"}) @Profile("default") -@EnableLdapRepositories(basePackages="com.baeldung.ldap.**") +@EnableLdapRepositories(basePackages = "com.baeldung.ldap.**") public class AppConfig { @Autowired diff --git a/spring-ldap/src/main/resources/logback.xml b/spring-ldap/src/main/resources/logback.xml index ec0dc2469ae0..32b78577ee9e 100644 --- a/spring-ldap/src/main/resources/logback.xml +++ b/spring-ldap/src/main/resources/logback.xml @@ -7,13 +7,13 @@ - - + + - + - + \ No newline at end of file diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java index b65588dc38f7..f5b74d64c618 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java @@ -1,7 +1,6 @@ package com.baeldung.ldap.client; -import java.util.List; - +import com.baeldung.ldap.javaconfig.TestConfig; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; @@ -13,11 +12,11 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.baeldung.ldap.javaconfig.TestConfig; +import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("testlive") -@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) public class LdapClientLiveTest { private static final String USER2 = "TEST02"; diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java index 8460fb3eb93b..9f38af92637f 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java @@ -1,10 +1,7 @@ package com.baeldung.ldap.client; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.util.List; - +import com.baeldung.ldap.data.service.UserService; +import com.baeldung.ldap.javaconfig.TestConfig; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -14,12 +11,14 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.baeldung.ldap.data.service.UserService; -import com.baeldung.ldap.javaconfig.TestConfig; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("testlive") -@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) public class LdapDataRepositoryTest { private static final String USER2 = "TEST02"; diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java index 0752262159bf..c6293982daa4 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java @@ -1,5 +1,6 @@ package com.baeldung.ldap.javaconfig; +import com.baeldung.ldap.client.LdapClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -13,12 +14,10 @@ import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.ldap.test.TestContextSourceFactoryBean; -import com.baeldung.ldap.client.LdapClient; - @Configuration @PropertySource("classpath:test_application.properties") -@ComponentScan(basePackages = { "com.baeldung.ldap.*" }) -@EnableLdapRepositories(basePackages="com.baeldung.ldap.**") +@ComponentScan(basePackages = {"com.baeldung.ldap.*"}) +@EnableLdapRepositories(basePackages = "com.baeldung.ldap.**") @Profile("testlive") public class TestConfig { @Autowired From 9308baeb9c6ca5b449746bb02935f69391e3746c Mon Sep 17 00:00:00 2001 From: Mohit Sinha Date: Tue, 15 Aug 2017 14:52:38 +0530 Subject: [PATCH 58/90] BAEL-1105: Apache Commons CSV, Test cases --- libraries/pom.xml | 8 ++- .../commons/csv/CSVReaderWriterTest.java | 60 +++++++++++++++++++ libraries/src/test/resources/book.csv | 3 + 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java create mode 100644 libraries/src/test/resources/book.csv diff --git a/libraries/pom.xml b/libraries/pom.xml index a16a4de59dfc..c70db4ffb2dc 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -212,6 +212,11 @@ commons-chain ${commons-chain.version} + + org.apache.commons + commons-csv + ${commons-csv.version} + commons-dbutils commons-dbutils @@ -480,6 +485,7 @@ 1.1 1.9.3 1.2 + 1.4 1.9.2 1.2 3.21.0-GA @@ -515,4 +521,4 @@ 1.0 8.2.0 - \ No newline at end of file + diff --git a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java new file mode 100644 index 000000000000..deab15a8121c --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java @@ -0,0 +1,60 @@ +package com.baeldung.commons.csv; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.csv.CSVRecord; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.io.StringWriter; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class CSVReaderWriterTest { + + public static final Map AUTHOR_BOOK_MAP = Collections.unmodifiableMap(new LinkedHashMap() { + { + put("Dan Simmons", "Hyperion"); + put("Douglas Adams", "The Hitchhiker's Guide to the Galaxy"); + } + }); + public static final String[] HEADERS = { "author", "title" }; + public static final String EXPECTED_FILESTREAM = "author,title\r\n" + "Dan Simmons,Hyperion\r\n" + "Douglas Adams,The Hitchhiker's Guide to the Galaxy"; + + @Test + public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException { + Reader in = new FileReader("src/test/resources/book.csv"); + Iterable records = CSVFormat.DEFAULT + .withHeader(HEADERS) + .withFirstRecordAsHeader() + .parse(in); + for (CSVRecord record : records) { + String author = record.get("author"); + String title = record.get("title"); + assertEquals(AUTHOR_BOOK_MAP.get(author), title); + } + } + + @Test + public void givenAuthorBookMap_whenProcessed_thenFileCreatedAsExpected() throws IOException { + StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(HEADERS))) { + AUTHOR_BOOK_MAP.forEach((author, title) -> { + try { + printer.printRecord(author, title); + } catch (IOException e) { + e.printStackTrace(); + } + }); + } + assertEquals(EXPECTED_FILESTREAM, sw + .toString() + .trim()); + } + +} diff --git a/libraries/src/test/resources/book.csv b/libraries/src/test/resources/book.csv new file mode 100644 index 000000000000..d709152a5e97 --- /dev/null +++ b/libraries/src/test/resources/book.csv @@ -0,0 +1,3 @@ +author,title +Dan Simmons,Hyperion +Douglas Adams,The Hitchhiker's Guide to the Galaxy From 299be4a62916101e53483de9ad5784c0c450ba5a Mon Sep 17 00:00:00 2001 From: Mohit Sinha Date: Tue, 15 Aug 2017 15:28:51 +0530 Subject: [PATCH 59/90] BAEL-1105: Apache Commons CSV, Changed name of testcase --- .../test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java index deab15a8121c..6f47b8939665 100644 --- a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java +++ b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java @@ -41,7 +41,7 @@ public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException { } @Test - public void givenAuthorBookMap_whenProcessed_thenFileCreatedAsExpected() throws IOException { + public void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(HEADERS))) { AUTHOR_BOOK_MAP.forEach((author, title) -> { From 00e3483531aeb25421d33e48c2aa7b7c5e430f46 Mon Sep 17 00:00:00 2001 From: deep20jain Date: Tue, 15 Aug 2017 17:12:33 +0530 Subject: [PATCH 60/90] Bael 1053 - Removing java from package name (#2443) * Adding code for java broadcasting and multicasting * Changing multicast ip * Adding code to iterate thorugh all network interfaces * Formatting again and fixing bug * Applying formatting rules on all classes * Fixing formatting * Removing java from package name * Deleting duplicate files * Removing unused imports --- .../src/main/java/com/baeldung/{java => }/networking/README.md | 0 .../{java => }/networking/cookies/PersistentCookieStore.java | 2 +- .../{java => }/networking/cookies/ProxyAcceptCookiePolicy.java | 2 +- .../java/com/baeldung/{java => }/networking/udp/EchoClient.java | 2 +- .../java/com/baeldung/{java => }/networking/udp/EchoServer.java | 2 +- .../{java => }/networking/udp/broadcast/BroadcastingClient.java | 2 +- .../networking/udp/broadcast/BroadcastingEchoServer.java | 2 +- .../networking/udp/multicast/MulticastEchoServer.java | 2 +- .../{java => }/networking/udp/multicast/MulticastingClient.java | 2 +- .../baeldung/{java => }/networking/udp/UDPIntegrationTest.java | 2 +- .../networking/udp/broadcast/BroadcastIntegrationTest.java | 2 +- .../networking/udp/multicast/MulticastIntegrationTest.java | 2 +- 12 files changed, 11 insertions(+), 11 deletions(-) rename core-java/src/main/java/com/baeldung/{java => }/networking/README.md (100%) rename core-java/src/main/java/com/baeldung/{java => }/networking/cookies/PersistentCookieStore.java (96%) rename core-java/src/main/java/com/baeldung/{java => }/networking/cookies/ProxyAcceptCookiePolicy.java (93%) rename core-java/src/main/java/com/baeldung/{java => }/networking/udp/EchoClient.java (96%) rename core-java/src/main/java/com/baeldung/{java => }/networking/udp/EchoServer.java (96%) rename core-java/src/main/java/com/baeldung/{java => }/networking/udp/broadcast/BroadcastingClient.java (98%) rename core-java/src/main/java/com/baeldung/{java => }/networking/udp/broadcast/BroadcastingEchoServer.java (96%) rename core-java/src/main/java/com/baeldung/{java => }/networking/udp/multicast/MulticastEchoServer.java (96%) rename core-java/src/main/java/com/baeldung/{java => }/networking/udp/multicast/MulticastingClient.java (96%) rename core-java/src/test/java/com/baeldung/{java => }/networking/udp/UDPIntegrationTest.java (95%) rename core-java/src/test/java/com/baeldung/{java => }/networking/udp/broadcast/BroadcastIntegrationTest.java (95%) rename core-java/src/test/java/com/baeldung/{java => }/networking/udp/multicast/MulticastIntegrationTest.java (95%) diff --git a/core-java/src/main/java/com/baeldung/java/networking/README.md b/core-java/src/main/java/com/baeldung/networking/README.md similarity index 100% rename from core-java/src/main/java/com/baeldung/java/networking/README.md rename to core-java/src/main/java/com/baeldung/networking/README.md diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java b/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java rename to core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java index 0d66406ac23d..5d30491cfeb5 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java +++ b/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.cookies; +package com.baeldung.networking.cookies; import java.net.*; import java.util.List; diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java b/core-java/src/main/java/com/baeldung/networking/cookies/ProxyAcceptCookiePolicy.java similarity index 93% rename from core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java rename to core-java/src/main/java/com/baeldung/networking/cookies/ProxyAcceptCookiePolicy.java index 6d6371bfe000..0b5f6d771485 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java +++ b/core-java/src/main/java/com/baeldung/networking/cookies/ProxyAcceptCookiePolicy.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.cookies; +package com.baeldung.networking.cookies; import java.net.*; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java b/core-java/src/main/java/com/baeldung/networking/udp/EchoClient.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java rename to core-java/src/main/java/com/baeldung/networking/udp/EchoClient.java index 916442533bfb..35a083de26f9 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/EchoClient.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp; +package com.baeldung.networking.udp; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java b/core-java/src/main/java/com/baeldung/networking/udp/EchoServer.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java rename to core-java/src/main/java/com/baeldung/networking/udp/EchoServer.java index 900d330786d3..34f2971cc45a 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/EchoServer.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp; +package com.baeldung.networking.udp; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java b/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingClient.java similarity index 98% rename from core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java rename to core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingClient.java index 3162ff0b1e62..09794c259618 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingClient.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingClient.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp.broadcast; +package com.baeldung.networking.udp.broadcast; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java b/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingEchoServer.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java rename to core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingEchoServer.java index afc50e1f40ce..b519f899bb08 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/broadcast/BroadcastingEchoServer.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingEchoServer.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp.broadcast; +package com.baeldung.networking.udp.broadcast; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java b/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastEchoServer.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java rename to core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastEchoServer.java index cae5c27d95e1..9d63dd6386c2 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastEchoServer.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastEchoServer.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp.multicast; +package com.baeldung.networking.udp.multicast; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java b/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastingClient.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java rename to core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastingClient.java index 4e425055fecc..e89abc939d46 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/multicast/MulticastingClient.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastingClient.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp.multicast; +package com.baeldung.networking.udp.multicast; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java b/core-java/src/test/java/com/baeldung/networking/udp/UDPIntegrationTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java rename to core-java/src/test/java/com/baeldung/networking/udp/UDPIntegrationTest.java index aff851ae4b63..968c01d24ea9 100644 --- a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/networking/udp/UDPIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp; +package com.baeldung.networking.udp; import org.junit.After; import org.junit.Before; diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java b/core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastIntegrationTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java rename to core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastIntegrationTest.java index e3ffbcc0523f..c4f1e1f42c3f 100644 --- a/core-java/src/test/java/com/baeldung/java/networking/udp/broadcast/BroadcastIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp.broadcast; +package com.baeldung.networking.udp.broadcast; import org.junit.After; import org.junit.Test; diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java b/core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastIntegrationTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java rename to core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastIntegrationTest.java index 26c0704b01ce..404f6c4e85c2 100644 --- a/core-java/src/test/java/com/baeldung/java/networking/udp/multicast/MulticastIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp.multicast; +package com.baeldung.networking.udp.multicast; import org.junit.After; import org.junit.Test; From 1a9c33f76f5ecf270d417914b0adacf4032e5aa4 Mon Sep 17 00:00:00 2001 From: buddhini81 Date: Tue, 15 Aug 2017 17:25:07 +0530 Subject: [PATCH 61/90] Commit source code for BAEL-698 (#2429) * Commit source for BAEL-698 * Commit model classes for BAEL-698 * remove file BAEL-698 * Commit source for BAEL-698 * Commit util class for BAEL-698 * delete file * Commit source for BAEL-698 * Commit spring config class for BAEL-698 * delete file * Commit source for BAEL-698 * Commit DAO classes for BAEL-698 * delete file * Commit source for BAEL-698 * Commit DAO Impl classes for BAEL-698 * delete file * Add Hibernate config XML BAEL-698 * Commit source for BAEL-698 * Commit test classes for BAEL-698 * delete file * Upgrade versions Upgrade spring framework version & tomcat-dbcp.version version, add mysql-connector-java dependency * Fix typo in class name * Fix type in PersistenceConfig class name * Remove class with typo error * Create tst.txt * Commit the corrected class * Delete tst.txt * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues * Fix minor formatting issues --- spring-hibernate5/pom.xml | 11 ++- .../hibernate/manytomany/model/Employee.java | 86 +++++++++++++++++++ .../hibernate/manytomany/model/Project.java | 61 +++++++++++++ .../manytomany/util/HibernateUtil.java | 41 +++++++++ .../manytomany/spring/PersistenceConfig.java | 70 +++++++++++++++ .../manytomany/dao/IEmployeeDao.java | 8 ++ .../manytomany/dao/IProjectDao.java | 8 ++ .../manytomany/dao/impl/EmployeeDao.java | 16 ++++ .../manytomany/dao/impl/ProjectDao.java | 17 ++++ .../src/main/resources/manytomany.cfg.xml | 27 ++++++ ...notationJavaConfigMainIntegrationTest.java | 53 ++++++++++++ ...nnotationXMLConfigMainIntegrationTest.java | 84 ++++++++++++++++++ 12 files changed, 480 insertions(+), 2 deletions(-) create mode 100644 spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java create mode 100644 spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java create mode 100644 spring-hibernate5/src/main/resources/manytomany.cfg.xml create mode 100644 spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java create mode 100644 spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java diff --git a/spring-hibernate5/pom.xml b/spring-hibernate5/pom.xml index e3309ff10b83..dac43c4dd3bc 100644 --- a/spring-hibernate5/pom.xml +++ b/spring-hibernate5/pom.xml @@ -120,6 +120,12 @@ hsqldb ${hsqldb.version} + + + mysql + mysql-connector-java + ${mysql-connector-java.version} + com.h2database @@ -167,7 +173,7 @@ - 4.3.5.RELEASE + 4.3.10.RELEASE 1.10.6.RELEASE @@ -177,7 +183,8 @@ 5.2.10.Final - 8.5.15 + 8.0.7-dmr + 9.0.0.M26 1.1 2.3.4 1.4.195 diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java new file mode 100644 index 000000000000..f1ad30b090cf --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java @@ -0,0 +1,86 @@ +package com.baeldung.hibernate.manytomany.model; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.JoinTable; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "Employee") +public class Employee implements Serializable { + @Id + @Column(name = "employee_id") + @GeneratedValue + private Long employeeId; + + @Column(name = "first_name") + private String firstName; + + @Column(name = "last_name") + private String lastName; + + @ManyToMany(cascade = { CascadeType.ALL }) + @JoinTable( + name = "Employee_Project", + joinColumns = { @JoinColumn(name = "employee_id") }, + inverseJoinColumns = { @JoinColumn(name = "project_id") } + ) + Set projects = new HashSet(); + + + public Employee() { + super(); + } + + public Employee(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public Employee(String firstName, String lastName, Set projects) { + this.firstName = firstName; + this.lastName = lastName; + this.projects = projects; + } + + + public Long getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(Long employeeId) { + this.employeeId = employeeId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Set getProjects() { + return projects; + } + + public void setProjects(Set projects) { + this.projects = projects; + } +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java new file mode 100644 index 000000000000..d6c049f33ee3 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.manytomany.model; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "Project") +public class Project implements Serializable { + + @Id + @Column(name = "project_id") + @GeneratedValue + private Long projectId; + + @Column(name = "title") + private String title; + + @ManyToMany(mappedBy = "projects") + private Set employees = new HashSet(); + + public Project() { + super(); + } + + public Project(String title) { + this.title = title; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Set getEmployees() { + return employees; + } + + public void setEmployees(Set employees) { + this.employees = employees; + } + + +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java new file mode 100644 index 000000000000..5f489dd027ea --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.manytomany.util; + +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.hibernate.manytomany.model.Project; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + + private static SessionFactory buildSessionFactory() { + try { + // Create the SessionFactory from hibernate-annotation.cfg.xml + Configuration configuration = new Configuration(); + configuration.addAnnotatedClass(Employee.class); + configuration.addAnnotatedClass(Project.class); + configuration.configure("manytomany.cfg.xml"); + System.out.println("Hibernate Annotation Configuration loaded"); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + System.out.println("Hibernate Annotation serviceRegistry created"); + + SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); + + return sessionFactory; + } catch (Throwable ex) { + System.err.println("Initial SessionFactory creation failed." + ex); + ex.printStackTrace(); + throw new ExceptionInInitializerError(ex); + } + } + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) + sessionFactory = buildSessionFactory(); + return sessionFactory; + } +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java new file mode 100644 index 000000000000..6f359054b695 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java @@ -0,0 +1,70 @@ +package com.baeldung.manytomany.spring; + +import java.util.Properties; +import javax.sql.DataSource; +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + + + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-mysql.properties" }) +@ComponentScan({ "com.baeldung.hibernate.manytomany" }) +public class PersistenceConfig { + + @Autowired + private Environment env; + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(restDataSource()); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.manytomany" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean + public DataSource restDataSource() { + final BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); + dataSource.setUrl(env.getProperty("jdbc.url")); + dataSource.setUsername(env.getProperty("jdbc.user")); + dataSource.setPassword(env.getProperty("jdbc.pass")); + + return dataSource; + } + + @Bean + public PlatformTransactionManager hibernateTransactionManager() { + final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); + transactionManager.setSessionFactory(sessionFactory().getObject()); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + private final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + //hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.show_sql", "true"); + + return hibernateProperties; + } +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java new file mode 100644 index 000000000000..d619807b64f4 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.manytomany.dao; + +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.persistence.dao.common.IOperations; + +public interface IEmployeeDao extends IOperations{ + +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java new file mode 100644 index 000000000000..4a55714f8d20 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.manytomany.dao; + +import com.baeldung.hibernate.manytomany.model.Project; +import com.baeldung.persistence.dao.common.IOperations; + +public interface IProjectDao extends IOperations{ + +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java new file mode 100644 index 000000000000..b062c00ff9c9 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java @@ -0,0 +1,16 @@ +package com.baeldung.persistence.manytomany.dao.impl; + +import org.springframework.stereotype.Repository; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.persistence.dao.common.AbstractHibernateDao; +import com.baeldung.persistence.manytomany.dao.IEmployeeDao; + +@Repository +public class EmployeeDao extends AbstractHibernateDao implements IEmployeeDao { + + public EmployeeDao() { + super(); + + setClazz(Employee.class); + } +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java new file mode 100644 index 000000000000..772026fbc1ef --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java @@ -0,0 +1,17 @@ +package com.baeldung.persistence.manytomany.dao.impl; + +import org.springframework.stereotype.Repository; +import com.baeldung.hibernate.manytomany.model.Project; +import com.baeldung.persistence.dao.common.AbstractHibernateDao; +import com.baeldung.persistence.manytomany.dao.IProjectDao; + + +@Repository +public class ProjectDao extends AbstractHibernateDao implements IProjectDao { + + public ProjectDao() { + super(); + + setClazz(Project.class); + } +} diff --git a/spring-hibernate5/src/main/resources/manytomany.cfg.xml b/spring-hibernate5/src/main/resources/manytomany.cfg.xml new file mode 100644 index 000000000000..8a10fc158008 --- /dev/null +++ b/spring-hibernate5/src/main/resources/manytomany.cfg.xml @@ -0,0 +1,27 @@ + + + + + + com.mysql.jdbc.Driver + + + buddhinisam123 + + + jdbc:mysql://localhost:3306/spring_hibernate_many_to_many + + + root + + + org.hibernate.dialect.MySQLDialect + + + thread + + true + + diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java new file mode 100644 index 000000000000..61d821e85efb --- /dev/null +++ b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java @@ -0,0 +1,53 @@ +package com.baeldung.hibernate.manytomany; + + +import java.util.HashSet; +import java.util.Set; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.hibernate.manytomany.model.Project; +import com.baeldung.manytomany.spring.PersistenceConfig; + + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest { + + @Autowired + private SessionFactory sessionFactory; + + private Session session; + + + @Before + public final void before() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @After + public final void after() { + session.getTransaction().commit(); + session.close(); + } + + @Test + public final void whenEntitiesAreCreated_thenNoExceptions() { + Set projects = new HashSet(); + projects.add(new Project("IT Project")); + projects.add(new Project("Networking Project")); + session.persist(new Employee("Peter", "Oven", projects)); + session.persist(new Employee("Allan", "Norman", projects)); + } + +} diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java new file mode 100644 index 000000000000..5308134faca6 --- /dev/null +++ b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java @@ -0,0 +1,84 @@ +package com.baeldung.hibernate.manytomany; + +import static org.junit.Assert.assertNotNull; +import static junit.framework.TestCase.assertEquals; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import com.baeldung.hibernate.manytomany.util.HibernateUtil; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.hibernate.manytomany.model.Project; + + +public class HibernateManyToManyAnnotationXMLConfigMainIntegrationTest { + private static SessionFactory sessionFactory; + + private Session session; + + + @BeforeClass + public static void beforeTests() { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + + @Test + public void givenSession_checkIfDatabaseIsPopulated() { + Employee employee1 = new Employee("Peter", "Oven"); + Set projects = new HashSet(); + projects = employee1.getProjects(); + int noProjects = projects.size(); + assertEquals(0,noProjects); + Project project1 = new Project("IT Project"); + assertNotNull(project1); + projects.add(project1); + Project project2 = new Project("Networking Project"); + assertNotNull(project2); + projects.add(project2); + employee1.setProjects(projects); + assertNotNull(employee1); + Employee employee2 = new Employee("Allan", "Norman"); + employee2.setProjects(projects); + assertNotNull(employee2); + + session.persist(employee1); + session.persist(employee2); + session.getTransaction().commit(); + session.close(); + + session = sessionFactory.openSession(); + session.beginTransaction(); + @SuppressWarnings("unchecked") + List projectList = session.createQuery("FROM Project").list(); + assertNotNull(projectList); + @SuppressWarnings("unchecked") + List employeeList = session.createQuery("FROM Employee").list(); + assertNotNull(employeeList); + } + + + @After + public void tearDown() { + session.getTransaction().commit(); + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } + +} From 3b5d9585ed6a7c8e8d0d23cdcb5a3ef34107032c Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Tue, 15 Aug 2017 13:41:02 +0100 Subject: [PATCH 62/90] Example Code for Apache Shiro (#2441) * added updated example codes * updated example code StringToCharStream * deleted StringToCharStream.java locally * removed redundant file * added code for apache commons collection SetUtils * refactored example code * added example code for bytebuddy * added example code for PCollections * update pom * refactored tests for PCollections * spring security xml config * spring security xml config * remove redundant comment * example code for apache-shiro * Fixed indentation. * Fix formatting issues --- apache-shiro/.gitignore | 4 + apache-shiro/README.md | 0 apache-shiro/pom.xml | 65 +++++++++++ .../src/main/java/com/baeldung/Main.java | 84 +++++++++++++++ .../main/java/com/baeldung/MyCustomRealm.java | 102 ++++++++++++++++++ .../src/main/resources/log4j.properties | 12 +++ apache-shiro/src/main/resources/shiro.ini | 3 + 7 files changed, 270 insertions(+) create mode 100644 apache-shiro/.gitignore create mode 100644 apache-shiro/README.md create mode 100644 apache-shiro/pom.xml create mode 100644 apache-shiro/src/main/java/com/baeldung/Main.java create mode 100644 apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java create mode 100644 apache-shiro/src/main/resources/log4j.properties create mode 100644 apache-shiro/src/main/resources/shiro.ini diff --git a/apache-shiro/.gitignore b/apache-shiro/.gitignore new file mode 100644 index 000000000000..020cda48984d --- /dev/null +++ b/apache-shiro/.gitignore @@ -0,0 +1,4 @@ + +/.idea/ +/target/ +/apache-shiro.iml \ No newline at end of file diff --git a/apache-shiro/README.md b/apache-shiro/README.md new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml new file mode 100644 index 000000000000..97ed872a2641 --- /dev/null +++ b/apache-shiro/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + com.baeldung + apache-shiro + 1.0-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 1.4.0 + 1.2.17 + 1.7.25 + + + + + org.apache.shiro + shiro-core + ${apache-shiro-core-version} + + + org.slf4j + jcl-over-slf4j + ${slf4j-version} + runtime + + + org.slf4j + slf4j-log4j12 + ${slf4j-version} + runtime + + + log4j + log4j + ${log4j-version} + runtime + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.2 + + 1.8 + 1.8 + + + + + + + \ No newline at end of file diff --git a/apache-shiro/src/main/java/com/baeldung/Main.java b/apache-shiro/src/main/java/com/baeldung/Main.java new file mode 100644 index 000000000000..68af5d7b46d8 --- /dev/null +++ b/apache-shiro/src/main/java/com/baeldung/Main.java @@ -0,0 +1,84 @@ +package com.baeldung; + +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.*; +import org.apache.shiro.config.IniSecurityManagerFactory; +import org.apache.shiro.mgt.SecurityManager; +import org.apache.shiro.session.Session; +import org.apache.shiro.subject.Subject; +import org.apache.shiro.util.Factory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Main { + private static final transient Logger log = LoggerFactory.getLogger(Main.class); + + public static void main(String[] args) { + + Factory factory + = new IniSecurityManagerFactory("classpath:shiro.ini"); + SecurityManager securityManager = factory.getInstance(); + + SecurityUtils.setSecurityManager(securityManager); + Subject currentUser = SecurityUtils.getSubject(); + + if (!currentUser.isAuthenticated()) { + UsernamePasswordToken token + = new UsernamePasswordToken("user", "password"); + token.setRememberMe(true); + try { + currentUser.login(token); + } catch (UnknownAccountException uae) { + log.error("Username Not Found!", uae); + } catch (IncorrectCredentialsException ice) { + log.error("Invalid Credentials!", ice); + } catch (LockedAccountException lae) { + log.error("Your Account is Locked!", lae); + } catch (AuthenticationException ae) { + log.error("Unexpected Error!", ae); + } + } + + log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); + + if (currentUser.hasRole("admin")) { + log.info("Welcome Admin"); + } else if(currentUser.hasRole("editor")) { + log.info("Welcome, Editor!"); + } else if(currentUser.hasRole("author")) { + log.info("Welcome, Author"); + } else { + log.info("Welcome, Guest"); + } + + if(currentUser.isPermitted("articles:compose")) { + log.info("You can compose an article"); + } else { + log.info("You are not permitted to compose an article!"); + } + + if(currentUser.isPermitted("articles:save")) { + log.info("You can save articles"); + } else { + log.info("You can not save articles"); + } + + if(currentUser.isPermitted("articles:publish")) { + log.info("You can publish articles"); + } else { + log.info("You can not publish articles"); + } + + Session session = currentUser.getSession(); + session.setAttribute("key", "value"); + String value = (String) session.getAttribute("key"); + if (value.equals("value")) { + log.info("Retrieved the correct value! [" + value + "]"); + } + + currentUser.logout(); + + System.exit(0); + } + +} diff --git a/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java b/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java new file mode 100644 index 000000000000..8d792c76a52d --- /dev/null +++ b/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java @@ -0,0 +1,102 @@ +package com.baeldung; + +import org.apache.shiro.authc.*; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.SimpleAuthorizationInfo; +import org.apache.shiro.realm.jdbc.JdbcRealm; +import org.apache.shiro.subject.PrincipalCollection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.*; + +public class MyCustomRealm extends JdbcRealm { + + private Map credentials = new HashMap<>(); + private Map> roles = new HashMap<>(); + private Map> perm = new HashMap<>(); + + { + credentials.put("user", "password"); + credentials.put("user2", "password2"); + credentials.put("user3", "password3"); + + roles.put("user", new HashSet<>(Arrays.asList("admin"))); + roles.put("user2", new HashSet<>(Arrays.asList("editor"))); + roles.put("user3", new HashSet<>(Arrays.asList("author"))); + + perm.put("admin", new HashSet<>(Arrays.asList("*"))); + perm.put("editor", new HashSet<>(Arrays.asList("articles:*"))); + perm.put("author", + new HashSet<>(Arrays.asList("articles:compose", + "articles:save"))); + + } + + @Override + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) + throws AuthenticationException { + + UsernamePasswordToken uToken = (UsernamePasswordToken) token; + + if(uToken.getUsername() == null + || uToken.getUsername().isEmpty() + || !credentials.containsKey(uToken.getUsername()) + ) { + throw new UnknownAccountException("username not found!"); + } + + + return new SimpleAuthenticationInfo( + uToken.getUsername(), credentials.get(uToken.getUsername()), + getName()); + } + + @Override + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { + Set roleNames = new HashSet<>(); + Set permissions = new HashSet<>(); + + principals.forEach(p -> { + try { + Set roles = getRoleNamesForUser(null, (String) p); + roleNames.addAll(roles); + permissions.addAll(getPermissions(null, null,roles)); + } catch (SQLException e) { + e.printStackTrace(); + } + }); + + SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames); + info.setStringPermissions(permissions); + return info; + } + + @Override + protected Set getRoleNamesForUser(Connection conn, String username) throws SQLException { + if(!roles.containsKey(username)) { + throw new SQLException("username not found!"); + } + + return roles.get(username); + } + + @Override + protected Set getPermissions(Connection conn, String username, Collection roleNames) throws SQLException { + for (String role : roleNames) { + if (!perm.containsKey(role)) { + throw new SQLException("role not found!"); + } + } + + Set finalSet = new HashSet<>(); + for (String role : roleNames) { + finalSet.addAll(perm.get(role)); + } + + return finalSet; + } + +} diff --git a/apache-shiro/src/main/resources/log4j.properties b/apache-shiro/src/main/resources/log4j.properties new file mode 100644 index 000000000000..897bf08221dc --- /dev/null +++ b/apache-shiro/src/main/resources/log4j.properties @@ -0,0 +1,12 @@ +log4j.rootLogger=INFO, stdout + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n + +log4j.logger.org.apache=WARN + +log4j.logger.org.apache.shiro=INFO + +log4j.logger.org.apache.shiro.util.ThreadContext=WARN +log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN \ No newline at end of file diff --git a/apache-shiro/src/main/resources/shiro.ini b/apache-shiro/src/main/resources/shiro.ini new file mode 100644 index 000000000000..a75f59101502 --- /dev/null +++ b/apache-shiro/src/main/resources/shiro.ini @@ -0,0 +1,3 @@ +jdbcRealm = com.baeldung.MyCustomRealm + +securityManager.realms = $jdbcRealm \ No newline at end of file From 6db067d2c9d433828d49cd4d697ddc145019b433 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Tue, 15 Aug 2017 15:17:24 +0200 Subject: [PATCH 63/90] Refactor volatile (#2444) --- .../volatilekeyword/SharedObject.java | 2 +- .../SharedObjectManualTest.java | 82 ++++++------------- 2 files changed, 28 insertions(+), 56 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java b/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java index 3f24df5059b2..063c83548177 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java +++ b/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java @@ -4,7 +4,7 @@ public class SharedObject { private volatile int count=0; - public void increamentCount(){ + void increamentCount(){ count++; } public int getCount(){ diff --git a/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java b/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java index 260a7c060bdc..8770cb4e9077 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java @@ -8,92 +8,64 @@ public class SharedObjectManualTest { - SharedObject sharedObject; - int valueReadByThread2; - int valueReadByThread3; + private SharedObject sharedObject; + private int valueReadByThread2; + private int valueReadByThread3; @Before - public void setUp(){ + public void setUp() { sharedObject = new SharedObject(); } @Test public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { - Thread writer = new Thread(){ - public void run(){ - sharedObject.increamentCount(); - } - }; + Thread writer = new Thread(() -> sharedObject.increamentCount()); writer.start(); - Thread readerOne = new Thread(){ - public void run(){ - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - valueReadByThread2= sharedObject.getCount(); + Thread readerOne = new Thread(() -> { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); } - }; + valueReadByThread2 = sharedObject.getCount(); + }); readerOne.start(); - Thread readerTwo = new Thread(){ - public void run(){ - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - valueReadByThread3=sharedObject.getCount(); + Thread readerTwo = new Thread(() -> { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); } - }; + valueReadByThread3 = sharedObject.getCount(); + }); readerTwo.start(); - assertEquals(1,valueReadByThread2); - assertEquals(1,valueReadByThread3); + assertEquals(1, valueReadByThread2); + assertEquals(1, valueReadByThread3); } @Test public void whenTwoThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { - Thread writerOne = new Thread(){ - public void run(){ - sharedObject.increamentCount(); - } - }; + Thread writerOne = new Thread(() -> sharedObject.increamentCount()); writerOne.start(); Thread.sleep(100); - Thread writerTwo = new Thread(){ - public void run(){ - sharedObject.increamentCount(); - } - }; + Thread writerTwo = new Thread(() -> sharedObject.increamentCount()); writerTwo.start(); Thread.sleep(100); - Thread readerOne = new Thread(){ - public void run(){ - valueReadByThread2= sharedObject.getCount(); - } - }; + Thread readerOne = new Thread(() -> valueReadByThread2 = sharedObject.getCount()); readerOne.start(); - Thread readerTwo = new Thread(){ - public void run(){ - valueReadByThread3=sharedObject.getCount(); - } - }; + Thread readerTwo = new Thread(() -> valueReadByThread3 = sharedObject.getCount()); readerTwo.start(); - assertEquals(2,valueReadByThread2); - assertEquals(2,valueReadByThread3); + assertEquals(2, valueReadByThread2); + assertEquals(2, valueReadByThread3); } - @After - public void cleanup(){ - sharedObject = null; - } } From 7ec1db1be2c508793f16a6a317bf5d2eab49343a Mon Sep 17 00:00:00 2001 From: juan Date: Tue, 15 Aug 2017 23:48:47 -0300 Subject: [PATCH 64/90] Sample code for article - JIRA: (BAEL-1079) Java 8 Streams distinctBy() some property(+ external tools) --- libraries/pom.xml | 23 ++++--- .../distinct/DistinctWithJavaFunction.java | 15 +++++ .../java/com/baeldung/distinct/Person.java | 65 +++++++++++++++++++ ...istinctWithEclipseCollectionsUnitTest.java | 32 +++++++++ .../DistinctWithJavaFunctionUnitTest.java | 44 +++++++++++++ .../DistinctWithStreamexUnitTest.java | 36 ++++++++++ .../distinct/DistinctWithVavrUnitTest.java | 34 ++++++++++ .../distinct/PersonDataGenerator.java | 19 ++++++ 8 files changed, 260 insertions(+), 8 deletions(-) create mode 100644 libraries/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java create mode 100644 libraries/src/main/java/com/baeldung/distinct/Person.java create mode 100644 libraries/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java create mode 100644 libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java create mode 100644 libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java create mode 100644 libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java create mode 100644 libraries/src/test/java/com/baeldung/distinct/PersonDataGenerator.java diff --git a/libraries/pom.xml b/libraries/pom.xml index a16a4de59dfc..70ee008925ec 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -186,11 +186,11 @@ rome ${rome.version} - - io.specto - hoverfly-java - 0.8.0 - + + io.specto + hoverfly-java + 0.8.0 + org.apache.httpcomponents httpclient @@ -380,7 +380,7 @@ one.util streamex - 0.6.5 + ${streamex.version} org.jooq @@ -467,11 +467,16 @@ noexception 1.1.0 - + org.eclipse.collections eclipse-collections ${eclipse-collections.version} + + io.vavr + vavr + ${vavr.version} + 0.7.0 @@ -513,6 +518,8 @@ 1.7.1 2.1.2 1.0 - 8.2.0 + 8.2.0 + 0.6.5 + 0.9.0 \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java b/libraries/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java new file mode 100644 index 000000000000..0d08c94b47e7 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java @@ -0,0 +1,15 @@ +package com.baeldung.distinct; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Predicate; + +public class DistinctWithJavaFunction { + + public static Predicate distinctByKey(Function keyExtractor) { + Map seen = new ConcurrentHashMap<>(); + return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; + } + +} diff --git a/libraries/src/main/java/com/baeldung/distinct/Person.java b/libraries/src/main/java/com/baeldung/distinct/Person.java new file mode 100644 index 000000000000..8a2a5f7a45ff --- /dev/null +++ b/libraries/src/main/java/com/baeldung/distinct/Person.java @@ -0,0 +1,65 @@ +package com.baeldung.distinct; + +public class Person { + int age; + String name; + String email; + + public Person(int age, String name, String email) { + super(); + this.age = age; + this.name = name; + this.email = email; + } + + public int getAge() { + return age; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Person [age="); + builder.append(age); + builder.append(", name="); + builder.append(name); + builder.append(", email="); + builder.append(email); + builder.append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((email == null) ? 0 : email.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Person other = (Person) obj; + if (email == null) { + if (other.email != null) + return false; + } else if (!email.equals(other.email)) + return false; + return true; + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java new file mode 100644 index 000000000000..dffde3917c70 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.distinct; + +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.eclipse.collections.impl.block.factory.HashingStrategies; +import org.eclipse.collections.impl.utility.ListIterate; +import org.junit.Before; +import org.junit.Test; + +public class DistinctWithEclipseCollectionsUnitTest { + List personList; + + @Before + public void init() { + personList = PersonDataGenerator.getPersonListWithFakeValues(); + } + + @Test + public void whenFilterListByName_thenSizeShouldBe4() { + List personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromFunction(Person::getName)); + assertTrue(personListFiltered.size() == 4); + } + + @Test + public void whenFilterListByAge_thenSizeShouldBe2() { + List personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromIntFunction(Person::getAge)); + assertTrue(personListFiltered.size() == 2); + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java new file mode 100644 index 000000000000..68775fac66ef --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.distinct; + +import static org.junit.Assert.assertTrue; +import static com.baeldung.distinct.DistinctWithJavaFunction.distinctByKey; + +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; + +public class DistinctWithJavaFunctionUnitTest { + List personList; + + @Before + public void init() { + personList = PersonDataGenerator.getPersonListWithFakeValues(); + } + + @Test + public void whenFilterListByName_thenSizeShouldBe4() { + List personListFiltered = personList.stream() + .filter(distinctByKey(p -> p.getName())) + .collect(Collectors.toList()); + assertTrue(personListFiltered.size() == 4); + } + + @Test + public void whenFilterListByAge_thenSizeShouldBe2() { + List personListFiltered = personList.stream() + .filter(distinctByKey(p -> p.getAge())) + .collect(Collectors.toList()); + assertTrue(personListFiltered.size() == 2); + } + + @Test + public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() { + List personListFiltered = personList.stream() + .distinct() + .collect(Collectors.toList()); + assertTrue(personListFiltered.size() == 5); + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java new file mode 100644 index 000000000000..f50c76a4869a --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.distinct; + +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import one.util.streamex.StreamEx; + +public class DistinctWithStreamexUnitTest { + List personList; + + @Before + public void init() { + personList = PersonDataGenerator.getPersonListWithFakeValues(); + } + + @Test + public void whenFilterListByName_thenSizeShouldBe4() { + List personListFiltered = StreamEx.of(personList) + .distinct(Person::getName) + .toList(); + assertTrue(personListFiltered.size() == 4); + } + + @Test + public void whenFilterListByAge_thenSizeShouldBe2() { + List personListFiltered = StreamEx.of(personList) + .distinct(Person::getAge) + .toList(); + assertTrue(personListFiltered.size() == 2); + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java new file mode 100644 index 000000000000..b4025cd313e0 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.distinct; + +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class DistinctWithVavrUnitTest { + List personList; + + @Before + public void init() { + personList = PersonDataGenerator.getPersonListWithFakeValues(); + } + + @Test + public void whenFilterListByName_thenSizeShouldBe4() { + List personListFiltered = io.vavr.collection.List.ofAll(personList) + .distinctBy(Person::getName) + .toJavaList(); + assertTrue(personListFiltered.size() == 4); + } + + @Test + public void whenFilterListByAge_thenSizeShouldBe2() { + List personListFiltered = io.vavr.collection.List.ofAll(personList) + .distinctBy(Person::getAge) + .toJavaList(); + assertTrue(personListFiltered.size() == 2); + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/PersonDataGenerator.java b/libraries/src/test/java/com/baeldung/distinct/PersonDataGenerator.java new file mode 100644 index 000000000000..51590005ac18 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/PersonDataGenerator.java @@ -0,0 +1,19 @@ +package com.baeldung.distinct; + +import java.util.Arrays; +import java.util.List; + +public class PersonDataGenerator { + + public static List getPersonListWithFakeValues() { + // @formatter:off + return Arrays.asList( + new Person(20, "Jhon", "jhon@test.com"), + new Person(20, "Jhon", "jhon1@test.com"), + new Person(20, "Jhon", "jhon2@test.com"), + new Person(21, "Tom", "Tom@test.com"), + new Person(21, "Mark", "Mark@test.com"), + new Person(20, "Julia", "jhon@test.com")); + // @formatter:on + } +} From da3273af6ebe6c3223e5206b0a9ad4a724c485e3 Mon Sep 17 00:00:00 2001 From: Shivang Sarawagi Date: Wed, 16 Aug 2017 11:26:42 +0530 Subject: [PATCH 65/90] Binary Search algorithm (#2448) --- .../com/baeldung/algorithms/BinarySearch.java | 26 +++++++++++++++++++ .../java/algorithms/BinarySearchTest.java | 14 ++++++++++ 2 files changed, 40 insertions(+) create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java create mode 100644 algorithms/src/test/java/algorithms/BinarySearchTest.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java b/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java new file mode 100644 index 000000000000..be4a9e578a2e --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java @@ -0,0 +1,26 @@ +public class BinarySearch { + + public int runBinarySearch() { + int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; + int key = 6; + + int low = 0; + int high = sortedArray.length - 1; + int index = Integer.MAX_VALUE; + + while (low <= high) { + + int mid = (low + high) / 2; + + if (sortedArray[mid] < key) { + low = mid + 1; + } else if (sortedArray[mid] > key) { + high = mid - 1; + } else if (sortedArray[mid] == key) { + index = mid; + break; + } + } + return index; + } +} diff --git a/algorithms/src/test/java/algorithms/BinarySearchTest.java b/algorithms/src/test/java/algorithms/BinarySearchTest.java new file mode 100644 index 000000000000..d53b074cc470 --- /dev/null +++ b/algorithms/src/test/java/algorithms/BinarySearchTest.java @@ -0,0 +1,14 @@ +import org.junit.Assert; +import org.junit.Test; + + +public class BinarySearchTest { + + @Test + public void givenASortedArrayOfIntegers_whenBinarySearchRunForANumber_thenGetIndexOfTheNumber() { + BinarySearch binSearch = new BinarySearch(); + int expectedIndexForSearchKey = 7; + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearch()); + } + +} From 491fc883bef942482a26710000df16dfe877d940 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Wed, 16 Aug 2017 18:17:07 +0100 Subject: [PATCH 66/90] Update Apache Shiro Example code (#2453) * added updated example codes * updated example code StringToCharStream * deleted StringToCharStream.java locally * removed redundant file * added code for apache commons collection SetUtils * refactored example code * added example code for bytebuddy * added example code for PCollections * update pom * refactored tests for PCollections * spring security xml config * spring security xml config * remove redundant comment * example code for apache-shiro --- apache-shiro/src/main/java/com/baeldung/Main.java | 11 ++++++----- apache-shiro/src/main/resources/shiro.ini | 10 ++++++++-- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/apache-shiro/src/main/java/com/baeldung/Main.java b/apache-shiro/src/main/java/com/baeldung/Main.java index 68af5d7b46d8..5e341f251b42 100644 --- a/apache-shiro/src/main/java/com/baeldung/Main.java +++ b/apache-shiro/src/main/java/com/baeldung/Main.java @@ -2,22 +2,23 @@ import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; -import org.apache.shiro.config.IniSecurityManagerFactory; +import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.mgt.SecurityManager; +import org.apache.shiro.realm.Realm; +import org.apache.shiro.realm.text.IniRealm; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; -import org.apache.shiro.util.Factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Main { + private static final transient Logger log = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { - Factory factory - = new IniSecurityManagerFactory("classpath:shiro.ini"); - SecurityManager securityManager = factory.getInstance(); + Realm realm = new MyCustomRealm(); + SecurityManager securityManager = new DefaultSecurityManager(realm); SecurityUtils.setSecurityManager(securityManager); Subject currentUser = SecurityUtils.getSubject(); diff --git a/apache-shiro/src/main/resources/shiro.ini b/apache-shiro/src/main/resources/shiro.ini index a75f59101502..0bb7567d1e6e 100644 --- a/apache-shiro/src/main/resources/shiro.ini +++ b/apache-shiro/src/main/resources/shiro.ini @@ -1,3 +1,9 @@ -jdbcRealm = com.baeldung.MyCustomRealm +[users] +user = password,admin +user2 = password2,editor +user3 = password3,author -securityManager.realms = $jdbcRealm \ No newline at end of file +[roles] +admin = * +editor = articles:* +author = articles:compose,articles:save \ No newline at end of file From 4226100ea92afba457903442590127b732a555c8 Mon Sep 17 00:00:00 2001 From: Nancy Bosecker Date: Wed, 16 Aug 2017 12:10:01 -0700 Subject: [PATCH 67/90] moved test file to correct location (#2437) --- .../commons/collections4/BagTests.java | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java new file mode 100644 index 000000000000..1270c5000887 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java @@ -0,0 +1,85 @@ +package com.baeldung.commons.collections4; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.collections4.Bag; +import org.apache.commons.collections4.bag.CollectionBag; +import org.apache.commons.collections4.bag.HashBag; +import org.apache.commons.collections4.bag.TreeBag; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class BagTests { + + Bag baseBag; + TreeBag treeBag; + + @Before + public void before() { + baseBag = new HashBag(); + treeBag = new TreeBag(); + treeBag = new TreeBag(); + } + + @Test + public void whenAdd_thenRemoveFromBaseBag_thenContainsCorrect() { + baseBag.add("apple", 2); + baseBag.add("lemon", 6); + baseBag.add("lime"); + + baseBag.remove("lemon"); + Assert.assertEquals(3, baseBag.size()); + Assert.assertFalse(baseBag.contains("lemon")); + + Assert.assertTrue(baseBag.uniqueSet().contains("apple")); + Assert.assertFalse(baseBag.uniqueSet().contains("lemon")); + Assert.assertTrue(baseBag.uniqueSet().contains("lime")); + + List containList = new ArrayList(); + containList.add("apple"); + containList.add("lemon"); + containList.add("lime"); + Assert.assertFalse(baseBag.containsAll(containList)); + } + + @Test + public void whenAdd_thenRemoveFromBaseCollectionBag_thenContainsCorrect() { + baseBag.add("apple", 2); + baseBag.add("lemon", 6); + baseBag.add("lime"); + + CollectionBag baseCollectionBag = new CollectionBag( + baseBag); + + baseCollectionBag.remove("lemon"); + Assert.assertEquals(8, baseCollectionBag.size()); + Assert.assertTrue(baseCollectionBag.contains("lemon")); + + Assert.assertTrue(baseBag.uniqueSet().contains("apple")); + Assert.assertTrue(baseBag.uniqueSet().contains("lemon")); + Assert.assertTrue(baseBag.uniqueSet().contains("lime")); + + List containList = new ArrayList(); + containList.add("apple"); + containList.add("lemon"); + containList.add("lime"); + Assert.assertTrue(baseBag.containsAll(containList)); + } + + @Test + public void whenAddtoTreeBag_thenRemove_thenContainsCorrect() { + treeBag.add("banana", 8); + treeBag.add("apple", 2); + treeBag.add("lime"); + + Assert.assertEquals(11, treeBag.size()); + Assert.assertEquals("apple", treeBag.first()); + Assert.assertEquals("lime", treeBag.last()); + + treeBag.remove("apple"); + Assert.assertEquals(9, treeBag.size()); + Assert.assertEquals("banana", treeBag.first()); + } +} From dc105bc6f22b2b4ab9d504fdbf0dd9988ba26ec1 Mon Sep 17 00:00:00 2001 From: felipeazv Date: Wed, 16 Aug 2017 21:58:42 +0200 Subject: [PATCH 68/90] BAEL-812: List of Rules Engines in Java (#2319) * spring beans DI examples * fix-1: shortening examples * List of Rules Engines in Java * BAEL-812: Openl-Tablets example added * BAEL-812: artifacts names changed --- easy-rules/pom.xml | 15 ++++ .../baeldung/easyrules/HelloWorldRule.java | 20 +++++ .../java/com/baeldung/easyrules/Launcher.java | 21 ++++++ openl-tablets/pom.xml | 23 ++++++ .../com/baeldung/openltablets/model/Case.java | 23 ++++++ .../baeldung/openltablets/model/Greeting.java | 20 +++++ .../com/baeldung/openltablets/model/User.java | 14 ++++ .../baeldung/openltablets/rules/IRule.java | 7 ++ .../com/baeldung/openltablets/rules/Main.java | 31 ++++++++ .../baeldung/openltablets/rules/Response.java | 24 ++++++ .../main/resources/openltablets/HelloUser.xls | Bin 0 -> 25088 bytes rulebook/pom.xml | 15 ++++ .../com/baeldung/rulebook/HelloWorldRule.java | 17 +++++ .../java/com/baeldung/rulebook/Launcher.java | 12 +++ .../autowired/TypesOfBeanInjectionSpring.java | 70 ++++++++++++++++++ ...sOfBeanInjectionSpringIntegrationTest.java | 25 +++++++ 16 files changed, 337 insertions(+) create mode 100644 easy-rules/pom.xml create mode 100644 easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java create mode 100644 easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java create mode 100644 openl-tablets/pom.xml create mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java create mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java create mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java create mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java create mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java create mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java create mode 100644 openl-tablets/src/main/resources/openltablets/HelloUser.xls create mode 100644 rulebook/pom.xml create mode 100644 rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java create mode 100644 rulebook/src/main/java/com/baeldung/rulebook/Launcher.java create mode 100644 spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java create mode 100644 spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java diff --git a/easy-rules/pom.xml b/easy-rules/pom.xml new file mode 100644 index 000000000000..b74b16f34c6d --- /dev/null +++ b/easy-rules/pom.xml @@ -0,0 +1,15 @@ + + 4.0.0 + com.baeldung.easyrules + easy-rules + 1.0.0-SNAPSHOT + + + + org.jeasy + easy-rules-core + 3.0.0 + + + \ No newline at end of file diff --git a/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java b/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java new file mode 100644 index 000000000000..5448eabf2acc --- /dev/null +++ b/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java @@ -0,0 +1,20 @@ +package com.baeldung.easyrules; + +import org.jeasy.rules.annotation.Action; +import org.jeasy.rules.annotation.Condition; +import org.jeasy.rules.annotation.Rule; + +@Rule(name = "Hello World rule", description = "Always say hello world") +public class HelloWorldRule { + + @Condition + public boolean when() { + return true; + } + + @Action + public void then() throws Exception { + System.out.println("hello world"); + } + +} diff --git a/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java b/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java new file mode 100644 index 000000000000..427e3eace056 --- /dev/null +++ b/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java @@ -0,0 +1,21 @@ +package com.baeldung.easyrules; + +import org.jeasy.rules.api.Facts; +import org.jeasy.rules.api.Rules; +import org.jeasy.rules.api.RulesEngine; +import org.jeasy.rules.core.DefaultRulesEngine; + +public class Launcher { + public static void main(String... args) { + // create facts + Facts facts = new Facts(); + + // create rules + Rules rules = new Rules(); + rules.register(new HelloWorldRule()); + + // create a rules engine and fire rules on known facts + RulesEngine rulesEngine = new DefaultRulesEngine(); + rulesEngine.fire(rules, facts); + } +} diff --git a/openl-tablets/pom.xml b/openl-tablets/pom.xml new file mode 100644 index 000000000000..77b9f47b3854 --- /dev/null +++ b/openl-tablets/pom.xml @@ -0,0 +1,23 @@ + + 4.0.0 + com.baeldung.openltablets + openl-tablets + 0.0.1-SNAPSHOT + + UTF-8 + UTF-8 + 1.8 + + + + org.openl + org.openl.core + 5.19.4 + + + org.openl.rules + org.openl.rules + 5.19.4 + + + \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java b/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java new file mode 100644 index 000000000000..f9f5f4bd5f40 --- /dev/null +++ b/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java @@ -0,0 +1,23 @@ +package com.baeldung.openltablets.model; + +public class Case { + + private User user; + private int hourOfDay; + + public User getUser() { + return user; + } + + public void setUser(final User user) { + this.user = user; + } + + public int getHourOfDay() { + return hourOfDay; + } + + public void setHourOfDay(final int hourOfDay) { + this.hourOfDay = hourOfDay; + } +} diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java b/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java new file mode 100644 index 000000000000..5dc7bcd11726 --- /dev/null +++ b/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java @@ -0,0 +1,20 @@ +package com.baeldung.openltablets.model; + +public enum Greeting { + + GOOD_MORNING("Good Morning"), + GOOD_AFTERNOON("Good Afternoon"), + GOOD_EVENING("Good Evening"), + GOOD_NIGHT("Good Night"); + + private final String literal; + + private Greeting(final String literal) { + this.literal = literal; + } + + public String getLiteral() { + return literal; + } + +} \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java b/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java new file mode 100644 index 000000000000..8e45487497d2 --- /dev/null +++ b/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java @@ -0,0 +1,14 @@ +package com.baeldung.openltablets.model; + +public class User { + + private String name; + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java new file mode 100644 index 000000000000..857a6433ef54 --- /dev/null +++ b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java @@ -0,0 +1,7 @@ +package com.baeldung.openltablets.rules; + +import com.baeldung.openltablets.model.Case; + +public interface IRule { + void helloUser(final Case aCase, final Response response); +} \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java new file mode 100644 index 000000000000..34f5c48ed120 --- /dev/null +++ b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java @@ -0,0 +1,31 @@ +package com.baeldung.openltablets.rules; + + +import java.time.LocalDateTime; + +import org.openl.rules.runtime.RulesEngineFactory; +import org.openl.runtime.EngineFactory; + +import com.baeldung.openltablets.model.Case; +import com.baeldung.openltablets.model.User; + +public class Main { + private IRule instance; + + public static void main(String[] args) { + Main rules = new Main(); + User user = new User(); + user.setName("Donald Duck"); + Case aCase = new Case(); + aCase.setUser(user); + aCase.setHourOfDay(23); + rules.process(aCase); + } + + public void process(Case aCase) { + final EngineFactory engineFactory = new RulesEngineFactory(getClass().getClassLoader() + .getResource("openltablets/HelloUser.xls"), IRule.class); + instance = engineFactory.newEngineInstance(); + instance.helloUser(aCase, new Response()); + } +} diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java new file mode 100644 index 000000000000..27fa634866dd --- /dev/null +++ b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java @@ -0,0 +1,24 @@ +package com.baeldung.openltablets.rules; + +import java.util.HashMap; +import java.util.Map; + +public class Response { + private String result; + private Map map = new HashMap<>(); + + public Response() { } + + public String getResult() { + return result; + } + + public void setResult(final String s) { + result = s; + } + + public Map getMap() { + return map; + } + +} diff --git a/openl-tablets/src/main/resources/openltablets/HelloUser.xls b/openl-tablets/src/main/resources/openltablets/HelloUser.xls new file mode 100644 index 0000000000000000000000000000000000000000..1e85d0ce2de54ddc812ec9639211a313a5024b45 GIT binary patch literal 25088 zcmeHv2Ut{B)9~44ft8{(5m8`4P>>?Uf-QiE9YLBEae)O^mt6u2q7lWGh%t&imY66p z8Vh!eVnK}s#S&{2dyR^QSYwI%&78aSvWw(>^Zn2Ne$RWCbN8M(b7tnunVD1WVb7el zzPWOX<1NCvJ|RZrgQ5{J(Smc}856y%2;ss5=07MD3I<3BJpT9k57NM2AgiCU58J`F zF(mABQ%HPBjUbspGKXXV$r4gyNKGJt2@q>YHjr!~*+FUw$sSTONDh#iLvn=F0#Zvz zPLP}-xj+&?a)smusTCx5NFI<{Luv!b6OtFCwvfCb`9Si8g!ZON|3Rw$|5DT#B7=_{ z`XYiz;X9j*0}VI)vImP%H4I~cfR9mukP3Pyz3|Je*6Eu(t8<*5Y)V zz&)FcA<0yZFPdzR(M4R3`|L6EQqX8C1P@PbGhBQ$zVa@^#ME%e4tJ>w6UAhzkT*5D#L31Tt4w`v+c4!z~UgGtztRG zcN}97j^j!wBpgQuKthUl0TIUv#OWoHh_k>=L*cpb&-=&KaRl=J&Q+iM+zTf!Eca_+ zHGeV4@AIY<F)Tz?^{T z0>S^As|S@qNMm~iD7!m{4?5>Uoad3{@NEq<3)CURf4JMy`zDILhu*u>SqUNULq50! z0|xfk5N;^N`-_zV7_t;@D-Dav6H!EoG~X1VzU_Hv4pTn$v=4c03a2V~Y?+LC++tqf7uHQ~fTYcgPL!BHjvW@g_3(GWFfc6t38aVA%x zHeXe{#*`CIbtQ&T9rYFfUW^#lAHm>|_9_Vt(9mkX0Sp2(l=?G>q1LcLj88sF!|tOP z-9CcBAzeSxT8ymqw}lJw$1p})k^vUnRgGcE>K6e-S}{onJCM^p^5J|;Cf-Leu7aI? ztX&+i6{Vf(=>Y+?MYZ?U@Hw$CKT8K&6%hf6Cw+-C&kzs^L${118bcmUk%;}t!ISm;D^F0s4I&X2*GB@fV4P< zglKrSht(9U_0&97^_3#1>Qc^{dN-AG)|U!Uiu$S$ARGfFg}+c0)DOoHrVrl`9I5KV z|Gy09pz*0MMxQv#pnBM@EZ}`h^ELb) zg`cOBO9*a^J>YCmm;OGAUl+c^0Gy#;7k`@pd`6#j@tOAGZjf%f7(L?-k*=H@DSZw^ zGYYQ-1bV6BMq9mboK@@6Vfr0+s3?57wY9yuJ?N9MXPhtSqmQd^3J3i&dS>*`foQA` zA9uAVoE6`2cCQbPs{(y+2NnE0T{OTZ7}H+dC8PKZ9LO?o+&NRi1+eac>MS@*9^7S9 z;tL7+L`|Oq5ud_YdIofe-9S1EpYUSno5B-?=To2>jyVdCHUJOR2ZvVVtMt6gPBo5j zaE#99Sa&68=WMtNe?t=uK4?izhk-M4)}^n3>(bZ2_0b19{z|w~57-(ir@xX88y;*3 zA2&v!U2J@RefoiJwK4!_^@}l;2k`T;Mj_~Jh70NkR%ak5g)0eZ_hVf+B2oNkCAyBB zu;;7Rvv$7-U`eae8w1zai3+aWUx4pvO|_t_2MV_;cLMo!_=5g}b>(5&>#Eb<34A*; z0hhw+YdA484W3iL4HyS2_!LI>CuulvV!N}JDBB)2hL@*pSfC#=jFiZqv=SPWD4XD3& zFwi!DNd3J7{?QO3_4f{j@CHayfA4??G=xa~y@P{510<=xcko@!M~MUm)!#e#vZnz= z>hB%g0c-$~`g;dP!iEs3zjp);BT|3wKrm~FB=z@>o0W%>(fXMVx(;Fbq9men2ntii3YGV1!&KgsIX3S4ZzR)C@Es7s`CLx?Cslu^n6kuD7( zqMke`iLf;cyPQf5>uW!^fFIB5l5S9eXL!1gHo>n zGkC8K&$t8uOYy+f2ePqdvk9!r#;qPUff_c(qO|vSFY0Gw!)6mymrd(>*q{R{TVo<^jKP}de~@N zTGfC*Pi)lB#(~X7kEOM#hmE$SRSl@FuGY_{Ih&0hOY^RWjkcv#4N%-)qMwZ;n~fez zYgZ2&ZA+^fu=mna{cKvW+32yfpnBM7TUynCBR99}XVVhdbgbXf1i+?a11v2tX!ef= z`o@XPMvtYr*TY8J(gK5CY@VjSHO_1{dMwSe9yZ#R78q1nS*f3m3!9A|OY^CRjkcu) z1}QG5>1QKgv(aN|{`IiYwzR;YWe4x;XXDCdqsP+P*TY8J(gK5iJTqG#8$NM^z(;z> zGUxF->yDWmM}-mTK~Ej1f}=4^op70o<0C%fT2?teTEL-DSU!Z`lBDEHWb^prbcu28 z6{aK{4y#B=3LK%609l+T;-HI!a5|_Wifda+)CA71Vj)hyIDo93Ez~f9pQ9p zQxN8%Bv&F7q>2OyqHJ-RI7Rs24v4mpC0a8@QxNST2!(aRSIFRjO79@(byJR!5~OCF0`Ogv{q!!0}z^HTAS9OqUVQ33|=YR0)nY zW&d2a`AD>lhA0FSHc?j=QSBf?$diHq{X{)AL?L{ziF&YzYKIJF2ck|#p`>0Kq7W?D zM7>xffXa8IPfq+dkfJIc>`Qe4p#@_mg z`XJE=sXUvS8QW*=fT-%AvC614K8vesm4V?BT*vtTzRxy>c{!~5`$|(}+1VmF_-TZ$ zF>+eKe>mWY+Z6D^Z1{-aBn*ZTX5xmCLIG=Ql}NY%SH>nD@hjvh=J5r(1dVxs90?>u zN{1of5j@ha&=hbzS-7UaT!Skh!(re}1m;-B9G+qSWuPb*6giI{qFa^I5?pN{Fv$gZ zvz4By3VgT*S4#}5eYM1-kbo3!EK-D$!sg>qFo}|XBUr+~8gHOX4&0M{Jj7@uhz;LN!YzWYZ&*W6%GdY#` zOb*3wUuXj2_t6!=*hJAB1Q5X+Ry^R1Hjlbi4G5VKWF>F_3(G{Xbkwy1ThalBArdFb zm&3Ck1bfE9=9vf!F48pF9-5xf*c>s65sBY8kP2OzkPR#^m^w9+E%VX6mjw;1XX z`B@Se&E(=dV9=Mvpo79%hd~6e$^yBWK@1P6=dswJvntt`lTK*LaZluQ6c5s+ZPWxz zCJwqst{%e~VNGEU(KBu|rNWudwS-rLu>5AI2w*wRa%Cec1z(4bK)DFVhHKN};(%oe zw#^JRNV&5XWf)x8l&$MfW`-97locVXe!2x#hm^Z$QHBwQP1&XnWoC>qK$)3!b1CJn zT9jd!>BQ2iZ5_%u(A3o|Y(tolZsHS4{>1MBqzu z_!kv?iiDI3wuk>d5eOlIu|l~PhW7Esj$|IWt$e=>^C|+40ItB?@ZUx#1Re?zq`Vcv zcOhorp`xM!z6!~bB?_`6C=DiORip~=)8L~3I7x$i6%vFniywTX^e6>NgE9mhtXBo~ z6^bQf3FH+^pf1pb@s9+hDM(ON6~F--(-KH&Kt62=S+r;o0R$4X1OQ+vJ$v>9SqPOU zC};_Bb8{mjtQzC=n=+@(Bctfy=IL-$)UgM`o3Ia%PX`y-)DMez1kaIA2bAWKm^UTL z6YIPR}G2r4sDuI*bC0b<&p9LkI;8V)s!4rqq3`__2 zZjF>8_7TL0a-Fk3PrAps}$cxj@wl$o7`WQU#H+ zY$;TR;g)8@(&VCSsZ1tSl}F@>u-r^pK2V&VAqV-joB{elB9x}*3e!cAmn)5}NGcTgdAT#j6n=_kvT z`(=Sn0RHJiQ7) zn)YZ_Ok82iDnlfZ$f&F+I3vD3o3a3#Y6>=`0RQI`C-4X898v+_o8a3YHr-vo2M)vc zcKA-=+e3l^Z-n0sR2A%Clg*L~hkz31C+`PNXr$HOT{XCGZPq2kyQcl*j;x2}nQ z_jF(JAWk#)P8Djt<>~ ztDAiNV)wp1o}IoZ>|3-nX7y+Hv(g7_?LNCW+okyXvu}gBCpzS{F8r&o@yXmlR~;S~ z%?-X&8Gh-WQQ2mvA>E(ed-JvX?c(jbLpl!J&@Y@nbz8-}^EGSV^s2P);dgvjo0opy zdl#)dIrL!Mo93H;8!77WONX`B1<%Z9*&NzzQIvE#UC`Y3{{F5jifXDa4wdY=Hhb&r z2^~jP4LqQ*8}%~eH`{YnlZHgSoLjtSNTLmk}7GLg^Qtla%y!AwB`708>+%fFv zcW1w?zI5--)J~^v*j-rG-*TwWa#PEhqLY3zcGgbtS<_J3=dlO(HabM;#*X`ZPA9{|vTV$Qz zEQo7zEiQh`kofoO;_m*{uC&$Y#N;D=ZC*`|zNj}R ze6XO?s@`9X-T=h2Oyu3xZ*U;O)_enE-yB~Ol=IVtw;dATI) z)!Oc(yEqm^Ow8&1U|*XM$GvXH@0NFcF~8Dk!`ffGSIxR!z4EomwF7+?Z<-PK_G06L z^6M_UG9&l7nRykp%Uk<+?r@_oZjCSbQQvWP zPAPG>7LA|WdO~`iM=76vJ2&n{O&h_5(&9buo|f;F?JIb9|99E`w~wAI+kZdDdywOe zR(9>yPq?9Y*h%r`P`izj6i?>dnDke*T(xU~NeXTlph8&6u zx)Z+L#xt;J`N|mymJ_G+%!tX}oi=fyw8}Vte33Z$E2FAiMGs~j81FrBk{LfG@10j- z?=Bv;cMrNh=Xvy9n7v?xMY!GS)>piW4z+!fGLhptbHnqVUmuIIE%@Tt*jl5RuXn%m zIIy%_W-_H2DUDy)k>j?1Xu#BVF1LGrdE?{S1m$$csO%0njy5kMczub9oLj+boYrn_8g zvUx-EmGKj1yUwpkzL*%FGx)--LUZ4zSDii`HipK*#6d;fS5zQF3($0y6T+!u`b`tZdJZ?XxhC# zk|U2tc5a;5cJ82^SC&0Z^cpEHk4wDRgH!n~pkG|;a|<&Z7i2V>dbZEHHRip7JXa>X z>bw0n$L+uM`D6O}yzS&dzfBcUQuB#xUrSCK+mD)()^fpv$uDB>KRQ@`e956?a_UTb(M2o$b8p$kDgE%Rl|` zhZXIoFKyCeOi8cu=dQle$760*A2D$pJa@{Gi}9zW9lG>m} zncaR=XmHDx!Am+AaoY$ziZgG^yaVoS9^QRsOu&M#S}pzD^R#EY|LJ2*7c73XcIR1> zg*zvl9Cc=9-)B98laBL-cUZS5^2CO@4>xyue7(xucQEH<L(KCW{m89Vc`8uq+74( zd!-q9r%uM^&mUBIE+_5ertiL++QquDi_Jo}(q=v}RY;#tdUW%uuW z@3lNH_2%WbF49M__;kDkpxD)rhsZ{dZX zdv_gk!n5>1+^EWfqia0}^&8ziYD$NjO|N>`q}R&AY-<-s^);KFvh~HikR(?V>GyL| z{+#?+?&$Q>aQE|H_FQ;dII`P@nAWmEcl}MS-x>Oqu{8GFeb2sky8hIDMA`1CCziGQ zz96sT?y3Fb7ax3iz-ZeGrxDKl#hv?cv!2>7C-*JFjHK(vk0OfCY*Vg1E4W_?wYbw(Islms3lM2YhH}6O@hf| z-RY&}FU8-MK}idkeB$nf_6&`gQ&Wi6BvU!Zjx;;yZ#V7rl(Br7?A&gvxvj6wIJ5D* z(X_iAEIWp{52|@$S?a_0`$D*HiMV|6HV719-=W z@813M4RzBwTwgepWoXd_Xj+$^C0KNST>|V?h^Dqb=u>M=!mh}k)oUs?hvklTC$QDe zro^6NYbagRM~P0j*)-TjprMfu>s@VW>M@Dv{>HG|fSX0eBoSJl1N%ILEQ39{Wm+p= zC?K-{HcJbJc(BVsm|upl()ncwb1v*`zy)og|FYyCPRP7o`0Ez%v6)do~pLcerH}84 zdti4cb6hw>f%bsBvA=slVsfzC4Vc&ySjGdaaOiJU&In$LqxP{3->3G#m*~nIVxq>G zGNg&R#+(UY_JVI!j!Sye-4~|J2!5XiHMpqNMR!F(j-FA)K`0!rj@M#JwaFdui=pvR9Dr9emxxsP$C_CCH8EU_p>B#@;E`oU(kAO*ITVaq=! zC0m>fZvbH65#)$6g;KdVB?plZAWXqmB=9Jd3&x5i5<#*^Aj%h|m zmW>qv@f?u^HjDx6nIe;>im_gf0Nw>4nG~5MHxshq0Ro{kRS+I15M~26c>j`Il%A+x^khCVjjG|p-n;ZS=q1?pDjp%eP-a8BZhX#vAqo2 zE&@00Hvq7|&E%Ck{*V{RQ~U&iuoQW&P$C(})D`6mGqXSlAd{PeZyk_P6m0kpXami{ zB2+AWgQV7|5VVj5Ki-6G!ltK*vvcGE3A|HL=@T~o1#VjJ6x{r}f#HB4`Iw&n{T z9`9eWG|luENwpgY%ZjM~9BcdMr@sTirZm&v%+8uTT3cT;O`cAFJvDhc{cWttGt*y9 zo|*n?@-QLdxHkfY&_f9agTFC3Y{3w^sJH~v z=`84i@4#4zhHCpQOgsLz-$I>#!EbS;hklDek;7qTYN%*b??=2C>eY7{ z!+KIiPx)uUaXLI*`}cm2I2a_r37YDvkC&zcFm9 zc;k0ND&j;kvmuBL#QD4Y8%VanX#W;}^b4JHadZnobNr21fXQNy;qP#u=Az+{lUR}= z%mKI6l%VtWg)=hQu<(-Q2nNbBMZ#2>1_z4uUL5#UX;_HRJ`}KiJKPm&sJIDIWr9d? zO13OVmL?ZOA9?7n=b;ZtE9JUUc62sa~%C1*$agKS6v! A1ONa4 literal 0 HcmV?d00001 diff --git a/rulebook/pom.xml b/rulebook/pom.xml new file mode 100644 index 000000000000..2a42e36d938f --- /dev/null +++ b/rulebook/pom.xml @@ -0,0 +1,15 @@ + + 4.0.0 + com.baeldung.rulebook + rulebook + 1.0.0-SNAPSHOT + + + + com.deliveredtechnologies + rulebook-core + 0.6.2 + + + \ No newline at end of file diff --git a/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java b/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java new file mode 100644 index 000000000000..c09772a3c673 --- /dev/null +++ b/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java @@ -0,0 +1,17 @@ +package com.baeldung.rulebook; + +import com.deliveredtechnologies.rulebook.lang.RuleBookBuilder; +import com.deliveredtechnologies.rulebook.model.RuleBook; + +public class HelloWorldRule { + public RuleBook defineHelloWorldRules() { + + return RuleBookBuilder.create() + .addRule(rule -> rule.withNoSpecifiedFactType() + .then(f -> System.out.print("Hello "))) + .addRule(rule -> rule.withNoSpecifiedFactType() + .then(f -> System.out.println("World"))) + .build(); + + } +} diff --git a/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java b/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java new file mode 100644 index 000000000000..57965457ecf1 --- /dev/null +++ b/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java @@ -0,0 +1,12 @@ +package com.baeldung.rulebook; + +import com.deliveredtechnologies.rulebook.FactMap; + +public class Launcher { + + public static void main(String[] args) { + HelloWorldRule ruleBook = new HelloWorldRule(); + ruleBook.defineHelloWorldRules() + .run(new FactMap<>()); + } +} diff --git a/spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java b/spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java new file mode 100644 index 000000000000..ca6018a21e5b --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java @@ -0,0 +1,70 @@ +package com.baeldung.autowired; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Service; + +@SpringBootApplication +public class TypesOfBeanInjectionSpring { + private final UserService userService; + + @Autowired // the @Autowired can even be omitted, in case there's only one explicit constructor + public TypesOfBeanInjectionSpring(UserService userService) { + this.userService = userService; + } + + public static void main(String[] args) { + SpringApplication.run(TypesOfBeanInjectionSpring.class, args); + } + + @Bean + CommandLineRunner runIt() { + return args -> { + userService.listUsers() + .stream() + .forEach(System.out::println); + }; + } +} + +class User { + private String name; + + public User(String name) { + this.name = name; + } + + // getters and setters ... + public String getName() { + return this.name; + } + + public String toString() { + return name; + } + +} + +interface UserService { + List listUsers(); +} + +@Service +class UserServiceImpl implements UserService { + + @Override + public List listUsers() { + ArrayList users = new ArrayList<>(3); + users.add(new User("Snoopy")); + users.add(new User("Woodstock")); + users.add(new User("Charlie Brown")); + return users; + } + +} diff --git a/spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java b/spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java new file mode 100644 index 000000000000..206a062a571e --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung.autowired; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class TypesOfBeanInjectionSpringIntegrationTest { + @Autowired + UserService userService; + + private static final String[] expected = new String[] { "Snoopy", "Woodstock", "Charlie Brown" }; + + @Test + public void givenDI_whenInjectObject_thenUserNamesAreListed() { + Assert.assertArrayEquals(expected, userService.listUsers() + .stream() + .map(User::getName) + .toArray()); + } +} From c8c0c1e51dcd611f111bf7baf887ddd71e24bec9 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Thu, 17 Aug 2017 03:12:07 +0530 Subject: [PATCH 69/90] undertow (#2426) * moving jmh into libraries module * refactoring jmh * Update pom.xml * manual algorightm * with BM result * fix for space issue * Fixed indentation * change as per suggestion * vavr either * adding unit test and othe rutilities * adding concurrent module * concurrent package description * concurrent package description * Update EitherUnitTest.java * introducing lambda expression * jooby project * jooby project * reducing employee bean content * bootique module * bootique * bootique * undertow module * undertow module * refactoring * using lambda * as per baeldung formatter --- pom.xml | 1 + undertow/pom.xml | 58 ++++++++++++++ .../com/baeldung/undertow/SimpleServer.java | 16 ++++ .../com/baeldung/undertow/ftp/FileServer.java | 20 +++++ .../secure/CustomIdentityManager.java | 77 +++++++++++++++++++ .../undertow/secure/SecureServer.java | 52 +++++++++++++ .../undertow/socket/SocketServer.java | 36 +++++++++ 7 files changed, 260 insertions(+) create mode 100644 undertow/pom.xml create mode 100644 undertow/src/main/java/com/baeldung/undertow/SimpleServer.java create mode 100644 undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java create mode 100644 undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java create mode 100644 undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java create mode 100644 undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java diff --git a/pom.xml b/pom.xml index 8b3df8de0d8e..99e9d5a7e398 100644 --- a/pom.xml +++ b/pom.xml @@ -237,6 +237,7 @@ liquibase spring-boot-property-exp mockserver + undertow diff --git a/undertow/pom.xml b/undertow/pom.xml new file mode 100644 index 000000000000..a0f2dc53ee75 --- /dev/null +++ b/undertow/pom.xml @@ -0,0 +1,58 @@ + + 4.0.0 + com.baeldung.undertow + undertow + jar + 1.0-SNAPSHOT + undertow + http://maven.apache.org + + + 1.8 + 1.8 + + + + + io.undertow + undertow-core + 1.4.18.Final + + + io.undertow + undertow-servlet + 1.4.18.Final + + + + + ${project.artifactId} + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.baeldung.undertow.SimpleServer + + + + + + + + \ No newline at end of file diff --git a/undertow/src/main/java/com/baeldung/undertow/SimpleServer.java b/undertow/src/main/java/com/baeldung/undertow/SimpleServer.java new file mode 100644 index 000000000000..7f869746bece --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/SimpleServer.java @@ -0,0 +1,16 @@ +package com.baeldung.undertow; + +import io.undertow.Undertow; +import io.undertow.util.Headers; + +public class SimpleServer { + + public static void main(String[] args) { + Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(exchange -> { + exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); + exchange.getResponseSender().send("Hello Baeldung"); + }).build(); + server.start(); + } + +} diff --git a/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java b/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java new file mode 100644 index 000000000000..90cad9ebbd1e --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java @@ -0,0 +1,20 @@ +package com.baeldung.undertow.ftp; + +import java.nio.file.Paths; + +import io.undertow.Undertow; +import io.undertow.server.handlers.resource.PathResourceManager; + +import static io.undertow.Handlers.resource; + +public class FileServer { + + public static void main(String[] args) { + Undertow server = Undertow.builder().addHttpListener(8080, "localhost") + .setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100)) + .setDirectoryListingEnabled(true)) + .build(); + server.start(); + } + +} diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java new file mode 100644 index 000000000000..e0984f65a588 --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java @@ -0,0 +1,77 @@ +package com.baeldung.undertow.secure; + +import java.security.Principal; +import java.util.Arrays; +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +import io.undertow.security.idm.Account; +import io.undertow.security.idm.Credential; +import io.undertow.security.idm.PasswordCredential; + +public class CustomIdentityManager implements io.undertow.security.idm.IdentityManager { + + private final Map users; + + CustomIdentityManager(final Map users) { + this.users = users; + } + + @Override + public Account verify(Account account) { + return account; + } + + @Override + public Account verify(Credential credential) { + return null; + } + + @Override + public Account verify(String id, Credential credential) { + Account account = getAccount(id); + if (account != null && verifyCredential(account, credential)) { + return account; + } + return null; + } + + private boolean verifyCredential(Account account, Credential credential) { + if (credential instanceof PasswordCredential) { + char[] password = ((PasswordCredential) credential).getPassword(); + char[] expectedPassword = users.get(account.getPrincipal().getName()); + + return Arrays.equals(password, expectedPassword); + } + return false; + } + + private Account getAccount(final String id) { + if (users.containsKey(id)) { + return new Account() { + + private static final long serialVersionUID = 1L; + + private final Principal principal = new Principal() { + @Override + public String getName() { + return id; + } + }; + + @Override + public Principal getPrincipal() { + return principal; + } + + @Override + public Set getRoles() { + return Collections.emptySet(); + } + }; + } + return null; + } + +} diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java new file mode 100644 index 000000000000..6f520944db78 --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java @@ -0,0 +1,52 @@ +package com.baeldung.undertow.secure; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.undertow.Undertow; +import io.undertow.io.IoCallback; +import io.undertow.security.api.AuthenticationMechanism; +import io.undertow.security.api.AuthenticationMode; +import io.undertow.security.api.SecurityContext; +import io.undertow.security.handlers.AuthenticationCallHandler; +import io.undertow.security.handlers.AuthenticationConstraintHandler; +import io.undertow.security.handlers.AuthenticationMechanismsHandler; +import io.undertow.security.handlers.SecurityInitialHandler; +import io.undertow.security.idm.IdentityManager; +import io.undertow.security.impl.BasicAuthenticationMechanism; +import io.undertow.server.HttpHandler; +import io.undertow.server.HttpServerExchange; + +public class SecureServer { + + public static void main(String[] args) { + final Map users = new HashMap<>(2); + users.put("root", "password".toCharArray()); + users.put("admin", "password".toCharArray()); + + final IdentityManager idm = new CustomIdentityManager(users); + + Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(addSecurity((exchange) -> { + final SecurityContext context = exchange.getSecurityContext(); + exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), + IoCallback.END_EXCHANGE); + }, idm)).build(); + + server.start(); + + } + + private static HttpHandler addSecurity(final HttpHandler toWrap, final IdentityManager identityManager) { + HttpHandler handler = toWrap; + handler = new AuthenticationCallHandler(handler); + handler = new AuthenticationConstraintHandler(handler); + final List mechanisms = Collections + . singletonList(new BasicAuthenticationMechanism("Baeldung_Realm")); + handler = new AuthenticationMechanismsHandler(handler, mechanisms); + handler = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, handler); + return handler; + } + +} diff --git a/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java b/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java new file mode 100644 index 000000000000..9e0e065c3a07 --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java @@ -0,0 +1,36 @@ +package com.baeldung.undertow.socket; + +import io.undertow.Undertow; +import io.undertow.server.handlers.resource.ClassPathResourceManager; +import io.undertow.websockets.core.AbstractReceiveListener; +import io.undertow.websockets.core.BufferedTextMessage; +import io.undertow.websockets.core.WebSocketChannel; +import io.undertow.websockets.core.WebSockets; + +import static io.undertow.Handlers.path; +import static io.undertow.Handlers.resource; +import static io.undertow.Handlers.websocket; + +public class SocketServer { + + public static void main(String[] args) { + Undertow server = Undertow.builder().addHttpListener(8080, "localhost") + .setHandler(path().addPrefixPath("/baeldungApp", websocket((exchange, channel) -> { + channel.getReceiveSetter().set(new AbstractReceiveListener() { + @Override + protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) { + final String messageData = message.getData(); + for (WebSocketChannel session : channel.getPeerConnections()) { + WebSockets.sendText(messageData, session, null); + } + } + }); + channel.resumeReceives(); + })).addPrefixPath("/", resource(new ClassPathResourceManager(SocketServer.class.getClassLoader(), + SocketServer.class.getPackage())).addWelcomeFiles("index.html"))) + .build(); + + server.start(); + } + +} From 04689cc2498b6661dfdcbb06be239d7c091de0d9 Mon Sep 17 00:00:00 2001 From: Rokon Uddin Ahmed Date: Thu, 17 Aug 2017 21:41:57 +0600 Subject: [PATCH 70/90] pull 16.08 (#2454) * Update README.md * Update README.md * Create README.md * Create README.md * Create README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.MD * Create README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md * Update README.MD * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md --- asciidoctor/README.md | 3 ++- kotlin/README.md | 7 +++++++ libraries/README.md | 1 + ratpack/README.md | 1 + spring-5/README.md | 3 +-- spring-activiti/README.md | 3 +++ spring-cloud-bus/README.md | 3 +++ spring-core/README.md | 2 ++ spring-rest/README.md | 1 + testing/README.md | 1 + vavr/README.md | 1 + 11 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 spring-activiti/README.md create mode 100644 spring-cloud-bus/README.md diff --git a/asciidoctor/README.md b/asciidoctor/README.md index 164200d22723..3c602b6abdd8 100644 --- a/asciidoctor/README.md +++ b/asciidoctor/README.md @@ -1,3 +1,4 @@ ### Relevant articles -- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor) \ No newline at end of file +- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor) +- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book) diff --git a/kotlin/README.md b/kotlin/README.md index 6b3fb93dccc6..91933e94dc7e 100644 --- a/kotlin/README.md +++ b/kotlin/README.md @@ -7,3 +7,10 @@ - [Difference Between “==” and “===” in Kotlin](http://www.baeldung.com/kotlin-equality-operators) - [Generics in Kotlin](http://www.baeldung.com/kotlin-generics) - [Introduction to Kotlin Coroutines](http://www.baeldung.com/kotlin-coroutines) +- [Destructuring Declarations in Kotlin](http://www.baeldung.com/kotlin-destructuring-declarations) +- [Kotlin with Mockito](http://www.baeldung.com/kotlin-mockito) +- [Lazy Initialization in Kotlin](http://www.baeldung.com/kotlin-lazy-initialization) +- [Overview of Kotlin Collections API](http://www.baeldung.com/kotlin-collections-api) +- [Converting a List to Map in Kotlin](http://www.baeldung.com/kotlin-list-to-map) +- [Data Classes in Kotlin](http://www.baeldung.com/kotlin-data-classes) + diff --git a/libraries/README.md b/libraries/README.md index 88075af3903d..ed6d214c7a64 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -23,6 +23,7 @@ - [Serenity BDD with Spring and JBehave](http://www.baeldung.com/serenity-spring-jbehave) - [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing) - [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map) +- [Introduction to Apache Commons Text](http://www.baeldung.com/java-apache-commons-text) - [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) - [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) - [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) diff --git a/ratpack/README.md b/ratpack/README.md index 91c8e025f0ee..8215f74148bc 100644 --- a/ratpack/README.md +++ b/ratpack/README.md @@ -2,3 +2,4 @@ - [Introduction to Ratpack](http://www.baeldung.com/ratpack) - [Ratpack Google Guice Integration](http://www.baeldung.com/ratpack-google-guice) +- [Ratpack Integration with Spring Boot](http://www.baeldung.com/ratpack-spring-boot) diff --git a/spring-5/README.md b/spring-5/README.md index 03b8121f90bc..4ce0fd4c79b6 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -8,5 +8,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests) - [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) - [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) - - +- [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) diff --git a/spring-activiti/README.md b/spring-activiti/README.md new file mode 100644 index 000000000000..fc6eea7f8710 --- /dev/null +++ b/spring-activiti/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [A Guide to Activiti with Java](http://www.baeldung.com/java-activiti) diff --git a/spring-cloud-bus/README.md b/spring-cloud-bus/README.md new file mode 100644 index 000000000000..c5410ca4e242 --- /dev/null +++ b/spring-cloud-bus/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [Spring Cloud Bus](http://www.baeldung.com/spring-cloud-bus) diff --git a/spring-core/README.md b/spring-core/README.md index b0d0b8408c26..237f8cd4e99b 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -6,4 +6,6 @@ - [Constructor Injection in Spring with Lombok](http://www.baeldung.com/spring-injection-lombok) - [A Quick Guide to Spring @Value](http://www.baeldung.com/spring-value-annotation) - [Spring YAML Configuration](http://www.baeldung.com/spring-yaml) +- [Introduction to Spring’s StreamUtils](http://www.baeldung.com/spring-stream-utils) - [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults) + diff --git a/spring-rest/README.md b/spring-rest/README.md index 66c893e45f9f..2cea31518841 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -15,3 +15,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Custom Media Type for a Spring REST API](http://www.baeldung.com/spring-rest-custom-media-type) - [HTTP PUT vs HTTP PATCH in a REST API](http://www.baeldung.com/http-put-patch-difference-spring) - [Exploring the Spring Boot TestRestTemplate](http://www.baeldung.com/spring-boot-testresttemplate) +- [Spring – Log Incoming Requests](http://www.baeldung.com/spring-http-logging) diff --git a/testing/README.md b/testing/README.md index 6338a52f3d67..a691737e4fed 100644 --- a/testing/README.md +++ b/testing/README.md @@ -12,3 +12,4 @@ - [Testing with Google Truth](http://www.baeldung.com/google-truth) - [Testing with JGoTesting](http://www.baeldung.com/jgotesting) - [Introduction to JUnitParams](http://www.baeldung.com/junit-params) +- [Cucumber Java 8 Support](http://www.baeldung.com/cucumber-java-8-support) diff --git a/vavr/README.md b/vavr/README.md index c4155c2680b0..d7816f3f9fc1 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -5,3 +5,4 @@ - [Property Testing Example With Vavr](http://www.baeldung.com/javaslang-property-testing) - [Exceptions in Lambda Expression Using Vavr](http://www.baeldung.com/exceptions-using-vavr) - [Vavr (ex-Javaslang) Support in Spring Data](http://www.baeldung.com/spring-vavr) + From ee9152a091831948b8cb7271d7ee331cb8f06cbe Mon Sep 17 00:00:00 2001 From: "Eunice A. Obugyei" Date: Sat, 19 Aug 2017 03:08:06 +0000 Subject: [PATCH 71/90] BAEL-1014 [Spring MVC with Kotlin] (#2459) * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Removed unnecessary comment * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] Added Exception test cases * Applied baeldung formatter in Eclipse * Merged from https://github.com/eugenp/tutorials Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Revert "Merged from https://github.com/eugenp/tutorials" This reverts commit 74447a163b9e3f244a2578315fbdb525d20cd16b. * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Spring Security for a Java EE Application[http://jira.baeldung.com/browse/BAEL-884] * Updated spring-security version to 4.2.3.RELEASE * Added spring-mvc-kotlin module for http://jira.baeldung.com/browse/BAEL-1014 --- pom.xml | 1 + spring-mvc-kotlin/pom.xml | 79 +++++++++++++++++++ .../kotlin/mvc/ApplicationWebConfig.kt | 37 +++++++++ .../kotlin/mvc/ApplicationWebInitializer.kt | 19 +++++ .../main/webapp/WEB-INF/spring-web-config.xml | 24 ++++++ .../src/main/webapp/WEB-INF/view/welcome.jsp | 7 ++ .../src/main/webapp/WEB-INF/web.xml | 24 ++++++ 7 files changed, 191 insertions(+) create mode 100644 spring-mvc-kotlin/pom.xml create mode 100644 spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt create mode 100644 spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt create mode 100644 spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml create mode 100644 spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp create mode 100755 spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml diff --git a/pom.xml b/pom.xml index 99e9d5a7e398..f2dd0ae48c01 100644 --- a/pom.xml +++ b/pom.xml @@ -175,6 +175,7 @@ spring-mvc-webflow spring-mvc-xml spring-mvc-simple + spring-mvc-kotlin spring-security-openid spring-protobuf spring-quartz diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml new file mode 100644 index 000000000000..087f02fc6881 --- /dev/null +++ b/spring-mvc-kotlin/pom.xml @@ -0,0 +1,79 @@ + + + 4.0.0 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + spring-mvc-kotlin + 0.1-SNAPSHOT + + spring-mvc-kotlin + + war + + + + org.jetbrains.kotlin + kotlin-stdlib-jre8 + 1.1.4 + + + org.jetbrains.kotlin + kotlin-reflect + 1.1.4 + + + + org.springframework + spring-web + 4.3.10.RELEASE + + + org.springframework + spring-webmvc + 4.3.10.RELEASE + + + javax.servlet + jstl + 1.2 + + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/test/kotlin + + + kotlin-maven-plugin + org.jetbrains.kotlin + 1.1.4 + + + + compile + compile + + compile + + + + + test-compile + test-compile + + test-compile + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt new file mode 100644 index 000000000000..4907e46efb96 --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt @@ -0,0 +1,37 @@ +package com.baeldung.kotlin.mvc + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.web.servlet.ViewResolver +import org.springframework.web.servlet.config.annotation.EnableWebMvc +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter +import org.springframework.web.servlet.view.InternalResourceViewResolver +import org.springframework.web.servlet.view.JstlView + + + + + +@EnableWebMvc +@Configuration +open class ApplicationWebConfig: WebMvcConfigurerAdapter() { + + override fun addViewControllers(registry: ViewControllerRegistry?) { + super.addViewControllers(registry) + + registry!!.addViewController("/welcome.html") + } + + @Bean + open fun viewResolver(): ViewResolver { + val bean = InternalResourceViewResolver() + + bean.setViewClass(JstlView::class.java) + bean.setPrefix("/WEB-INF/view/") + bean.setSuffix(".jsp") + + return bean + } + +} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt new file mode 100644 index 000000000000..a4d1614271b8 --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt @@ -0,0 +1,19 @@ +package com.baeldung.kotlin.mvc + +import com.baeldung.kotlin.mvc.ApplicationWebConfig +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer + +class ApplicationWebInitializer: AbstractAnnotationConfigDispatcherServletInitializer() { + + override fun getRootConfigClasses(): Array>? { + return null + } + + override fun getServletMappings(): Array { + return arrayOf("/") + } + + override fun getServletConfigClasses(): Array> { + return arrayOf(ApplicationWebConfig::class.java) + } +} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml b/spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml new file mode 100644 index 000000000000..ffe83a66fa4e --- /dev/null +++ b/spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp new file mode 100644 index 000000000000..bdb671688970 --- /dev/null +++ b/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp @@ -0,0 +1,7 @@ + + Welcome + + +

This is the body of the welcome view 2

+ + \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml b/spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml new file mode 100755 index 000000000000..cbee6a1b11e3 --- /dev/null +++ b/spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,24 @@ + + + Spring Kotlin MVC Application + + + spring-web-mvc + org.springframework.web.servlet.DispatcherServlet + 1 + + contextConfigLocation + /WEB-INF/spring-web-config.xml + + + + + spring-web-mvc + / + + + \ No newline at end of file From f2efbd9a67ee3cadf256ef6bca332539befc8d13 Mon Sep 17 00:00:00 2001 From: felipeazv Date: Sat, 19 Aug 2017 16:40:45 +0200 Subject: [PATCH 72/90] BAEL-812: moving examples to rule-engines folder (#2461) * spring beans DI examples * fix-1: shortening examples * List of Rules Engines in Java * BAEL-812: Openl-Tablets example added * BAEL-812: artifacts names changed * BAEL-812: moving rule-engines examples to rule-engines folder * BAEL-812: removing evaluation article files * BAEL-812: folder renamed * BAEL-812: folder renamed * BAEL-812: pom.xml - parent added --- rule-engines/easy-rules/pom.xml | 24 ++++++++++++++ .../baeldung/easyrules/HelloWorldRule.java | 20 +++++++++++ .../java/com/baeldung/easyrules/Launcher.java | 21 ++++++++++++ rule-engines/openl-tablets/pom.xml | 29 ++++++++++++++++ .../com/baeldung/openltablets/model/Case.java | 23 +++++++++++++ .../baeldung/openltablets/model/Greeting.java | 20 +++++++++++ .../com/baeldung/openltablets/model/User.java | 14 ++++++++ .../baeldung/openltablets/rules/IRule.java | 7 ++++ .../com/baeldung/openltablets/rules/Main.java | 31 ++++++++++++++++++ .../baeldung/openltablets/rules/Response.java | 24 ++++++++++++++ .../main/resources/openltablets/HelloUser.xls | Bin 0 -> 25088 bytes rule-engines/rulebook/pom.xml | 24 ++++++++++++++ .../com/baeldung/rulebook/HelloWorldRule.java | 17 ++++++++++ .../java/com/baeldung/rulebook/Launcher.java | 12 +++++++ 14 files changed, 266 insertions(+) create mode 100644 rule-engines/easy-rules/pom.xml create mode 100644 rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java create mode 100644 rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java create mode 100644 rule-engines/openl-tablets/pom.xml create mode 100644 rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java create mode 100644 rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java create mode 100644 rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java create mode 100644 rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java create mode 100644 rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java create mode 100644 rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java create mode 100644 rule-engines/openl-tablets/src/main/resources/openltablets/HelloUser.xls create mode 100644 rule-engines/rulebook/pom.xml create mode 100644 rule-engines/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java create mode 100644 rule-engines/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java diff --git a/rule-engines/easy-rules/pom.xml b/rule-engines/easy-rules/pom.xml new file mode 100644 index 000000000000..78edc09d1a26 --- /dev/null +++ b/rule-engines/easy-rules/pom.xml @@ -0,0 +1,24 @@ + + 4.0.0 + + com.baeldung.easyrules + easy-rules + 1.0 + + easy-rules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.jeasy + easy-rules-core + 3.0.0 + + + \ No newline at end of file diff --git a/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java b/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java new file mode 100644 index 000000000000..5448eabf2acc --- /dev/null +++ b/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java @@ -0,0 +1,20 @@ +package com.baeldung.easyrules; + +import org.jeasy.rules.annotation.Action; +import org.jeasy.rules.annotation.Condition; +import org.jeasy.rules.annotation.Rule; + +@Rule(name = "Hello World rule", description = "Always say hello world") +public class HelloWorldRule { + + @Condition + public boolean when() { + return true; + } + + @Action + public void then() throws Exception { + System.out.println("hello world"); + } + +} diff --git a/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java b/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java new file mode 100644 index 000000000000..427e3eace056 --- /dev/null +++ b/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java @@ -0,0 +1,21 @@ +package com.baeldung.easyrules; + +import org.jeasy.rules.api.Facts; +import org.jeasy.rules.api.Rules; +import org.jeasy.rules.api.RulesEngine; +import org.jeasy.rules.core.DefaultRulesEngine; + +public class Launcher { + public static void main(String... args) { + // create facts + Facts facts = new Facts(); + + // create rules + Rules rules = new Rules(); + rules.register(new HelloWorldRule()); + + // create a rules engine and fire rules on known facts + RulesEngine rulesEngine = new DefaultRulesEngine(); + rulesEngine.fire(rules, facts); + } +} diff --git a/rule-engines/openl-tablets/pom.xml b/rule-engines/openl-tablets/pom.xml new file mode 100644 index 000000000000..e983d4e56666 --- /dev/null +++ b/rule-engines/openl-tablets/pom.xml @@ -0,0 +1,29 @@ + + 4.0.0 + + com.baeldung.openltablets + openl-tablets + 1.0 + + openl-tablets + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.openl + org.openl.core + 5.19.4 + + + org.openl.rules + org.openl.rules + 5.19.4 + + + \ No newline at end of file diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java new file mode 100644 index 000000000000..f9f5f4bd5f40 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java @@ -0,0 +1,23 @@ +package com.baeldung.openltablets.model; + +public class Case { + + private User user; + private int hourOfDay; + + public User getUser() { + return user; + } + + public void setUser(final User user) { + this.user = user; + } + + public int getHourOfDay() { + return hourOfDay; + } + + public void setHourOfDay(final int hourOfDay) { + this.hourOfDay = hourOfDay; + } +} diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java new file mode 100644 index 000000000000..5dc7bcd11726 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java @@ -0,0 +1,20 @@ +package com.baeldung.openltablets.model; + +public enum Greeting { + + GOOD_MORNING("Good Morning"), + GOOD_AFTERNOON("Good Afternoon"), + GOOD_EVENING("Good Evening"), + GOOD_NIGHT("Good Night"); + + private final String literal; + + private Greeting(final String literal) { + this.literal = literal; + } + + public String getLiteral() { + return literal; + } + +} \ No newline at end of file diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java new file mode 100644 index 000000000000..8e45487497d2 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java @@ -0,0 +1,14 @@ +package com.baeldung.openltablets.model; + +public class User { + + private String name; + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java new file mode 100644 index 000000000000..857a6433ef54 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java @@ -0,0 +1,7 @@ +package com.baeldung.openltablets.rules; + +import com.baeldung.openltablets.model.Case; + +public interface IRule { + void helloUser(final Case aCase, final Response response); +} \ No newline at end of file diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java new file mode 100644 index 000000000000..34f5c48ed120 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java @@ -0,0 +1,31 @@ +package com.baeldung.openltablets.rules; + + +import java.time.LocalDateTime; + +import org.openl.rules.runtime.RulesEngineFactory; +import org.openl.runtime.EngineFactory; + +import com.baeldung.openltablets.model.Case; +import com.baeldung.openltablets.model.User; + +public class Main { + private IRule instance; + + public static void main(String[] args) { + Main rules = new Main(); + User user = new User(); + user.setName("Donald Duck"); + Case aCase = new Case(); + aCase.setUser(user); + aCase.setHourOfDay(23); + rules.process(aCase); + } + + public void process(Case aCase) { + final EngineFactory engineFactory = new RulesEngineFactory(getClass().getClassLoader() + .getResource("openltablets/HelloUser.xls"), IRule.class); + instance = engineFactory.newEngineInstance(); + instance.helloUser(aCase, new Response()); + } +} diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java new file mode 100644 index 000000000000..27fa634866dd --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java @@ -0,0 +1,24 @@ +package com.baeldung.openltablets.rules; + +import java.util.HashMap; +import java.util.Map; + +public class Response { + private String result; + private Map map = new HashMap<>(); + + public Response() { } + + public String getResult() { + return result; + } + + public void setResult(final String s) { + result = s; + } + + public Map getMap() { + return map; + } + +} diff --git a/rule-engines/openl-tablets/src/main/resources/openltablets/HelloUser.xls b/rule-engines/openl-tablets/src/main/resources/openltablets/HelloUser.xls new file mode 100644 index 0000000000000000000000000000000000000000..1e85d0ce2de54ddc812ec9639211a313a5024b45 GIT binary patch literal 25088 zcmeHv2Ut{B)9~44ft8{(5m8`4P>>?Uf-QiE9YLBEae)O^mt6u2q7lWGh%t&imY66p z8Vh!eVnK}s#S&{2dyR^QSYwI%&78aSvWw(>^Zn2Ne$RWCbN8M(b7tnunVD1WVb7el zzPWOX<1NCvJ|RZrgQ5{J(Smc}856y%2;ss5=07MD3I<3BJpT9k57NM2AgiCU58J`F zF(mABQ%HPBjUbspGKXXV$r4gyNKGJt2@q>YHjr!~*+FUw$sSTONDh#iLvn=F0#Zvz zPLP}-xj+&?a)smusTCx5NFI<{Luv!b6OtFCwvfCb`9Si8g!ZON|3Rw$|5DT#B7=_{ z`XYiz;X9j*0}VI)vImP%H4I~cfR9mukP3Pyz3|Je*6Eu(t8<*5Y)V zz&)FcA<0yZFPdzR(M4R3`|L6EQqX8C1P@PbGhBQ$zVa@^#ME%e4tJ>w6UAhzkT*5D#L31Tt4w`v+c4!z~UgGtztRG zcN}97j^j!wBpgQuKthUl0TIUv#OWoHh_k>=L*cpb&-=&KaRl=J&Q+iM+zTf!Eca_+ zHGeV4@AIY<F)Tz?^{T z0>S^As|S@qNMm~iD7!m{4?5>Uoad3{@NEq<3)CURf4JMy`zDILhu*u>SqUNULq50! z0|xfk5N;^N`-_zV7_t;@D-Dav6H!EoG~X1VzU_Hv4pTn$v=4c03a2V~Y?+LC++tqf7uHQ~fTYcgPL!BHjvW@g_3(GWFfc6t38aVA%x zHeXe{#*`CIbtQ&T9rYFfUW^#lAHm>|_9_Vt(9mkX0Sp2(l=?G>q1LcLj88sF!|tOP z-9CcBAzeSxT8ymqw}lJw$1p})k^vUnRgGcE>K6e-S}{onJCM^p^5J|;Cf-Leu7aI? ztX&+i6{Vf(=>Y+?MYZ?U@Hw$CKT8K&6%hf6Cw+-C&kzs^L${118bcmUk%;}t!ISm;D^F0s4I&X2*GB@fV4P< zglKrSht(9U_0&97^_3#1>Qc^{dN-AG)|U!Uiu$S$ARGfFg}+c0)DOoHrVrl`9I5KV z|Gy09pz*0MMxQv#pnBM@EZ}`h^ELb) zg`cOBO9*a^J>YCmm;OGAUl+c^0Gy#;7k`@pd`6#j@tOAGZjf%f7(L?-k*=H@DSZw^ zGYYQ-1bV6BMq9mboK@@6Vfr0+s3?57wY9yuJ?N9MXPhtSqmQd^3J3i&dS>*`foQA` zA9uAVoE6`2cCQbPs{(y+2NnE0T{OTZ7}H+dC8PKZ9LO?o+&NRi1+eac>MS@*9^7S9 z;tL7+L`|Oq5ud_YdIofe-9S1EpYUSno5B-?=To2>jyVdCHUJOR2ZvVVtMt6gPBo5j zaE#99Sa&68=WMtNe?t=uK4?izhk-M4)}^n3>(bZ2_0b19{z|w~57-(ir@xX88y;*3 zA2&v!U2J@RefoiJwK4!_^@}l;2k`T;Mj_~Jh70NkR%ak5g)0eZ_hVf+B2oNkCAyBB zu;;7Rvv$7-U`eae8w1zai3+aWUx4pvO|_t_2MV_;cLMo!_=5g}b>(5&>#Eb<34A*; z0hhw+YdA484W3iL4HyS2_!LI>CuulvV!N}JDBB)2hL@*pSfC#=jFiZqv=SPWD4XD3& zFwi!DNd3J7{?QO3_4f{j@CHayfA4??G=xa~y@P{510<=xcko@!M~MUm)!#e#vZnz= z>hB%g0c-$~`g;dP!iEs3zjp);BT|3wKrm~FB=z@>o0W%>(fXMVx(;Fbq9men2ntii3YGV1!&KgsIX3S4ZzR)C@Es7s`CLx?Cslu^n6kuD7( zqMke`iLf;cyPQf5>uW!^fFIB5l5S9eXL!1gHo>n zGkC8K&$t8uOYy+f2ePqdvk9!r#;qPUff_c(qO|vSFY0Gw!)6mymrd(>*q{R{TVo<^jKP}de~@N zTGfC*Pi)lB#(~X7kEOM#hmE$SRSl@FuGY_{Ih&0hOY^RWjkcv#4N%-)qMwZ;n~fez zYgZ2&ZA+^fu=mna{cKvW+32yfpnBM7TUynCBR99}XVVhdbgbXf1i+?a11v2tX!ef= z`o@XPMvtYr*TY8J(gK5CY@VjSHO_1{dMwSe9yZ#R78q1nS*f3m3!9A|OY^CRjkcu) z1}QG5>1QKgv(aN|{`IiYwzR;YWe4x;XXDCdqsP+P*TY8J(gK5iJTqG#8$NM^z(;z> zGUxF->yDWmM}-mTK~Ej1f}=4^op70o<0C%fT2?teTEL-DSU!Z`lBDEHWb^prbcu28 z6{aK{4y#B=3LK%609l+T;-HI!a5|_Wifda+)CA71Vj)hyIDo93Ez~f9pQ9p zQxN8%Bv&F7q>2OyqHJ-RI7Rs24v4mpC0a8@QxNST2!(aRSIFRjO79@(byJR!5~OCF0`Ogv{q!!0}z^HTAS9OqUVQ33|=YR0)nY zW&d2a`AD>lhA0FSHc?j=QSBf?$diHq{X{)AL?L{ziF&YzYKIJF2ck|#p`>0Kq7W?D zM7>xffXa8IPfq+dkfJIc>`Qe4p#@_mg z`XJE=sXUvS8QW*=fT-%AvC614K8vesm4V?BT*vtTzRxy>c{!~5`$|(}+1VmF_-TZ$ zF>+eKe>mWY+Z6D^Z1{-aBn*ZTX5xmCLIG=Ql}NY%SH>nD@hjvh=J5r(1dVxs90?>u zN{1of5j@ha&=hbzS-7UaT!Skh!(re}1m;-B9G+qSWuPb*6giI{qFa^I5?pN{Fv$gZ zvz4By3VgT*S4#}5eYM1-kbo3!EK-D$!sg>qFo}|XBUr+~8gHOX4&0M{Jj7@uhz;LN!YzWYZ&*W6%GdY#` zOb*3wUuXj2_t6!=*hJAB1Q5X+Ry^R1Hjlbi4G5VKWF>F_3(G{Xbkwy1ThalBArdFb zm&3Ck1bfE9=9vf!F48pF9-5xf*c>s65sBY8kP2OzkPR#^m^w9+E%VX6mjw;1XX z`B@Se&E(=dV9=Mvpo79%hd~6e$^yBWK@1P6=dswJvntt`lTK*LaZluQ6c5s+ZPWxz zCJwqst{%e~VNGEU(KBu|rNWudwS-rLu>5AI2w*wRa%Cec1z(4bK)DFVhHKN};(%oe zw#^JRNV&5XWf)x8l&$MfW`-97locVXe!2x#hm^Z$QHBwQP1&XnWoC>qK$)3!b1CJn zT9jd!>BQ2iZ5_%u(A3o|Y(tolZsHS4{>1MBqzu z_!kv?iiDI3wuk>d5eOlIu|l~PhW7Esj$|IWt$e=>^C|+40ItB?@ZUx#1Re?zq`Vcv zcOhorp`xM!z6!~bB?_`6C=DiORip~=)8L~3I7x$i6%vFniywTX^e6>NgE9mhtXBo~ z6^bQf3FH+^pf1pb@s9+hDM(ON6~F--(-KH&Kt62=S+r;o0R$4X1OQ+vJ$v>9SqPOU zC};_Bb8{mjtQzC=n=+@(Bctfy=IL-$)UgM`o3Ia%PX`y-)DMez1kaIA2bAWKm^UTL z6YIPR}G2r4sDuI*bC0b<&p9LkI;8V)s!4rqq3`__2 zZjF>8_7TL0a-Fk3PrAps}$cxj@wl$o7`WQU#H+ zY$;TR;g)8@(&VCSsZ1tSl}F@>u-r^pK2V&VAqV-joB{elB9x}*3e!cAmn)5}NGcTgdAT#j6n=_kvT z`(=Sn0RHJiQ7) zn)YZ_Ok82iDnlfZ$f&F+I3vD3o3a3#Y6>=`0RQI`C-4X898v+_o8a3YHr-vo2M)vc zcKA-=+e3l^Z-n0sR2A%Clg*L~hkz31C+`PNXr$HOT{XCGZPq2kyQcl*j;x2}nQ z_jF(JAWk#)P8Djt<>~ ztDAiNV)wp1o}IoZ>|3-nX7y+Hv(g7_?LNCW+okyXvu}gBCpzS{F8r&o@yXmlR~;S~ z%?-X&8Gh-WQQ2mvA>E(ed-JvX?c(jbLpl!J&@Y@nbz8-}^EGSV^s2P);dgvjo0opy zdl#)dIrL!Mo93H;8!77WONX`B1<%Z9*&NzzQIvE#UC`Y3{{F5jifXDa4wdY=Hhb&r z2^~jP4LqQ*8}%~eH`{YnlZHgSoLjtSNTLmk}7GLg^Qtla%y!AwB`708>+%fFv zcW1w?zI5--)J~^v*j-rG-*TwWa#PEhqLY3zcGgbtS<_J3=dlO(HabM;#*X`ZPA9{|vTV$Qz zEQo7zEiQh`kofoO;_m*{uC&$Y#N;D=ZC*`|zNj}R ze6XO?s@`9X-T=h2Oyu3xZ*U;O)_enE-yB~Ol=IVtw;dATI) z)!Oc(yEqm^Ow8&1U|*XM$GvXH@0NFcF~8Dk!`ffGSIxR!z4EomwF7+?Z<-PK_G06L z^6M_UG9&l7nRykp%Uk<+?r@_oZjCSbQQvWP zPAPG>7LA|WdO~`iM=76vJ2&n{O&h_5(&9buo|f;F?JIb9|99E`w~wAI+kZdDdywOe zR(9>yPq?9Y*h%r`P`izj6i?>dnDke*T(xU~NeXTlph8&6u zx)Z+L#xt;J`N|mymJ_G+%!tX}oi=fyw8}Vte33Z$E2FAiMGs~j81FrBk{LfG@10j- z?=Bv;cMrNh=Xvy9n7v?xMY!GS)>piW4z+!fGLhptbHnqVUmuIIE%@Tt*jl5RuXn%m zIIy%_W-_H2DUDy)k>j?1Xu#BVF1LGrdE?{S1m$$csO%0njy5kMczub9oLj+boYrn_8g zvUx-EmGKj1yUwpkzL*%FGx)--LUZ4zSDii`HipK*#6d;fS5zQF3($0y6T+!u`b`tZdJZ?XxhC# zk|U2tc5a;5cJ82^SC&0Z^cpEHk4wDRgH!n~pkG|;a|<&Z7i2V>dbZEHHRip7JXa>X z>bw0n$L+uM`D6O}yzS&dzfBcUQuB#xUrSCK+mD)()^fpv$uDB>KRQ@`e956?a_UTb(M2o$b8p$kDgE%Rl|` zhZXIoFKyCeOi8cu=dQle$760*A2D$pJa@{Gi}9zW9lG>m} zncaR=XmHDx!Am+AaoY$ziZgG^yaVoS9^QRsOu&M#S}pzD^R#EY|LJ2*7c73XcIR1> zg*zvl9Cc=9-)B98laBL-cUZS5^2CO@4>xyue7(xucQEH<L(KCW{m89Vc`8uq+74( zd!-q9r%uM^&mUBIE+_5ertiL++QquDi_Jo}(q=v}RY;#tdUW%uuW z@3lNH_2%WbF49M__;kDkpxD)rhsZ{dZX zdv_gk!n5>1+^EWfqia0}^&8ziYD$NjO|N>`q}R&AY-<-s^);KFvh~HikR(?V>GyL| z{+#?+?&$Q>aQE|H_FQ;dII`P@nAWmEcl}MS-x>Oqu{8GFeb2sky8hIDMA`1CCziGQ zz96sT?y3Fb7ax3iz-ZeGrxDKl#hv?cv!2>7C-*JFjHK(vk0OfCY*Vg1E4W_?wYbw(Islms3lM2YhH}6O@hf| z-RY&}FU8-MK}idkeB$nf_6&`gQ&Wi6BvU!Zjx;;yZ#V7rl(Br7?A&gvxvj6wIJ5D* z(X_iAEIWp{52|@$S?a_0`$D*HiMV|6HV719-=W z@813M4RzBwTwgepWoXd_Xj+$^C0KNST>|V?h^Dqb=u>M=!mh}k)oUs?hvklTC$QDe zro^6NYbagRM~P0j*)-TjprMfu>s@VW>M@Dv{>HG|fSX0eBoSJl1N%ILEQ39{Wm+p= zC?K-{HcJbJc(BVsm|upl()ncwb1v*`zy)og|FYyCPRP7o`0Ez%v6)do~pLcerH}84 zdti4cb6hw>f%bsBvA=slVsfzC4Vc&ySjGdaaOiJU&In$LqxP{3->3G#m*~nIVxq>G zGNg&R#+(UY_JVI!j!Sye-4~|J2!5XiHMpqNMR!F(j-FA)K`0!rj@M#JwaFdui=pvR9Dr9emxxsP$C_CCH8EU_p>B#@;E`oU(kAO*ITVaq=! zC0m>fZvbH65#)$6g;KdVB?plZAWXqmB=9Jd3&x5i5<#*^Aj%h|m zmW>qv@f?u^HjDx6nIe;>im_gf0Nw>4nG~5MHxshq0Ro{kRS+I15M~26c>j`Il%A+x^khCVjjG|p-n;ZS=q1?pDjp%eP-a8BZhX#vAqo2 zE&@00Hvq7|&E%Ck{*V{RQ~U&iuoQW&P$C(})D`6mGqXSlAd{PeZyk_P6m0kpXami{ zB2+AWgQV7|5VVj5Ki-6G!ltK*vvcGE3A|HL=@T~o1#VjJ6x{r}f#HB4`Iw&n{T z9`9eWG|luENwpgY%ZjM~9BcdMr@sTirZm&v%+8uTT3cT;O`cAFJvDhc{cWttGt*y9 zo|*n?@-QLdxHkfY&_f9agTFC3Y{3w^sJH~v z=`84i@4#4zhHCpQOgsLz-$I>#!EbS;hklDek;7qTYN%*b??=2C>eY7{ z!+KIiPx)uUaXLI*`}cm2I2a_r37YDvkC&zcFm9 zc;k0ND&j;kvmuBL#QD4Y8%VanX#W;}^b4JHadZnobNr21fXQNy;qP#u=Az+{lUR}= z%mKI6l%VtWg)=hQu<(-Q2nNbBMZ#2>1_z4uUL5#UX;_HRJ`}KiJKPm&sJIDIWr9d? zO13OVmL?ZOA9?7n=b;ZtE9JUUc62sa~%C1*$agKS6v! A1ONa4 literal 0 HcmV?d00001 diff --git a/rule-engines/rulebook/pom.xml b/rule-engines/rulebook/pom.xml new file mode 100644 index 000000000000..711bee8c916f --- /dev/null +++ b/rule-engines/rulebook/pom.xml @@ -0,0 +1,24 @@ + + 4.0.0 + + com.baeldung.rulebook + rulebook + 1.0 + + rulebook + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.deliveredtechnologies + rulebook-core + 0.6.2 + + + \ No newline at end of file diff --git a/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java b/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java new file mode 100644 index 000000000000..c09772a3c673 --- /dev/null +++ b/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java @@ -0,0 +1,17 @@ +package com.baeldung.rulebook; + +import com.deliveredtechnologies.rulebook.lang.RuleBookBuilder; +import com.deliveredtechnologies.rulebook.model.RuleBook; + +public class HelloWorldRule { + public RuleBook defineHelloWorldRules() { + + return RuleBookBuilder.create() + .addRule(rule -> rule.withNoSpecifiedFactType() + .then(f -> System.out.print("Hello "))) + .addRule(rule -> rule.withNoSpecifiedFactType() + .then(f -> System.out.println("World"))) + .build(); + + } +} diff --git a/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java b/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java new file mode 100644 index 000000000000..57965457ecf1 --- /dev/null +++ b/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java @@ -0,0 +1,12 @@ +package com.baeldung.rulebook; + +import com.deliveredtechnologies.rulebook.FactMap; + +public class Launcher { + + public static void main(String[] args) { + HelloWorldRule ruleBook = new HelloWorldRule(); + ruleBook.defineHelloWorldRules() + .run(new FactMap<>()); + } +} From a3cbc25dd805b0e0c94c33d995ecc71727c97855 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 19 Aug 2017 18:13:57 +0200 Subject: [PATCH 73/90] Undertow refactor (#2464) --- undertow/pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/undertow/pom.xml b/undertow/pom.xml index a0f2dc53ee75..33bac571789b 100644 --- a/undertow/pom.xml +++ b/undertow/pom.xml @@ -14,11 +14,6 @@ - - io.undertow - undertow-core - 1.4.18.Final - io.undertow undertow-servlet From b65bccabd19fa596fe95ca530b0c489991768d06 Mon Sep 17 00:00:00 2001 From: dimitarsazdovski Date: Sun, 20 Aug 2017 04:04:56 +0200 Subject: [PATCH 74/90] Bael 817 (#2411) * Stashed changes * Changed method access restriction * Added test class * Changes to pom file * Changed formatting. Changed file path variable * Changed pom file. Changed unit test name * pom file --- libraries/pom.xml | 1093 +++++++++-------- .../java/com/baeldung/geotools/ShapeFile.java | 187 +++ .../geotools/GeoToolsUnitTestTest.java | 27 + 3 files changed, 779 insertions(+), 528 deletions(-) create mode 100644 libraries/src/main/java/com/baeldung/geotools/ShapeFile.java create mode 100644 libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index ddfd75da823f..cf77d197a225 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -1,531 +1,568 @@ - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - - 4.0.0 - libraries - libraries - - - - org.apache.maven.plugins - maven-dependency-plugin - - - org.apache.felix - maven-bundle-plugin - 3.3.0 - maven-plugin - - - true - - - maven-failsafe-plugin - 2.20 - - - chromedriver - - - - - net.serenity-bdd.maven.plugins - serenity-maven-plugin - ${serenity.plugin.version} - - - serenity-reports - post-integration-test - - aggregate - - - - - - - org.datanucleus - datanucleus-maven-plugin - 5.0.2 - - JDO - ${basedir}/datanucleus.properties - ${basedir}/log4j.properties - true - false - - - - - process-classes - - enhance - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 3.0.2 - - - **/log4j.properties - - - - com.baeldung.neuroph.NeurophXOR - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.18.1 - - - test - test - - test - - - - test/java/com/baeldung/neuroph/XORTest.java - - - - - - - - - - - - org.beykery - neuroph - ${neuroph.version} - - - - cglib - cglib - ${cglib.version} - - - commons-beanutils - commons-beanutils - ${commons-beanutils.version} - - - org.apache.commons - commons-lang3 - ${commons-lang.version} - - - org.apache.commons - commons-text - ${commons-text.version} - - - org.apache.commons - commons-collections4 - ${commons.collections.version} - - - org.jasypt - jasypt - ${jasypt.version} - - - org.javatuples - javatuples - ${javatuples.version} - - - org.javassist - javassist - ${javaassist.version} - - - - org.assertj - assertj-core - ${assertj.version} - - - org.skyscreamer - jsonassert - ${jsonassert.version} - - - org.javers - javers-core - ${javers.version} - - - org.eclipse.jetty - jetty-server - ${jetty.version} - - - org.eclipse.jetty - jetty-servlet - ${jetty.version} - - - rome - rome - ${rome.version} - - - io.specto - hoverfly-java - 0.8.0 - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - commons-logging - commons-logging - - - - - commons-io - commons-io - ${commons.io.version} - - - commons-chain - commons-chain - ${commons-chain.version} - - - org.apache.commons - commons-csv - ${commons-csv.version} - - - commons-dbutils - commons-dbutils - ${commons.dbutils.version} - - - org.apache.flink - flink-core - ${flink.version} - - - commons-logging - commons-logging - - - - - org.apache.flink - flink-java - ${flink.version} - - - commons-logging - commons-logging - - - - - org.apache.flink - flink-test-utils_2.10 - ${flink.version} - test - - - org.apache.commons - commons-math3 - 3.6.1 - - - net.serenity-bdd - serenity-core - ${serenity.version} - test - - - net.serenity-bdd - serenity-junit - ${serenity.version} - test - - - net.serenity-bdd - serenity-jbehave - ${serenity.jbehave.version} - test - - - net.serenity-bdd - serenity-rest-assured - ${serenity.version} - test - - - net.serenity-bdd - serenity-jira-requirements-provider - ${serenity.jira.version} - test - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - org.datanucleus - javax.jdo - 3.2.0-m6 - - - org.datanucleus - datanucleus-core - 5.1.0-m1 - - - org.datanucleus - datanucleus-api-jdo - 5.1.0-m1 - - - org.datanucleus - datanucleus-rdbms - 5.1.0-m1 - - - org.datanucleus - datanucleus-maven-plugin - 5.0.2 - - - org.datanucleus - datanucleus-xml - 5.0.0-release - - - net.openhft - chronicle - 3.6.4 - - - org.springframework - spring-web - 4.3.8.RELEASE - - - net.serenity-bdd - serenity-spring - ${serenity.version} - test - - - net.serenity-bdd - serenity-screenplay - ${serenity.version} - test - - - net.serenity-bdd - serenity-screenplay-webdriver - ${serenity.version} - test - - - io.rest-assured - spring-mock-mvc - 3.0.3 - test - - - org.multiverse - multiverse-core - ${multiverse.version} - - - com.zaxxer - HikariCP - 2.6.1 - compile - - - com.h2database - h2 - ${h2.version} - - - pl.pragmatists - JUnitParams - ${jUnitParams.version} - test - - - org.quartz-scheduler - quartz - 2.3.0 - - - one.util - streamex - ${streamex.version} - - - org.jooq - jool - 0.9.12 - - - org.openjdk.jmh - jmh-core - 1.19 - - - org.openjdk.jmh - jmh-generator-annprocess - 1.19 - - - io.netty - netty-all - ${netty.version} - - - junit - junit - ${junit.version} - test - - - info.debatty - java-lsh - ${java-lsh.version} - - - au.com.dius - pact-jvm-consumer-junit_2.11 - ${pact.version} - test - - - org.codehaus.groovy - groovy-all - 2.4.10 - - - org.awaitility - awaitility - ${awaitility.version} - test - - - org.awaitility - awaitility-proxy - ${awaitility.version} - test - - - org.hamcrest - java-hamcrest - ${org.hamcrest.java-hamcrest.version} - test - - - net.agkn - hll - ${hll.version} - - - net.bytebuddy - byte-buddy - ${bytebuddy.version} - - - net.bytebuddy - byte-buddy-agent - ${bytebuddy.version} - - - org.pcollections - pcollections - ${pcollections.version} - - - com.machinezoo.noexception - noexception - 1.1.0 - - - org.eclipse.collections - eclipse-collections - ${eclipse-collections.version} - - - io.vavr - vavr - ${vavr.version} - - - - 0.7.0 - 3.2.4 - 3.5 - 1.1 - 1.9.3 - 1.2 - 1.4 - 1.9.2 - 1.2 - 3.21.0-GA - 3.6.2 - 1.5.0 - 3.1.0 - 9.4.3.v20170317 - 4.5.3 - 2.5 - 1.6 - 1.4.196 - 9.4.2.v20170220 - 4.5.3 - 2.5 - 1.2.0 - 2.8.5 - 2.92 - 1.4.0 - 1.24.0 - 1.1.3-rc.5 - 1.4.0 - 1.1.0 - 4.1.10.Final - 4.1 - 4.12 - 0.10 - 3.5.0 - 3.0.0 - 2.0.0.0 - 1.6.0 - 1.7.1 - 2.1.2 - 1.0 - 8.2.0 - 0.6.5 - 0.9.0 - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + libraries + libraries + + + + org.apache.maven.plugins + maven-dependency-plugin + + + org.apache.felix + maven-bundle-plugin + 3.3.0 + maven-plugin + + + true + + + maven-failsafe-plugin + 2.20 + + + chromedriver + + + + + net.serenity-bdd.maven.plugins + serenity-maven-plugin + ${serenity.plugin.version} + + + serenity-reports + post-integration-test + + aggregate + + + + + + + org.datanucleus + datanucleus-maven-plugin + 5.0.2 + + JDO + ${basedir}/datanucleus.properties + ${basedir}/log4j.properties + true + false + + + + + process-classes + + enhance + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.0.2 + + + **/log4j.properties + + + + com.baeldung.neuroph.NeurophXOR + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.18.1 + + + test + test + + test + + + + test/java/com/baeldung/neuroph/XORTest.java + + + + + + + + + + + + org.beykery + neuroph + ${neuroph.version} + + + + cglib + cglib + ${cglib.version} + + + commons-beanutils + commons-beanutils + ${commons-beanutils.version} + + + org.apache.commons + commons-lang3 + ${commons-lang.version} + + + org.apache.commons + commons-text + ${commons-text.version} + + + org.apache.commons + commons-collections4 + ${commons.collections.version} + + + org.jasypt + jasypt + ${jasypt.version} + + + org.javatuples + javatuples + ${javatuples.version} + + + org.javassist + javassist + ${javaassist.version} + + + + org.assertj + assertj-core + ${assertj.version} + + + org.skyscreamer + jsonassert + ${jsonassert.version} + + + org.javers + javers-core + ${javers.version} + + + org.eclipse.jetty + jetty-server + ${jetty.version} + + + org.eclipse.jetty + jetty-servlet + ${jetty.version} + + + rome + rome + ${rome.version} + + + io.specto + hoverfly-java + 0.8.0 + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + commons-logging + commons-logging + + + + + commons-io + commons-io + ${commons.io.version} + + + commons-chain + commons-chain + ${commons-chain.version} + + + org.apache.commons + commons-csv + ${commons-csv.version} + + + commons-dbutils + commons-dbutils + ${commons.dbutils.version} + + + org.apache.flink + flink-core + ${flink.version} + + + commons-logging + commons-logging + + + + + org.apache.flink + flink-java + ${flink.version} + + + commons-logging + commons-logging + + + + + org.apache.flink + flink-test-utils_2.10 + ${flink.version} + test + + + org.apache.commons + commons-math3 + 3.6.1 + + + net.serenity-bdd + serenity-core + ${serenity.version} + test + + + net.serenity-bdd + serenity-junit + ${serenity.version} + test + + + net.serenity-bdd + serenity-jbehave + ${serenity.jbehave.version} + test + + + net.serenity-bdd + serenity-rest-assured + ${serenity.version} + test + + + net.serenity-bdd + serenity-jira-requirements-provider + ${serenity.jira.version} + test + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + org.datanucleus + javax.jdo + 3.2.0-m6 + + + org.datanucleus + datanucleus-core + 5.1.0-m1 + + + org.datanucleus + datanucleus-api-jdo + 5.1.0-m1 + + + org.datanucleus + datanucleus-rdbms + 5.1.0-m1 + + + org.datanucleus + datanucleus-maven-plugin + 5.0.2 + + + org.datanucleus + datanucleus-xml + 5.0.0-release + + + net.openhft + chronicle + 3.6.4 + + + org.springframework + spring-web + 4.3.8.RELEASE + + + net.serenity-bdd + serenity-spring + ${serenity.version} + test + + + net.serenity-bdd + serenity-screenplay + ${serenity.version} + test + + + net.serenity-bdd + serenity-screenplay-webdriver + ${serenity.version} + test + + + io.rest-assured + spring-mock-mvc + 3.0.3 + test + + + org.multiverse + multiverse-core + ${multiverse.version} + + + com.zaxxer + HikariCP + 2.6.1 + compile + + + com.h2database + h2 + ${h2.version} + + + pl.pragmatists + JUnitParams + ${jUnitParams.version} + test + + + org.quartz-scheduler + quartz + 2.3.0 + + + one.util + streamex + ${streamex.version} + + + org.jooq + jool + 0.9.12 + + + org.openjdk.jmh + jmh-core + 1.19 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.19 + + + io.netty + netty-all + ${netty.version} + + + junit + junit + ${junit.version} + test + + + info.debatty + java-lsh + ${java-lsh.version} + + + au.com.dius + pact-jvm-consumer-junit_2.11 + ${pact.version} + test + + + org.codehaus.groovy + groovy-all + 2.4.10 + + + org.awaitility + awaitility + ${awaitility.version} + test + + + org.awaitility + awaitility-proxy + ${awaitility.version} + test + + + org.hamcrest + java-hamcrest + ${org.hamcrest.java-hamcrest.version} + test + + + net.agkn + hll + ${hll.version} + + + net.bytebuddy + byte-buddy + ${bytebuddy.version} + + + net.bytebuddy + byte-buddy-agent + ${bytebuddy.version} + + + org.pcollections + pcollections + ${pcollections.version} + + + com.machinezoo.noexception + noexception + 1.1.0 + + + org.eclipse.collections + eclipse-collections + ${eclipse-collections.version} + + + io.vavr + vavr + ${vavr.version} + + + org.geotools + gt-shapefile + ${geotools.version} + + + org.geotools + gt-epsg-hsql + ${geotools.version} + + + org.geotools + gt-swing + ${geotools.version} + + + + + maven2-repository.dev.java.net + Java.net repository + http://download.java.net/maven/2 + + + osgeo + Open Source Geospatial Foundation Repository + http://download.osgeo.org/webdav/geotools/ + + + + true + + opengeo + OpenGeo Maven Repository + http://repo.opengeo.org + + + + 0.7.0 + 3.2.4 + 3.5 + 1.1 + 1.9.3 + 1.2 + 1.4 + 1.9.2 + 1.2 + 3.21.0-GA + 3.6.2 + 1.5.0 + 3.1.0 + 9.4.3.v20170317 + 4.5.3 + 2.5 + 1.6 + 1.4.196 + 9.4.2.v20170220 + 4.5.3 + 2.5 + 1.2.0 + 2.8.5 + 2.92 + 1.4.0 + 1.24.0 + 1.1.3-rc.5 + 1.4.0 + 1.1.0 + 4.1.10.Final + 4.1 + 4.12 + 0.10 + 3.5.0 + 3.0.0 + 2.0.0.0 + 1.6.0 + 1.7.1 + 2.1.2 + 1.0 + 8.2.0 + 0.6.5 + 0.9.0 + 15.2 + + diff --git a/libraries/src/main/java/com/baeldung/geotools/ShapeFile.java b/libraries/src/main/java/com/baeldung/geotools/ShapeFile.java new file mode 100644 index 000000000000..77c67abc84a5 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/geotools/ShapeFile.java @@ -0,0 +1,187 @@ +package com.baeldung.geotools; + +import java.io.File; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.geotools.data.DataUtilities; +import org.geotools.data.DefaultTransaction; +import org.geotools.data.Transaction; +import org.geotools.data.shapefile.ShapefileDataStore; +import org.geotools.data.shapefile.ShapefileDataStoreFactory; +import org.geotools.data.simple.SimpleFeatureSource; +import org.geotools.data.simple.SimpleFeatureStore; +import org.geotools.feature.DefaultFeatureCollection; +import org.geotools.feature.simple.SimpleFeatureBuilder; +import org.geotools.feature.simple.SimpleFeatureTypeBuilder; +import org.geotools.geometry.jts.JTSFactoryFinder; +import org.geotools.referencing.crs.DefaultGeographicCRS; +import org.geotools.swing.data.JFileDataStoreChooser; +import org.opengis.feature.simple.SimpleFeature; +import org.opengis.feature.simple.SimpleFeatureType; + +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.GeometryFactory; +import com.vividsolutions.jts.geom.Point; + +public class ShapeFile { + + private static final String FILE_NAME = "shapefile.shp"; + + public static void main(String[] args) throws Exception { + + DefaultFeatureCollection collection = new DefaultFeatureCollection(); + + GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); + + SimpleFeatureType TYPE = DataUtilities.createType("Location", "location:Point:srid=4326," + "name:String"); + + SimpleFeatureType CITY = createFeatureType(); + + SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY); + + addLocations(featureBuilder, collection); + + File shapeFile = getNewShapeFile(); + + ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); + + Map params = new HashMap(); + params.put("url", shapeFile.toURI() + .toURL()); + params.put("create spatial index", Boolean.TRUE); + + ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); + dataStore.createSchema(CITY); + + // If you decide to use the TYPE type and create a Data Store with it, + // You will need to uncomment this line to set the Coordinate Reference System + // newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); + + Transaction transaction = new DefaultTransaction("create"); + + String typeName = dataStore.getTypeNames()[0]; + SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName); + + if (featureSource instanceof SimpleFeatureStore) { + SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; + + featureStore.setTransaction(transaction); + try { + featureStore.addFeatures(collection); + transaction.commit(); + + } catch (Exception problem) { + problem.printStackTrace(); + transaction.rollback(); + + } finally { + transaction.close(); + } + System.exit(0); // success! + } else { + System.out.println(typeName + " does not support read/write access"); + System.exit(1); + } + + } + + public static SimpleFeatureType createFeatureType() { + + SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); + builder.setName("Location"); + builder.setCRS(DefaultGeographicCRS.WGS84); + + builder.add("Location", Point.class); + builder.length(15) + .add("Name", String.class); + + SimpleFeatureType CITY = builder.buildFeatureType(); + + return CITY; + } + + public static void addLocations(SimpleFeatureBuilder featureBuilder, DefaultFeatureCollection collection) { + + Map> locations = new HashMap<>(); + + double lat = 13.752222; + double lng = 100.493889; + String name = "Bangkok"; + addToLocationMap(name, lat, lng, locations); + + lat = 53.083333; + lng = -0.15; + name = "New York"; + addToLocationMap(name, lat, lng, locations); + + lat = -33.925278; + lng = 18.423889; + name = "Cape Town"; + addToLocationMap(name, lat, lng, locations); + + lat = -33.859972; + lng = 151.211111; + name = "Sydney"; + addToLocationMap(name, lat, lng, locations); + + lat = 45.420833; + lng = -75.69; + name = "Ottawa"; + addToLocationMap(name, lat, lng, locations); + + lat = 30.07708; + lng = 31.285909; + name = "Cairo"; + addToLocationMap(name, lat, lng, locations); + + GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); + + for (Map.Entry> location : locations.entrySet()) { + Point point = geometryFactory.createPoint(new Coordinate(location.getValue() + .get(0), + location.getValue() + .get(1))); + featureBuilder.add(point); + featureBuilder.add(name); + SimpleFeature feature = featureBuilder.buildFeature(null); + collection.add(feature); + } + + } + + private static void addToLocationMap(String name, double lat, double lng, Map> locations) { + List coordinates = new ArrayList<>(); + + coordinates.add(lat); + coordinates.add(lng); + locations.put(name, coordinates); + } + + private static File getNewShapeFile() { + String filePath = new File(".").getAbsolutePath() + FILE_NAME; + + + JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp"); + chooser.setDialogTitle("Save shapefile"); + chooser.setSelectedFile(new File(filePath)); + + int returnVal = chooser.showSaveDialog(null); + + if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) { + System.exit(0); + } + + File shapeFile = chooser.getSelectedFile(); + if (shapeFile.equals(filePath)) { + System.out.println("Error: cannot replace " + filePath); + System.exit(0); + } + + return shapeFile; + } + +} diff --git a/libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java b/libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java new file mode 100644 index 000000000000..44cd47edc37e --- /dev/null +++ b/libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java @@ -0,0 +1,27 @@ +package com.baeldung.geotools; + +import static org.junit.Assert.assertNotNull; + +import org.geotools.feature.DefaultFeatureCollection; +import org.geotools.feature.simple.SimpleFeatureBuilder; +import org.junit.Test; +import org.opengis.feature.simple.SimpleFeatureType; + +public class GeoToolsUnitTestTest { + + @Test + public void givenFeatureType_whenAddLocations_returnFeatureCollection() { + + DefaultFeatureCollection collection = new DefaultFeatureCollection(); + + SimpleFeatureType CITY = ShapeFile.createFeatureType(); + + SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY); + + ShapeFile.addLocations(featureBuilder, collection); + + assertNotNull(collection); + + } + +} From a0198e143ebf0f1783c24f3e3482e180895c0a88 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Sun, 20 Aug 2017 08:17:05 +0200 Subject: [PATCH 75/90] upgrade jackson (#2465) * fix spring config * fix spring config * fix spring config * minor fix * fix spring-boot module * fix pom * upgrade jackson --- jackson/pom.xml | 2 +- .../java/com/baeldung/jackson/sandbox/SandboxUnitTest.java | 2 +- .../jackson/test/JacksonSerializationIgnoreUnitTest.java | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/jackson/pom.xml b/jackson/pom.xml index 1a538670c670..f970b6a68c22 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -129,7 +129,7 @@ - 2.8.7 + 2.9.0 19.0 diff --git a/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java index a600577cb0a5..33aca2a1ed0c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java @@ -17,7 +17,7 @@ public final void whenDeserializing_thenCorrect() throws JsonParseException, Jso testElement.setX(10); testElement.setY("adasd"); final ObjectMapper om = new ObjectMapper(); - om.setVisibilityChecker(om.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE)); + om.setVisibility(om.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE)); final String serialized = om.writeValueAsString(testElement); System.err.println(serialized); diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java index 71499b8a2475..bc0e24cdfa24 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java @@ -24,7 +24,6 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; import com.fasterxml.jackson.databind.ser.FilterProvider; @@ -194,7 +193,8 @@ public final void givenIgnoringNullFieldsGlobally_whenWritingObjectWithNullField @Test public final void givenIgnoringMapNullValue_whenWritingMapObjectWithNullValue_thenIgnored() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); + // mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); + mapper.setSerializationInclusion(Include.NON_NULL); final MyDto dtoObject1 = new MyDto(); From a02e758d7078168e2a18eee4af1a18d7622d2959 Mon Sep 17 00:00:00 2001 From: lor6 Date: Sun, 20 Aug 2017 11:20:45 +0300 Subject: [PATCH 76/90] thread pools examples (#2400) * thread pools examples * add logs --- guest/thread-pools/pom.xml | 28 +++++ .../java/com/stackify/models/Employee.java | 28 +++++ .../stackify/services/EmployeeService.java | 9 ++ .../stackify/threadpools/FactorialTask.java | 64 +++++++++++ .../threadpools/ThreadsApplication.java | 102 ++++++++++++++++++ 5 files changed, 231 insertions(+) create mode 100644 guest/thread-pools/pom.xml create mode 100644 guest/thread-pools/src/main/java/com/stackify/models/Employee.java create mode 100644 guest/thread-pools/src/main/java/com/stackify/services/EmployeeService.java create mode 100644 guest/thread-pools/src/main/java/com/stackify/threadpools/FactorialTask.java create mode 100644 guest/thread-pools/src/main/java/com/stackify/threadpools/ThreadsApplication.java diff --git a/guest/thread-pools/pom.xml b/guest/thread-pools/pom.xml new file mode 100644 index 000000000000..72a10213c49e --- /dev/null +++ b/guest/thread-pools/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + com.stackify + thread-pools + 0.0.1-SNAPSHOT + + + + ch.qos.logback + logback-classic + 1.2.3 + + + + + + + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/guest/thread-pools/src/main/java/com/stackify/models/Employee.java b/guest/thread-pools/src/main/java/com/stackify/models/Employee.java new file mode 100644 index 000000000000..65661f38d59e --- /dev/null +++ b/guest/thread-pools/src/main/java/com/stackify/models/Employee.java @@ -0,0 +1,28 @@ +package com.stackify.models; + +public class Employee { + private String name; + private double salary; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + + public Employee(String name, double salary) { + super(); + this.name = name; + this.salary = salary; + } +} diff --git a/guest/thread-pools/src/main/java/com/stackify/services/EmployeeService.java b/guest/thread-pools/src/main/java/com/stackify/services/EmployeeService.java new file mode 100644 index 000000000000..824f87a6254a --- /dev/null +++ b/guest/thread-pools/src/main/java/com/stackify/services/EmployeeService.java @@ -0,0 +1,9 @@ +package com.stackify.services; + +import com.stackify.models.Employee; + +public class EmployeeService { + public double calculateBonus(Employee employee) { + return 0.1 * employee.getSalary(); + } +} diff --git a/guest/thread-pools/src/main/java/com/stackify/threadpools/FactorialTask.java b/guest/thread-pools/src/main/java/com/stackify/threadpools/FactorialTask.java new file mode 100644 index 000000000000..2dd83d9b20ee --- /dev/null +++ b/guest/thread-pools/src/main/java/com/stackify/threadpools/FactorialTask.java @@ -0,0 +1,64 @@ +package com.stackify.threadpools; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.RecursiveTask; +import java.util.stream.IntStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class FactorialTask extends RecursiveTask { + + private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + + private static final long serialVersionUID = 1L; + + private int start = 1; + private int n; + + private static final int THRESHOLD = 20; + + public FactorialTask(int n) { + this.n = n; + } + + public FactorialTask(int start, int n) { + logger.info("New FactorialTask Created"); + this.start = start; + this.n = n; + } + + @Override + protected BigInteger compute() { + if ((n - start) >= THRESHOLD) { + return ForkJoinTask.invokeAll(createSubtasks()) + .stream() + .map(ForkJoinTask::join) + .reduce(BigInteger.ONE, BigInteger::multiply); + } else { + return calculate(start, n); + } + } + + private Collection createSubtasks() { + List dividedTasks = new ArrayList<>(); + + int mid = (start + n) / 2; + + dividedTasks.add(new FactorialTask(start, mid)); + dividedTasks.add(new FactorialTask(mid + 1, n)); + return dividedTasks; + } + + private BigInteger calculate(int start, int n) { + logger.info("Calculate factorial from " + start + " to " + n); + return IntStream.rangeClosed(start, n) + .mapToObj(BigInteger::valueOf) + .reduce(BigInteger.ONE, BigInteger::multiply); + } + +} diff --git a/guest/thread-pools/src/main/java/com/stackify/threadpools/ThreadsApplication.java b/guest/thread-pools/src/main/java/com/stackify/threadpools/ThreadsApplication.java new file mode 100644 index 000000000000..cc9048eee77f --- /dev/null +++ b/guest/thread-pools/src/main/java/com/stackify/threadpools/ThreadsApplication.java @@ -0,0 +1,102 @@ +package com.stackify.threadpools; + +import java.math.BigInteger; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.stackify.models.Employee; +import com.stackify.services.EmployeeService; + +public class ThreadsApplication { + + private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + + public static void main(String[] args) { + testExecutor(); + testExecutorService(); + testScheduledExecutorService(); + testThreadPoolExecutor(); + testForkJoinPool(); + } + + private static EmployeeService employeeService = new EmployeeService(); + + public static void testExecutor() { + Executor executor = Executors.newSingleThreadExecutor(); + executor.execute(() -> System.out.println("Single thread pool test")); + } + + public static void testExecutorService() { + + Employee employee = new Employee("John", 2000); + + ExecutorService executor = Executors.newFixedThreadPool(10); + + Callable callableTask = () -> { + return employeeService.calculateBonus(employee); + }; + Future future = executor.submit(callableTask); + + try { + if (future.isDone()) { + double result = future.get(); + System.out.println("Bonus is:" + result); + } + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + + executor.shutdown(); + } + + public static void testScheduledExecutorService() { + Employee employee = new Employee("John", 2000); + + ScheduledExecutorService executor = Executors.newScheduledThreadPool(10); + + Callable callableTask = () -> { + return employeeService.calculateBonus(employee); + }; + + Future futureScheduled = executor.schedule(callableTask, 2, TimeUnit.MILLISECONDS); + + try { + System.out.println("Bonus:" + futureScheduled.get()); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + + executor.scheduleAtFixedRate(() -> System.out.println("Fixed Rate Scheduled"), 2, 2000, TimeUnit.MILLISECONDS); + executor.scheduleWithFixedDelay(() -> System.out.println("Fixed Delay Scheduled"), 2, 2000, TimeUnit.MILLISECONDS); + } + + public static void testThreadPoolExecutor() { + ThreadPoolExecutor fixedPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10); + ThreadPoolExecutor cachedPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); + + ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 6, 60, TimeUnit.SECONDS, new LinkedBlockingQueue()); + executor.setMaximumPoolSize(8); + + ScheduledThreadPoolExecutor scheduledExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5); + } + + public static void testForkJoinPool() { + ForkJoinPool pool = ForkJoinPool.commonPool(); + logger.info("Thread Pool Created"); + BigInteger result = pool.invoke(new FactorialTask(100)); + System.out.println(result.toString()); + } +} From b7ad275bdd3b9386798dc99d5234cd03eac45124 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Sun, 20 Aug 2017 13:26:34 +0200 Subject: [PATCH 77/90] minor fix (#2468) * fix spring config * fix spring config * fix spring config * minor fix * fix spring-boot module * fix pom * upgrade jackson * minor fix --- .../src/main/java/org/baeldung/config/UiApplication.java | 3 +-- .../src/main/java/org/baeldung/config/UiSecurityConfig.java | 2 ++ 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java index 6e29879cb3a7..e186046e833c 100644 --- a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java @@ -2,12 +2,11 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.web.context.request.RequestContextListener; -@EnableOAuth2Sso + @SpringBootApplication public class UiApplication extends SpringBootServletInitializer { diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java index 5dbe9ada34e6..f9119e20f51a 100644 --- a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java @@ -1,9 +1,11 @@ package org.baeldung.config; +import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +@EnableOAuth2Sso @Configuration public class UiSecurityConfig extends WebSecurityConfigurerAdapter { From e6c2fd3bbec4e94e0482ea50ef61013354122143 Mon Sep 17 00:00:00 2001 From: adamd1985 Date: Sun, 20 Aug 2017 15:44:20 +0200 Subject: [PATCH 78/90] Revert "BAEL-812: List of Rules Engines in Java (#2319)" (#2455) This reverts commit dc105bc6f22b2b4ab9d504fdbf0dd9988ba26ec1. --- easy-rules/pom.xml | 15 ---- .../baeldung/easyrules/HelloWorldRule.java | 20 ----- .../java/com/baeldung/easyrules/Launcher.java | 21 ------ openl-tablets/pom.xml | 23 ------ .../com/baeldung/openltablets/model/Case.java | 23 ------ .../baeldung/openltablets/model/Greeting.java | 20 ----- .../com/baeldung/openltablets/model/User.java | 14 ---- .../baeldung/openltablets/rules/IRule.java | 7 -- .../com/baeldung/openltablets/rules/Main.java | 31 -------- .../baeldung/openltablets/rules/Response.java | 24 ------ .../main/resources/openltablets/HelloUser.xls | Bin 25088 -> 0 bytes rulebook/pom.xml | 15 ---- .../com/baeldung/rulebook/HelloWorldRule.java | 17 ----- .../java/com/baeldung/rulebook/Launcher.java | 12 --- .../autowired/TypesOfBeanInjectionSpring.java | 70 ------------------ ...sOfBeanInjectionSpringIntegrationTest.java | 25 ------- 16 files changed, 337 deletions(-) delete mode 100644 easy-rules/pom.xml delete mode 100644 easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java delete mode 100644 easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java delete mode 100644 openl-tablets/pom.xml delete mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java delete mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java delete mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java delete mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java delete mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java delete mode 100644 openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java delete mode 100644 openl-tablets/src/main/resources/openltablets/HelloUser.xls delete mode 100644 rulebook/pom.xml delete mode 100644 rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java delete mode 100644 rulebook/src/main/java/com/baeldung/rulebook/Launcher.java delete mode 100644 spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java delete mode 100644 spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java diff --git a/easy-rules/pom.xml b/easy-rules/pom.xml deleted file mode 100644 index b74b16f34c6d..000000000000 --- a/easy-rules/pom.xml +++ /dev/null @@ -1,15 +0,0 @@ - - 4.0.0 - com.baeldung.easyrules - easy-rules - 1.0.0-SNAPSHOT - - - - org.jeasy - easy-rules-core - 3.0.0 - - - \ No newline at end of file diff --git a/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java b/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java deleted file mode 100644 index 5448eabf2acc..000000000000 --- a/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.easyrules; - -import org.jeasy.rules.annotation.Action; -import org.jeasy.rules.annotation.Condition; -import org.jeasy.rules.annotation.Rule; - -@Rule(name = "Hello World rule", description = "Always say hello world") -public class HelloWorldRule { - - @Condition - public boolean when() { - return true; - } - - @Action - public void then() throws Exception { - System.out.println("hello world"); - } - -} diff --git a/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java b/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java deleted file mode 100644 index 427e3eace056..000000000000 --- a/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.easyrules; - -import org.jeasy.rules.api.Facts; -import org.jeasy.rules.api.Rules; -import org.jeasy.rules.api.RulesEngine; -import org.jeasy.rules.core.DefaultRulesEngine; - -public class Launcher { - public static void main(String... args) { - // create facts - Facts facts = new Facts(); - - // create rules - Rules rules = new Rules(); - rules.register(new HelloWorldRule()); - - // create a rules engine and fire rules on known facts - RulesEngine rulesEngine = new DefaultRulesEngine(); - rulesEngine.fire(rules, facts); - } -} diff --git a/openl-tablets/pom.xml b/openl-tablets/pom.xml deleted file mode 100644 index 77b9f47b3854..000000000000 --- a/openl-tablets/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - 4.0.0 - com.baeldung.openltablets - openl-tablets - 0.0.1-SNAPSHOT - - UTF-8 - UTF-8 - 1.8 - - - - org.openl - org.openl.core - 5.19.4 - - - org.openl.rules - org.openl.rules - 5.19.4 - - - \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java b/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java deleted file mode 100644 index f9f5f4bd5f40..000000000000 --- a/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.openltablets.model; - -public class Case { - - private User user; - private int hourOfDay; - - public User getUser() { - return user; - } - - public void setUser(final User user) { - this.user = user; - } - - public int getHourOfDay() { - return hourOfDay; - } - - public void setHourOfDay(final int hourOfDay) { - this.hourOfDay = hourOfDay; - } -} diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java b/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java deleted file mode 100644 index 5dc7bcd11726..000000000000 --- a/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.openltablets.model; - -public enum Greeting { - - GOOD_MORNING("Good Morning"), - GOOD_AFTERNOON("Good Afternoon"), - GOOD_EVENING("Good Evening"), - GOOD_NIGHT("Good Night"); - - private final String literal; - - private Greeting(final String literal) { - this.literal = literal; - } - - public String getLiteral() { - return literal; - } - -} \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java b/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java deleted file mode 100644 index 8e45487497d2..000000000000 --- a/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.openltablets.model; - -public class User { - - private String name; - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } -} \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java deleted file mode 100644 index 857a6433ef54..000000000000 --- a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.openltablets.rules; - -import com.baeldung.openltablets.model.Case; - -public interface IRule { - void helloUser(final Case aCase, final Response response); -} \ No newline at end of file diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java deleted file mode 100644 index 34f5c48ed120..000000000000 --- a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.openltablets.rules; - - -import java.time.LocalDateTime; - -import org.openl.rules.runtime.RulesEngineFactory; -import org.openl.runtime.EngineFactory; - -import com.baeldung.openltablets.model.Case; -import com.baeldung.openltablets.model.User; - -public class Main { - private IRule instance; - - public static void main(String[] args) { - Main rules = new Main(); - User user = new User(); - user.setName("Donald Duck"); - Case aCase = new Case(); - aCase.setUser(user); - aCase.setHourOfDay(23); - rules.process(aCase); - } - - public void process(Case aCase) { - final EngineFactory engineFactory = new RulesEngineFactory(getClass().getClassLoader() - .getResource("openltablets/HelloUser.xls"), IRule.class); - instance = engineFactory.newEngineInstance(); - instance.helloUser(aCase, new Response()); - } -} diff --git a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java b/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java deleted file mode 100644 index 27fa634866dd..000000000000 --- a/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.openltablets.rules; - -import java.util.HashMap; -import java.util.Map; - -public class Response { - private String result; - private Map map = new HashMap<>(); - - public Response() { } - - public String getResult() { - return result; - } - - public void setResult(final String s) { - result = s; - } - - public Map getMap() { - return map; - } - -} diff --git a/openl-tablets/src/main/resources/openltablets/HelloUser.xls b/openl-tablets/src/main/resources/openltablets/HelloUser.xls deleted file mode 100644 index 1e85d0ce2de54ddc812ec9639211a313a5024b45..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 25088 zcmeHv2Ut{B)9~44ft8{(5m8`4P>>?Uf-QiE9YLBEae)O^mt6u2q7lWGh%t&imY66p z8Vh!eVnK}s#S&{2dyR^QSYwI%&78aSvWw(>^Zn2Ne$RWCbN8M(b7tnunVD1WVb7el zzPWOX<1NCvJ|RZrgQ5{J(Smc}856y%2;ss5=07MD3I<3BJpT9k57NM2AgiCU58J`F zF(mABQ%HPBjUbspGKXXV$r4gyNKGJt2@q>YHjr!~*+FUw$sSTONDh#iLvn=F0#Zvz zPLP}-xj+&?a)smusTCx5NFI<{Luv!b6OtFCwvfCb`9Si8g!ZON|3Rw$|5DT#B7=_{ z`XYiz;X9j*0}VI)vImP%H4I~cfR9mukP3Pyz3|Je*6Eu(t8<*5Y)V zz&)FcA<0yZFPdzR(M4R3`|L6EQqX8C1P@PbGhBQ$zVa@^#ME%e4tJ>w6UAhzkT*5D#L31Tt4w`v+c4!z~UgGtztRG zcN}97j^j!wBpgQuKthUl0TIUv#OWoHh_k>=L*cpb&-=&KaRl=J&Q+iM+zTf!Eca_+ zHGeV4@AIY<F)Tz?^{T z0>S^As|S@qNMm~iD7!m{4?5>Uoad3{@NEq<3)CURf4JMy`zDILhu*u>SqUNULq50! z0|xfk5N;^N`-_zV7_t;@D-Dav6H!EoG~X1VzU_Hv4pTn$v=4c03a2V~Y?+LC++tqf7uHQ~fTYcgPL!BHjvW@g_3(GWFfc6t38aVA%x zHeXe{#*`CIbtQ&T9rYFfUW^#lAHm>|_9_Vt(9mkX0Sp2(l=?G>q1LcLj88sF!|tOP z-9CcBAzeSxT8ymqw}lJw$1p})k^vUnRgGcE>K6e-S}{onJCM^p^5J|;Cf-Leu7aI? ztX&+i6{Vf(=>Y+?MYZ?U@Hw$CKT8K&6%hf6Cw+-C&kzs^L${118bcmUk%;}t!ISm;D^F0s4I&X2*GB@fV4P< zglKrSht(9U_0&97^_3#1>Qc^{dN-AG)|U!Uiu$S$ARGfFg}+c0)DOoHrVrl`9I5KV z|Gy09pz*0MMxQv#pnBM@EZ}`h^ELb) zg`cOBO9*a^J>YCmm;OGAUl+c^0Gy#;7k`@pd`6#j@tOAGZjf%f7(L?-k*=H@DSZw^ zGYYQ-1bV6BMq9mboK@@6Vfr0+s3?57wY9yuJ?N9MXPhtSqmQd^3J3i&dS>*`foQA` zA9uAVoE6`2cCQbPs{(y+2NnE0T{OTZ7}H+dC8PKZ9LO?o+&NRi1+eac>MS@*9^7S9 z;tL7+L`|Oq5ud_YdIofe-9S1EpYUSno5B-?=To2>jyVdCHUJOR2ZvVVtMt6gPBo5j zaE#99Sa&68=WMtNe?t=uK4?izhk-M4)}^n3>(bZ2_0b19{z|w~57-(ir@xX88y;*3 zA2&v!U2J@RefoiJwK4!_^@}l;2k`T;Mj_~Jh70NkR%ak5g)0eZ_hVf+B2oNkCAyBB zu;;7Rvv$7-U`eae8w1zai3+aWUx4pvO|_t_2MV_;cLMo!_=5g}b>(5&>#Eb<34A*; z0hhw+YdA484W3iL4HyS2_!LI>CuulvV!N}JDBB)2hL@*pSfC#=jFiZqv=SPWD4XD3& zFwi!DNd3J7{?QO3_4f{j@CHayfA4??G=xa~y@P{510<=xcko@!M~MUm)!#e#vZnz= z>hB%g0c-$~`g;dP!iEs3zjp);BT|3wKrm~FB=z@>o0W%>(fXMVx(;Fbq9men2ntii3YGV1!&KgsIX3S4ZzR)C@Es7s`CLx?Cslu^n6kuD7( zqMke`iLf;cyPQf5>uW!^fFIB5l5S9eXL!1gHo>n zGkC8K&$t8uOYy+f2ePqdvk9!r#;qPUff_c(qO|vSFY0Gw!)6mymrd(>*q{R{TVo<^jKP}de~@N zTGfC*Pi)lB#(~X7kEOM#hmE$SRSl@FuGY_{Ih&0hOY^RWjkcv#4N%-)qMwZ;n~fez zYgZ2&ZA+^fu=mna{cKvW+32yfpnBM7TUynCBR99}XVVhdbgbXf1i+?a11v2tX!ef= z`o@XPMvtYr*TY8J(gK5CY@VjSHO_1{dMwSe9yZ#R78q1nS*f3m3!9A|OY^CRjkcu) z1}QG5>1QKgv(aN|{`IiYwzR;YWe4x;XXDCdqsP+P*TY8J(gK5iJTqG#8$NM^z(;z> zGUxF->yDWmM}-mTK~Ej1f}=4^op70o<0C%fT2?teTEL-DSU!Z`lBDEHWb^prbcu28 z6{aK{4y#B=3LK%609l+T;-HI!a5|_Wifda+)CA71Vj)hyIDo93Ez~f9pQ9p zQxN8%Bv&F7q>2OyqHJ-RI7Rs24v4mpC0a8@QxNST2!(aRSIFRjO79@(byJR!5~OCF0`Ogv{q!!0}z^HTAS9OqUVQ33|=YR0)nY zW&d2a`AD>lhA0FSHc?j=QSBf?$diHq{X{)AL?L{ziF&YzYKIJF2ck|#p`>0Kq7W?D zM7>xffXa8IPfq+dkfJIc>`Qe4p#@_mg z`XJE=sXUvS8QW*=fT-%AvC614K8vesm4V?BT*vtTzRxy>c{!~5`$|(}+1VmF_-TZ$ zF>+eKe>mWY+Z6D^Z1{-aBn*ZTX5xmCLIG=Ql}NY%SH>nD@hjvh=J5r(1dVxs90?>u zN{1of5j@ha&=hbzS-7UaT!Skh!(re}1m;-B9G+qSWuPb*6giI{qFa^I5?pN{Fv$gZ zvz4By3VgT*S4#}5eYM1-kbo3!EK-D$!sg>qFo}|XBUr+~8gHOX4&0M{Jj7@uhz;LN!YzWYZ&*W6%GdY#` zOb*3wUuXj2_t6!=*hJAB1Q5X+Ry^R1Hjlbi4G5VKWF>F_3(G{Xbkwy1ThalBArdFb zm&3Ck1bfE9=9vf!F48pF9-5xf*c>s65sBY8kP2OzkPR#^m^w9+E%VX6mjw;1XX z`B@Se&E(=dV9=Mvpo79%hd~6e$^yBWK@1P6=dswJvntt`lTK*LaZluQ6c5s+ZPWxz zCJwqst{%e~VNGEU(KBu|rNWudwS-rLu>5AI2w*wRa%Cec1z(4bK)DFVhHKN};(%oe zw#^JRNV&5XWf)x8l&$MfW`-97locVXe!2x#hm^Z$QHBwQP1&XnWoC>qK$)3!b1CJn zT9jd!>BQ2iZ5_%u(A3o|Y(tolZsHS4{>1MBqzu z_!kv?iiDI3wuk>d5eOlIu|l~PhW7Esj$|IWt$e=>^C|+40ItB?@ZUx#1Re?zq`Vcv zcOhorp`xM!z6!~bB?_`6C=DiORip~=)8L~3I7x$i6%vFniywTX^e6>NgE9mhtXBo~ z6^bQf3FH+^pf1pb@s9+hDM(ON6~F--(-KH&Kt62=S+r;o0R$4X1OQ+vJ$v>9SqPOU zC};_Bb8{mjtQzC=n=+@(Bctfy=IL-$)UgM`o3Ia%PX`y-)DMez1kaIA2bAWKm^UTL z6YIPR}G2r4sDuI*bC0b<&p9LkI;8V)s!4rqq3`__2 zZjF>8_7TL0a-Fk3PrAps}$cxj@wl$o7`WQU#H+ zY$;TR;g)8@(&VCSsZ1tSl}F@>u-r^pK2V&VAqV-joB{elB9x}*3e!cAmn)5}NGcTgdAT#j6n=_kvT z`(=Sn0RHJiQ7) zn)YZ_Ok82iDnlfZ$f&F+I3vD3o3a3#Y6>=`0RQI`C-4X898v+_o8a3YHr-vo2M)vc zcKA-=+e3l^Z-n0sR2A%Clg*L~hkz31C+`PNXr$HOT{XCGZPq2kyQcl*j;x2}nQ z_jF(JAWk#)P8Djt<>~ ztDAiNV)wp1o}IoZ>|3-nX7y+Hv(g7_?LNCW+okyXvu}gBCpzS{F8r&o@yXmlR~;S~ z%?-X&8Gh-WQQ2mvA>E(ed-JvX?c(jbLpl!J&@Y@nbz8-}^EGSV^s2P);dgvjo0opy zdl#)dIrL!Mo93H;8!77WONX`B1<%Z9*&NzzQIvE#UC`Y3{{F5jifXDa4wdY=Hhb&r z2^~jP4LqQ*8}%~eH`{YnlZHgSoLjtSNTLmk}7GLg^Qtla%y!AwB`708>+%fFv zcW1w?zI5--)J~^v*j-rG-*TwWa#PEhqLY3zcGgbtS<_J3=dlO(HabM;#*X`ZPA9{|vTV$Qz zEQo7zEiQh`kofoO;_m*{uC&$Y#N;D=ZC*`|zNj}R ze6XO?s@`9X-T=h2Oyu3xZ*U;O)_enE-yB~Ol=IVtw;dATI) z)!Oc(yEqm^Ow8&1U|*XM$GvXH@0NFcF~8Dk!`ffGSIxR!z4EomwF7+?Z<-PK_G06L z^6M_UG9&l7nRykp%Uk<+?r@_oZjCSbQQvWP zPAPG>7LA|WdO~`iM=76vJ2&n{O&h_5(&9buo|f;F?JIb9|99E`w~wAI+kZdDdywOe zR(9>yPq?9Y*h%r`P`izj6i?>dnDke*T(xU~NeXTlph8&6u zx)Z+L#xt;J`N|mymJ_G+%!tX}oi=fyw8}Vte33Z$E2FAiMGs~j81FrBk{LfG@10j- z?=Bv;cMrNh=Xvy9n7v?xMY!GS)>piW4z+!fGLhptbHnqVUmuIIE%@Tt*jl5RuXn%m zIIy%_W-_H2DUDy)k>j?1Xu#BVF1LGrdE?{S1m$$csO%0njy5kMczub9oLj+boYrn_8g zvUx-EmGKj1yUwpkzL*%FGx)--LUZ4zSDii`HipK*#6d;fS5zQF3($0y6T+!u`b`tZdJZ?XxhC# zk|U2tc5a;5cJ82^SC&0Z^cpEHk4wDRgH!n~pkG|;a|<&Z7i2V>dbZEHHRip7JXa>X z>bw0n$L+uM`D6O}yzS&dzfBcUQuB#xUrSCK+mD)()^fpv$uDB>KRQ@`e956?a_UTb(M2o$b8p$kDgE%Rl|` zhZXIoFKyCeOi8cu=dQle$760*A2D$pJa@{Gi}9zW9lG>m} zncaR=XmHDx!Am+AaoY$ziZgG^yaVoS9^QRsOu&M#S}pzD^R#EY|LJ2*7c73XcIR1> zg*zvl9Cc=9-)B98laBL-cUZS5^2CO@4>xyue7(xucQEH<L(KCW{m89Vc`8uq+74( zd!-q9r%uM^&mUBIE+_5ertiL++QquDi_Jo}(q=v}RY;#tdUW%uuW z@3lNH_2%WbF49M__;kDkpxD)rhsZ{dZX zdv_gk!n5>1+^EWfqia0}^&8ziYD$NjO|N>`q}R&AY-<-s^);KFvh~HikR(?V>GyL| z{+#?+?&$Q>aQE|H_FQ;dII`P@nAWmEcl}MS-x>Oqu{8GFeb2sky8hIDMA`1CCziGQ zz96sT?y3Fb7ax3iz-ZeGrxDKl#hv?cv!2>7C-*JFjHK(vk0OfCY*Vg1E4W_?wYbw(Islms3lM2YhH}6O@hf| z-RY&}FU8-MK}idkeB$nf_6&`gQ&Wi6BvU!Zjx;;yZ#V7rl(Br7?A&gvxvj6wIJ5D* z(X_iAEIWp{52|@$S?a_0`$D*HiMV|6HV719-=W z@813M4RzBwTwgepWoXd_Xj+$^C0KNST>|V?h^Dqb=u>M=!mh}k)oUs?hvklTC$QDe zro^6NYbagRM~P0j*)-TjprMfu>s@VW>M@Dv{>HG|fSX0eBoSJl1N%ILEQ39{Wm+p= zC?K-{HcJbJc(BVsm|upl()ncwb1v*`zy)og|FYyCPRP7o`0Ez%v6)do~pLcerH}84 zdti4cb6hw>f%bsBvA=slVsfzC4Vc&ySjGdaaOiJU&In$LqxP{3->3G#m*~nIVxq>G zGNg&R#+(UY_JVI!j!Sye-4~|J2!5XiHMpqNMR!F(j-FA)K`0!rj@M#JwaFdui=pvR9Dr9emxxsP$C_CCH8EU_p>B#@;E`oU(kAO*ITVaq=! zC0m>fZvbH65#)$6g;KdVB?plZAWXqmB=9Jd3&x5i5<#*^Aj%h|m zmW>qv@f?u^HjDx6nIe;>im_gf0Nw>4nG~5MHxshq0Ro{kRS+I15M~26c>j`Il%A+x^khCVjjG|p-n;ZS=q1?pDjp%eP-a8BZhX#vAqo2 zE&@00Hvq7|&E%Ck{*V{RQ~U&iuoQW&P$C(})D`6mGqXSlAd{PeZyk_P6m0kpXami{ zB2+AWgQV7|5VVj5Ki-6G!ltK*vvcGE3A|HL=@T~o1#VjJ6x{r}f#HB4`Iw&n{T z9`9eWG|luENwpgY%ZjM~9BcdMr@sTirZm&v%+8uTT3cT;O`cAFJvDhc{cWttGt*y9 zo|*n?@-QLdxHkfY&_f9agTFC3Y{3w^sJH~v z=`84i@4#4zhHCpQOgsLz-$I>#!EbS;hklDek;7qTYN%*b??=2C>eY7{ z!+KIiPx)uUaXLI*`}cm2I2a_r37YDvkC&zcFm9 zc;k0ND&j;kvmuBL#QD4Y8%VanX#W;}^b4JHadZnobNr21fXQNy;qP#u=Az+{lUR}= z%mKI6l%VtWg)=hQu<(-Q2nNbBMZ#2>1_z4uUL5#UX;_HRJ`}KiJKPm&sJIDIWr9d? zO13OVmL?ZOA9?7n=b;ZtE9JUUc62sa~%C1*$agKS6v! A1ONa4 diff --git a/rulebook/pom.xml b/rulebook/pom.xml deleted file mode 100644 index 2a42e36d938f..000000000000 --- a/rulebook/pom.xml +++ /dev/null @@ -1,15 +0,0 @@ - - 4.0.0 - com.baeldung.rulebook - rulebook - 1.0.0-SNAPSHOT - - - - com.deliveredtechnologies - rulebook-core - 0.6.2 - - - \ No newline at end of file diff --git a/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java b/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java deleted file mode 100644 index c09772a3c673..000000000000 --- a/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.rulebook; - -import com.deliveredtechnologies.rulebook.lang.RuleBookBuilder; -import com.deliveredtechnologies.rulebook.model.RuleBook; - -public class HelloWorldRule { - public RuleBook defineHelloWorldRules() { - - return RuleBookBuilder.create() - .addRule(rule -> rule.withNoSpecifiedFactType() - .then(f -> System.out.print("Hello "))) - .addRule(rule -> rule.withNoSpecifiedFactType() - .then(f -> System.out.println("World"))) - .build(); - - } -} diff --git a/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java b/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java deleted file mode 100644 index 57965457ecf1..000000000000 --- a/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.rulebook; - -import com.deliveredtechnologies.rulebook.FactMap; - -public class Launcher { - - public static void main(String[] args) { - HelloWorldRule ruleBook = new HelloWorldRule(); - ruleBook.defineHelloWorldRules() - .run(new FactMap<>()); - } -} diff --git a/spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java b/spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java deleted file mode 100644 index ca6018a21e5b..000000000000 --- a/spring-core/src/main/java/com/baeldung/autowired/TypesOfBeanInjectionSpring.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.baeldung.autowired; - -import java.util.ArrayList; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.stereotype.Service; - -@SpringBootApplication -public class TypesOfBeanInjectionSpring { - private final UserService userService; - - @Autowired // the @Autowired can even be omitted, in case there's only one explicit constructor - public TypesOfBeanInjectionSpring(UserService userService) { - this.userService = userService; - } - - public static void main(String[] args) { - SpringApplication.run(TypesOfBeanInjectionSpring.class, args); - } - - @Bean - CommandLineRunner runIt() { - return args -> { - userService.listUsers() - .stream() - .forEach(System.out::println); - }; - } -} - -class User { - private String name; - - public User(String name) { - this.name = name; - } - - // getters and setters ... - public String getName() { - return this.name; - } - - public String toString() { - return name; - } - -} - -interface UserService { - List listUsers(); -} - -@Service -class UserServiceImpl implements UserService { - - @Override - public List listUsers() { - ArrayList users = new ArrayList<>(3); - users.add(new User("Snoopy")); - users.add(new User("Woodstock")); - users.add(new User("Charlie Brown")); - return users; - } - -} diff --git a/spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java b/spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java deleted file mode 100644 index 206a062a571e..000000000000 --- a/spring-core/src/test/java/com/baeldung/autowired/TypesOfBeanInjectionSpringIntegrationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.autowired; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class TypesOfBeanInjectionSpringIntegrationTest { - @Autowired - UserService userService; - - private static final String[] expected = new String[] { "Snoopy", "Woodstock", "Charlie Brown" }; - - @Test - public void givenDI_whenInjectObject_thenUserNamesAreListed() { - Assert.assertArrayEquals(expected, userService.listUsers() - .stream() - .map(User::getName) - .toArray()); - } -} From def5758f0ae642851048fda8b8120b087b76b380 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Mon, 21 Aug 2017 16:30:44 +0530 Subject: [PATCH 79/90] easy code added for simplicity (#2473) * moving jmh into libraries module * refactoring jmh * Update pom.xml * manual algorightm * with BM result * fix for space issue * Fixed indentation * change as per suggestion * vavr either * adding unit test and othe rutilities * adding concurrent module * concurrent package description * concurrent package description * Update EitherUnitTest.java * introducing lambda expression * jooby project * jooby project * reducing employee bean content * bootique module * bootique * bootique * undertow module * undertow module * refactoring * using lambda * as per baeldung formatter * easy code added for simplicity --- .../baeldung/undertow/secure/CustomIdentityManager.java | 3 ++- .../java/com/baeldung/undertow/secure/SecureServer.java | 8 +++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java index e0984f65a588..16231f036d64 100644 --- a/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java +++ b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java @@ -8,9 +8,10 @@ import io.undertow.security.idm.Account; import io.undertow.security.idm.Credential; +import io.undertow.security.idm.IdentityManager; import io.undertow.security.idm.PasswordCredential; -public class CustomIdentityManager implements io.undertow.security.idm.IdentityManager { +public class CustomIdentityManager implements IdentityManager { private final Map users; diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java index 6f520944db78..9997883da610 100644 --- a/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java +++ b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java @@ -29,13 +29,15 @@ public static void main(String[] args) { final IdentityManager idm = new CustomIdentityManager(users); Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(addSecurity((exchange) -> { - final SecurityContext context = exchange.getSecurityContext(); - exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), - IoCallback.END_EXCHANGE); + setExchange(exchange); }, idm)).build(); server.start(); + } + private static void setExchange(HttpServerExchange exchange) { + final SecurityContext context = exchange.getSecurityContext(); + exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(),IoCallback.END_EXCHANGE); } private static HttpHandler addSecurity(final HttpHandler toWrap, final IdentityManager identityManager) { From 82c8d8888693e82504a1133fd20d7a37a4854a72 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Mon, 21 Aug 2017 17:55:21 +0530 Subject: [PATCH 80/90] simplifying (#2476) * moving jmh into libraries module * refactoring jmh * Update pom.xml * manual algorightm * with BM result * fix for space issue * Fixed indentation * change as per suggestion * vavr either * adding unit test and othe rutilities * adding concurrent module * concurrent package description * concurrent package description * Update EitherUnitTest.java * introducing lambda expression * jooby project * jooby project * reducing employee bean content * bootique module * bootique * bootique * undertow module * undertow module * refactoring * using lambda * as per baeldung formatter * easy code added for simplicity * simpliflying --- .../undertow/socket/SocketServer.java | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java b/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java index 9e0e065c3a07..295586e16f76 100644 --- a/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java +++ b/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java @@ -16,15 +16,7 @@ public class SocketServer { public static void main(String[] args) { Undertow server = Undertow.builder().addHttpListener(8080, "localhost") .setHandler(path().addPrefixPath("/baeldungApp", websocket((exchange, channel) -> { - channel.getReceiveSetter().set(new AbstractReceiveListener() { - @Override - protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) { - final String messageData = message.getData(); - for (WebSocketChannel session : channel.getPeerConnections()) { - WebSockets.sendText(messageData, session, null); - } - } - }); + channel.getReceiveSetter().set(getListener()); channel.resumeReceives(); })).addPrefixPath("/", resource(new ClassPathResourceManager(SocketServer.class.getClassLoader(), SocketServer.class.getPackage())).addWelcomeFiles("index.html"))) @@ -33,4 +25,16 @@ protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage m server.start(); } + private static AbstractReceiveListener getListener() { + return new AbstractReceiveListener() { + @Override + protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) { + final String messageData = message.getData(); + for (WebSocketChannel session : channel.getPeerConnections()) { + WebSockets.sendText(messageData, session, null); + } + } + }; + } + } From 84cbc580e5460309f6d7da71fe266e84456ec05c Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 21 Aug 2017 14:52:31 +0200 Subject: [PATCH 81/90] Undertow refactor (#2462) --- .../com/baeldung/undertow/ftp/FileServer.java | 10 +++++----- .../secure/CustomIdentityManager.java | 7 +------ .../undertow/secure/SecureServer.java | 20 +++++++++---------- 3 files changed, 16 insertions(+), 21 deletions(-) diff --git a/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java b/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java index 90cad9ebbd1e..f5cdb827a637 100644 --- a/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java +++ b/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java @@ -1,19 +1,19 @@ package com.baeldung.undertow.ftp; -import java.nio.file.Paths; - import io.undertow.Undertow; import io.undertow.server.handlers.resource.PathResourceManager; +import java.nio.file.Paths; + import static io.undertow.Handlers.resource; public class FileServer { public static void main(String[] args) { Undertow server = Undertow.builder().addHttpListener(8080, "localhost") - .setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100)) - .setDirectoryListingEnabled(true)) - .build(); + .setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100)) + .setDirectoryListingEnabled(true)) + .build(); server.start(); } diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java index 16231f036d64..491941261a9d 100644 --- a/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java +++ b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java @@ -54,12 +54,7 @@ private Account getAccount(final String id) { private static final long serialVersionUID = 1L; - private final Principal principal = new Principal() { - @Override - public String getName() { - return id; - } - }; + private final Principal principal = () -> id; @Override public Principal getPrincipal() { diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java index 9997883da610..6532c3ed7cf4 100644 --- a/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java +++ b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java @@ -1,10 +1,5 @@ package com.baeldung.undertow.secure; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import io.undertow.Undertow; import io.undertow.io.IoCallback; import io.undertow.security.api.AuthenticationMechanism; @@ -19,6 +14,11 @@ import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + public class SecureServer { public static void main(String[] args) { @@ -28,16 +28,16 @@ public static void main(String[] args) { final IdentityManager idm = new CustomIdentityManager(users); - Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(addSecurity((exchange) -> { - setExchange(exchange); - }, idm)).build(); + Undertow server = Undertow.builder() + .addHttpListener(8080, "localhost") + .setHandler(addSecurity(SecureServer::setExchange, idm)).build(); server.start(); } private static void setExchange(HttpServerExchange exchange) { final SecurityContext context = exchange.getSecurityContext(); - exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(),IoCallback.END_EXCHANGE); + exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), IoCallback.END_EXCHANGE); } private static HttpHandler addSecurity(final HttpHandler toWrap, final IdentityManager identityManager) { @@ -45,7 +45,7 @@ private static HttpHandler addSecurity(final HttpHandler toWrap, final IdentityM handler = new AuthenticationCallHandler(handler); handler = new AuthenticationConstraintHandler(handler); final List mechanisms = Collections - . singletonList(new BasicAuthenticationMechanism("Baeldung_Realm")); + .singletonList(new BasicAuthenticationMechanism("Baeldung_Realm")); handler = new AuthenticationMechanismsHandler(handler, mechanisms); handler = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, handler); return handler; From 6d7fa197dd9982dbcaf0ae73ac43b00fa0ae9187 Mon Sep 17 00:00:00 2001 From: "Eunice A. Obugyei" Date: Mon, 21 Aug 2017 15:55:26 +0000 Subject: [PATCH 82/90] BAEL-1014 [Spring MVC with Kotlin] (#2475) * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Removed unnecessary comment * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] Added Exception test cases * Applied baeldung formatter in Eclipse * Merged from https://github.com/eugenp/tutorials Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Revert "Merged from https://github.com/eugenp/tutorials" This reverts commit 74447a163b9e3f244a2578315fbdb525d20cd16b. * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Introduction to JAX-WS[http://jira.baeldung.com/browse/BAEL-611] * Spring Security for a Java EE Application[http://jira.baeldung.com/browse/BAEL-884] * Updated spring-security version to 4.2.3.RELEASE * Added spring-mvc-kotlin module for http://jira.baeldung.com/browse/BAEL-1014 * Removed dependency for kotlin-reflect --- spring-mvc-kotlin/pom.xml | 5 ----- spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp | 2 +- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml index 087f02fc6881..5375ecae7c5f 100644 --- a/spring-mvc-kotlin/pom.xml +++ b/spring-mvc-kotlin/pom.xml @@ -23,11 +23,6 @@ kotlin-stdlib-jre8 1.1.4 - - org.jetbrains.kotlin - kotlin-reflect - 1.1.4 - org.springframework diff --git a/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp index bdb671688970..3f68f128bc0f 100644 --- a/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp +++ b/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp @@ -2,6 +2,6 @@ Welcome -

This is the body of the welcome view 2

+

This is the body of the welcome view

\ No newline at end of file From 04fa1782a24f7ca9b257829b677d4ab3d170b1ea Mon Sep 17 00:00:00 2001 From: lor6 Date: Mon, 21 Aug 2017 21:25:12 +0300 Subject: [PATCH 83/90] reladomo example (#2469) * reladomo example * fix formatting * add plugin versions * fix closing streams --- libraries/pom.xml | 100 +++++++++++++++++- .../com/baeldung/reladomo/Department.java | 15 +++ .../reladomo/DepartmentDatabaseObject.java | 4 + .../com/baeldung/reladomo/DepartmentList.java | 25 +++++ .../java/com/baeldung/reladomo/Employee.java | 16 +++ .../reladomo/EmployeeDatabaseObject.java | 4 + .../com/baeldung/reladomo/EmployeeList.java | 25 +++++ .../reladomo/ReladomoApplication.java | 54 ++++++++++ .../reladomo/ReladomoConnectionManager.java | 92 ++++++++++++++++ .../main/resources/ReladomoRuntimeConfig.xml | 6 ++ .../main/resources/reladomo/Department.xml | 11 ++ .../src/main/resources/reladomo/Employee.xml | 9 ++ .../resources/reladomo/ReladomoClassList.xml | 4 + .../com/baeldung/reladomo/ReladomoTest.java | 38 +++++++ .../resources/reladomo/ReladomoTestConfig.xml | 7 ++ .../src/test/resources/reladomo/test-data.txt | 7 ++ 16 files changed, 415 insertions(+), 2 deletions(-) create mode 100644 libraries/src/main/java/com/baeldung/reladomo/Department.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/DepartmentList.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/Employee.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/EmployeeList.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/ReladomoApplication.java create mode 100644 libraries/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java create mode 100644 libraries/src/main/resources/ReladomoRuntimeConfig.xml create mode 100644 libraries/src/main/resources/reladomo/Department.xml create mode 100644 libraries/src/main/resources/reladomo/Employee.xml create mode 100644 libraries/src/main/resources/reladomo/ReladomoClassList.xml create mode 100644 libraries/src/test/java/com/baeldung/reladomo/ReladomoTest.java create mode 100644 libraries/src/test/resources/reladomo/ReladomoTestConfig.xml create mode 100644 libraries/src/test/resources/reladomo/test-data.txt diff --git a/libraries/pom.xml b/libraries/pom.xml index cf77d197a225..e9603b14530e 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -105,6 +105,92 @@ + + + + maven-antrun-plugin + 1.8 + + + generateMithra + generate-sources + + run + + + + + + + + + + + + + + + + + + com.goldmansachs.reladomo + reladomogen + ${reladomo.version} + + + + com.goldmansachs.reladomo + reladomo-gen-util + ${reladomo.version} + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + ${project.build.directory}/generated-sources/reladomo + + + + + add-resource + generate-resources + + add-resource + + + + + ${project.build.directory}/generated-db/ + + + + + + + + @@ -497,6 +583,16 @@ gt-swing ${geotools.version}
+ + com.goldmansachs.reladomo + reladomo + ${reladomo.version} + + + com.goldmansachs.reladomo + reladomo-test-util + ${reladomo.version} + @@ -563,6 +659,6 @@ 0.6.5 0.9.0 15.2 + 16.5.1 - - + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/reladomo/Department.java b/libraries/src/main/java/com/baeldung/reladomo/Department.java new file mode 100644 index 000000000000..d26ddafbf4d8 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/Department.java @@ -0,0 +1,15 @@ +package com.baeldung.reladomo; + +public class Department extends DepartmentAbstract { + public Department() { + super(); + // You must not modify this constructor. Mithra calls this internally. + // You can call this constructor. You can also add new constructors. + } + + public Department(long id, String name) { + super(); + this.setId(id); + this.setName(name); + } +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java b/libraries/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java new file mode 100644 index 000000000000..4cfb5cb0554a --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java @@ -0,0 +1,4 @@ +package com.baeldung.reladomo; +public class DepartmentDatabaseObject extends DepartmentDatabaseObjectAbstract +{ +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/DepartmentList.java b/libraries/src/main/java/com/baeldung/reladomo/DepartmentList.java new file mode 100644 index 000000000000..edad6bc1f491 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/DepartmentList.java @@ -0,0 +1,25 @@ +package com.baeldung.reladomo; +import com.gs.fw.finder.Operation; +import java.util.*; +public class DepartmentList extends DepartmentListAbstract +{ + public DepartmentList() + { + super(); + } + + public DepartmentList(int initialSize) + { + super(initialSize); + } + + public DepartmentList(Collection c) + { + super(c); + } + + public DepartmentList(Operation operation) + { + super(operation); + } +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/Employee.java b/libraries/src/main/java/com/baeldung/reladomo/Employee.java new file mode 100644 index 000000000000..519e841282bd --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/Employee.java @@ -0,0 +1,16 @@ +package com.baeldung.reladomo; +public class Employee extends EmployeeAbstract +{ + public Employee() + { + super(); + // You must not modify this constructor. Mithra calls this internally. + // You can call this constructor. You can also add new constructors. + } + + public Employee(long id, String name){ + super(); + this.setId(id); + this.setName(name); + } +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java b/libraries/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java new file mode 100644 index 000000000000..407049f342a7 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java @@ -0,0 +1,4 @@ +package com.baeldung.reladomo; +public class EmployeeDatabaseObject extends EmployeeDatabaseObjectAbstract +{ +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/EmployeeList.java b/libraries/src/main/java/com/baeldung/reladomo/EmployeeList.java new file mode 100644 index 000000000000..4e759898c373 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/EmployeeList.java @@ -0,0 +1,25 @@ +package com.baeldung.reladomo; +import com.gs.fw.finder.Operation; +import java.util.*; +public class EmployeeList extends EmployeeListAbstract +{ + public EmployeeList() + { + super(); + } + + public EmployeeList(int initialSize) + { + super(initialSize); + } + + public EmployeeList(Collection c) + { + super(c); + } + + public EmployeeList(Operation operation) + { + super(operation); + } +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/ReladomoApplication.java b/libraries/src/main/java/com/baeldung/reladomo/ReladomoApplication.java new file mode 100644 index 000000000000..c6b242d3aea8 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/ReladomoApplication.java @@ -0,0 +1,54 @@ +package com.baeldung.reladomo; + +import java.io.InputStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.gs.fw.common.mithra.MithraManager; +import com.gs.fw.common.mithra.MithraManagerProvider; + +public class ReladomoApplication { + + public static void main(String[] args) { + + try { + ReladomoConnectionManager.getInstance().createTables(); + } catch (Exception e1) { + e1.printStackTrace(); + } + + MithraManager mithraManager = MithraManagerProvider.getMithraManager(); + mithraManager.setTransactionTimeout(120); + + try (InputStream is = ReladomoApplication.class.getClassLoader().getResourceAsStream("ReladomoRuntimeConfig.xml")) { + MithraManagerProvider.getMithraManager().readConfiguration(is); + + Department department = new Department(1, "IT"); + Employee employee = new Employee(1, "John"); + department.getEmployees().add(employee); + department.cascadeInsert(); + + Department depFound = DepartmentFinder.findByPrimaryKey(1); + System.out.println("Department Name:" + department.getName()); + + Employee empFound = EmployeeFinder.findOne(EmployeeFinder.name().eq("John")); + System.out.println("Employee Id:" + empFound.getId()); + empFound.setName("Steven"); + empFound.delete(); + Department depDetached = DepartmentFinder.findByPrimaryKey(1).getDetachedCopy(); + + mithraManager.executeTransactionalCommand(tx -> { + Department dep = new Department(2, "HR"); + Employee emp = new Employee(2, "Jim"); + dep.getEmployees().add(emp); + dep.cascadeInsert(); + return null; + }); + + } catch (java.io.IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/libraries/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java b/libraries/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java new file mode 100644 index 000000000000..66a8f9ff9926 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java @@ -0,0 +1,92 @@ +package com.baeldung.reladomo; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.TimeZone; +import java.util.stream.Stream; + +import org.h2.tools.RunScript; + +import com.gs.fw.common.mithra.bulkloader.BulkLoader; +import com.gs.fw.common.mithra.bulkloader.BulkLoaderException; +import com.gs.fw.common.mithra.connectionmanager.SourcelessConnectionManager; +import com.gs.fw.common.mithra.connectionmanager.XAConnectionManager; +import com.gs.fw.common.mithra.databasetype.DatabaseType; +import com.gs.fw.common.mithra.databasetype.H2DatabaseType; + +public class ReladomoConnectionManager implements SourcelessConnectionManager { + + private static ReladomoConnectionManager instance; + + private XAConnectionManager xaConnectionManager; + + private final String databaseName = "myDb"; + + public static synchronized ReladomoConnectionManager getInstance() { + if (instance == null) { + instance = new ReladomoConnectionManager(); + } + return instance; + } + + private ReladomoConnectionManager() { + this.createConnectionManager(); + } + + private XAConnectionManager createConnectionManager() { + xaConnectionManager = new XAConnectionManager(); + xaConnectionManager.setDriverClassName("org.h2.Driver"); + xaConnectionManager.setJdbcConnectionString("jdbc:h2:mem:" + databaseName); + xaConnectionManager.setJdbcUser("sa"); + xaConnectionManager.setJdbcPassword(""); + xaConnectionManager.setPoolName("My Connection Pool"); + xaConnectionManager.setInitialSize(1); + xaConnectionManager.setPoolSize(10); + xaConnectionManager.initialisePool(); + return xaConnectionManager; + } + + @Override + public BulkLoader createBulkLoader() throws BulkLoaderException { + return null; + } + + @Override + public Connection getConnection() { + return xaConnectionManager.getConnection(); + } + + @Override + public DatabaseType getDatabaseType() { + return H2DatabaseType.getInstance(); + } + + @Override + public TimeZone getDatabaseTimeZone() { + return TimeZone.getDefault(); + } + + @Override + public String getDatabaseIdentifier() { + return databaseName; + } + + public void createTables() throws Exception { + Path ddlPath = Paths.get(ClassLoader.getSystemResource("sql").toURI()); + + try (Connection conn = xaConnectionManager.getConnection(); Stream list = Files.list(ddlPath);) { + list.forEach(path -> { + try { + RunScript.execute(conn, Files.newBufferedReader(path)); + } catch (SQLException | IOException exc) { + exc.printStackTrace(); + } + }); + } + } + +} diff --git a/libraries/src/main/resources/ReladomoRuntimeConfig.xml b/libraries/src/main/resources/ReladomoRuntimeConfig.xml new file mode 100644 index 000000000000..7181e75406b7 --- /dev/null +++ b/libraries/src/main/resources/ReladomoRuntimeConfig.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/libraries/src/main/resources/reladomo/Department.xml b/libraries/src/main/resources/reladomo/Department.xml new file mode 100644 index 000000000000..a284965cd6b9 --- /dev/null +++ b/libraries/src/main/resources/reladomo/Department.xml @@ -0,0 +1,11 @@ + + com.baeldung.reladomo + Department + departments + + + + + Employee.departmentId = this.id + + \ No newline at end of file diff --git a/libraries/src/main/resources/reladomo/Employee.xml b/libraries/src/main/resources/reladomo/Employee.xml new file mode 100644 index 000000000000..00e360bc6799 --- /dev/null +++ b/libraries/src/main/resources/reladomo/Employee.xml @@ -0,0 +1,9 @@ + + com.baeldung.reladomo + Employee + employees + + + + + \ No newline at end of file diff --git a/libraries/src/main/resources/reladomo/ReladomoClassList.xml b/libraries/src/main/resources/reladomo/ReladomoClassList.xml new file mode 100644 index 000000000000..99118a745dee --- /dev/null +++ b/libraries/src/main/resources/reladomo/ReladomoClassList.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/reladomo/ReladomoTest.java b/libraries/src/test/java/com/baeldung/reladomo/ReladomoTest.java new file mode 100644 index 000000000000..61c29e8aa320 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/reladomo/ReladomoTest.java @@ -0,0 +1,38 @@ +package com.baeldung.reladomo; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.gs.fw.common.mithra.test.ConnectionManagerForTests; +import com.gs.fw.common.mithra.test.MithraTestResource; + +public class ReladomoTest { + private MithraTestResource mithraTestResource; + + @Before + public void setUp() throws Exception { + this.mithraTestResource = new MithraTestResource("reladomo/ReladomoTestConfig.xml"); + + final ConnectionManagerForTests connectionManager = ConnectionManagerForTests.getInstanceForDbName("testDb"); + this.mithraTestResource.createSingleDatabase(connectionManager); + + mithraTestResource.addTestDataToDatabase("reladomo/test-data.txt", connectionManager); + + this.mithraTestResource.setUp(); + } + + @Test + public void whenGetTestData_thenOk() { + Employee employee = EmployeeFinder.findByPrimaryKey(1); + assertEquals(employee.getName(), "Paul"); + } + + @After + public void tearDown() throws Exception { + this.mithraTestResource.tearDown(); + } + +} diff --git a/libraries/src/test/resources/reladomo/ReladomoTestConfig.xml b/libraries/src/test/resources/reladomo/ReladomoTestConfig.xml new file mode 100644 index 000000000000..a1951f09b7a6 --- /dev/null +++ b/libraries/src/test/resources/reladomo/ReladomoTestConfig.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/libraries/src/test/resources/reladomo/test-data.txt b/libraries/src/test/resources/reladomo/test-data.txt new file mode 100644 index 000000000000..8e407278ac2b --- /dev/null +++ b/libraries/src/test/resources/reladomo/test-data.txt @@ -0,0 +1,7 @@ +class com.baeldung.reladomo.Department +id, name +1, "Marketing" + +class com.baeldung.reladomo.Employee +id, name +1, "Paul" \ No newline at end of file From 706b3d6c676e198707d00f0febc51c1180c788d0 Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Mon, 21 Aug 2017 20:01:41 +0100 Subject: [PATCH 84/90] Example for a GraphQL Application in Spring Boot (#2477) --- spring-boot/pom.xml | 16 +++++ .../java/com/baeldung/graphql/Author.java | 31 ++++++++++ .../java/com/baeldung/graphql/AuthorDao.java | 18 ++++++ .../com/baeldung/graphql/AuthorResolver.java | 17 ++++++ .../graphql/GraphqlConfiguration.java | 59 +++++++++++++++++++ .../java/com/baeldung/graphql/Mutation.java | 25 ++++++++ .../main/java/com/baeldung/graphql/Post.java | 49 +++++++++++++++ .../java/com/baeldung/graphql/PostDao.java | 29 +++++++++ .../com/baeldung/graphql/PostResolver.java | 17 ++++++ .../main/java/com/baeldung/graphql/Query.java | 17 ++++++ .../org/baeldung/boot/DemoApplication.java | 3 + .../src/main/resources/graphql/blog.graphqls | 24 ++++++++ 12 files changed, 305 insertions(+) create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/Author.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/Mutation.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/Post.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/PostDao.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java create mode 100644 spring-boot/src/main/java/com/baeldung/graphql/Query.java create mode 100644 spring-boot/src/main/resources/graphql/blog.graphqls diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 0cf7df86cd7d..9d44de64a3cb 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -40,6 +40,22 @@ spring-boot-starter-security + + com.graphql-java + graphql-spring-boot-starter + 3.6.0 + + + com.graphql-java + graphiql-spring-boot-starter + 3.6.0 + + + com.graphql-java + graphql-java-tools + 3.2.0 + + org.springframework.boot spring-boot-starter-tomcat diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Author.java b/spring-boot/src/main/java/com/baeldung/graphql/Author.java new file mode 100644 index 000000000000..11e927c56460 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/Author.java @@ -0,0 +1,31 @@ +package com.baeldung.graphql; + +public class Author { + private String id; + private String name; + private String thumbnail; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getThumbnail() { + return thumbnail; + } + + public void setThumbnail(String thumbnail) { + this.thumbnail = thumbnail; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java b/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java new file mode 100644 index 000000000000..522732faeb22 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java @@ -0,0 +1,18 @@ +package com.baeldung.graphql; + +import java.util.List; +import java.util.Optional; + +public class AuthorDao { + private List authors; + + public AuthorDao(List authors) { + this.authors = authors; + } + + public Optional getAuthor(String id) { + return authors.stream() + .filter(author -> id.equals(author.getId())) + .findFirst(); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java b/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java new file mode 100644 index 000000000000..982c6cebc196 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java @@ -0,0 +1,17 @@ +package com.baeldung.graphql; + +import java.util.List; + +import com.coxautodev.graphql.tools.GraphQLResolver; + +public class AuthorResolver implements GraphQLResolver { + private PostDao postDao; + + public AuthorResolver(PostDao postDao) { + this.postDao = postDao; + } + + public List getPosts(Author author) { + return postDao.getAuthorPosts(author.getId()); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java b/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java new file mode 100644 index 000000000000..a7a864cf96e5 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java @@ -0,0 +1,59 @@ +package com.baeldung.graphql; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class GraphqlConfiguration { + @Bean + public PostDao postDao() { + List posts = new ArrayList<>(); + for (int postId = 0; postId < 10; ++postId) { + for (int authorId = 0; authorId < 10; ++authorId) { + Post post = new Post(); + post.setId("Post" + authorId + postId); + post.setTitle("Post " + authorId + ":" + postId); + post.setText("Post " + postId + " + by author " + authorId); + post.setAuthorId("Author" + authorId); + posts.add(post); + } + } + return new PostDao(posts); + } + + @Bean + public AuthorDao authorDao() { + List authors = new ArrayList<>(); + for (int authorId = 0; authorId < 10; ++authorId) { + Author author = new Author(); + author.setId("Author" + authorId); + author.setName("Author " + authorId); + author.setThumbnail("http://example.com/authors/" + authorId); + authors.add(author); + } + return new AuthorDao(authors); + } + + @Bean + public PostResolver postResolver(AuthorDao authorDao) { + return new PostResolver(authorDao); + } + + @Bean + public AuthorResolver authorResolver(PostDao postDao) { + return new AuthorResolver(postDao); + } + + @Bean + public Query query(PostDao postDao) { + return new Query(postDao); + } + + @Bean + public Mutation mutation(PostDao postDao) { + return new Mutation(postDao); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java b/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java new file mode 100644 index 000000000000..0e16e3c8b721 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java @@ -0,0 +1,25 @@ +package com.baeldung.graphql; + +import java.util.UUID; + +import com.coxautodev.graphql.tools.GraphQLMutationResolver; + +public class Mutation implements GraphQLMutationResolver { + private PostDao postDao; + + public Mutation(PostDao postDao) { + this.postDao = postDao; + } + + public Post writePost(String title, String text, String category, String author) { + Post post = new Post(); + post.setId(UUID.randomUUID().toString()); + post.setTitle(title); + post.setText(text); + post.setCategory(category); + post.setAuthorId(author); + postDao.savePost(post); + + return post; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Post.java b/spring-boot/src/main/java/com/baeldung/graphql/Post.java new file mode 100644 index 000000000000..14d30848411e --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/Post.java @@ -0,0 +1,49 @@ +package com.baeldung.graphql; + +public class Post { + private String id; + private String title; + private String text; + private String category; + private String authorId; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getAuthorId() { + return authorId; + } + + public void setAuthorId(String authorId) { + this.authorId = authorId; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java b/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java new file mode 100644 index 000000000000..f8d243ee3ad5 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java @@ -0,0 +1,29 @@ +package com.baeldung.graphql; + +import java.util.List; +import java.util.stream.Collectors; + +public class PostDao { + private List posts; + + public PostDao(List posts) { + this.posts = posts; + } + + public List getRecentPosts(int count, int offset) { + return posts.stream() + .skip(offset) + .limit(count) + .collect(Collectors.toList()); + } + + public List getAuthorPosts(String author) { + return posts.stream() + .filter(post -> author.equals(post.getAuthorId())) + .collect(Collectors.toList()); + } + + public void savePost(Post post) { + posts.add(0, post); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java b/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java new file mode 100644 index 000000000000..dbfde330eadb --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java @@ -0,0 +1,17 @@ +package com.baeldung.graphql; + +import java.util.Optional; + +import com.coxautodev.graphql.tools.GraphQLResolver; + +public class PostResolver implements GraphQLResolver { + private AuthorDao authorDao; + + public PostResolver(AuthorDao authorDao) { + this.authorDao = authorDao; + } + + public Optional getAuthor(Post post) { + return authorDao.getAuthor(post.getAuthorId()); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Query.java b/spring-boot/src/main/java/com/baeldung/graphql/Query.java new file mode 100644 index 000000000000..7bb625798c31 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/Query.java @@ -0,0 +1,17 @@ +package com.baeldung.graphql; + +import java.util.List; + +import com.coxautodev.graphql.tools.GraphQLQueryResolver; + +public class Query implements GraphQLQueryResolver { + private PostDao postDao; + + public Query(PostDao postDao) { + this.postDao = postDao; + } + + public List recentPosts(int count, int offset) { + return postDao.getRecentPosts(count, offset); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java b/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java index 2d83b650ecc4..5de413473998 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java +++ b/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java @@ -1,11 +1,14 @@ package org.baeldung.boot; +import com.baeldung.graphql.GraphqlConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; +import org.springframework.context.annotation.Import; @SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@Import(GraphqlConfiguration.class) public class DemoApplication { public static void main(String[] args) { diff --git a/spring-boot/src/main/resources/graphql/blog.graphqls b/spring-boot/src/main/resources/graphql/blog.graphqls new file mode 100644 index 000000000000..aa0c8757e9b5 --- /dev/null +++ b/spring-boot/src/main/resources/graphql/blog.graphqls @@ -0,0 +1,24 @@ +type Post { + id: ID! + title: String! + text: String! + category: String + author: Author +} + +type Author { + id: ID! + name: String! + thumbnail: String + posts: [Post]! +} + +# The Root Query for the application +type Query { + recentPosts(count: Int, offset: Int): [Post]! +} + +# The Root Mutation for the application +type Mutation { + writePost(title: String!, text: String!, category: String, author: String!) : Post! +} From 802c0b09e044c7047b10e349cf8e31c844c1913e Mon Sep 17 00:00:00 2001 From: Tian Baoqiang Date: Mon, 21 Aug 2017 15:58:37 -0500 Subject: [PATCH 85/90] #BAEL-1025 (#2445) --- ratpack/pom.xml | 22 ++++++++ .../hystrix/HystrixAsyncHttpCommand.java | 54 ++++++++++++++++++ .../hystrix/HystrixReactiveHttpCommand.java | 44 +++++++++++++++ .../hystrix/HystrixSyncHttpCommand.java | 55 +++++++++++++++++++ .../baeldung/hystrix/RatpackHystrixApp.java | 30 ++++++++++ .../RatpackHystrixAppFallbackLiveTest.java | 50 +++++++++++++++++ .../hystrix/RatpackHystrixAppLiveTest.java | 50 +++++++++++++++++ 7 files changed, 305 insertions(+) create mode 100644 ratpack/src/main/java/com/baeldung/hystrix/HystrixAsyncHttpCommand.java create mode 100644 ratpack/src/main/java/com/baeldung/hystrix/HystrixReactiveHttpCommand.java create mode 100644 ratpack/src/main/java/com/baeldung/hystrix/HystrixSyncHttpCommand.java create mode 100644 ratpack/src/main/java/com/baeldung/hystrix/RatpackHystrixApp.java create mode 100644 ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppFallbackLiveTest.java create mode 100644 ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppLiveTest.java diff --git a/ratpack/pom.xml b/ratpack/pom.xml index 7a75ec50b729..3f953b3ed00d 100644 --- a/ratpack/pom.xml +++ b/ratpack/pom.xml @@ -40,16 +40,38 @@ ratpack-hikari ${ratpack.version} + + io.ratpack + ratpack-hystrix + ${ratpack.version} + + + io.ratpack + ratpack-rx + ${ratpack.version} + io.ratpack ratpack-test ${ratpack.version} + test com.h2database h2 1.4.193 + + + org.apache.httpcomponents + httpclient + 4.5.3 + + + org.apache.httpcomponents + httpcore + 4.4.6 + diff --git a/ratpack/src/main/java/com/baeldung/hystrix/HystrixAsyncHttpCommand.java b/ratpack/src/main/java/com/baeldung/hystrix/HystrixAsyncHttpCommand.java new file mode 100644 index 000000000000..a1a19150c312 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/hystrix/HystrixAsyncHttpCommand.java @@ -0,0 +1,54 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.HystrixCommand; +import com.netflix.hystrix.HystrixCommandGroupKey; +import com.netflix.hystrix.HystrixCommandProperties; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; + +import java.net.URI; +import java.util.Collections; + +/** + * @author aiet + */ +public class HystrixAsyncHttpCommand extends HystrixCommand { + + private URI uri; + private RequestConfig requestConfig; + + HystrixAsyncHttpCommand(URI uri, int timeoutMillis) { + super(Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-async")) + .andCommandPropertiesDefaults(HystrixCommandProperties + .Setter() + .withExecutionTimeoutInMilliseconds(timeoutMillis))); + requestConfig = RequestConfig + .custom() + .setSocketTimeout(timeoutMillis) + .setConnectTimeout(timeoutMillis) + .setConnectionRequestTimeout(timeoutMillis) + .build(); + this.uri = uri; + } + + @Override + protected String run() throws Exception { + return EntityUtils.toString(HttpClientBuilder + .create() + .setDefaultRequestConfig(requestConfig) + .setDefaultHeaders(Collections.singleton(new BasicHeader("User-Agent", "Baeldung Blocking HttpClient"))) + .build() + .execute(new HttpGet(uri)) + .getEntity()); + } + + @Override + protected String getFallback() { + return "eugenp's async fallback profile"; + } + +} diff --git a/ratpack/src/main/java/com/baeldung/hystrix/HystrixReactiveHttpCommand.java b/ratpack/src/main/java/com/baeldung/hystrix/HystrixReactiveHttpCommand.java new file mode 100644 index 000000000000..f9f85c705bd3 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/hystrix/HystrixReactiveHttpCommand.java @@ -0,0 +1,44 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.HystrixCommandGroupKey; +import com.netflix.hystrix.HystrixCommandProperties; +import com.netflix.hystrix.HystrixObservableCommand; +import ratpack.http.client.HttpClient; +import ratpack.rx.RxRatpack; +import rx.Observable; + +import java.net.URI; + +/** + * @author aiet + */ +public class HystrixReactiveHttpCommand extends HystrixObservableCommand { + + private HttpClient httpClient; + private URI uri; + + HystrixReactiveHttpCommand(HttpClient httpClient, URI uri, int timeoutMillis) { + super(Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-reactive")) + .andCommandPropertiesDefaults(HystrixCommandProperties + .Setter() + .withExecutionTimeoutInMilliseconds(timeoutMillis))); + this.httpClient = httpClient; + this.uri = uri; + } + + @Override + protected Observable construct() { + return RxRatpack.observe(httpClient + .get(uri, requestSpec -> requestSpec.headers(mutableHeaders -> mutableHeaders.add("User-Agent", "Baeldung HttpClient"))) + .map(receivedResponse -> receivedResponse + .getBody() + .getText())); + } + + @Override + protected Observable resumeWithFallback() { + return Observable.just("eugenp's reactive fallback profile"); + } + +} diff --git a/ratpack/src/main/java/com/baeldung/hystrix/HystrixSyncHttpCommand.java b/ratpack/src/main/java/com/baeldung/hystrix/HystrixSyncHttpCommand.java new file mode 100644 index 000000000000..7c848331caad --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/hystrix/HystrixSyncHttpCommand.java @@ -0,0 +1,55 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.HystrixCommand; +import com.netflix.hystrix.HystrixCommandGroupKey; +import com.netflix.hystrix.HystrixCommandProperties; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; + +import java.net.URI; +import java.util.Collections; + +/** + * @author aiet + */ +public class HystrixSyncHttpCommand extends HystrixCommand { + + private URI uri; + private RequestConfig requestConfig; + + HystrixSyncHttpCommand(URI uri, int timeoutMillis) { + super(Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-sync")) + .andCommandPropertiesDefaults(HystrixCommandProperties + .Setter() + .withExecutionTimeoutInMilliseconds(timeoutMillis))); + requestConfig = RequestConfig + .custom() + .setSocketTimeout(timeoutMillis) + .setConnectTimeout(timeoutMillis) + .setConnectionRequestTimeout(timeoutMillis) + .build(); + this.uri = uri; + } + + @Override + protected String run() throws Exception { + HttpGet request = new HttpGet(uri); + return EntityUtils.toString(HttpClientBuilder + .create() + .setDefaultRequestConfig(requestConfig) + .setDefaultHeaders(Collections.singleton(new BasicHeader("User-Agent", "Baeldung Blocking HttpClient"))) + .build() + .execute(request) + .getEntity()); + } + + @Override + protected String getFallback() { + return "eugenp's sync fallback profile"; + } + +} diff --git a/ratpack/src/main/java/com/baeldung/hystrix/RatpackHystrixApp.java b/ratpack/src/main/java/com/baeldung/hystrix/RatpackHystrixApp.java new file mode 100644 index 000000000000..1e4724bd96fb --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/hystrix/RatpackHystrixApp.java @@ -0,0 +1,30 @@ +package com.baeldung.hystrix; + +import ratpack.guice.Guice; +import ratpack.http.client.HttpClient; +import ratpack.hystrix.HystrixMetricsEventStreamHandler; +import ratpack.hystrix.HystrixModule; +import ratpack.server.RatpackServer; + +import java.net.URI; + +public class RatpackHystrixApp { + + public static void main(String[] args) throws Exception { + final int timeout = Integer.valueOf(System.getProperty("ratpack.hystrix.timeout")); + final URI eugenGithubProfileUri = new URI("https://api.github.com/users/eugenp"); + + RatpackServer.start(server -> server + .registry(Guice.registry(bindingsSpec -> bindingsSpec.module(new HystrixModule().sse()))) + .handlers(chain -> chain + .get("rx", ctx -> new HystrixReactiveHttpCommand(ctx.get(HttpClient.class), eugenGithubProfileUri, timeout) + .toObservable() + .subscribe(ctx::render)) + .get("async", ctx -> ctx.render(new HystrixAsyncHttpCommand(eugenGithubProfileUri, timeout) + .queue() + .get())) + .get("sync", ctx -> ctx.render(new HystrixSyncHttpCommand(eugenGithubProfileUri, timeout).execute())) + .get("hystrix", new HystrixMetricsEventStreamHandler()))); + + } +} diff --git a/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppFallbackLiveTest.java b/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppFallbackLiveTest.java new file mode 100644 index 000000000000..25287a5cbd0c --- /dev/null +++ b/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppFallbackLiveTest.java @@ -0,0 +1,50 @@ +package com.baeldung.hystrix; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import ratpack.test.MainClassApplicationUnderTest; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; + +/** + * @author aiet + */ +public class RatpackHystrixAppFallbackLiveTest { + + static MainClassApplicationUnderTest appUnderTest; + + @BeforeClass + public static void setup() { + System.setProperty("ratpack.hystrix.timeout", "10"); + appUnderTest = new MainClassApplicationUnderTest(RatpackHystrixApp.class); + } + + @Test + public void whenFetchReactive_thenGotFallbackProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("rx"), containsString("reactive fallback profile")); + } + + @Test + public void whenFetchAsync_thenGotFallbackProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("async"), containsString("async fallback profile")); + } + + @Test + public void whenFetchSync_thenGotFallbackProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("sync"), containsString("sync fallback profile")); + } + + @AfterClass + public static void clean() { + appUnderTest.close(); + } + +} diff --git a/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppLiveTest.java b/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppLiveTest.java new file mode 100644 index 000000000000..843ef68e1326 --- /dev/null +++ b/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppLiveTest.java @@ -0,0 +1,50 @@ +package com.baeldung.hystrix; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import ratpack.test.MainClassApplicationUnderTest; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; + +/** + * @author aiet + */ +public class RatpackHystrixAppLiveTest { + + static MainClassApplicationUnderTest appUnderTest; + + @BeforeClass + public static void setup() { + System.setProperty("ratpack.hystrix.timeout", "5000"); + appUnderTest = new MainClassApplicationUnderTest(RatpackHystrixApp.class); + } + + @Test + public void whenFetchReactive_thenGotEugenProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("rx"), containsString("www.baeldung.com")); + } + + @Test + public void whenFetchAsync_thenGotEugenProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("async"), containsString("www.baeldung.com")); + } + + @Test + public void whenFetchSync_thenGotEugenProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("sync"), containsString("www.baeldung.com")); + } + + @AfterClass + public static void clean() { + appUnderTest.close(); + } + +} From 822e8682b64a41a1d99a4790719d131f114708df Mon Sep 17 00:00:00 2001 From: lor6 Date: Tue, 22 Aug 2017 00:03:12 +0300 Subject: [PATCH 86/90] lambda example (#2480) --- .../LambdaExpressionsIntegrationTest.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java new file mode 100644 index 000000000000..a1454c16cc5c --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.logging.log4j2.tests; + +import java.util.Random; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.Test; + +public class LambdaExpressionsIntegrationTest { + + private static final Logger logger = LogManager.getRootLogger(); + + @Test + public void whenCheckLogMessage_thenOk() { + if (logger.isTraceEnabled()) { + logger.trace("Numer is {}", getRandomNumber()); + } + } + + @Test + public void whenUseLambdaExpression_thenOk() { + logger.trace("Number is {}", () -> getRandomNumber()); + logger.trace("Name is {} and age is {}", () -> getName(), () -> getRandomNumber()); + } + + private int getRandomNumber() { + return (new Random()).nextInt(10); + } + + private String getName() { + return "John"; + } +} From 8c0ce48aaee0bfa5b4cf772db424c9e6828eba87 Mon Sep 17 00:00:00 2001 From: Mansi Date: Tue, 22 Aug 2017 02:38:41 +0530 Subject: [PATCH 87/90] BAEL-1045 Lambda Behave (#2456) * Example Code For Evaluation Article This is an example code for the evaluation article on "Different Types of Bean Injection in Spring" * Added unit tests * Minor changes to application context * Removed code committed for evaluation article * BAEL-944 Demonstrating the problems with new Url pattern matching in Spring 5 * BAEL-944 Demonstrating the problems with new Url pattern matching in Spring 5 * BAEL-944 Exploring the Spring MVC URL Matching Improvements * BAEL-944 Exploring the Spring MVC URL Matching Improvements * BAEL-944 Exploring the Spring MVC URL Matching Improvements * BAEL-944 Code Formatting and solving build issue * BAEL-944 Resolving build issue due to change in Spring version * BAEL-944 Resolving build issue * BAEL-944 Formatting code * BAEL-944 Moving tests to correct package * BAEL-944 Moving tests to correct package * BAEL-944 Replacing @RequestMapping by @GetMapping * BAEL-944 Remove unnecessary attribute name, "value" in annotations * BAEL-79 Intro to Activiti with Spring * BAEL-79 Intro to Activiti with Spring * BAEL-79 Adding activiti module to the parent modules * BAEL-79 Using latest version * BAEL-79 Update Spring boot version that works with Activiti * BAEL-79 Replace RequestMapping with GetMapping * BAEL-79 Use Java 8 Syntax * BAEL-79 Formatting * BAEL-79 changed module name * BAEL-378 A Guide to Activiti with Java * BAEL-79 Fixed unit tests * BAEL-79 Simplified the process * BAEL-79 Fix test cases * BAEL-1045 Lambda Behave * BAEL-1045 Lambda Behave * BAEL-1045 Lambda Behave --- testing/pom.xml | 5 ++ .../com/baeldung/lambdabehave/Calculator.java | 24 +++++++++ .../baeldung/lambdabehave/CalculatorTest.java | 54 +++++++++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 testing/src/main/java/com/baeldung/lambdabehave/Calculator.java create mode 100644 testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java diff --git a/testing/pom.xml b/testing/pom.xml index bfd47dbc4a18..72ec2b2f0c38 100644 --- a/testing/pom.xml +++ b/testing/pom.xml @@ -13,6 +13,11 @@ + + com.insightfullogic + lambda-behave + 0.4 + com.google.guava guava diff --git a/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java b/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java new file mode 100644 index 000000000000..b194dce500c3 --- /dev/null +++ b/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java @@ -0,0 +1,24 @@ +package com.baeldung.lambdabehave; + +public class Calculator { + + private int x; + private int y; + + Calculator(int x, int y) { + this.x = x; + this.y = y; + } + + public int add() { + return this.x + this.y; + } + + public int divide(int a, int b) { + return a / b; + } + + public int add(int a, int b) { + return a + b; + } +} diff --git a/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java b/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java new file mode 100644 index 000000000000..d179c6eb0e3a --- /dev/null +++ b/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java @@ -0,0 +1,54 @@ +package com.baeldung.lambdabehave; + +import com.insightfullogic.lambdabehave.JunitSuiteRunner; +import com.insightfullogic.lambdabehave.Suite; +import com.insightfullogic.lambdabehave.generators.Generator; +import com.insightfullogic.lambdabehave.generators.SourceGenerator; +import org.junit.runner.RunWith; + +@RunWith(JunitSuiteRunner.class) +public class CalculatorTest { + + private Calculator calculator; + + { + Suite.describe("Lambda behave example tests", it -> { + + it.isSetupWith(() -> { + calculator = new Calculator(1, 2); + }); + it.should("Add the given numbers", expect -> { + expect.that(calculator.add()).is(3); + }); + it.should("Throw an exception if divide by 0", expect -> { + expect.exception(ArithmeticException.class, () -> { + calculator.divide(1, 0); + }); + }); + it.uses(2, 3, 5) + .and(23, 10, 33) + .toShow("%d + %d = %d", (expect, a, b, c) -> { + expect.that(calculator.add(a, b)).is(c); + }); + it.requires(2) + .example(Generator.asciiStrings()) + .toShow("Reversing a String twice returns the original String", (expect, str) -> { + String same = new StringBuilder(str).reverse() + .reverse() + .toString(); + expect.that(same) + .isEqualTo(str); + }); + it.requires(2) + .withSource(SourceGenerator.deterministicNumbers(5626689007407L)) + .example(Generator.asciiStrings()) + .toShow("Reversing a String twice returns the original String", (expect, str) -> { + String same = new StringBuilder(str).reverse() + .reverse() + .toString(); + expect.that(same) + .isEqualTo(str); + }); + }); + } +} From 8a344330950ecd9c728c80148373be24851fd2f2 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Tue, 22 Aug 2017 13:13:24 +0200 Subject: [PATCH 88/90] Optimize libraries (#2458) --- .../com/baeldung/chronicle/queue/ChronicleQueue.java | 2 +- ...Test.java => AsyncServiceLongRunningUnitTest.java} | 11 +++++++---- ...ueTest.java => ChronicleQueueIntegrationTest.java} | 2 +- .../{HLLUnitTest.java => HLLLongRunningUnitTest.java} | 2 +- 4 files changed, 10 insertions(+), 7 deletions(-) rename libraries/src/test/java/com/baeldung/awaitility/{AsyncServiceUnitTest.java => AsyncServiceLongRunningUnitTest.java} (86%) rename libraries/src/test/java/com/baeldung/chronicle/queue/{ChronicleQueueTest.java => ChronicleQueueIntegrationTest.java} (96%) rename libraries/src/test/java/com/baeldung/hll/{HLLUnitTest.java => HLLLongRunningUnitTest.java} (98%) diff --git a/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java b/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java index b7770e0b781c..f6bd25c0fec3 100644 --- a/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java +++ b/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java @@ -7,7 +7,7 @@ public class ChronicleQueue { - public static void writeToQueue( + static void writeToQueue( Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue) throws IOException { ExcerptAppender appender = chronicle.createAppender(); diff --git a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceUnitTest.java b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java similarity index 86% rename from libraries/src/test/java/com/baeldung/awaitility/AsyncServiceUnitTest.java rename to libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java index 43537965f878..d17a7dcf1b99 100644 --- a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceUnitTest.java +++ b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java @@ -11,10 +11,13 @@ import static org.awaitility.Awaitility.await; import static org.awaitility.Awaitility.fieldIn; import static org.awaitility.Awaitility.given; +import static org.awaitility.Awaitility.setDefaultPollDelay; +import static org.awaitility.Awaitility.setDefaultPollInterval; +import static org.awaitility.Awaitility.setDefaultTimeout; import static org.awaitility.proxy.AwaitilityClassProxy.to; import static org.hamcrest.Matchers.equalTo; -public class AsyncServiceUnitTest { +public class AsyncServiceLongRunningUnitTest { private AsyncService asyncService; @Before @@ -41,9 +44,9 @@ public void givenAsyncService_whenInitialize_thenInitOccurs2() { @Test public void givenAsyncService_whenInitialize_thenInitOccurs_withDefualts() { - Awaitility.setDefaultPollInterval(10, TimeUnit.MILLISECONDS); - Awaitility.setDefaultPollDelay(Duration.ZERO); - Awaitility.setDefaultTimeout(Duration.ONE_MINUTE); + setDefaultPollInterval(10, TimeUnit.MILLISECONDS); + setDefaultPollDelay(Duration.ZERO); + setDefaultTimeout(Duration.ONE_MINUTE); asyncService.initialize(); await().until(asyncService::isInitialized); diff --git a/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueTest.java b/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java similarity index 96% rename from libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueTest.java rename to libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java index e64aaed544a2..9c0a0ac91078 100644 --- a/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueTest.java +++ b/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java @@ -13,7 +13,7 @@ import net.openhft.chronicle.ExcerptTailer; import net.openhft.chronicle.tools.ChronicleTools; -public class ChronicleQueueTest { +public class ChronicleQueueIntegrationTest { @Test public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException { diff --git a/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java b/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java similarity index 98% rename from libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java rename to libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java index e208add3c860..5ecd4442d856 100644 --- a/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java +++ b/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java @@ -11,7 +11,7 @@ import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; -public class HLLUnitTest { +public class HLLLongRunningUnitTest { @Test public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() { From dc867672e9441d9d3c4c67b77dd78566c8321b57 Mon Sep 17 00:00:00 2001 From: lor6 Date: Tue, 22 Aug 2017 14:22:49 +0300 Subject: [PATCH 89/90] logback example app (#2354) --- guest/logback-example/pom.xml | 41 +++++ .../stackify/logging/IgnoreLoggerFilter.java | 28 ++++ .../java/com/stackify/models/Employee.java | 43 +++++ .../stackify/services/EmployeeService.java | 11 ++ .../src/main/resources/application.properties | 1 + .../src/main/resources/logback.xml | 151 ++++++++++++++++++ .../services/EmployeeServiceTest.java | 74 +++++++++ 7 files changed, 349 insertions(+) create mode 100644 guest/logback-example/pom.xml create mode 100644 guest/logback-example/src/main/java/com/stackify/logging/IgnoreLoggerFilter.java create mode 100644 guest/logback-example/src/main/java/com/stackify/models/Employee.java create mode 100644 guest/logback-example/src/main/java/com/stackify/services/EmployeeService.java create mode 100644 guest/logback-example/src/main/resources/application.properties create mode 100644 guest/logback-example/src/main/resources/logback.xml create mode 100644 guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java diff --git a/guest/logback-example/pom.xml b/guest/logback-example/pom.xml new file mode 100644 index 000000000000..9d88c9419786 --- /dev/null +++ b/guest/logback-example/pom.xml @@ -0,0 +1,41 @@ + + 4.0.0 + com.stackify + logback-example + 0.0.1-SNAPSHOT + + + + ch.qos.logback + logback-classic + 1.2.3 + + + + junit + junit + 4.12 + + + + org.codehaus.janino + janino + 3.0.7 + + + + + + + + maven-compiler-plugin + 3.5 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/guest/logback-example/src/main/java/com/stackify/logging/IgnoreLoggerFilter.java b/guest/logback-example/src/main/java/com/stackify/logging/IgnoreLoggerFilter.java new file mode 100644 index 000000000000..c0eb4145884e --- /dev/null +++ b/guest/logback-example/src/main/java/com/stackify/logging/IgnoreLoggerFilter.java @@ -0,0 +1,28 @@ +package com.stackify.logging; + +import org.slf4j.Marker; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.turbo.TurboFilter; +import ch.qos.logback.core.spi.FilterReply; + +public class IgnoreLoggerFilter extends TurboFilter { + + private String loggerName; + + @Override + public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { + if (loggerName == null) { + return FilterReply.NEUTRAL; + } else if (loggerName.equals(logger.getName())) { + return FilterReply.DENY; + } else + return FilterReply.NEUTRAL; + } + + public void setLoggerName(String loggerName) { + this.loggerName = loggerName; + } + +} diff --git a/guest/logback-example/src/main/java/com/stackify/models/Employee.java b/guest/logback-example/src/main/java/com/stackify/models/Employee.java new file mode 100644 index 000000000000..1d040b372b86 --- /dev/null +++ b/guest/logback-example/src/main/java/com/stackify/models/Employee.java @@ -0,0 +1,43 @@ +package com.stackify.models; + +public class Employee { + + private String email; + private String name; + + private double salary; + + public Employee() { + } + + public Employee(String email, String name, double salary) { + this.email = email; + this.name = name; + this.salary = salary; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/guest/logback-example/src/main/java/com/stackify/services/EmployeeService.java b/guest/logback-example/src/main/java/com/stackify/services/EmployeeService.java new file mode 100644 index 000000000000..1795101f406e --- /dev/null +++ b/guest/logback-example/src/main/java/com/stackify/services/EmployeeService.java @@ -0,0 +1,11 @@ +package com.stackify.services; + +import com.stackify.models.Employee; + +public class EmployeeService { + + public double calculateBonus(Employee user) { + return 0.1 * user.getSalary(); + } + +} diff --git a/guest/logback-example/src/main/resources/application.properties b/guest/logback-example/src/main/resources/application.properties new file mode 100644 index 000000000000..601f964ff3b7 --- /dev/null +++ b/guest/logback-example/src/main/resources/application.properties @@ -0,0 +1 @@ +env=dev \ No newline at end of file diff --git a/guest/logback-example/src/main/resources/logback.xml b/guest/logback-example/src/main/resources/logback.xml new file mode 100644 index 000000000000..d8ec24c7c3c2 --- /dev/null +++ b/guest/logback-example/src/main/resources/logback.xml @@ -0,0 +1,151 @@ + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + System.out + + + + + + + + + log-%d{yyyy-MM-dd}.log + 30 + 3GB + + + 3MB + + + %d [%thread] %-5level %logger{50} - %msg%n + + + + + + userRole + ANONYMOUS + + + + ${userRole}.log + + %d [%thread] %level %mdc %logger{50} - %msg%n + + + + + + + + + %d %green([%thread]) %highlight(%level) %logger{50} - %msg%n + + + + + + + %thread%level%logger%msg + + + log.html + + + + + + ERROR + ACCEPT + DENY + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + System.err + + + + + WARN + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + return (level > DEBUG && message.toLowerCase().contains("employee")); + + DENY + NEUTRAL + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + 2 + + + + ignoredColorLogger + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java b/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java new file mode 100644 index 000000000000..187b27e1dfd6 --- /dev/null +++ b/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java @@ -0,0 +1,74 @@ +package com.stackify.services; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +import com.stackify.models.Employee; + +import ch.qos.logback.classic.Level; + +public class EmployeeServiceTest { + private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + + private EmployeeService employeeService = new EmployeeService(); + + @Test + public void testAppenders() { + Logger rollingFileLogger = LoggerFactory.getLogger("rollingFileLogger"); + rollingFileLogger.info("Testing rolling file logger"); + + MDC.put("userRole", "ADMIN"); + Logger siftingLogger = LoggerFactory.getLogger("roleSiftingLogger"); + siftingLogger.info("Admin Action"); + } + + @Test + public void testLayouts() { + Logger htmlLogger = LoggerFactory.getLogger("htmlLogger"); + htmlLogger.error("Employee Information Update Failed"); + htmlLogger.info("New Account Created"); + + Logger colorLogger = LoggerFactory.getLogger("colorLogger"); + colorLogger.error("Employee Information Update Failed"); + colorLogger.info("New Account Created"); + } + + @Test + public void testLogLevel() { + ch.qos.logback.classic.Logger rollingFileLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("rollingFileLogger"); + rollingFileLogger.setLevel(Level.DEBUG); + rollingFileLogger.debug("Testing Log Level"); + } + + @Test + public void testParameter() { + Employee employee = new Employee("john@gmail.com", "John", 2000); + if (logger.isDebugEnabled()) { + logger.debug("The bonus for employee: " + employee.getName() + " is " + employeeService.calculateBonus(employee)); + } + logger.debug("The bonus for employee {} is {}", employee.getName(), employeeService.calculateBonus(employee)); + } + + @Test + public void testFilters() { + Logger levelFilterLogger = LoggerFactory.getLogger("levelFilterLogger"); + levelFilterLogger.error("Employee Information Update Failed"); + Logger thresholdFilterLogger = LoggerFactory.getLogger("thresholdFilterLogger"); + thresholdFilterLogger.trace("Employee record inserted"); + Logger evaluatorFilterLogger = LoggerFactory.getLogger("evaluatorFilterLogger"); + evaluatorFilterLogger.debug("Employee account deactivated"); + } + + @Test + public void testIgnoredLogger() { + Logger colorLogger = LoggerFactory.getLogger("ignoredColorLogger"); + colorLogger.info("Ignored Log Message"); + } + + @Test + public void testConditionalConfiguration() { + logger.trace("Employee record updated"); + } +} From ccba3de76531e1b01ab10156dd4ba6247e360c74 Mon Sep 17 00:00:00 2001 From: Buddhini Samarakkody Date: Wed, 23 Aug 2017 06:22:06 +0530 Subject: [PATCH 90/90] Delete and add new test for BAEL-698 (#2479) * Delete HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java * Add new test class * Rename test methods --- ...yToManyAnnotationMainIntegrationTest.java} | 57 ++++++++----------- 1 file changed, 25 insertions(+), 32 deletions(-) rename spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/{HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java => HibernateManyToManyAnnotationMainIntegrationTest.java} (50%) diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java similarity index 50% rename from spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java rename to spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java index 5308134faca6..2ec1246961c0 100644 --- a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationXMLConfigMainIntegrationTest.java +++ b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java @@ -12,17 +12,16 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; + import com.baeldung.hibernate.manytomany.util.HibernateUtil; import com.baeldung.hibernate.manytomany.model.Employee; import com.baeldung.hibernate.manytomany.model.Project; - -public class HibernateManyToManyAnnotationXMLConfigMainIntegrationTest { +public class HibernateManyToManyAnnotationMainIntegrationTest { private static SessionFactory sessionFactory; private Session session; - @BeforeClass public static void beforeTests() { sessionFactory = HibernateUtil.getSessionFactory(); @@ -34,45 +33,39 @@ public void setUp() { session.beginTransaction(); } - @Test - public void givenSession_checkIfDatabaseIsPopulated() { - Employee employee1 = new Employee("Peter", "Oven"); + public void givenData_whenInsert_thenCreatesMtoMrelationship() { + String[] employeeData = { "Peter Oven", "Allan Norman" }; + String[] projectData = { "IT Project", "Networking Project" }; Set projects = new HashSet(); - projects = employee1.getProjects(); - int noProjects = projects.size(); - assertEquals(0,noProjects); - Project project1 = new Project("IT Project"); - assertNotNull(project1); - projects.add(project1); - Project project2 = new Project("Networking Project"); - assertNotNull(project2); - projects.add(project2); - employee1.setProjects(projects); - assertNotNull(employee1); - Employee employee2 = new Employee("Allan", "Norman"); - employee2.setProjects(projects); - assertNotNull(employee2); - - session.persist(employee1); - session.persist(employee2); - session.getTransaction().commit(); - session.close(); - session = sessionFactory.openSession(); - session.beginTransaction(); - @SuppressWarnings("unchecked") - List projectList = session.createQuery("FROM Project").list(); - assertNotNull(projectList); + for (String proj : projectData) { + projects.add(new Project(proj)); + } + + for (String emp : employeeData) { + Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]); + assertEquals(0, employee.getProjects().size()); + employee.setProjects(projects); + assertNotNull(employee); + session.persist(employee); + } + } + + @Test + public void givenSession_whenRead_thenReturnsMtoMdata() { @SuppressWarnings("unchecked") List employeeList = session.createQuery("FROM Employee").list(); assertNotNull(employeeList); + for(Employee employee : employeeList) { + assertNotNull(employee.getProjects()); + } } - @After public void tearDown() { - session.getTransaction().commit(); + session.getTransaction() + .commit(); session.close(); }