From 38989db6c1c37ec68698d1da4679789adba5fafb Mon Sep 17 00:00:00 2001 From: Ganesh Pagade Date: Sat, 29 Jul 2017 00:29:28 +0530 Subject: [PATCH 01/32] 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 0000000000..056db0c3fe --- /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 0000000000..1a1809387f --- /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 0000000000..9f119fe45d --- /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 0000000000..b08ad02c97 --- /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 0000000000..4f53191ab9 --- /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 c5f029b46c3f916130dbc0d7afb94e054a108a19 Mon Sep 17 00:00:00 2001 From: Ante Pocedulic Date: Sat, 29 Jul 2017 16:16:23 +0200 Subject: [PATCH 02/32] - added custom theme for asciidoc book (#2327) - changed AsciiDoc document - added new things in pom --- asciidoctor/pom.xml | 5 +++++ asciidoctor/src/docs/asciidoc/test.adoc | 14 ++++++++++-- asciidoctor/src/themes/custom-theme.yml | 29 +++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 asciidoctor/src/themes/custom-theme.yml diff --git a/asciidoctor/pom.xml b/asciidoctor/pom.xml index 989f6e5354..a602cd11b9 100644 --- a/asciidoctor/pom.xml +++ b/asciidoctor/pom.xml @@ -35,7 +35,12 @@ src/docs/asciidoc target/docs/asciidoc + + ${project.basedir}/src/themes + custom + pdf + book diff --git a/asciidoctor/src/docs/asciidoc/test.adoc b/asciidoctor/src/docs/asciidoc/test.adoc index 5a86a00440..fec1f73584 100644 --- a/asciidoctor/src/docs/asciidoc/test.adoc +++ b/asciidoctor/src/docs/asciidoc/test.adoc @@ -1,3 +1,13 @@ -== Introduction Section +:icons: font -Hi. I'm a simple test to see if this Maven build is working. If you see me in a nice PDF, then it means everything is [red]#working#. \ No newline at end of file + += Generating book with AsciiDoctorj +Baeldung + +[abstract] +This is the actual content. + +== First Section + +This is first section of the book where you can include some nice icons like icon:comment[]. +You can also create http://www.baeldung.com[links] diff --git a/asciidoctor/src/themes/custom-theme.yml b/asciidoctor/src/themes/custom-theme.yml new file mode 100644 index 0000000000..a3c8c00510 --- /dev/null +++ b/asciidoctor/src/themes/custom-theme.yml @@ -0,0 +1,29 @@ +title_page: + align: left + +page: + layout: portrait + margin: [0.75in, 1in, 0.75in, 1in] + size: A4 +base: + font_color: #333333 + line_height_length: 17 + line_height: $base_line_height_length / $base_font_size +link: + font_color: #009900 + +header: + height: 0.5in + line_height: 1 + recto_content: + center: '{document-title}' + verso_content: + center: '{document-title}' + +footer: + height: 0.5in + line_height: 1 + recto_content: + right: '{chapter-title} | *{page-number}*' + verso_content: + left: '*{page-number}* | {chapter-title}' \ No newline at end of file From ae33aa6386ce0947389c94fe189c5cb0e786efef Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Sat, 29 Jul 2017 15:44:40 +0100 Subject: [PATCH 03/32] Refactored tests for PCollections (#2331) * 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 --- .../pcollections/PCollectionsUnitTest.java | 43 +++++++++---------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java index b2f815074a..23f9abf2f3 100644 --- a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java @@ -39,41 +39,41 @@ public class PCollectionsUnitTest { public void whenHashPMapMethods_thenPerformOperations() { HashPMap pmap = HashTreePMap.empty(); - pmap = pmap.plus("key1", "value1"); - assertEquals(pmap.size(), 1); + HashPMap pmap0 = pmap.plus("key1", "value1"); Map map = new HashMap(); map.put("key2", "val2"); map.put("key3", "val3"); - pmap = pmap.plusAll(map); - assertEquals(pmap.size(), 3); - - pmap = pmap.minus("key1"); - assertFalse(pmap.containsKey("key1")); - - pmap = pmap.minusAll(map.keySet()); - assertEquals(pmap.size(), 0); + HashPMap pmap1 = pmap0.plusAll(map); + HashPMap pmap2 = pmap1.minus("key1"); + HashPMap pmap3 = pmap2.minusAll(map.keySet()); + assertEquals(pmap0.size(), 1); + assertEquals(pmap1.size(), 3); + assertFalse(pmap2.containsKey("key1")); + assertEquals(pmap3.size(), 0); } @Test public void whenTreePVectorMethods_thenPerformOperations() { TreePVector pVector = TreePVector.empty(); - pVector = pVector.plus("e1"); - pVector = pVector.plusAll(Arrays.asList("e2", "e3", "e4")); - assertEquals(4, pVector.size()); + TreePVector pV1 = pVector.plus("e1"); + TreePVector pV2 = pV1.plusAll(Arrays.asList("e2", "e3", "e4")); + assertEquals(1, pV1.size()); + assertEquals(4, pV2.size()); - TreePVector pSub = pVector.subList(0, 2); + 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); assertTrue(pSub.contains("e1") && pSub.contains("e2")); - TreePVector pVW = (TreePVector) pVector.with(0, "e10"); + TreePVector pVW = (TreePVector) pV2.with(0, "e10"); assertEquals(pVW.get(0), "e10"); - - pVector = pVector.minus("e1"); - TreePVector pV1 = pVector.minusAll(Arrays.asList("e2", "e3")); - assertEquals(pV1.size(), 1); } @Test @@ -83,9 +83,8 @@ public class PCollectionsUnitTest { .plusAll(Arrays.asList("e1","e2","e3","e4")); assertEquals(pSet.size(), 4); - pSet = pSet.minus("e4"); - assertFalse(pSet.contains("e4")); - + MapPSet pSet1 = pSet.minus("e4"); + assertFalse(pSet1.contains("e4")); } } From 5c1bf55e34f8ffb8db2d803b7796f653bbfbab04 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 29 Jul 2017 17:45:12 +0300 Subject: [PATCH 04/32] minor cleanup work --- feign/pom.xml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/feign/pom.xml b/feign/pom.xml index 9c3868c82f..78e1bbcf4c 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -1,12 +1,9 @@ - + 4.0.0 com.baeldung.feign feign-client - 1.0.0-SNAPSHOT com.baeldung From 244a678b463a43ea150c200d2966dda6d0222f52 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Sat, 29 Jul 2017 20:26:24 +0530 Subject: [PATCH 05/32] jooby project (#2330) * 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 --- .../cyclicbarrier/CyclicBarrierExample.java | 1 + jooby/conf/application.conf | 2 + jooby/conf/logback.xml | 42 ++++++++ jooby/pom.xml | 56 +++++++++++ jooby/public/form.html | 17 ++++ jooby/public/welcome.html | 10 ++ jooby/src/etc/stork.yml | 41 ++++++++ .../src/main/java/com/baeldung/jooby/App.java | 95 +++++++++++++++++++ .../com/baeldung/jooby/bean/Employee.java | 20 ++++ .../com/baeldung/jooby/mvc/GetController.java | 22 +++++ .../baeldung/jooby/mvc/PostController.java | 14 +++ .../test/java/com/baeldung/jooby/AppTest.java | 29 ++++++ 12 files changed, 349 insertions(+) create mode 100644 jooby/conf/application.conf create mode 100644 jooby/conf/logback.xml create mode 100644 jooby/pom.xml create mode 100644 jooby/public/form.html create mode 100644 jooby/public/welcome.html create mode 100644 jooby/src/etc/stork.yml create mode 100644 jooby/src/main/java/com/baeldung/jooby/App.java create mode 100644 jooby/src/main/java/com/baeldung/jooby/bean/Employee.java create mode 100644 jooby/src/main/java/com/baeldung/jooby/mvc/GetController.java create mode 100644 jooby/src/main/java/com/baeldung/jooby/mvc/PostController.java create mode 100644 jooby/src/test/java/com/baeldung/jooby/AppTest.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java index dd80a7971c..a9b92d9f4a 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java +++ b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java @@ -21,3 +21,4 @@ public class CyclicBarrierExample { } } } + diff --git a/jooby/conf/application.conf b/jooby/conf/application.conf new file mode 100644 index 0000000000..2f89e0eb6b --- /dev/null +++ b/jooby/conf/application.conf @@ -0,0 +1,2 @@ +#application.secret = 2o128940921eo298e21 +#db = /url/to/the/datastore \ No newline at end of file diff --git a/jooby/conf/logback.xml b/jooby/conf/logback.xml new file mode 100644 index 0000000000..50733ee6d6 --- /dev/null +++ b/jooby/conf/logback.xml @@ -0,0 +1,42 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + log/jooby.log + + log/jooby.%d{yyyy-MM-dd}.log + 1mb + 7 + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n + + + + + log/access.log + + log/access.%d{yyyy-MM-dd}.log + 1mb + 7 + + + + %msg%n + + + + + + + + + + + diff --git a/jooby/pom.xml b/jooby/pom.xml new file mode 100644 index 0000000000..1935c646ee --- /dev/null +++ b/jooby/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + jooby + com.baeldung.jooby + 1.0 + jooby + + + org.jooby + modules + 1.1.3 + + + + 1.1.3 + com.baeldung.jooby.App + + + + + org.jooby + jooby-netty + + + org.jooby + jooby-jedis + 1.1.3 + + + ch.qos.logback + logback-classic + + + junit + junit + test + + + io.rest-assured + rest-assured + test + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + + diff --git a/jooby/public/form.html b/jooby/public/form.html new file mode 100644 index 0000000000..a23620812a --- /dev/null +++ b/jooby/public/form.html @@ -0,0 +1,17 @@ + + + + +Insert title here + + +
+ + + + + + +
+ + \ No newline at end of file diff --git a/jooby/public/welcome.html b/jooby/public/welcome.html new file mode 100644 index 0000000000..cd21fb1988 --- /dev/null +++ b/jooby/public/welcome.html @@ -0,0 +1,10 @@ + + + + +Insert title here + + +i m welcomed + + \ No newline at end of file diff --git a/jooby/src/etc/stork.yml b/jooby/src/etc/stork.yml new file mode 100644 index 0000000000..f2f2790cd1 --- /dev/null +++ b/jooby/src/etc/stork.yml @@ -0,0 +1,41 @@ +# Name of application (make sure it has no spaces) +name: "${project.artifactId}" + +# Display name of application (can have spaces) +display_name: "${project.name}" + +# Type of launcher (CONSOLE or DAEMON) +type: DAEMON + +# Java class to run +main_class: "${application.class}" + +domain: "${project.groupId}" + +short_description: "${project.artifactId}" + +# Platform launchers to generate (WINDOWS, LINUX, MAC_OSX) +# Linux launcher is suitable for Bourne shells (e.g. Linux/BSD) +platforms: [ LINUX ] + +# Working directory for app +# RETAIN will not change the working directory +# APP_HOME will change the working directory to the home of the app +# (where it was intalled) before running the main class +working_dir_mode: RETAIN + +# Minimum version of java required (system will be searched for acceptable jvm) +min_java_version: "1.8" + +# Min/max fixed memory (measured in MB) +min_java_memory: 512 +max_java_memory: 512 + +# Min/max memory by percentage of system +#min_java_memory_pct: 10 +#max_java_memory_pct: 20 + +# Try to create a symbolic link to java executable in /run with +# the name of "-java" so that commands like "ps" will make it +# easier to find your app +symlink_java: true diff --git a/jooby/src/main/java/com/baeldung/jooby/App.java b/jooby/src/main/java/com/baeldung/jooby/App.java new file mode 100644 index 0000000000..94a24048c2 --- /dev/null +++ b/jooby/src/main/java/com/baeldung/jooby/App.java @@ -0,0 +1,95 @@ +package com.baeldung.jooby; + +import org.jooby.Jooby; +import org.jooby.Mutant; +import org.jooby.Session; +import org.jooby.jedis.Redis; +import org.jooby.jedis.RedisSessionStore; + +import com.baeldung.jooby.bean.Employee; + +public class App extends Jooby { + + { + port(8080); + securePort(8443); + } + + { + get("/", () -> "Hello World!"); + } + + { + get("/user/{id}", req -> "Hello user : " + req.param("id").value()); + get("/user/:id", req -> "Hello user: " + req.param("id").value()); + get("/uid:{id}", req -> "Hello User with id : uid" + req.param("id").value()); + } + + { + onStart(() -> { + System.out.println("starting app"); + }); + + onStop(() -> { + System.out.println("stopping app"); + }); + + onStarted(() -> { + System.out.println("app started"); + }); + } + + { + get("/login", () -> "Hello from Baeldung"); + } + + { + post("/save", req -> { + Mutant token = req.param("token"); + return token.intValue(); + }); + } + + { + { + assets("/employee", "form.html"); + } + + post("/submitForm", req -> { + Employee employee = req.params(Employee.class); + // TODO + return "empoyee data saved successfullly"; + }); + } + + { + get("/filter", (req, resp, chain) -> { + // TODO + // resp.send(...); + chain.next(req, resp); + }); + get("/filter", (req, resp) -> { + resp.send("filter response"); + }); + } + + { +// cookieSession(); + +// use(new Redis()); +// +// session(RedisSessionStore.class); + + get("/session", req -> { + Session session = req.session(); + session.set("token", "value"); + return session.get("token").value(); + }); + } + + public static void main(final String[] args) { + + run(App::new, args); + } + +} diff --git a/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java b/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java new file mode 100644 index 0000000000..6e18495ef1 --- /dev/null +++ b/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java @@ -0,0 +1,20 @@ +package com.baeldung.jooby.bean; + +public class Employee { + + String id; + String name; + String email; + String phone; + String address; + + public Employee(String id, String name, String email, String phone, String address) { + super(); + this.id = id; + this.name = name; + this.email = email; + this.phone = phone; + this.address = address; + } + +} diff --git a/jooby/src/main/java/com/baeldung/jooby/mvc/GetController.java b/jooby/src/main/java/com/baeldung/jooby/mvc/GetController.java new file mode 100644 index 0000000000..a2c51bae70 --- /dev/null +++ b/jooby/src/main/java/com/baeldung/jooby/mvc/GetController.java @@ -0,0 +1,22 @@ +package com.baeldung.jooby.mvc; + +import org.jooby.Result; +import org.jooby.Results; +import org.jooby.mvc.GET; +import org.jooby.mvc.Path; + +@Path("/hello") +public class GetController { + + @GET + public String hello() { + return "Hello Baeldung"; + } + + @GET + @Path("/home") + public Result home() { + return Results.html("welcome").put("model", new Object()); + } + +} diff --git a/jooby/src/main/java/com/baeldung/jooby/mvc/PostController.java b/jooby/src/main/java/com/baeldung/jooby/mvc/PostController.java new file mode 100644 index 0000000000..df00e47da5 --- /dev/null +++ b/jooby/src/main/java/com/baeldung/jooby/mvc/PostController.java @@ -0,0 +1,14 @@ +package com.baeldung.jooby.mvc; + +import org.jooby.mvc.POST; +import org.jooby.mvc.Path; + +@Path("/submit") +public class PostController { + + @POST + public String hello() { + return "Submit Baeldung"; + } + +} diff --git a/jooby/src/test/java/com/baeldung/jooby/AppTest.java b/jooby/src/test/java/com/baeldung/jooby/AppTest.java new file mode 100644 index 0000000000..af2626c046 --- /dev/null +++ b/jooby/src/test/java/com/baeldung/jooby/AppTest.java @@ -0,0 +1,29 @@ +package com.baeldung.jooby; + +import static io.restassured.RestAssured.get; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; + +import org.jooby.test.JoobyRule; +import org.jooby.test.MockRouter; +import org.junit.ClassRule; +import org.junit.Test; + +public class AppTest { + + @ClassRule + public static JoobyRule app = new JoobyRule(new App()); + + @Test + public void given_defaultUrl_expect_fixedString() { + get("/").then().assertThat().body(equalTo("Hello World!")).statusCode(200) + .contentType("text/html;charset=UTF-8"); + } + + @Test + public void given_defaultUrl_with_mockrouter_expect_fixedString() throws Throwable { + String result = new MockRouter(new App()).get("/"); + assertEquals("Hello World!", result); + } + +} From fd6e7c51fc4cf2f7284cadca7da0dae9332078c9 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Sun, 30 Jul 2017 01:18:06 +0530 Subject: [PATCH 06/32] reducing employee bean content (#2332) * 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 --- jooby/src/main/java/com/baeldung/jooby/bean/Employee.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java b/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java index 6e18495ef1..2c4a1038b5 100644 --- a/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java +++ b/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java @@ -5,16 +5,12 @@ public class Employee { String id; String name; String email; - String phone; - String address; - public Employee(String id, String name, String email, String phone, String address) { + public Employee(String id, String name, String email) { super(); this.id = id; this.name = name; this.email = email; - this.phone = phone; - this.address = address; } } From 9f45d709db9ad7144614e78d0c19124f468e40ad Mon Sep 17 00:00:00 2001 From: baljeet20 Date: Sun, 30 Jul 2017 01:50:14 +0530 Subject: [PATCH 07/32] BAEL-1024 introduction to mock server (#2333) * review changes * BAEL-1024 Removed the proxy reference * BAEL-1024 Renamed methods --- .../java/com/baeldung/mock/server/MockServerLiveTest.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java b/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java index 56d354be7f..e7b972f6a4 100644 --- a/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java +++ b/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java @@ -28,13 +28,11 @@ import static org.mockserver.model.StringBody.exact; public class MockServerLiveTest { - private static ClientAndProxy proxy; private static ClientAndServer mockServer; @BeforeClass - public static void startProxy() { + public static void startServer() { mockServer = startClientAndServer(1080); - proxy = startClientAndProxy(1090); } @@ -169,8 +167,7 @@ public class MockServerLiveTest { } @AfterClass - public static void stopProxy() { - proxy.stop(); + public static void stopServer() { mockServer.stop(); } } From f445a4d11bdb58a5d14a98166092344a04b64942 Mon Sep 17 00:00:00 2001 From: Jose Carvajal Date: Sun, 30 Jul 2017 00:29:25 +0200 Subject: [PATCH 08/32] BAEL-373: Improve/Upgrade existing Mockito articles to Mockito 2 (#2311) * BAEL-373: Improve/Upgrade existing Mockito articles to Mockito 2 * Fix formatting issue with LoginControllerIntegrationTest --- core-java/pom.xml | 4 +- .../MappedByteBufferUnitTest.java | 2 +- .../com/baeldung/money/JavaMoneyUnitTest.java | 2 +- .../baeldung/java/io/JavaScannerUnitTest.java | 2 + mockito/pom.xml | 4 +- mockito2/pom.xml | 2 +- mocks/mock-comparisons/pom.xml | 2 +- .../LoginControllerIntegrationTest.java | 67 +++++++++++++------ pom.xml | 2 +- video-tutorials/jackson-annotations/pom.xml | 2 +- 10 files changed, 57 insertions(+), 32 deletions(-) diff --git a/core-java/pom.xml b/core-java/pom.xml index ee0d6b4b4a..78338fc439 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -382,7 +382,7 @@ - + 2.8.5 @@ -408,7 +408,7 @@ 1.3 4.12 - 1.10.19 + 2.8.9 3.6.1 1.7.0 diff --git a/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java index 3c2d9904d4..0a0993a0d7 100644 --- a/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java +++ b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java @@ -63,6 +63,6 @@ public class MappedByteBufferUnitTest { private Path getFileURIFromResources(String fileName) throws Exception { ClassLoader classLoader = getClass().getClassLoader(); - return Paths.get(classLoader.getResource(fileName).getPath()); + return Paths.get(classLoader.getResource(fileName).toURI()); } } diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java index 8948d1ebf7..3d52a9eea9 100644 --- a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java +++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java @@ -179,7 +179,7 @@ public class JavaMoneyUnitTest { MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder .of(Locale.US) .set(CurrencyStyle.NAME) - .set("pattern", "00000.00 ¤") + .set("pattern", "00000.00 ¤") .build()); String customFormatted = customFormat.format(oneDollar); diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java index 5af286dbca..1c16a5d435 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; +import java.util.Locale; import java.util.Scanner; import org.junit.Test; @@ -105,6 +106,7 @@ public class JavaScannerUnitTest { public void whenScanString_thenCorrect() throws IOException { final String input = "Hello 1 F 3.5"; final Scanner scanner = new Scanner(input); + scanner.useLocale(Locale.US); assertEquals("Hello", scanner.next()); assertEquals(1, scanner.nextInt()); diff --git a/mockito/pom.xml b/mockito/pom.xml index c77d42f97d..19dd2f6468 100644 --- a/mockito/pom.xml +++ b/mockito/pom.xml @@ -41,7 +41,7 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 ${powermock.version} test @@ -65,7 +65,7 @@ 3.5 - 1.6.6 + 1.7.0 diff --git a/mockito2/pom.xml b/mockito2/pom.xml index 523cfa816d..a7c4683c30 100644 --- a/mockito2/pom.xml +++ b/mockito2/pom.xml @@ -53,6 +53,6 @@ UTF-8 - 2.7.5 + 2.8.9
diff --git a/mocks/mock-comparisons/pom.xml b/mocks/mock-comparisons/pom.xml index 2ab35651f1..e350457f54 100644 --- a/mocks/mock-comparisons/pom.xml +++ b/mocks/mock-comparisons/pom.xml @@ -13,7 +13,7 @@ mock-comparisons - 1.10.19 + 2.8.9 3.4 1.29 diff --git a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java index 18bc2ae189..8f8918ab22 100644 --- a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java +++ b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java @@ -7,7 +7,12 @@ import org.baeldung.mocks.testCase.UserForm; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.mockito.*; +import org.mockito.ArgumentMatcher; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; public class LoginControllerIntegrationTest { @@ -41,50 +46,63 @@ public class LoginControllerIntegrationTest { public void assertTwoMethodsHaveBeenCalled() { UserForm userForm = new UserForm(); userForm.username = "foo"; - Mockito.when(loginService.login(userForm)).thenReturn(true); + Mockito.when(loginService.login(userForm)) + .thenReturn(true); String login = loginController.login(userForm); Assert.assertEquals("OK", login); - Mockito.verify(loginService).login(userForm); - Mockito.verify(loginService).setCurrentUser("foo"); + Mockito.verify(loginService) + .login(userForm); + Mockito.verify(loginService) + .setCurrentUser("foo"); } @Test public void assertOnlyOneMethodHasBeenCalled() { UserForm userForm = new UserForm(); userForm.username = "foo"; - Mockito.when(loginService.login(userForm)).thenReturn(false); + Mockito.when(loginService.login(userForm)) + .thenReturn(false); String login = loginController.login(userForm); Assert.assertEquals("KO", login); - Mockito.verify(loginService).login(userForm); + Mockito.verify(loginService) + .login(userForm); Mockito.verifyNoMoreInteractions(loginService); } @Test public void mockExceptionThrowing() { UserForm userForm = new UserForm(); - Mockito.when(loginService.login(userForm)).thenThrow(IllegalArgumentException.class); + Mockito.when(loginService.login(userForm)) + .thenThrow(IllegalArgumentException.class); String login = loginController.login(userForm); Assert.assertEquals("ERROR", login); - Mockito.verify(loginService).login(userForm); + Mockito.verify(loginService) + .login(userForm); Mockito.verifyZeroInteractions(loginService); } @Test public void mockAnObjectToPassAround() { - UserForm userForm = Mockito.when(Mockito.mock(UserForm.class).getUsername()).thenReturn("foo").getMock(); - Mockito.when(loginService.login(userForm)).thenReturn(true); + UserForm userForm = Mockito.when(Mockito.mock(UserForm.class) + .getUsername()) + .thenReturn("foo") + .getMock(); + Mockito.when(loginService.login(userForm)) + .thenReturn(true); String login = loginController.login(userForm); Assert.assertEquals("OK", login); - Mockito.verify(loginService).login(userForm); - Mockito.verify(loginService).setCurrentUser("foo"); + Mockito.verify(loginService) + .login(userForm); + Mockito.verify(loginService) + .setCurrentUser("foo"); } @Test @@ -92,19 +110,22 @@ public class LoginControllerIntegrationTest { UserForm userForm = new UserForm(); userForm.username = "foo"; // default matcher - Mockito.when(loginService.login(Mockito.any(UserForm.class))).thenReturn(true); + Mockito.when(loginService.login(Mockito.any(UserForm.class))) + .thenReturn(true); String login = loginController.login(userForm); Assert.assertEquals("OK", login); - Mockito.verify(loginService).login(userForm); + Mockito.verify(loginService) + .login(userForm); // complex matcher - Mockito.verify(loginService).setCurrentUser(Mockito.argThat(new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - return argument instanceof String && ((String) argument).startsWith("foo"); - } - })); + Mockito.verify(loginService) + .setCurrentUser(Mockito.argThat(new ArgumentMatcher() { + @Override + public boolean matches(String argument) { + return argument.startsWith("foo"); + } + })); } @Test @@ -114,12 +135,14 @@ public class LoginControllerIntegrationTest { UserForm userForm = new UserForm(); userForm.username = "foo"; // let service's login use implementation so let's mock DAO call - Mockito.when(loginDao.login(userForm)).thenReturn(1); + Mockito.when(loginDao.login(userForm)) + .thenReturn(1); String login = loginController.login(userForm); Assert.assertEquals("OK", login); // verify mocked call - Mockito.verify(spiedLoginService).setCurrentUser("foo"); + Mockito.verify(spiedLoginService) + .setCurrentUser("foo"); } } diff --git a/pom.xml b/pom.xml index fa6a3e5673..6641155044 100644 --- a/pom.xml +++ b/pom.xml @@ -18,7 +18,7 @@ 4.12 1.3 - 1.10.19 + 2.8.9 1.7.21 1.1.7 diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index 853c84a1b8..e44611fab0 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -164,7 +164,7 @@ 2.5 - 2.2.26 + 2.8.9 4.4.1 4.5 From 34a793a0fc50cec22edbaf113cea31a078ebc989 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 30 Jul 2017 07:42:16 +0200 Subject: [PATCH 09/32] Manual money tests (#2338) --- ...Test.java => JavaMoneyUnitManualTest.java} | 380 +++++++++--------- 1 file changed, 190 insertions(+), 190 deletions(-) rename core-java/src/test/java/com/baeldung/money/{JavaMoneyUnitTest.java => JavaMoneyUnitManualTest.java} (96%) diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java rename to core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java index 3d52a9eea9..fe2747bcee 100644 --- a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java +++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java @@ -1,190 +1,190 @@ -package com.baeldung.money; - -import org.javamoney.moneta.FastMoney; -import org.javamoney.moneta.Money; -import org.javamoney.moneta.format.CurrencyStyle; -import org.junit.Ignore; -import org.junit.Test; - -import javax.money.CurrencyUnit; -import javax.money.Monetary; -import javax.money.MonetaryAmount; -import javax.money.UnknownCurrencyException; -import javax.money.convert.CurrencyConversion; -import javax.money.convert.MonetaryConversions; -import javax.money.format.AmountFormatQueryBuilder; -import javax.money.format.MonetaryAmountFormat; -import javax.money.format.MonetaryFormats; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class JavaMoneyUnitTest { - - @Test - public void givenCurrencyCode_whenString_thanExist() { - CurrencyUnit usd = Monetary.getCurrency("USD"); - - assertNotNull(usd); - assertEquals(usd.getCurrencyCode(), "USD"); - assertEquals(usd.getNumericCode(), 840); - assertEquals(usd.getDefaultFractionDigits(), 2); - } - - @Test(expected = UnknownCurrencyException.class) - public void givenCurrencyCode_whenNoExist_thanThrowsError() { - Monetary.getCurrency("AAA"); - } - - @Test - public void givenAmounts_whenStringified_thanEquals() { - CurrencyUnit usd = Monetary.getCurrency("USD"); - MonetaryAmount fstAmtUSD = Monetary - .getDefaultAmountFactory() - .setCurrency(usd) - .setNumber(200) - .create(); - Money moneyof = Money.of(12, usd); - FastMoney fastmoneyof = FastMoney.of(2, usd); - - assertEquals("USD", usd.toString()); - assertEquals("USD 200", fstAmtUSD.toString()); - assertEquals("USD 12", moneyof.toString()); - assertEquals("USD 2.00000", fastmoneyof.toString()); - } - - @Test - public void givenCurrencies_whenCompared_thanNotequal() { - MonetaryAmount oneDolar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - Money oneEuro = Money.of(1, "EUR"); - - assertFalse(oneEuro.equals(FastMoney.of(1, "EUR"))); - assertTrue(oneDolar.equals(Money.of(1, "USD"))); - } - - @Test(expected = ArithmeticException.class) - public void givenAmount_whenDivided_thanThrowsException() { - MonetaryAmount oneDolar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - oneDolar.divide(3); - fail(); // if no exception - } - - @Test - public void givenAmounts_whenSummed_thanCorrect() { - List monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF")); - - Money sumAmtCHF = (Money) monetaryAmounts - .stream() - .reduce(Money.of(0, "CHF"), MonetaryAmount::add); - - assertEquals("CHF 111.35", sumAmtCHF.toString()); - } - - @Test - public void givenArithmetic_whenStringified_thanEqualsAmount() { - CurrencyUnit usd = Monetary.getCurrency("USD"); - - Money moneyof = Money.of(12, usd); - MonetaryAmount fstAmtUSD = Monetary - .getDefaultAmountFactory() - .setCurrency(usd) - .setNumber(200.50) - .create(); - MonetaryAmount oneDolar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - Money subtractedAmount = Money - .of(1, "USD") - .subtract(fstAmtUSD); - MonetaryAmount multiplyAmount = oneDolar.multiply(0.25); - MonetaryAmount divideAmount = oneDolar.divide(0.25); - - assertEquals("USD", usd.toString()); - assertEquals("USD 1", oneDolar.toString()); - assertEquals("USD 200.5", fstAmtUSD.toString()); - assertEquals("USD 12", moneyof.toString()); - assertEquals("USD -199.5", subtractedAmount.toString()); - assertEquals("USD 0.25", multiplyAmount.toString()); - assertEquals("USD 4", divideAmount.toString()); - } - - @Test - public void givenAmount_whenRounded_thanEquals() { - MonetaryAmount fstAmtEUR = Monetary - .getDefaultAmountFactory() - .setCurrency("EUR") - .setNumber(1.30473908) - .create(); - MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding()); - assertEquals("EUR 1.30473908", fstAmtEUR.toString()); - assertEquals("EUR 1.3", roundEUR.toString()); - } - - @Test - @Ignore("Currency providers are not always available") - public void givenAmount_whenConversion_thenNotNull() { - MonetaryAmount oneDollar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - - CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR"); - - MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR); - - assertEquals("USD 1", oneDollar.toString()); - assertNotNull(convertedAmountUSDtoEUR); - } - - @Test - public void givenLocale_whenFormatted_thanEquals() { - MonetaryAmount oneDollar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US); - String usFormatted = formatUSD.format(oneDollar); - - assertEquals("USD 1", oneDollar.toString()); - assertNotNull(formatUSD); - assertEquals("USD1.00", usFormatted); - } - - @Test - public void givenAmount_whenCustomFormat_thanEquals() { - MonetaryAmount oneDollar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - - MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder - .of(Locale.US) - .set(CurrencyStyle.NAME) - .set("pattern", "00000.00 ¤") - .build()); - String customFormatted = customFormat.format(oneDollar); - - assertNotNull(customFormat); - assertEquals("USD 1", oneDollar.toString()); - assertEquals("00001.00 US Dollar", customFormatted); - } -} +package com.baeldung.money; + +import org.javamoney.moneta.FastMoney; +import org.javamoney.moneta.Money; +import org.javamoney.moneta.format.CurrencyStyle; +import org.junit.Ignore; +import org.junit.Test; + +import javax.money.CurrencyUnit; +import javax.money.Monetary; +import javax.money.MonetaryAmount; +import javax.money.UnknownCurrencyException; +import javax.money.convert.CurrencyConversion; +import javax.money.convert.MonetaryConversions; +import javax.money.format.AmountFormatQueryBuilder; +import javax.money.format.MonetaryAmountFormat; +import javax.money.format.MonetaryFormats; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class JavaMoneyUnitManualTest { + + @Test + public void givenCurrencyCode_whenString_thanExist() { + CurrencyUnit usd = Monetary.getCurrency("USD"); + + assertNotNull(usd); + assertEquals(usd.getCurrencyCode(), "USD"); + assertEquals(usd.getNumericCode(), 840); + assertEquals(usd.getDefaultFractionDigits(), 2); + } + + @Test(expected = UnknownCurrencyException.class) + public void givenCurrencyCode_whenNoExist_thanThrowsError() { + Monetary.getCurrency("AAA"); + } + + @Test + public void givenAmounts_whenStringified_thanEquals() { + CurrencyUnit usd = Monetary.getCurrency("USD"); + MonetaryAmount fstAmtUSD = Monetary + .getDefaultAmountFactory() + .setCurrency(usd) + .setNumber(200) + .create(); + Money moneyof = Money.of(12, usd); + FastMoney fastmoneyof = FastMoney.of(2, usd); + + assertEquals("USD", usd.toString()); + assertEquals("USD 200", fstAmtUSD.toString()); + assertEquals("USD 12", moneyof.toString()); + assertEquals("USD 2.00000", fastmoneyof.toString()); + } + + @Test + public void givenCurrencies_whenCompared_thanNotequal() { + MonetaryAmount oneDolar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + Money oneEuro = Money.of(1, "EUR"); + + assertFalse(oneEuro.equals(FastMoney.of(1, "EUR"))); + assertTrue(oneDolar.equals(Money.of(1, "USD"))); + } + + @Test(expected = ArithmeticException.class) + public void givenAmount_whenDivided_thanThrowsException() { + MonetaryAmount oneDolar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + oneDolar.divide(3); + fail(); // if no exception + } + + @Test + public void givenAmounts_whenSummed_thanCorrect() { + List monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF")); + + Money sumAmtCHF = (Money) monetaryAmounts + .stream() + .reduce(Money.of(0, "CHF"), MonetaryAmount::add); + + assertEquals("CHF 111.35", sumAmtCHF.toString()); + } + + @Test + public void givenArithmetic_whenStringified_thanEqualsAmount() { + CurrencyUnit usd = Monetary.getCurrency("USD"); + + Money moneyof = Money.of(12, usd); + MonetaryAmount fstAmtUSD = Monetary + .getDefaultAmountFactory() + .setCurrency(usd) + .setNumber(200.50) + .create(); + MonetaryAmount oneDolar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + Money subtractedAmount = Money + .of(1, "USD") + .subtract(fstAmtUSD); + MonetaryAmount multiplyAmount = oneDolar.multiply(0.25); + MonetaryAmount divideAmount = oneDolar.divide(0.25); + + assertEquals("USD", usd.toString()); + assertEquals("USD 1", oneDolar.toString()); + assertEquals("USD 200.5", fstAmtUSD.toString()); + assertEquals("USD 12", moneyof.toString()); + assertEquals("USD -199.5", subtractedAmount.toString()); + assertEquals("USD 0.25", multiplyAmount.toString()); + assertEquals("USD 4", divideAmount.toString()); + } + + @Test + public void givenAmount_whenRounded_thanEquals() { + MonetaryAmount fstAmtEUR = Monetary + .getDefaultAmountFactory() + .setCurrency("EUR") + .setNumber(1.30473908) + .create(); + MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding()); + assertEquals("EUR 1.30473908", fstAmtEUR.toString()); + assertEquals("EUR 1.3", roundEUR.toString()); + } + + @Test + @Ignore("Currency providers are not always available") + public void givenAmount_whenConversion_thenNotNull() { + MonetaryAmount oneDollar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + + CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR"); + + MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR); + + assertEquals("USD 1", oneDollar.toString()); + assertNotNull(convertedAmountUSDtoEUR); + } + + @Test + public void givenLocale_whenFormatted_thanEquals() { + MonetaryAmount oneDollar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US); + String usFormatted = formatUSD.format(oneDollar); + + assertEquals("USD 1", oneDollar.toString()); + assertNotNull(formatUSD); + assertEquals("USD1.00", usFormatted); + } + + @Test + public void givenAmount_whenCustomFormat_thanEquals() { + MonetaryAmount oneDollar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + + MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder + .of(Locale.US) + .set(CurrencyStyle.NAME) + .set("pattern", "00000.00 �") + .build()); + String customFormatted = customFormat.format(oneDollar); + + assertNotNull(customFormat); + assertEquals("USD 1", oneDollar.toString()); + assertEquals("00001.00 US Dollar", customFormatted); + } +} From 4441d969faff309b1a387bdbe60644c332256ce1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Ju=C3=A1rez?= Date: Sun, 30 Jul 2017 00:57:36 -0500 Subject: [PATCH 10/32] BAEL-1023 Introduction to Kryo (#2336) --- libraries/pom.xml | 6 + .../java/com/baeldung/kryo/ComplexClass.java | 16 +++ .../main/java/com/baeldung/kryo/Person.java | 54 ++++++++ .../com/baeldung/kryo/PersonSerializer.java | 33 +++++ .../java/com/baeldung/kryo/KryoUnitTest.java | 125 ++++++++++++++++++ 5 files changed, 234 insertions(+) create mode 100644 libraries/src/main/java/com/baeldung/kryo/ComplexClass.java create mode 100644 libraries/src/main/java/com/baeldung/kryo/Person.java create mode 100644 libraries/src/main/java/com/baeldung/kryo/PersonSerializer.java create mode 100644 libraries/src/test/java/com/baeldung/kryo/KryoUnitTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index a655f5267a..9e8ff9b9ab 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -453,6 +453,11 @@ pcollections ${pcollections.version} + + com.esotericsoftware + kryo + ${kryo.version} + 0.7.0 @@ -493,5 +498,6 @@ 1.6.0 1.7.1 2.1.2 + 4.0.1
diff --git a/libraries/src/main/java/com/baeldung/kryo/ComplexClass.java b/libraries/src/main/java/com/baeldung/kryo/ComplexClass.java new file mode 100644 index 0000000000..0e125e48a9 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/kryo/ComplexClass.java @@ -0,0 +1,16 @@ +package com.baeldung.kryo; + +import java.io.Serializable; + +public class ComplexClass implements Serializable{ + private static final long serialVersionUID = 123456L; + private String name = "Bael"; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/libraries/src/main/java/com/baeldung/kryo/Person.java b/libraries/src/main/java/com/baeldung/kryo/Person.java new file mode 100644 index 0000000000..f9be5cfd62 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/kryo/Person.java @@ -0,0 +1,54 @@ +package com.baeldung.kryo; + +import com.esotericsoftware.kryo.DefaultSerializer; +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.KryoSerializable; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; +import java.util.Date; + +@DefaultSerializer(PersonSerializer.class) +public class Person implements KryoSerializable { + private String name = "John Doe"; + private int age = 18; + private Date birthDate = new Date(933191282821L); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public Date getBirthDate() { + return birthDate; + } + + public void setBirthDate(Date birthDate) { + this.birthDate = birthDate; + } + + @Override + public void write(Kryo kryo, Output output) { + output.writeString(name); + output.writeLong(birthDate.getTime()); + output.writeInt(age); + } + + @Override + public void read(Kryo kryo, Input input) { + name = input.readString(); + birthDate = new Date(input.readLong()); + age = input.readInt(); + } + +} diff --git a/libraries/src/main/java/com/baeldung/kryo/PersonSerializer.java b/libraries/src/main/java/com/baeldung/kryo/PersonSerializer.java new file mode 100644 index 0000000000..f5d01509a6 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/kryo/PersonSerializer.java @@ -0,0 +1,33 @@ +package com.baeldung.kryo; + +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.Serializer; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; +import java.util.Date; + +public class PersonSerializer extends Serializer { + + @Override + public void write(Kryo kryo, Output output, Person object) { + output.writeString(object.getName()); + output.writeLong(object.getBirthDate() + .getTime()); + } + + @Override + public Person read(Kryo kryo, Input input, Class type) { + Person person = new Person(); + person.setName(input.readString()); + long birthDate = input.readLong(); + person.setBirthDate(new Date(birthDate)); + person.setAge(calculateAge(birthDate)); + return person; + } + + private int calculateAge(long birthDate) { + // Some custom logic + return 18; + } + +} diff --git a/libraries/src/test/java/com/baeldung/kryo/KryoUnitTest.java b/libraries/src/test/java/com/baeldung/kryo/KryoUnitTest.java new file mode 100644 index 0000000000..c124ca618d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/kryo/KryoUnitTest.java @@ -0,0 +1,125 @@ +package com.baeldung.kryo; + +import static org.junit.Assert.assertEquals; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.util.Date; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.junit.Before; +import org.junit.Test; + +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; +import com.esotericsoftware.kryo.serializers.JavaSerializer; + +public class KryoUnitTest { + + private Kryo kryo; + private Output output; + private Input input; + + @Before + public void init() { + kryo = new Kryo(); + try { + output = new Output(new FileOutputStream("file.dat")); + input = new Input(new FileInputStream("file.dat")); + } catch (FileNotFoundException ex) { + Logger.getLogger(KryoUnitTest.class.getName()) + .log(Level.SEVERE, null, ex); + } + } + + @Test + public void givenObject_whenSerializing_thenReadCorrectly() { + Object someObject = "Some string"; + + kryo.writeClassAndObject(output, someObject); + output.close(); + + Object theObject = kryo.readClassAndObject(input); + input.close(); + + assertEquals(theObject, "Some string"); + } + + @Test + public void givenObjects_whenSerializing_thenReadCorrectly() { + String someString = "Multiple Objects"; + Date someDate = new Date(915170400000L); + + kryo.writeObject(output, someString); + kryo.writeObject(output, someDate); + output.close(); + + String readString = kryo.readObject(input, String.class); + Date readDate = kryo.readObject(input, Date.class); + input.close(); + + assertEquals(readString, "Multiple Objects"); + assertEquals(readDate.getTime(), 915170400000L); + } + + @Test + public void givenPerson_whenSerializing_thenReadCorrectly() { + Person person = new Person(); + + kryo.writeObject(output, person); + output.close(); + + Person readPerson = kryo.readObject(input, Person.class); + input.close(); + + assertEquals(readPerson.getName(), "John Doe"); + } + + @Test + public void givenPerson_whenUsingCustomSerializer_thenReadCorrectly() { + Person person = new Person(); + person.setAge(0); + kryo.register(Person.class, new PersonSerializer()); + + kryo.writeObject(output, person); + output.close(); + + Person readPerson = kryo.readObject(input, Person.class); + input.close(); + + assertEquals(readPerson.getName(), "John Doe"); + assertEquals(readPerson.getAge(), 18); + } + + @Test + public void givenPerson_whenCustomSerialization_thenReadCorrectly() { + Person person = new Person(); + + kryo.writeObject(output, person); + output.close(); + + Person readPerson = kryo.readObject(input, Person.class); + input.close(); + + assertEquals(readPerson.getName(), "John Doe"); + assertEquals(readPerson.getAge(), 18); + } + + @Test + public void givenJavaSerializable_whenSerializing_thenReadCorrectly() { + ComplexClass complexClass = new ComplexClass(); + kryo.register(ComplexClass.class, new JavaSerializer()); + + kryo.writeObject(output, complexClass); + output.close(); + + ComplexClass readComplexObject = kryo.readObject(input, ComplexClass.class); + input.close(); + + assertEquals(readComplexObject.getName(), "Bael"); + } + +} From 610bb0512389cf101a6c899e43a3271f351ebc67 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Sun, 30 Jul 2017 09:08:54 +0200 Subject: [PATCH 11/32] minor fix (#2334) * 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 --- .../spring/RedirectionSecurityConfig.java | 37 ++++++++----------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java index b68e7eab50..1472a1f89c 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java @@ -1,17 +1,14 @@ package org.baeldung.spring; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; -@Configuration +//@Configuration //@ImportResource({ "classpath:RedirectionWebSecurityConfig.xml" }) -@EnableWebSecurity -@Profile("!https") +//@EnableWebSecurity +//@Profile("!https") public class RedirectionSecurityConfig extends WebSecurityConfigurerAdapter { public RedirectionSecurityConfig() { @@ -20,25 +17,23 @@ public class RedirectionSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth - .inMemoryAuthentication() - .withUser("user1") - .password("user1Pass") - .roles("USER"); + auth.inMemoryAuthentication() + .withUser("user1") + .password("user1Pass") + .roles("USER"); } @Override protected void configure(final HttpSecurity http) throws Exception { - http - .authorizeRequests() - .antMatchers("/login*") - .permitAll() - .anyRequest() - .authenticated() - .and() - .formLogin() - .successHandler(new SavedRequestAwareAuthenticationSuccessHandler()); - //.successHandler(new RefererAuthenticationSuccessHandler()) + http.authorizeRequests() + .antMatchers("/login*") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin() + .successHandler(new SavedRequestAwareAuthenticationSuccessHandler()); + // .successHandler(new RefererAuthenticationSuccessHandler()) } } From dc037a4ce893b9a66f55f39ffa3ff0bc45b08fa7 Mon Sep 17 00:00:00 2001 From: Adam InTae Gerard Date: Sun, 30 Jul 2017 00:24:14 -0700 Subject: [PATCH 12/32] System outs for tests (#2321) --- .../java/com/baeldung/neuroph/XORTest.java | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/libraries/src/test/java/com/baeldung/neuroph/XORTest.java b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java index 063c57195b..4a6ecf8e46 100644 --- a/libraries/src/test/java/com/baeldung/neuroph/XORTest.java +++ b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java @@ -10,6 +10,10 @@ import static org.junit.Assert.*; public class XORTest { private NeuralNetwork ann = null; + private void print(String input, double output, double actual) { + System.out.println("Testing: " + input + " Expected: " + actual + " Result: " + output); + } + @Before public void annInit() { ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork()); @@ -19,32 +23,36 @@ public class XORTest { public void leftDisjunctTest() { ann.setInput(0, 1); ann.calculate(); - assertEquals(ann.getOutput()[0], 1.0,0.0); + print("0, 1", ann.getOutput()[0], 1.0); + assertEquals(ann.getOutput()[0], 1.0, 0.0); } @Test public void rightDisjunctTest() { ann.setInput(1, 0); ann.calculate(); - assertEquals(ann.getOutput()[0], 1.0,0.0); + print("1, 0", ann.getOutput()[0], 1.0); + assertEquals(ann.getOutput()[0], 1.0, 0.0); } @Test public void bothFalseConjunctTest() { ann.setInput(0, 0); ann.calculate(); - assertEquals(ann.getOutput()[0], 0.0,0.0); + print("0, 0", ann.getOutput()[0], 0.0); + assertEquals(ann.getOutput()[0], 0.0, 0.0); } @Test public void bothTrueConjunctTest() { ann.setInput(1, 1); ann.calculate(); - assertEquals(ann.getOutput()[0], 0.0,0.0); + print("1, 1", ann.getOutput()[0], 0.0); + assertEquals(ann.getOutput()[0], 0.0, 0.0); } @After public void annClose() { ann = null; } -} +} \ No newline at end of file From 36608b78ccf19f492f031074aba83c8ec3702146 Mon Sep 17 00:00:00 2001 From: Ahmed Tawila Date: Sun, 30 Jul 2017 10:57:10 +0300 Subject: [PATCH 13/32] BAEL-1033 Introduction to StreamUtils (#2337) * 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 --- .../CustomTemporalAdjusterTest.java | 2 +- .../com/baeldung/streamutils/CopyStream.java | 22 ++++ .../com/baeldung/streamutils/DrainStream.java | 11 ++ .../baeldung/streamutils/CopyStreamTest.java | 100 ++++++++++++++++++ libraries/src/test/resources/input.txt | 1 + libraries/src/test/resources/output.txt | 1 + 6 files changed, 136 insertions(+), 1 deletion(-) create mode 100644 libraries/src/main/java/com/baeldung/streamutils/CopyStream.java create mode 100644 libraries/src/main/java/com/baeldung/streamutils/DrainStream.java create mode 100644 libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java create mode 100644 libraries/src/test/resources/input.txt create mode 100644 libraries/src/test/resources/output.txt diff --git a/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java b/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java index ad8de82e1f..7b5f781620 100644 --- a/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java +++ b/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java @@ -41,4 +41,4 @@ public class CustomTemporalAdjusterTest { assertEquals(fourteenDaysAfterDate, result.toString()); } -} +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java new file mode 100644 index 0000000000..430759f3a0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java @@ -0,0 +1,22 @@ +package com.baeldung.streamutils; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import org.apache.commons.io.IOUtils; +import org.springframework.util.StreamUtils; + +public class CopyStream { + public static String getStringFromInputStream(InputStream input) throws IOException { + StringWriter writer = new StringWriter(); + IOUtils.copy(input, writer, "UTF-8"); + return writer.toString(); + } + + public InputStream getNonClosingInputStream() throws IOException { + InputStream in = new FileInputStream("src/test/resources/input.txt"); + return StreamUtils.nonClosing(in); + } +} diff --git a/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java new file mode 100644 index 0000000000..6ee4a1ef3a --- /dev/null +++ b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java @@ -0,0 +1,11 @@ +package com.baeldung.streamutils; + +import java.io.InputStream; + +import org.springframework.util.StreamUtils; + +public class DrainStream { + public InputStream getInputStream() { + return StreamUtils.emptyInput(); + } +} diff --git a/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java new file mode 100644 index 0000000000..9a65075e5b --- /dev/null +++ b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java @@ -0,0 +1,100 @@ +package com.baeldung.streamutils; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.util.StreamUtils; + +import static com.baeldung.streamutils.CopyStream.getStringFromInputStream; + +public class CopyStreamTest { + + @Test + public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copy(in, out); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(inputFileContent, outputFileContent); + } + + @Test + public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copyRange(in, out, 1, 10); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(inputFileContent.substring(1, 11), outputFileContent); + } + + @Test + public void whenCopyStringToOutputStream_thenCorrect() throws IOException { + String string = "Should be copied to OutputStream."; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(string, StandardCharsets.UTF_8, out); + + assertTrue(outputFile.exists()); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToString_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream is = new FileInputStream(inputFileName); + String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); + + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + Assert.assertEquals(inputFileContent, content); + } + + @Test + public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException { + String outputFileName = "src/test/resources/output.txt"; + String string = "Should be copied to OutputStream."; + byte[] byteArray = string.getBytes(); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(byteArray, out); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream in = new FileInputStream(inputFileName); + byte[] out = StreamUtils.copyToByteArray(in); + + String content = new String(out); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + Assert.assertEquals(inputFileContent, content); + } + +} diff --git a/libraries/src/test/resources/input.txt b/libraries/src/test/resources/input.txt new file mode 100644 index 0000000000..811232fa1f --- /dev/null +++ b/libraries/src/test/resources/input.txt @@ -0,0 +1 @@ +This file is merely for testing. \ No newline at end of file diff --git a/libraries/src/test/resources/output.txt b/libraries/src/test/resources/output.txt new file mode 100644 index 0000000000..34e1e27d5a --- /dev/null +++ b/libraries/src/test/resources/output.txt @@ -0,0 +1 @@ +Should be copied to OutputStream. \ No newline at end of file From 6bfd4d3aaed5e019ef2e4d9b04514f231020165d Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sun, 30 Jul 2017 09:31:09 -0500 Subject: [PATCH 14/32] BAEL-907: README updated (#2340) * 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) --- libraries/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/README.md b/libraries/README.md index f0484ec710..86baa39045 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -27,6 +27,7 @@ - [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) - [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) 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. From deb79bbd83c379cc2b888817964cf58d27f094f7 Mon Sep 17 00:00:00 2001 From: Yasin Date: Sun, 30 Jul 2017 22:03:51 +0530 Subject: [PATCH 15/32] BAEL-887 How to collect a Java Stream to an immutable collection? (#2339) * 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? --- core-java/pom.xml | 2 +- .../stream/StreamToImmutableTest.java | 69 +++++++++++++++++++ .../MyImmutableListCollector.java | 22 ++++++ 3 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java create mode 100644 core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java diff --git a/core-java/pom.xml b/core-java/pom.xml index 78338fc439..73b1c22ed8 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -391,7 +391,7 @@ 1.1.7 - 21.0 + 22.0 3.5 1.55 1.10 diff --git a/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java b/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java new file mode 100644 index 0000000000..d267bd6406 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java @@ -0,0 +1,69 @@ +package com.baeldung.stream; + +import static java.util.stream.Collectors.collectingAndThen; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toSet; + +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)); + + System.out.println(immutableSet.getClass()); + } + + @Test + public void whenUsingCollectingToUnmodifiableList_thenSuccess() { + List givenList = new ArrayList<>(Arrays.asList("a", "b", "c")); + List result = givenList.stream() + .collect(collectingAndThen(toList(), Collections::unmodifiableList)); + + System.out.println(result.getClass()); + } + + @Test + public void whenCollectToImmutableList_thenSuccess() { + List list = IntStream.range(0, 9) + .boxed() + .collect(ImmutableList.toImmutableList()); + + System.out.println(list.getClass()); + } + + @Test + public void whenCollectToMyImmutableListCollector_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c", "d"); + List result = givenList.stream() + .collect(MyImmutableListCollector.toImmutableList()); + + System.out.println(result.getClass()); + } + + @Test + public void whenPassingSupplier_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c", "d"); + List result = givenList.stream() + .collect(MyImmutableListCollector.toImmutableList(LinkedList::new)); + + System.out.println(result.getClass()); + } +} diff --git a/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java b/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java new file mode 100644 index 0000000000..cf6b3601c3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java @@ -0,0 +1,22 @@ +package com.baeldung.stream.mycollectors; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Collector; + +public class MyImmutableListCollector { + + public static > Collector> toImmutableList(Supplier supplier) { + return Collector.of(supplier, List::add, (left, right) -> { + left.addAll(right); + return left; + }, Collections::unmodifiableList); + } + + public static Collector, List> toImmutableList() { + return toImmutableList(ArrayList::new); + } + +} From 752086e80ca8abc3791fb50c6acfc637fb8eaf84 Mon Sep 17 00:00:00 2001 From: Alejandro Gervasio Date: Mon, 31 Jul 2017 08:36:15 -0300 Subject: [PATCH 16/32] Initial Commit (#2349) --- .../hashcode/application/Application.java | 23 +++++++++++ .../com/baeldung/hashcode/entities/User.java | 38 +++++++++++++++++++ .../hashcode/application/ApplicationTest.java | 30 +++++++++++++++ .../baeldung/hashcode/entities/UserTest.java | 34 +++++++++++++++++ 4 files changed, 125 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/hashcode/application/Application.java create mode 100644 core-java/src/main/java/com/baeldung/hashcode/entities/User.java create mode 100644 core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java create mode 100644 core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java 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 new file mode 100644 index 0000000000..08c670c82f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/hashcode/application/Application.java @@ -0,0 +1,23 @@ +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/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java new file mode 100644 index 0000000000..a976233562 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java @@ -0,0 +1,38 @@ +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/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java new file mode 100644 index 0000000000..dcd853f451 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java @@ -0,0 +1,30 @@ +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/src/test/java/com/baeldung/hashcode/entities/UserTest.java b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java new file mode 100644 index 0000000000..01f6085d7e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java @@ -0,0 +1,34 @@ +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 From 585597f11de7a4db83c44798e728ea44637846b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Ju=C3=A1rez?= Date: Mon, 31 Jul 2017 07:43:36 -0500 Subject: [PATCH 17/32] New libraries-data module (#2343) --- libraries-data/pom.xml | 22 +++++++++++++++++++ .../java/com/baeldung/kryo/ComplexClass.java | 0 .../main/java/com/baeldung/kryo/Person.java | 0 .../com/baeldung/kryo/PersonSerializer.java | 0 .../java/com/baeldung/kryo/KryoUnitTest.java | 0 libraries/pom.xml | 6 ----- pom.xml | 1 + 7 files changed, 23 insertions(+), 6 deletions(-) create mode 100644 libraries-data/pom.xml rename {libraries => libraries-data}/src/main/java/com/baeldung/kryo/ComplexClass.java (100%) rename {libraries => libraries-data}/src/main/java/com/baeldung/kryo/Person.java (100%) rename {libraries => libraries-data}/src/main/java/com/baeldung/kryo/PersonSerializer.java (100%) rename {libraries => libraries-data}/src/test/java/com/baeldung/kryo/KryoUnitTest.java (100%) diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml new file mode 100644 index 0000000000..94a9ca43f4 --- /dev/null +++ b/libraries-data/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + libraries-data + libraries-data + jar + + + com.esotericsoftware + kryo + ${kryo.version} + + + + 4.0.1 + + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/kryo/ComplexClass.java b/libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java similarity index 100% rename from libraries/src/main/java/com/baeldung/kryo/ComplexClass.java rename to libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java diff --git a/libraries/src/main/java/com/baeldung/kryo/Person.java b/libraries-data/src/main/java/com/baeldung/kryo/Person.java similarity index 100% rename from libraries/src/main/java/com/baeldung/kryo/Person.java rename to libraries-data/src/main/java/com/baeldung/kryo/Person.java diff --git a/libraries/src/main/java/com/baeldung/kryo/PersonSerializer.java b/libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/kryo/PersonSerializer.java rename to libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java diff --git a/libraries/src/test/java/com/baeldung/kryo/KryoUnitTest.java b/libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/kryo/KryoUnitTest.java rename to libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index 9e8ff9b9ab..a655f5267a 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -453,11 +453,6 @@ pcollections ${pcollections.version} - - com.esotericsoftware - kryo - ${kryo.version} - 0.7.0 @@ -498,6 +493,5 @@ 1.6.0 1.7.1 2.1.2 - 4.0.1 diff --git a/pom.xml b/pom.xml index 6641155044..eaf7f47a2b 100644 --- a/pom.xml +++ b/pom.xml @@ -94,6 +94,7 @@ jws libraries + libraries-data log-mdc log4j log4j2 From 4b53c00bca2d07420ed4add07a164789af454d2d Mon Sep 17 00:00:00 2001 From: Ahmed Tawila Date: Mon, 31 Jul 2017 15:57:52 +0300 Subject: [PATCH 18/32] BAEL-1033 Introduction to StreamUtils (#2341) * 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 --- libraries/pom.xml | 986 +++++++++--------- spring-core/pom.xml | 262 ++--- .../com/baeldung/streamutils/CopyStream.java | 22 + .../com/baeldung/streamutils/DrainStream.java | 11 + .../baeldung/streamutils/CopyStreamTest.java | 100 ++ spring-core/src/test/resources/input.txt | 1 + spring-core/src/test/resources/output.txt | 1 + 7 files changed, 762 insertions(+), 621 deletions(-) create mode 100644 spring-core/src/main/java/com/baeldung/streamutils/CopyStream.java create mode 100644 spring-core/src/main/java/com/baeldung/streamutils/DrainStream.java create mode 100644 spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java create mode 100644 spring-core/src/test/resources/input.txt create mode 100644 spring-core/src/test/resources/output.txt diff --git a/libraries/pom.xml b/libraries/pom.xml index a655f5267a..795f255f36 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -1,497 +1,497 @@ - - 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 + 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} - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - commons-logging - commons-logging - - - - - commons-io - commons-io - ${commons.io.version} - - - commons-chain - commons-chain - ${commons-chain.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 - 0.6.5 - - - 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} - - - - 0.7.0 - 3.2.4 - 3.5 - 1.1 - 1.9.3 - 1.2 - 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 - + + + 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} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + commons-logging + commons-logging + + + + + commons-io + commons-io + ${commons.io.version} + + + commons-chain + commons-chain + ${commons-chain.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 + 0.6.5 + + + 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} + + + + 0.7.0 + 3.2.4 + 3.5 + 1.1 + 1.9.3 + 1.2 + 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 + diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 85cf4573aa..deffaf41db 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -1,141 +1,147 @@ + xmlns="http://maven.apache.org/POM/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 + 4.0.0 - com.baeldung - spring-core - 0.0.1-SNAPSHOT - war + com.baeldung + spring-core + 0.0.1-SNAPSHOT + war - spring-core + spring-core - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - org.mockito - mockito-all - ${mockito.version} - - - org.springframework - spring-test - ${spring.version} - - - org.springframework - spring-core - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - javax.inject - javax.inject - ${javax.inject.version} - - - com.google.guava - guava - ${guava.version} - - - org.projectlombok - lombok - ${lombok.version} - - - org.springframework.boot - spring-boot-starter - 1.5.2.RELEASE - - - org.springframework.boot - spring-boot-test - ${mockito.spring.boot.version} - test - - + + + org.mockito + mockito-all + ${mockito.version} + + + org.springframework + spring-test + ${spring.version} + + + org.springframework + spring-core + ${spring.version} + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + javax.inject + javax.inject + ${javax.inject.version} + + + com.google.guava + guava + ${guava.version} + + + org.projectlombok + lombok + ${lombok.version} + + + org.springframework.boot + spring-boot-starter + 1.5.2.RELEASE + + + org.springframework.boot + spring-boot-test + ${mockito.spring.boot.version} + test + + + commons-io + commons-io + ${commons.io.version} + + - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + - + - + - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + - - 1.10.19 - 1.4.4.RELEASE - 4.3.4.RELEASE - 1 - 20.0 - 2.6 - 1.16.12 - + + 1.10.19 + 1.4.4.RELEASE + 4.3.4.RELEASE + 1 + 20.0 + 2.6 + 1.16.12 + 2.5 + - - - java.net - https://maven.java.net/content/repositories/releases/ - - + + + java.net + https://maven.java.net/content/repositories/releases/ + + - + \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/streamutils/CopyStream.java b/spring-core/src/main/java/com/baeldung/streamutils/CopyStream.java new file mode 100644 index 0000000000..d9097188b3 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/streamutils/CopyStream.java @@ -0,0 +1,22 @@ +package com.baeldung.streamutils; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import org.apache.commons.io.IOUtils; +import org.springframework.util.StreamUtils; + +public class CopyStream { + public static String getStringFromInputStream(InputStream input) throws IOException { + StringWriter writer = new StringWriter(); + IOUtils.copy(input, writer, "UTF-8"); + return writer.toString(); + } + + public InputStream getNonClosingInputStream() throws IOException { + InputStream in = new FileInputStream("src/test/resources/input.txt"); + return StreamUtils.nonClosing(in); + } +} diff --git a/spring-core/src/main/java/com/baeldung/streamutils/DrainStream.java b/spring-core/src/main/java/com/baeldung/streamutils/DrainStream.java new file mode 100644 index 0000000000..1ce67a075a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/streamutils/DrainStream.java @@ -0,0 +1,11 @@ +package com.baeldung.streamutils; + +import java.io.InputStream; + +import org.springframework.util.StreamUtils; + +public class DrainStream { + public InputStream getInputStream() { + return StreamUtils.emptyInput(); + } +} diff --git a/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java b/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java new file mode 100644 index 0000000000..9fe2f00a77 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java @@ -0,0 +1,100 @@ +package com.baeldung.streamutils; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.springframework.util.StreamUtils; + +import static com.baeldung.streamutils.CopyStream.getStringFromInputStream; + +public class CopyStreamTest { + + @Test + public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copy(in, out); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + assertEquals(inputFileContent, outputFileContent); + } + + @Test + public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copyRange(in, out, 1, 10); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + assertEquals(inputFileContent.substring(1, 11), outputFileContent); + } + + @Test + public void whenCopyStringToOutputStream_thenCorrect() throws IOException { + String string = "Should be copied to OutputStream."; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(string, StandardCharsets.UTF_8, out); + + assertTrue(outputFile.exists()); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToString_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream is = new FileInputStream(inputFileName); + String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); + + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + assertEquals(inputFileContent, content); + } + + @Test + public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException { + String outputFileName = "src/test/resources/output.txt"; + String string = "Should be copied to OutputStream."; + byte[] byteArray = string.getBytes(); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(byteArray, out); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream in = new FileInputStream(inputFileName); + byte[] out = StreamUtils.copyToByteArray(in); + + String content = new String(out); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + assertEquals(inputFileContent, content); + } + +} diff --git a/spring-core/src/test/resources/input.txt b/spring-core/src/test/resources/input.txt new file mode 100644 index 0000000000..811232fa1f --- /dev/null +++ b/spring-core/src/test/resources/input.txt @@ -0,0 +1 @@ +This file is merely for testing. \ No newline at end of file diff --git a/spring-core/src/test/resources/output.txt b/spring-core/src/test/resources/output.txt new file mode 100644 index 0000000000..34e1e27d5a --- /dev/null +++ b/spring-core/src/test/resources/output.txt @@ -0,0 +1 @@ +Should be copied to OutputStream. \ No newline at end of file From b4f7806ce6fc21291fa3710d97faf0d6517c8e18 Mon Sep 17 00:00:00 2001 From: Jose Carvajal Date: Mon, 31 Jul 2017 16:08:01 +0200 Subject: [PATCH 19/32] Matchers is now deprecated in Mockito 2, it's now replaced by ArgumentMatchers (#2342) --- .../baeldung/mocks/mockito/LoginControllerIntegrationTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java index 8f8918ab22..9d47b2f5d4 100644 --- a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java +++ b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java @@ -8,6 +8,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; +import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; @@ -120,7 +121,7 @@ public class LoginControllerIntegrationTest { .login(userForm); // complex matcher Mockito.verify(loginService) - .setCurrentUser(Mockito.argThat(new ArgumentMatcher() { + .setCurrentUser(ArgumentMatchers.argThat(new ArgumentMatcher() { @Override public boolean matches(String argument) { return argument.startsWith("foo"); From 7f5ca786e2d9ec6bb5fa7cb49eb6cfe2cee88792 Mon Sep 17 00:00:00 2001 From: Roman Cherepanov Date: Tue, 1 Aug 2017 15:59:55 +0300 Subject: [PATCH 20/32] Fix title formatting (#2314) --- feign/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/feign/README.md b/feign/README.md index 149f7320d9..4d6964a73a 100644 --- a/feign/README.md +++ b/feign/README.md @@ -4,5 +4,5 @@ This is the implementation of a [spring-hypermedia-api][1] client using Feign. [1]: https://github.com/eugenp/spring-hypermedia-api -###Relevant Articles: +### Relevant Articles: - [Intro to Feign](http://www.baeldung.com/intro-to-feign) From 0c60af84374b9eeefd1ea2967c74b3ff82176ba2 Mon Sep 17 00:00:00 2001 From: Roman Seleznov Date: Tue, 1 Aug 2017 14:03:07 +0100 Subject: [PATCH 21/32] Make projects executable (#2278) * 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 --- .../property-exp-custom/pom.xml | 17 +++++++++++++++++ .../property-exp-default/build.gradle | 4 ++++ .../property-exp-default/pom.xml | 12 ++++++++++++ 3 files changed, 33 insertions(+) diff --git a/spring-boot-property-exp/property-exp-custom/pom.xml b/spring-boot-property-exp/property-exp-custom/pom.xml index 234404a6c0..cfce323eab 100644 --- a/spring-boot-property-exp/property-exp-custom/pom.xml +++ b/spring-boot-property-exp/property-exp-custom/pom.xml @@ -40,6 +40,15 @@ **/application*.properties + + ${basedir}/src/main/resources + true + + **/application*.yml + **/application*.yaml + **/application*.properties + + @@ -53,6 +62,14 @@ true + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp + + diff --git a/spring-boot-property-exp/property-exp-default/build.gradle b/spring-boot-property-exp/property-exp-default/build.gradle index f3c5f4a378..ec27de7c41 100644 --- a/spring-boot-property-exp/property-exp-default/build.gradle +++ b/spring-boot-property-exp/property-exp-default/build.gradle @@ -27,6 +27,10 @@ repositories { mavenCentral() } +springBoot { + executable = true +} + import org.apache.tools.ant.filters.ReplaceTokens processResources { with copySpec { diff --git a/spring-boot-property-exp/property-exp-default/pom.xml b/spring-boot-property-exp/property-exp-default/pom.xml index 3629e56111..2544800e6a 100644 --- a/spring-boot-property-exp/property-exp-default/pom.xml +++ b/spring-boot-property-exp/property-exp-default/pom.xml @@ -30,4 +30,16 @@ + + + + org.springframework.boot + spring-boot-maven-plugin + + true + + + + + From ed92182fbfd8001721963d4abafc8d9243a81ec0 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Tue, 1 Aug 2017 17:00:03 +0200 Subject: [PATCH 22/32] Build optimization 1.08.2017 (#2351) * Refactor Spring-activiti module * Refactor vavr module --- pom.xml | 2 +- spring-activiti/pom.xml | 17 +++++ .../ActivitiController.java | 31 ++++---- .../ActivitiWithSpringApplication.java | 1 - ...=> ActivitiControllerIntegrationTest.java} | 73 +++++++++---------- ...WithSpringApplicationIntegrationTest.java} | 2 +- vavr/pom.xml | 22 ++++++ .../vavr/PatternMatchingUnitTest.java | 18 +++-- .../PropertyBasedLongRunningUnitTest.java | 4 +- .../java/com/baeldung/vavr/VavrUnitTest.java | 56 +++++++------- .../collections/CollectionAPIUnitTest.java | 25 +++---- .../baeldung/vavr/either/EitherUnitTest.java | 38 +++++----- .../exception/handling/VavrTryUnitTest.java | 34 +++++---- .../VavrRepositoryIntegrationTest.java | 8 +- 14 files changed, 189 insertions(+), 142 deletions(-) rename spring-activiti/src/test/java/com/example/activitiwithspring/{ActivitiControllerTest.java => ActivitiControllerIntegrationTest.java} (78%) rename spring-activiti/src/test/java/com/example/activitiwithspring/{ActivitiWithSpringApplicationTests.java => ActivitiWithSpringApplicationIntegrationTest.java} (84%) diff --git a/pom.xml b/pom.xml index eaf7f47a2b..3feba96d5a 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,6 @@ - spring-activiti aws akka-streams algorithms @@ -129,6 +128,7 @@ spark-java spring-5-mvc + spring-activiti spring-akka spring-amqp spring-all diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index 3d2f1386df..c5289b20a6 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -53,6 +53,23 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + true + + 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 3924d31f68..fd184556c4 100644 --- a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java @@ -1,9 +1,5 @@ package com.example.activitiwithspring; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - import org.activiti.engine.RuntimeService; import org.activiti.engine.TaskService; import org.activiti.engine.task.Task; @@ -12,12 +8,15 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.List; +import java.util.stream.Collectors; + @RestController public class ActivitiController { private static final Logger logger = LoggerFactory.getLogger(ActivitiController.class); + @Autowired private RuntimeService runtimeService; @@ -28,32 +27,30 @@ public class ActivitiController { public String startProcess() { runtimeService.startProcessInstanceByKey("my-process"); return "Process started. Number of currently running process instances = " + runtimeService.createProcessInstanceQuery() - .count(); + .count(); } @GetMapping("/get-tasks/{processInstanceId}") public List getTasks(@PathVariable String processInstanceId) { List usertasks = taskService.createTaskQuery() - .processInstanceId(processInstanceId) - .list(); + .processInstanceId(processInstanceId) + .list(); - List tasks = usertasks.stream().map(task -> { - TaskRepresentation taskRepresentation = new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId()); - return taskRepresentation; - }).collect(Collectors.toList()); - return tasks; + return usertasks.stream() + .map(task -> new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId())) + .collect(Collectors.toList()); } @GetMapping("/complete-task-A/{processInstanceId}") public TaskRepresentation completeTaskA(@PathVariable String processInstanceId) { Task task = taskService.createTaskQuery() - .processInstanceId(processInstanceId) - .singleResult(); + .processInstanceId(processInstanceId) + .singleResult(); taskService.complete(task.getId()); logger.info("Task completed"); task = taskService.createTaskQuery() - .processInstanceId(processInstanceId) - .singleResult(); + .processInstanceId(processInstanceId) + .singleResult(); return new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId()); } diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java index e98b8ad7ca..2cfacdcf0d 100644 --- a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java @@ -5,7 +5,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ActivitiWithSpringApplication { - public static void main(String[] args) { SpringApplication.run(ActivitiWithSpringApplication.class, args); } diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerTest.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java similarity index 78% rename from spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerTest.java rename to spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java index 3176207664..baca58f6ff 100644 --- a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerTest.java +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java @@ -1,10 +1,6 @@ package com.example.activitiwithspring; -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.List; - +import com.fasterxml.jackson.databind.ObjectMapper; import org.activiti.engine.RuntimeService; import org.activiti.engine.runtime.ProcessInstance; import org.junit.Before; @@ -21,13 +17,16 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @SpringBootTest -public class ActivitiControllerTest { - private static final Logger logger = LoggerFactory.getLogger(ActivitiControllerTest.class); +public class ActivitiControllerIntegrationTest { + private static final Logger logger = LoggerFactory.getLogger(ActivitiControllerIntegrationTest.class); private MockMvc mockMvc; @Autowired @@ -39,10 +38,10 @@ public class ActivitiControllerTest { @Before public void setUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) - .build(); + .build(); for (ProcessInstance instance : runtimeService.createProcessInstanceQuery() - .list()) { + .list()) { runtimeService.deleteProcessInstance(instance.getId(), "Reset Processes"); } } @@ -51,21 +50,21 @@ public class ActivitiControllerTest { public void givenProcess_whenStartProcess_thenIncreaseInProcessInstanceCount() throws Exception { String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) - .andReturn() - .getResponse() - .getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); assertEquals("Process started. Number of currently running process instances = 1", responseBody); responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) - .andReturn() - .getResponse() - .getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); assertEquals("Process started. Number of currently running process instances = 2", responseBody); responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) - .andReturn() - .getResponse() - .getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); assertEquals("Process started. Number of currently running process instances = 3", responseBody); } @@ -73,19 +72,19 @@ public class ActivitiControllerTest { public void givenProcess_whenProcessInstance_thenReceivedRunningTask() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) - .andReturn() - .getResponse(); + .andReturn() + .getResponse(); ProcessInstance pi = runtimeService.createProcessInstanceQuery() - .orderByProcessInstanceId() - .desc() - .list() - .get(0); + .orderByProcessInstanceId() + .desc() + .list() + .get(0); logger.info("process instance = " + pi.getId()); String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/get-tasks/" + pi.getId())) - .andReturn() - .getResponse() - .getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); ObjectMapper mapper = new ObjectMapper(); List tasks = Arrays.asList(mapper.readValue(responseBody, TaskRepresentation[].class)); @@ -98,19 +97,19 @@ public class ActivitiControllerTest { public void givenProcess_whenCompleteTaskA_thenReceivedNextTask() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) - .andReturn() - .getResponse(); + .andReturn() + .getResponse(); ProcessInstance pi = runtimeService.createProcessInstanceQuery() - .orderByProcessInstanceId() - .desc() - .list() - .get(0); + .orderByProcessInstanceId() + .desc() + .list() + .get(0); logger.info("process instance = " + pi.getId()); String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/complete-task-A/" + pi.getId())) - .andReturn() - .getResponse() - .getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); ObjectMapper mapper = new ObjectMapper(); TaskRepresentation task = mapper.readValue(responseBody, TaskRepresentation.class); diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java similarity index 84% rename from spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationTests.java rename to spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java index da22c6c7fa..7460c302d8 100644 --- a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationTests.java +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class ActivitiWithSpringApplicationTests { +public class ActivitiWithSpringApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/vavr/pom.xml b/vavr/pom.xml index d35a408389..426155263c 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -71,4 +71,26 @@ 4.12 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + true + + + + + \ No newline at end of file diff --git a/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java index 1adff2e845..1c7d70a9a4 100644 --- a/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java @@ -1,18 +1,24 @@ package com.baeldung.vavr; +import io.vavr.MatchError; +import io.vavr.control.Option; +import org.junit.Test; + import static io.vavr.API.$; import static io.vavr.API.Case; import static io.vavr.API.Match; import static io.vavr.API.run; -import static io.vavr.Predicates.*; +import static io.vavr.Predicates.allOf; +import static io.vavr.Predicates.anyOf; +import static io.vavr.Predicates.instanceOf; +import static io.vavr.Predicates.is; +import static io.vavr.Predicates.isIn; +import static io.vavr.Predicates.isNotNull; +import static io.vavr.Predicates.isNull; +import static io.vavr.Predicates.noneOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import org.junit.Test; - -import io.vavr.MatchError; -import io.vavr.control.Option; - public class PatternMatchingUnitTest { @Test public void whenMatchesDefault_thenCorrect() { diff --git a/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java index 8409dbfa60..e93084f2c0 100644 --- a/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java @@ -9,7 +9,9 @@ import org.junit.Test; import java.util.function.Predicate; -import static io.vavr.API.*; +import static io.vavr.API.$; +import static io.vavr.API.Case; +import static io.vavr.API.Match; public class PropertyBasedLongRunningUnitTest { diff --git a/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java index 5ddd344c5c..08a5e20b40 100644 --- a/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java @@ -5,7 +5,9 @@ import io.vavr.Function1; import io.vavr.Function2; import io.vavr.Function5; import io.vavr.Lazy; -import io.vavr.*; +import io.vavr.Tuple; +import io.vavr.Tuple2; +import io.vavr.Tuple3; import io.vavr.collection.List; import io.vavr.collection.Seq; import io.vavr.control.Option; @@ -13,23 +15,25 @@ import io.vavr.control.Try; import io.vavr.control.Validation; import org.junit.Test; -import com.baeldung.vavr.Person; -import com.baeldung.vavr.PersonValidator; - import java.util.Arrays; import java.util.Collections; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.IntStream; -import static io.vavr.API.*; -import static org.junit.Assert.*; +import static io.vavr.API.$; +import static io.vavr.API.Case; +import static io.vavr.API.Match; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class VavrUnitTest { @Test public void givenList_whenSorts_thenCorrect() { List sortedList = List.of(3, 2, 1) - .sorted(); + .sorted(); } /* @@ -123,7 +127,7 @@ public class VavrUnitTest { @Test public void whenCreatesFunction_thenCorrect0() { Function0 getClazzName = () -> this.getClass() - .getName(); + .getName(); String clazzName = getClazzName.apply(); assertEquals("com.baeldung.vavr.VavrUnitTest", clazzName); } @@ -257,7 +261,7 @@ public class VavrUnitTest { public void whenSumsJava8List_thenCorrect() { // Arrays.asList(1, 2, 3).stream().reduce((i, j) -> i + j); int sum = IntStream.of(1, 2, 3) - .sum(); + .sum(); assertEquals(6, sum); } @@ -273,8 +277,8 @@ public class VavrUnitTest { @Test public void whenSumsVavrList_thenCorrect() { int sum = List.of(1, 2, 3) - .sum() - .intValue(); + .sum() + .intValue(); assertEquals(6, sum); } @@ -307,21 +311,21 @@ public class VavrUnitTest { int input = 2; String output; switch (input) { - case 0: - output = "zero"; - break; - case 1: - output = "one"; - break; - case 2: - output = "two"; - break; - case 3: - output = "three"; - break; - default: - output = "unknown"; - break; + case 0: + output = "zero"; + break; + case 1: + output = "one"; + break; + case 2: + output = "two"; + break; + case 3: + output = "three"; + break; + default: + output = "unknown"; + break; } assertEquals("two", output); } diff --git a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java index 9f0c48e3ee..4b4eb55fc5 100644 --- a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java @@ -1,17 +1,5 @@ package com.baeldung.vavr.collections; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.util.Comparator; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import org.junit.Test; - import io.vavr.Tuple; import io.vavr.Tuple2; import io.vavr.collection.Array; @@ -28,6 +16,17 @@ import io.vavr.collection.Stream; import io.vavr.collection.TreeMap; import io.vavr.collection.TreeSet; import io.vavr.collection.Vector; +import org.junit.Test; + +import java.util.Comparator; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; public class CollectionAPIUnitTest { @@ -234,7 +233,7 @@ public class CollectionAPIUnitTest { .toJavaMap(i -> Tuple.of(i, Integer.valueOf(i))); assertEquals(new Integer(2), map.get("2")); } - + @Test public void givenVavrList_whenCollected_thenCorrect() { java.util.Set javaSet = List.of(1, 2, 3) diff --git a/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java index 6b0a34f9e4..155932888d 100644 --- a/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java @@ -7,32 +7,32 @@ import static org.junit.Assert.assertEquals; public class EitherUnitTest { - @Test - public void givenMarks_whenPassNumber_thenExpectNumber() { - Either result = EitherDemo.computeWithEither(100); - int marks = result.right() - .getOrElseThrow(x -> new IllegalStateException()); + @Test + public void givenMarks_whenPassNumber_thenExpectNumber() { + Either result = EitherDemo.computeWithEither(100); + int marks = result.right() + .getOrElseThrow(x -> new IllegalStateException()); - assertEquals(100, marks); - } + assertEquals(100, marks); + } - @Test - public void givenMarks_whenFailNumber_thenExpectErrorMesssage() { - Either result = EitherDemo.computeWithEither(50); - String error = result.left() + @Test + public void givenMarks_whenFailNumber_thenExpectErrorMesssage() { + Either result = EitherDemo.computeWithEither(50); + String error = result.left() .getOrNull(); - assertEquals("Marks not acceptable", error); - } + assertEquals("Marks not acceptable", error); + } - @Test - public void givenPassMarks_whenModified_thenExpectNumber() { - Either result = EitherDemo.computeWithEither(90); - int marks = result.right() + @Test + public void givenPassMarks_whenModified_thenExpectNumber() { + Either result = EitherDemo.computeWithEither(90); + int marks = result.right() .map(x -> x * 2) .get(); - assertEquals(180, marks); - } + assertEquals(180, marks); + } } diff --git a/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java index 9c3e5a9cae..c7f17c2afc 100644 --- a/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java @@ -3,16 +3,18 @@ package com.baeldung.vavr.exception.handling; import com.baeldung.vavr.exception.handling.client.ClientException; import com.baeldung.vavr.exception.handling.client.HttpClient; import com.baeldung.vavr.exception.handling.client.Response; -import com.baeldung.vavr.exception.handling.VavrTry; - import io.vavr.collection.Stream; import io.vavr.control.Option; import io.vavr.control.Try; import org.junit.Test; -import static io.vavr.API.*; +import static io.vavr.API.$; +import static io.vavr.API.Case; +import static io.vavr.API.Match; import static io.vavr.Predicates.instanceOf; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; public class VavrTryUnitTest { @@ -26,8 +28,8 @@ public class VavrTryUnitTest { //when Try response = new VavrTry(httpClient).getResponse(); Integer chainedResult = response - .map(this::actionThatTakesResponse) - .getOrElse(defaultChainedResult); + .map(this::actionThatTakesResponse) + .getOrElse(defaultChainedResult); Stream stream = response.toStream().map(it -> it.id); //then @@ -49,8 +51,8 @@ public class VavrTryUnitTest { //when Try response = new VavrTry(httpClient).getResponse(); Integer chainedResult = response - .map(this::actionThatTakesResponse) - .getOrElse(defaultChainedResult); + .map(this::actionThatTakesResponse) + .getOrElse(defaultChainedResult); Option optionalResponse = response.toOption(); //then @@ -70,9 +72,9 @@ public class VavrTryUnitTest { //when Try recovered = new VavrTry(httpClient).getResponse() - .recover(r -> Match(r).of( - Case($(instanceOf(ClientException.class)), defaultResponse) - )); + .recover(r -> Match(r).of( + Case($(instanceOf(ClientException.class)), defaultResponse) + )); //then assertTrue(recovered.isFailure()); @@ -92,10 +94,10 @@ public class VavrTryUnitTest { //when Try recovered = new VavrTry(httpClient).getResponse() - .recover(r -> Match(r).of( - Case($(instanceOf(ClientException.class)), defaultResponse), - Case($(instanceOf(IllegalArgumentException.class)), defaultResponse) - )); + .recover(r -> Match(r).of( + Case($(instanceOf(ClientException.class)), defaultResponse), + Case($(instanceOf(IllegalArgumentException.class)), defaultResponse) + )); //then assertTrue(recovered.isSuccess()); @@ -106,7 +108,7 @@ public class VavrTryUnitTest { return response.id.hashCode(); } - public int actionThatTakesTryResponse(Try response, int defaultTransformation){ + public int actionThatTakesTryResponse(Try response, int defaultTransformation) { return response.transform(responses -> response.map(it -> it.id.hashCode()).getOrElse(defaultTransformation)); } diff --git a/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java b/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java index c2e9f377dd..63338afc24 100644 --- a/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java @@ -3,18 +3,18 @@ package com.baeldung.vavr.repositories; import com.baeldung.Application; import com.baeldung.repositories.VavrUserRepository; import com.baeldung.vavr.User; - import io.vavr.collection.Seq; import io.vavr.control.Option; - -import org.junit.Test; import org.junit.Before; +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; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) From a3ed5a57a3989d36d1ac786a657d06fee02beef8 Mon Sep 17 00:00:00 2001 From: Syed Ali Raza Date: Tue, 1 Aug 2017 20:40:23 +0500 Subject: [PATCH 23/32] BAEL-1051: Introduction to Hoverfly Java (#2320) * BAEL-1051: Fixed merge issue * BAEL-1051: Updated examples based on review * BAEL-1051: Fixed Merge Issues --- libraries/pom.xml | 6 +- .../baeldung/hoverfly/HoverflyApiTest.java | 140 ++++++++++++++++++ 2 files changed, 145 insertions(+), 1 deletion(-) create mode 100644 libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index 795f255f36..efdf20423a 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -20,7 +20,6 @@ maven-bundle-plugin 3.3.0 maven-plugin - true @@ -182,6 +181,11 @@ jetty-servlet ${jetty.version} + + io.specto + hoverfly-java + 0.8.0 + org.apache.httpcomponents httpclient diff --git a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java new file mode 100644 index 0000000000..bdaf4d7bd9 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java @@ -0,0 +1,140 @@ +package com.baeldung.hoverfly; + +import static io.specto.hoverfly.junit.core.SimulationSource.dsl; +import static io.specto.hoverfly.junit.dsl.HoverflyDsl.service; +import static io.specto.hoverfly.junit.dsl.HttpBodyConverter.jsonWithSingleQuotes; +import static io.specto.hoverfly.junit.dsl.ResponseCreators.success; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.any; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsTo; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToJson; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToXml; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matches; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.startsWith; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesJsonPath; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesXPath; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.lang3.time.StopWatch; +import org.junit.ClassRule; +import org.junit.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import io.specto.hoverfly.junit.core.SimulationSource; +import io.specto.hoverfly.junit.rule.HoverflyRule; + +public class HoverflyApiTest { + + private static final SimulationSource source = dsl( + service("http://www.baeldung.com") + .get("/api/courses/1") + .willReturn(success().body( + jsonWithSingleQuotes("{'id':'1','name':'HCI'}"))) + + .post("/api/courses") + .willReturn(success()) + + .andDelay(3, TimeUnit.SECONDS) + .forMethod("POST"), + + service(matches("www.*dung.com")) + .get(startsWith("/api/student")) + .queryParam("page", any()) + .willReturn(success()) + + .post(equalsTo("/api/student")) + .body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}"))) + .willReturn(success()) + + .put("/api/student/1") + .body(matchesJsonPath("$.name")) + .willReturn(success()) + + .post("/api/student") + .body(equalsToXml("2John")) + .willReturn(success()) + + .put("/api/student/2") + .body(matchesXPath("/student/name")) + .willReturn(success())); + + @ClassRule + public static final HoverflyRule rule = HoverflyRule.inSimulationMode(source); + private final RestTemplate restTemplate = new RestTemplate(); + + @Test + public void givenGetCourseById_whenRequestSimulated_thenAPICalledSuccessfully() throws URISyntaxException { + final ResponseEntity courseResponse = restTemplate.getForEntity( + "http://www.baeldung.com/api/courses/1", String.class); + + assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); + assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody()); + } + + @Test + public void givenPostCourse_whenDelayInRequest_thenResponseIsDelayed() throws URISyntaxException { + StopWatch stopWatch = new StopWatch(); + stopWatch.start(); + final ResponseEntity postResponse = restTemplate.postForEntity( + "http://www.baeldung.com/api/courses", null, Void.class); + stopWatch.stop(); + long postTime = stopWatch.getTime(); + + assertEquals(HttpStatus.OK, postResponse.getStatusCode()); + assertTrue(3L <= TimeUnit.MILLISECONDS.toSeconds(postTime)); + } + + @Test + public void givenGetStudent_whenRequestMatcher_thenAPICalledSuccessfully() throws URISyntaxException { + final ResponseEntity courseResponse = restTemplate.getForEntity( + "http://www.baeldung.com/api/student?page=3", Void.class); + + assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); + } + + @Test + public void givenPostStudent_whenBodyRequestMatcherJson_thenResponseContainsEqualJson() throws URISyntaxException { + final ResponseEntity postResponse = restTemplate.postForEntity( + "http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class); + + assertEquals(HttpStatus.OK, postResponse.getStatusCode()); + } + + @Test + public void givenPutStudent_whenJsonPathMatcher_thenRequestJsonContainsElementInPath() throws URISyntaxException { + RequestEntity putRequest = RequestEntity + .put(new URI("http://www.baeldung.com/api/student/1")) + .body("{\"id\":\"1\",\"name\":\"Trevor\"}"); + + ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); + assertEquals(HttpStatus.OK, putResponse.getStatusCode()); + } + + @Test + public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException { + final ResponseEntity postResponse = restTemplate.postForEntity( + "http://www.baeldung.com/api/student", "2John", Void.class); + + assertEquals(HttpStatus.OK, postResponse.getStatusCode()); + } + + + @Test + public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException { + RequestEntity putRequest = RequestEntity + .put(new URI("http://www.baeldung.com/api/student/2")) + .body("" + + "2Monica"); + + ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); + assertEquals(HttpStatus.OK, putResponse.getStatusCode()); + } +} From 6fcbc9b065e88f65e47c4785d6ae83f22739a2e7 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Tue, 1 Aug 2017 22:31:21 +0100 Subject: [PATCH 24/32] 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 056db0c3fe..074075b5cc 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 9f119fe45d..8a2b94e53b 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 java.io.IOException; 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 25/32] 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 0000000000..8ae8d25cd7 --- /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 0000000000..47398ddcb8 --- /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 0000000000..0cc458c414 --- /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 26/32] 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 47398ddcb8..fa997b563d 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 class toLength implements Transformer { @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 0cc458c414..99ac0351be 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 class RxJavaCustomOperatorUnitTest { @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 27/32] 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 8ae8d25cd7..9abdd7e07d 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 @@ package com.baelding.rxjava.operator; 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 fa997b563d..ea954aa71c 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; 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 99ac0351be..ca1169486e 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; 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 class RxJavaCustomOperatorUnitTest { 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 class RxJavaCustomOperatorUnitTest { 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 28/32] 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 0cfb3e6dee..14590f3de4 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 9ace968bbe..b62ccae465 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 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @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 0000000000..e43238f8a6 --- /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 0000000000..b7a9256fc0 --- /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 0000000000..257dbc718a --- /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 d6bbf5eabd..3e5b416191 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 class WebInitializer implements WebApplicationInitializer { 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 0000000000..55179938fc --- /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 0000000000..8016f98d85 --- /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 0000000000..8dce9a88c9 --- /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 0000000000..291077fc2e --- /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 0000000000..c98f3283c0 --- /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 0000000000..7c2d9c73b1 --- /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 b6f1065cad..0000000000 --- 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 29/32] 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 9abdd7e07d..f6cf9fba68 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 @@ package com.baelding.rxjava.operator; 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 ea954aa71c..006d59de36 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 @@ package com.baelding.rxjava.operator; 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 040936a67a..458091fd1c 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 class RxJavaBackpressureLongRunningUnitTest { 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 class RxJavaBackpressureLongRunningUnitTest { 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 class RxJavaBackpressureLongRunningUnitTest { 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 class RxJavaBackpressureLongRunningUnitTest { 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 ca1169486e..a49103196c 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.Operator; 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 class RxJavaCustomOperatorUnitTest { @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 class RxJavaCustomOperatorUnitTest { @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 class RxJavaCustomOperatorUnitTest { 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 30/32] 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 a439de8a05..1b8b767ae3 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 608e8a6819..ed57088c56 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 @@ package org.baeldung.config; 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 31/32] 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 d267bd6406..69b0b6d3ef 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 static java.util.stream.Collectors.toSet; 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 32/32] 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 0000000000..9ea9f027fc --- /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 0000000000..c1c0f8823c --- /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 0000000000..7788305ea1 --- /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 0000000000..fc50730dfa --- /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 + } +}