From 8bcdfec23e382661627b55a7860f8ae803e0d8f4 Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Fri, 13 Jul 2018 02:26:19 +0530 Subject: [PATCH 01/12] Evaluation Article - Spring web-flux --- spring-5-reactive-webflux/pom.xml | 60 +++++++++++++++++ .../reactive/Spring5ReactiveApplication.java | 15 +++++ .../reactive/client/CabLocationConsumer.java | 66 +++++++++++++++++++ .../reactive/controller/CabController.java | 41 ++++++++++++ .../baeldung/reactive/model/CabLocation.java | 52 +++++++++++++++ .../baeldung/reactive/service/CabService.java | 66 +++++++++++++++++++ .../src/main/resources/logback.xml | 15 +++++ spring-5-reactive-webflux/src/site/site.xml | 26 ++++++++ .../baeldung/reactive/CapLocationTests.java | 66 +++++++++++++++++++ 9 files changed, 407 insertions(+) create mode 100644 spring-5-reactive-webflux/pom.xml create mode 100644 spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java create mode 100644 spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/client/CabLocationConsumer.java create mode 100644 spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/controller/CabController.java create mode 100644 spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/model/CabLocation.java create mode 100644 spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/service/CabService.java create mode 100644 spring-5-reactive-webflux/src/main/resources/logback.xml create mode 100644 spring-5-reactive-webflux/src/site/site.xml create mode 100644 spring-5-reactive-webflux/src/test/java/com/baeldung/reactive/CapLocationTests.java diff --git a/spring-5-reactive-webflux/pom.xml b/spring-5-reactive-webflux/pom.xml new file mode 100644 index 0000000000..891f997789 --- /dev/null +++ b/spring-5-reactive-webflux/pom.xml @@ -0,0 +1,60 @@ + + + + 4.0.0 + + com.baeldung + spring-5-reactive-webflux + 1.0-SNAPSHOT + + spring-5-reactive-webflux + A simple spring-5-reactive-webflux. + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-websocket + + + org.springframework.boot + spring-boot-starter-test + test + + + io.projectreactor + reactor-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.reactive.Spring5ReactiveApplication + JAR + + + + + diff --git a/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java new file mode 100644 index 0000000000..d4546efbeb --- /dev/null +++ b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.reactive; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * A Spring 5 reactive application + * + */ +@SpringBootApplication +public class Spring5ReactiveApplication { + public static void main(String[] args) { + SpringApplication.run(Spring5ReactiveApplication.class, args); + } +} diff --git a/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/client/CabLocationConsumer.java b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/client/CabLocationConsumer.java new file mode 100644 index 0000000000..42d96f30b8 --- /dev/null +++ b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/client/CabLocationConsumer.java @@ -0,0 +1,66 @@ +/** + * + */ +package com.baeldung.reactive.client; + +import java.util.UUID; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.reactive.function.client.WebClient; + +import com.baeldung.reactive.model.CabLocation; + +/** + * @author swpraman + * + */ +public class CabLocationConsumer { + + private static final Logger logger = LoggerFactory.getLogger(CabLocationConsumer.class); + + /** + * Main method to consume locations of a cab as a stream + * @param args + */ + public static void main(String[] args) { + + // The id of the booked cab + String cabId = UUID.randomUUID().toString(); + + // URI of the API + String uri = "http://localhost:8080/cab/location/" + cabId; + + // @formatter:off + WebClient.create(uri) + .get() + .retrieve() + .bodyToFlux(CabLocation.class) + .subscribe(CabLocationConsumer::showLocation); + //@formatter:on + + sleepIndefinitely(); + } + + /** + * Helper method to print location of the cab as received from stream + * @param location + */ + private static void showLocation(CabLocation location) { + logger.debug("Current Location : {}", location); + } + + /** + * This method blocks the current thread indefinitely + */ + private static void sleepIndefinitely() { + try { + while (true) { + Thread.sleep(10000); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + +} diff --git a/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/controller/CabController.java b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/controller/CabController.java new file mode 100644 index 0000000000..c9d54f917a --- /dev/null +++ b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/controller/CabController.java @@ -0,0 +1,41 @@ +/** + * + */ +package com.baeldung.reactive.controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.reactive.model.CabLocation; +import com.baeldung.reactive.service.CabService; + +import reactor.core.publisher.Flux; + +/** + * @author swpraman + * + */ +@RestController +public class CabController { + + /** + * Logger instance + */ + private static final Logger logger = LoggerFactory.getLogger(CabController.class); + + @Autowired + private CabService cabService; + + // Server sends location of the cab at the interval of 1 sec + @GetMapping(value = "cab/location/{cabId}", produces = MediaType.APPLICATION_STREAM_JSON_VALUE) + public Flux cabLocation(@PathVariable("cabId") String cabId) { + logger.debug("Getting location stream for cabId: {}", cabId); + return cabService.getLocation(cabId); + } + +} diff --git a/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/model/CabLocation.java b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/model/CabLocation.java new file mode 100644 index 0000000000..dc1ed44520 --- /dev/null +++ b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/model/CabLocation.java @@ -0,0 +1,52 @@ +/** + * + */ +package com.baeldung.reactive.model; + +import java.io.Serializable; + +/** + * @author swapanpramanick2004 + * + */ +public class CabLocation implements Serializable { + + /** + * Serial version UID + */ + private static final long serialVersionUID = -3923503044822400093L; + + private String cabId; + private double latititude; + private double longitude; + + public String getCabId() { + return cabId; + } + + public void setCabId(String cabId) { + this.cabId = cabId; + } + + public double getLatititude() { + return latititude; + } + + public void setLatititude(double latititude) { + this.latititude = latititude; + } + + public double getLongitude() { + return longitude; + } + + public void setLongitude(double longitude) { + this.longitude = longitude; + } + + @Override + public String toString() { + return "CabLocation [cabId=" + cabId + ", latititude=" + latititude + ", longitude=" + longitude + "]"; + } + +} diff --git a/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/service/CabService.java b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/service/CabService.java new file mode 100644 index 0000000000..2cee734ce6 --- /dev/null +++ b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/service/CabService.java @@ -0,0 +1,66 @@ +/** + * + */ +package com.baeldung.reactive.service; + +import java.time.Duration; +import java.util.Random; +import java.util.stream.Stream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import com.baeldung.reactive.model.CabLocation; + +import reactor.core.publisher.Flux; +import reactor.util.function.Tuple2; + +/** + * @author swpraman + * + */ +@Service +public class CabService { + + /** + * Logger instance + */ + private static final Logger logger = LoggerFactory.getLogger(CabService.class); + + /** + * getLocation service for cab + * @param cabId + * @return + */ + public Flux getLocation(String cabId) { + + // Create a flux to retrieve location + Flux locFlux = Flux.fromStream(Stream.generate(() -> retrieveNewLocation(cabId))); + + // Zip the flux with an interval flux + return Flux.interval(Duration.ofSeconds(1)) + .zipWith(locFlux) + .map(Tuple2::getT2); + } + + /** + * A random instance to create random location parameters + */ + private Random random = new Random(); + + /** + * A Dummy method to return random location. + * In a real project it should retrieve the location from a database or any other data source. + * @param cabId + * @return + */ + private CabLocation retrieveNewLocation(String cabId) { + logger.debug("Retrieveing location for cab: {}", cabId); + CabLocation location = new CabLocation(); + location.setCabId(cabId); + location.setLatititude(random.nextDouble()); + location.setLongitude(random.nextDouble()); + return location; + } +} diff --git a/spring-5-reactive-webflux/src/main/resources/logback.xml b/spring-5-reactive-webflux/src/main/resources/logback.xml new file mode 100644 index 0000000000..bf262ff721 --- /dev/null +++ b/spring-5-reactive-webflux/src/main/resources/logback.xml @@ -0,0 +1,15 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + \ No newline at end of file diff --git a/spring-5-reactive-webflux/src/site/site.xml b/spring-5-reactive-webflux/src/site/site.xml new file mode 100644 index 0000000000..7ca22305ea --- /dev/null +++ b/spring-5-reactive-webflux/src/site/site.xml @@ -0,0 +1,26 @@ + + + + + spring-5-reactive-webflux + https://maven.apache.org/images/apache-maven-project.png + https://www.apache.org/ + + + + https://maven.apache.org/images/maven-logo-black-on-white.png + https://maven.apache.org/ + + + + org.apache.maven.skins + maven-fluido-skin + 1.7 + + + + + + + \ No newline at end of file diff --git a/spring-5-reactive-webflux/src/test/java/com/baeldung/reactive/CapLocationTests.java b/spring-5-reactive-webflux/src/test/java/com/baeldung/reactive/CapLocationTests.java new file mode 100644 index 0000000000..821ba8228b --- /dev/null +++ b/spring-5-reactive-webflux/src/test/java/com/baeldung/reactive/CapLocationTests.java @@ -0,0 +1,66 @@ +package com.baeldung.reactive; + +import java.time.Duration; +import java.util.UUID; + +import org.assertj.core.api.Assertions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +import com.baeldung.reactive.controller.CabController; +import com.baeldung.reactive.model.CabLocation; +import com.baeldung.reactive.service.CabService; + +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; +/** + * Unit test for testing Cab Locations + */ +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { CabController.class, CabService.class }) +@WebFluxTest(controllers = { CabController.class }) +public class CapLocationTests { + + @Autowired + private WebTestClient webClient; + + @Test + public void whenGetAPIConsumed_thenShouldPrintTheLocationAtOneSecInterval() { + + // The id of the booked cab + String cabId = UUID.randomUUID().toString(); + + // URI of the API + String uri = "http://localhost:8080/cab/location/" + cabId; + + // @formatter:off + Flux resultFlux = webClient.get() + .uri(uri).accept(MediaType.APPLICATION_STREAM_JSON) + .exchange() + .returnResult(CabLocation.class) + .getResponseBody(); + + + StepVerifier.create(resultFlux) + .expectSubscription() + .thenAwait(Duration.ofSeconds(1)) + .assertNext(location -> Assertions.assertThat(location) + .hasFieldOrPropertyWithValue("cabId", cabId)) + .thenAwait(Duration.ofSeconds(1)) + .assertNext(location -> Assertions.assertThat(location) + .hasFieldOrPropertyWithValue("cabId", cabId)) + .thenAwait(Duration.ofSeconds(1)) + .assertNext(location -> Assertions.assertThat(location) + .hasFieldOrPropertyWithValue("cabId", cabId)) + .thenCancel() + .verify(); + + // @formatter:on + } +} From f03f66a474b439a732a716b4982709b575fbf798 Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Fri, 13 Jul 2018 02:29:40 +0530 Subject: [PATCH 02/12] Evaluation Article - Spring web-flux --- spring-5-reactive-webflux/src/site/site.xml | 26 --------------------- 1 file changed, 26 deletions(-) delete mode 100644 spring-5-reactive-webflux/src/site/site.xml diff --git a/spring-5-reactive-webflux/src/site/site.xml b/spring-5-reactive-webflux/src/site/site.xml deleted file mode 100644 index 7ca22305ea..0000000000 --- a/spring-5-reactive-webflux/src/site/site.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - spring-5-reactive-webflux - https://maven.apache.org/images/apache-maven-project.png - https://www.apache.org/ - - - - https://maven.apache.org/images/maven-logo-black-on-white.png - https://maven.apache.org/ - - - - org.apache.maven.skins - maven-fluido-skin - 1.7 - - - - - - - \ No newline at end of file From 292193e492a98ea06d6dd2596b49a3486733a609 Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Fri, 13 Jul 2018 10:31:01 +0530 Subject: [PATCH 03/12] Evaluation Article - Spring web-flux --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 0d78e88c7c..45fa1b6e72 100644 --- a/pom.xml +++ b/pom.xml @@ -272,6 +272,7 @@ antlr maven-archetype apache-meecrowave + spring-5-reactive-webflux From 9f88e41aa870ed675f3d19ab602d668162994c9e Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Sat, 14 Jul 2018 17:08:08 +0530 Subject: [PATCH 04/12] Evaluation Article - Spring web-flux --- .../baeldung/reactive/model/CabLocation.java | 23 ++++++++++++++----- .../baeldung/reactive/service/CabService.java | 6 +---- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/model/CabLocation.java b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/model/CabLocation.java index dc1ed44520..4bc6589c8a 100644 --- a/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/model/CabLocation.java +++ b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/model/CabLocation.java @@ -17,8 +17,19 @@ public class CabLocation implements Serializable { private static final long serialVersionUID = -3923503044822400093L; private String cabId; - private double latititude; + private double latitude; private double longitude; + + // default constructor + public CabLocation() { + // create a CabLocation with empty values + } + + public CabLocation(String cabId, double latt, double longt) { + this.cabId = cabId; + this.latitude = latt; + this.longitude = longt; + } public String getCabId() { return cabId; @@ -28,12 +39,12 @@ public class CabLocation implements Serializable { this.cabId = cabId; } - public double getLatititude() { - return latititude; + public double getLatitude() { + return latitude; } - public void setLatititude(double latititude) { - this.latititude = latititude; + public void setLatitude(double latititude) { + this.latitude = latititude; } public double getLongitude() { @@ -46,7 +57,7 @@ public class CabLocation implements Serializable { @Override public String toString() { - return "CabLocation [cabId=" + cabId + ", latititude=" + latititude + ", longitude=" + longitude + "]"; + return "CabLocation [cabId=" + cabId + ", latitude=" + latitude + ", longitude=" + longitude + "]"; } } diff --git a/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/service/CabService.java b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/service/CabService.java index 2cee734ce6..9df56474c1 100644 --- a/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/service/CabService.java +++ b/spring-5-reactive-webflux/src/main/java/com/baeldung/reactive/service/CabService.java @@ -57,10 +57,6 @@ public class CabService { */ private CabLocation retrieveNewLocation(String cabId) { logger.debug("Retrieveing location for cab: {}", cabId); - CabLocation location = new CabLocation(); - location.setCabId(cabId); - location.setLatititude(random.nextDouble()); - location.setLongitude(random.nextDouble()); - return location; + return new CabLocation(cabId, random.nextDouble(), random.nextDouble()); } } From d46873405a67addfaa69aa7855b37af9c4a3df14 Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Thu, 9 Aug 2018 02:07:23 +0530 Subject: [PATCH 05/12] core-scala: initial commit --- core-scala/build.gradle | 13 ++ core-scala/build.sbt | 12 ++ core-scala/pom.xml | 111 ++++++++++++++++++ core-scala/project/Dependencies.scala | 5 + core-scala/project/build.properties | 1 + .../com/baeldung/examples/ClassExamples.scala | 31 +++++ .../examples/CollectionExamples.scala | 22 ++++ .../examples/ExceptionHandlingExamples.scala | 19 +++ .../examples/FirstClassFunctionExamples.scala | 17 +++ .../examples/LoopAndCalculationExamples.scala | 39 ++++++ .../scala/com/baeldung/examples/MyApp.scala | 15 +++ .../baeldung/examples/ObjectExamples.scala | 23 ++++ .../com/baeldung/examples/OptionExample.scala | 12 ++ .../examples/PatternMatchingExample.scala | 22 ++++ .../com/baeldung/examples/TraitExample.scala | 23 ++++ .../com/baeldung/examples/TupleExamples.scala | 18 +++ .../examples/VariableDeclaration.scala | 24 ++++ core-scala/src/test/scala/samples/junit.scala | 17 +++ .../src/test/scala/samples/scalatest.scala | 108 +++++++++++++++++ core-scala/src/test/scala/samples/specs.scala | 31 +++++ core-scala/test.txt | 4 + 21 files changed, 567 insertions(+) create mode 100644 core-scala/build.gradle create mode 100644 core-scala/build.sbt create mode 100644 core-scala/pom.xml create mode 100644 core-scala/project/Dependencies.scala create mode 100644 core-scala/project/build.properties create mode 100644 core-scala/src/main/scala/com/baeldung/examples/ClassExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/CollectionExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/ExceptionHandlingExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/FirstClassFunctionExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/LoopAndCalculationExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/MyApp.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/ObjectExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/OptionExample.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/PatternMatchingExample.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/TraitExample.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/TupleExamples.scala create mode 100644 core-scala/src/main/scala/com/baeldung/examples/VariableDeclaration.scala create mode 100644 core-scala/src/test/scala/samples/junit.scala create mode 100644 core-scala/src/test/scala/samples/scalatest.scala create mode 100644 core-scala/src/test/scala/samples/specs.scala create mode 100644 core-scala/test.txt diff --git a/core-scala/build.gradle b/core-scala/build.gradle new file mode 100644 index 0000000000..05b5d5c55a --- /dev/null +++ b/core-scala/build.gradle @@ -0,0 +1,13 @@ +apply plugin: 'scala' + +repositories { + mavenCentral() +} + +dependencies { + compile 'org.scala-lang:scala-library:2.12.6' + testCompile 'org.scalatest:scalatest_2.12:3.0.5' + testCompile 'junit:junit:4.12' +} + + diff --git a/core-scala/build.sbt b/core-scala/build.sbt new file mode 100644 index 0000000000..1e21f71d39 --- /dev/null +++ b/core-scala/build.sbt @@ -0,0 +1,12 @@ +import Dependencies._ + +lazy val root = (project in file(".")). + settings( + inThisBuild(List( + organization := "com.example", + scalaVersion := "2.12.6", + version := "0.1.0-SNAPSHOT" + )), + name := "core-scala", + libraryDependencies += scalaTest % Test + ) diff --git a/core-scala/pom.xml b/core-scala/pom.xml new file mode 100644 index 0000000000..76b6ee0d22 --- /dev/null +++ b/core-scala/pom.xml @@ -0,0 +1,111 @@ + + 4.0.0 + core-scala + 1.0-SNAPSHOT + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 1.8 + 1.8 + UTF-8 + 2.12.6 + 2.12 + 4.2.0 + + + + + org.scala-lang + scala-library + ${scala.version} + + + + + junit + junit + 4.12 + test + + + org.scalatest + scalatest_${scala.compat.version} + 3.0.5 + test + + + org.specs2 + specs2-core_${scala.compat.version} + ${spec2.version} + test + + + org.specs2 + specs2-junit_${scala.compat.version} + ${spec2.version} + test + + + + + src/main/scala + src/test/scala + + + + net.alchim31.maven + scala-maven-plugin + 3.3.2 + + + + compile + testCompile + + + + -dependencyfile + ${project.build.directory}/.scala_dependencies + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.21.0 + + + true + + + + org.scalatest + scalatest-maven-plugin + 2.0.0 + + ${project.build.directory}/surefire-reports + . + TestSuiteReport.txt + + samples.AppTest + + + + test + + test + + + + + + + diff --git a/core-scala/project/Dependencies.scala b/core-scala/project/Dependencies.scala new file mode 100644 index 0000000000..558929deb6 --- /dev/null +++ b/core-scala/project/Dependencies.scala @@ -0,0 +1,5 @@ +import sbt._ + +object Dependencies { + lazy val scalaTest = "org.scalatest" %% "scalatest" % "3.0.5" +} diff --git a/core-scala/project/build.properties b/core-scala/project/build.properties new file mode 100644 index 0000000000..d6e35076cc --- /dev/null +++ b/core-scala/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.1.6 diff --git a/core-scala/src/main/scala/com/baeldung/examples/ClassExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/ClassExamples.scala new file mode 100644 index 0000000000..75a37e2bab --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/ClassExamples.scala @@ -0,0 +1,31 @@ +package com.baeldung.examples + +object ClassExamples extends App { + + import java.time._ + class Customer(val id:Int, val name:String, dob:LocalDate) { + + private var _age = calculateAge(dob) + + def age = _age // getter + def age_= (age:Int) = _age = age //setter + + private def calculateAge(dob:LocalDate) = Period + .between(dob, LocalDate.now) + .getYears + + //override def toString: String = s"(id:${id}, name:${name}, age:${age})" + } + val c = new Customer(1, "Varun Sharma", LocalDate.parse("1980-02-27")) + println(c) + + case class Address(addressLn1:String, area:String, city:String, zip:String) + + val address=Address("102, Raycon Lotus Apartment", "AECS Layout", "Bangalore", "560037") + + val anotherAddress = address.copy(addressLn1="41/2, ITPL Road") + + println(address) + println(anotherAddress) + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/CollectionExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/CollectionExamples.scala new file mode 100644 index 0000000000..1602516067 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/CollectionExamples.scala @@ -0,0 +1,22 @@ +package com.baeldung.examples + +object CollectionExamples extends App { + + val aList = List(5, 3, 9, 2) // create a list + val sortedAscList = aList.sorted // sort ascending + val sortedDescList = aList.sortWith(_ > _) // sort descending + val evenList = aList.filter(_%2 == 0) // filter on some condition + + val mySet = Set(10, 20, 5) // create a set + val changedSet = mySet + 50 // add an element + println(changedSet) + val changedSet2 = mySet - 20 // remove an element + println(changedSet2) + + val capitals = Map("Japan" -> "Tokyo", + "England" -> "London", + "India" -> "New Delhi") // create a map + val capitalOfJapan = capitals("Japan") // get from map + println(capitalOfJapan) + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/ExceptionHandlingExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/ExceptionHandlingExamples.scala new file mode 100644 index 0000000000..16ec7ffdf4 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/ExceptionHandlingExamples.scala @@ -0,0 +1,19 @@ +package com.baeldung.examples + +object ExceptionHandlingExamples extends App { + import java.io._ + def printLines(filename:String) = { + var reader:Option[BufferedReader] = None + try { + reader = Some(new BufferedReader(new FileReader(new File(filename)))) + reader.get.lines().forEach(println(_)) + } catch { + case e:FileNotFoundException => println(s"There was no file named ${filename}") + case e:Throwable => throw new Exception("Some error occurred", e) + } finally { + if (reader.isDefined) reader.get.close() + } + } + printLines("test.txt") + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/FirstClassFunctionExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/FirstClassFunctionExamples.scala new file mode 100644 index 0000000000..bf925f59c7 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/FirstClassFunctionExamples.scala @@ -0,0 +1,17 @@ +package com.baeldung.examples + +object FirstClassFunctionExamples extends App { + + def sum(x:Double, y:Double, f:Double => Double) = f(x) + f(y) + + println(sum(3, 4, x => x*x)) // returns 25.0 + + println(sum(3, 4, x => x*x*x)) // returns 91.0 + + println(sum(3, 4, Math.pow(_, 2))) // returns 25.0 + + def max(first:Int, second:Int) = if (first > second) first else second + + println(max(10, -2)) + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/LoopAndCalculationExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/LoopAndCalculationExamples.scala new file mode 100644 index 0000000000..17091c715d --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/LoopAndCalculationExamples.scala @@ -0,0 +1,39 @@ +package com.baeldung.examples + +object LoopAndCalculationExamples extends App { + import CalculationUtils._ + println(sumWithWhile(Array(10, 20, 30))) + println(sumWithFor(Array(10, 20, 30))) + println(checkEvenOdd((1 to 10).toArray).toList) + println(filterEvens((1 to 10).toArray).toList) +} + +object CalculationUtils { + + def sumWithWhile(values:Array[Int]) = { + var sum = 0 + var i = 0 + while ( i < values.length) { + sum += values(i) + i+=1 + } + sum + } + + def sumWithFor(values:Array[Int]) = { + var sum = 0 + for (i <- values) { + sum += i + } + sum + } + + def checkEvenOdd(values:Array[Int]) = { + for (i <- values) yield if (i%2 == 0) "Even" else "Odd" + } + + def filterEvens(values:Array[Int]) = + for (i <- values if i%2 == 0) + yield i + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/MyApp.scala b/core-scala/src/main/scala/com/baeldung/examples/MyApp.scala new file mode 100644 index 0000000000..d0861a8727 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/MyApp.scala @@ -0,0 +1,15 @@ +package com.baeldung.examples + +/** + * @author ${user.name} + */ +object MyApp { + + def foo(x : Array[String]) = x.foldLeft("")((a,b) => a + b) + + def main(args : Array[String]) { + println( "Hello World!" ) + println("Number of arguments passed:" + args.length) + } + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/ObjectExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/ObjectExamples.scala new file mode 100644 index 0000000000..29db276ebd --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/ObjectExamples.scala @@ -0,0 +1,23 @@ +package com.baeldung.examples + +object ObjectExamples extends App { + + import java.time._ + class Customer(val id:Int, val name:String, private var _age:Int) { + def age = this._age + def age_= (age:Int) = _age = age + } + object Customer { + def apply(id:Int, name:String, age:Int) = new Customer(id, name, age) + + def apply(id:Int, name:String, dob:LocalDate) = { + val p = Period.between(dob, LocalDate.now) + new Customer(id, name, p.getYears) + } + } + val c = Customer(1, "Varun Sharma", LocalDate.parse("1980-02-27")) + + c.age = 20 + println(c.age) + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/OptionExample.scala b/core-scala/src/main/scala/com/baeldung/examples/OptionExample.scala new file mode 100644 index 0000000000..b0d49af758 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/OptionExample.scala @@ -0,0 +1,12 @@ +package com.baeldung.examples + +object OptionExample extends App { + + def minimumEvenNumber(data:Array[Int]) = { + val evens = data.filter(_%2 == 0) + if (evens.isEmpty) None else Some(evens.min) + } + + val minEven = minimumEvenNumber(Array(21, 3, 11, 7)).getOrElse(0) + println(minEven) +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/PatternMatchingExample.scala b/core-scala/src/main/scala/com/baeldung/examples/PatternMatchingExample.scala new file mode 100644 index 0000000000..d476bed60b --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/PatternMatchingExample.scala @@ -0,0 +1,22 @@ +package com.baeldung.examples + +object PatternMatchingExample extends App { + + abstract class Item + case class Book(title:String, author:String, price:Double) extends Item + case class MusicCD(title:String, genre:String, price:Double) extends Item + + def describe(item:Item) = item match { + + case b:Book if b.price > 1000 => println(s"The book ${b.title} is expensive") + + case b:Book => println(s"The book ${b.title} is written by ${b.author}.") + + case MusicCD(title, "Jazz", _) => println(s"This is a CD of Jazz music.") + + case _ => println("Unknown Item") + + } + + describe(Book("Half Girlfriend", "Chetan Bhagat", 100)) +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/TraitExample.scala b/core-scala/src/main/scala/com/baeldung/examples/TraitExample.scala new file mode 100644 index 0000000000..0775a2bac2 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/TraitExample.scala @@ -0,0 +1,23 @@ +package com.baeldung.examples + +import java.io._ + +object TraitExample extends App { + + trait Loggable { + val logger:PrintStream + def getPrefix():String + def log(message:String) = logger.println(s"[${getPrefix()}]:${message}") + } + object CustomerService extends Loggable { + override val logger = System.out + override def getPrefix(): String = "CustomerService" + def retrieve(id:String) = { + log(s"Retrieve with id ${id} called") + // Code to retrieve Customer from DB + } + } + + CustomerService.retrieve("C100") + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/TupleExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/TupleExamples.scala new file mode 100644 index 0000000000..e9ffbd0aca --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/TupleExamples.scala @@ -0,0 +1,18 @@ +package com.baeldung.examples + +object TupleExamples extends App { + + val empSal:(String, Int) = ("David", 10000) + + def getMaxMinSalary(empSal:Array[(String, Int)]) = { + val minEmpSal = empSal.minBy(empSal => empSal._2) + val maxEmpSal = empSal.maxBy(empSal => empSal._2) + (maxEmpSal._2, minEmpSal._2) + } + val empSalArr = Array(("David", 12000), ("Maria", 15000), + ("Elisa", 11000), ("Adam", 8000)) + + val (maxSalary, minSalary) = getMaxMinSalary(empSalArr) + println("Max Salary: " + maxSalary + " and Min Salary: " + minSalary) + +} diff --git a/core-scala/src/main/scala/com/baeldung/examples/VariableDeclaration.scala b/core-scala/src/main/scala/com/baeldung/examples/VariableDeclaration.scala new file mode 100644 index 0000000000..6050b4f908 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/examples/VariableDeclaration.scala @@ -0,0 +1,24 @@ +package com.baeldung.examples + +object VariableDeclaration extends App { + + val x:Int = 0 + var friend:String = "David" + lazy val greet = "Hello" + friend + val data = Array(2, 4, 5) + + printHelloWorld() + println(sum(10, 20)) + + def printHelloWorld():Unit = { + println("Hello World") + } + + def sum(x:Int, y:Int) = x + y + + def sayGreeting(to:String, greet:String="Hi", message:String = "How are you?") = println(greet + " " + to + ", " + message) + + sayGreeting(to="David", message="How are you doing?") + sayGreeting(greet="Hello", to="Maria") + +} diff --git a/core-scala/src/test/scala/samples/junit.scala b/core-scala/src/test/scala/samples/junit.scala new file mode 100644 index 0000000000..89513d5bbc --- /dev/null +++ b/core-scala/src/test/scala/samples/junit.scala @@ -0,0 +1,17 @@ +package samples + +import org.junit._ +import Assert._ + +@Test +class AppTest { + + @Test + def testOK() = assertTrue(true) + +// @Test +// def testKO() = assertTrue(false) + +} + + diff --git a/core-scala/src/test/scala/samples/scalatest.scala b/core-scala/src/test/scala/samples/scalatest.scala new file mode 100644 index 0000000000..bd10412199 --- /dev/null +++ b/core-scala/src/test/scala/samples/scalatest.scala @@ -0,0 +1,108 @@ +/* + * Copyright 2001-2009 Artima, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package samples + +/* +ScalaTest facilitates different styles of testing by providing traits you can mix +together to get the behavior and syntax you prefer. A few examples are +included here. For more information, visit: + +http://www.scalatest.org/ + +One way to use ScalaTest is to help make JUnit or TestNG tests more +clear and concise. Here's an example: +*/ +import scala.collection._ +import org.scalatest.Assertions +import org.junit.Test + +class StackSuite extends Assertions { + + @Test def stackShouldPopValuesIinLastInFirstOutOrder() { + val stack = new mutable.ArrayStack[Int] + stack.push(1) + stack.push(2) + assert(stack.pop() === 2) + assert(stack.pop() === 1) + } + + @Test def stackShouldThrowRuntimeExceptionIfAnEmptyArrayStackIsPopped() { + val emptyStack = new mutable.ArrayStack[String] + intercept[RuntimeException] { + emptyStack.pop() + } + } +} + +/* +Here's an example of a FunSuite with Matchers mixed in: +*/ +import org.scalatest.FunSuite +import org.scalatest.Matchers + +import org.junit.runner.RunWith +import org.scalatest.junit.JUnitRunner +@RunWith(classOf[JUnitRunner]) +class ListSuite extends FunSuite with Matchers { + + test("An empty list should be empty") { + List() should be ('empty) + Nil should be ('empty) + } + + test("A non-empty list should not be empty") { + List(1, 2, 3) should not be ('empty) + List("fee", "fie", "foe", "fum") should not be ('empty) + } + + test("A list's length should equal the number of elements it contains") { + List() should have length (0) + List(1, 2) should have length (2) + List("fee", "fie", "foe", "fum") should have length (4) + } +} + +/* +ScalaTest also supports the behavior-driven development style, in which you +combine tests with text that specifies the behavior being tested. Here's +an example whose text output when run looks like: + +A Map +- should only contain keys and values that were added to it +- should report its size as the number of key/value pairs it contains +*/ +import org.scalatest.FunSpec + +class ExampleSpec extends FunSpec { + + describe("An ArrayStack") { + + it("should pop values in last-in-first-out order") { + val stack = new mutable.ArrayStack[Int] + stack.push(1) + stack.push(2) + assert(stack.pop() === 2) + assert(stack.pop() === 1) + } + + it("should throw RuntimeException if an empty array stack is popped") { + val emptyStack = new mutable.ArrayStack[Int] + intercept[RuntimeException] { + emptyStack.pop() + } + } + } +} diff --git a/core-scala/src/test/scala/samples/specs.scala b/core-scala/src/test/scala/samples/specs.scala new file mode 100644 index 0000000000..9e4dfe93bb --- /dev/null +++ b/core-scala/src/test/scala/samples/specs.scala @@ -0,0 +1,31 @@ +package samples + +import org.junit.runner.RunWith +import org.specs2.mutable._ +import org.specs2.runner._ + + +/** + * Sample specification. + * + * This specification can be executed with: scala -cp ${package}.SpecsTest + * Or using maven: mvn test + * + * For more information on how to write or run specifications, please visit: + * http://etorreborre.github.com/specs2/guide/org.specs2.guide.Runners.html + * + */ +@RunWith(classOf[JUnitRunner]) +class MySpecTest extends Specification { + "The 'Hello world' string" should { + "contain 11 characters" in { + "Hello world" must have size(11) + } + "start with 'Hello'" in { + "Hello world" must startWith("Hello") + } + "end with 'world'" in { + "Hello world" must endWith("world") + } + } +} diff --git a/core-scala/test.txt b/core-scala/test.txt new file mode 100644 index 0000000000..da431d2039 --- /dev/null +++ b/core-scala/test.txt @@ -0,0 +1,4 @@ +Hi, +This is the lines +from the test file. +Thanks. \ No newline at end of file From 63d89a6b42407c775e6e7c5079aa627640e15856 Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Thu, 9 Aug 2018 02:29:46 +0530 Subject: [PATCH 06/12] adding core-scala to pom --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index a9aaff3e22..1be2bb6120 100644 --- a/pom.xml +++ b/pom.xml @@ -315,6 +315,7 @@ core-java-persistence core-kotlin core-groovy + core-scala core-java-concurrency couchbase deltaspike From b7b9c2baa44b6ce44e06eda6f5d582f462922b83 Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Tue, 11 Sep 2018 21:14:15 +0530 Subject: [PATCH 07/12] Revert "core-scala: initial commit" This reverts commit d46873405a67addfaa69aa7855b37af9c4a3df14. --- core-scala/build.gradle | 13 -- core-scala/build.sbt | 12 -- core-scala/pom.xml | 111 ------------------ core-scala/project/Dependencies.scala | 5 - core-scala/project/build.properties | 1 - .../com/baeldung/examples/ClassExamples.scala | 31 ----- .../examples/CollectionExamples.scala | 22 ---- .../examples/ExceptionHandlingExamples.scala | 19 --- .../examples/FirstClassFunctionExamples.scala | 17 --- .../examples/LoopAndCalculationExamples.scala | 39 ------ .../scala/com/baeldung/examples/MyApp.scala | 15 --- .../baeldung/examples/ObjectExamples.scala | 23 ---- .../com/baeldung/examples/OptionExample.scala | 12 -- .../examples/PatternMatchingExample.scala | 22 ---- .../com/baeldung/examples/TraitExample.scala | 23 ---- .../com/baeldung/examples/TupleExamples.scala | 18 --- .../examples/VariableDeclaration.scala | 24 ---- core-scala/src/test/scala/samples/junit.scala | 17 --- .../src/test/scala/samples/scalatest.scala | 108 ----------------- core-scala/src/test/scala/samples/specs.scala | 31 ----- core-scala/test.txt | 4 - 21 files changed, 567 deletions(-) delete mode 100644 core-scala/build.gradle delete mode 100644 core-scala/build.sbt delete mode 100644 core-scala/pom.xml delete mode 100644 core-scala/project/Dependencies.scala delete mode 100644 core-scala/project/build.properties delete mode 100644 core-scala/src/main/scala/com/baeldung/examples/ClassExamples.scala delete mode 100644 core-scala/src/main/scala/com/baeldung/examples/CollectionExamples.scala delete mode 100644 core-scala/src/main/scala/com/baeldung/examples/ExceptionHandlingExamples.scala delete mode 100644 core-scala/src/main/scala/com/baeldung/examples/FirstClassFunctionExamples.scala delete mode 100644 core-scala/src/main/scala/com/baeldung/examples/LoopAndCalculationExamples.scala delete mode 100644 core-scala/src/main/scala/com/baeldung/examples/MyApp.scala delete mode 100644 core-scala/src/main/scala/com/baeldung/examples/ObjectExamples.scala delete mode 100644 core-scala/src/main/scala/com/baeldung/examples/OptionExample.scala delete mode 100644 core-scala/src/main/scala/com/baeldung/examples/PatternMatchingExample.scala delete mode 100644 core-scala/src/main/scala/com/baeldung/examples/TraitExample.scala delete mode 100644 core-scala/src/main/scala/com/baeldung/examples/TupleExamples.scala delete mode 100644 core-scala/src/main/scala/com/baeldung/examples/VariableDeclaration.scala delete mode 100644 core-scala/src/test/scala/samples/junit.scala delete mode 100644 core-scala/src/test/scala/samples/scalatest.scala delete mode 100644 core-scala/src/test/scala/samples/specs.scala delete mode 100644 core-scala/test.txt diff --git a/core-scala/build.gradle b/core-scala/build.gradle deleted file mode 100644 index 05b5d5c55a..0000000000 --- a/core-scala/build.gradle +++ /dev/null @@ -1,13 +0,0 @@ -apply plugin: 'scala' - -repositories { - mavenCentral() -} - -dependencies { - compile 'org.scala-lang:scala-library:2.12.6' - testCompile 'org.scalatest:scalatest_2.12:3.0.5' - testCompile 'junit:junit:4.12' -} - - diff --git a/core-scala/build.sbt b/core-scala/build.sbt deleted file mode 100644 index 1e21f71d39..0000000000 --- a/core-scala/build.sbt +++ /dev/null @@ -1,12 +0,0 @@ -import Dependencies._ - -lazy val root = (project in file(".")). - settings( - inThisBuild(List( - organization := "com.example", - scalaVersion := "2.12.6", - version := "0.1.0-SNAPSHOT" - )), - name := "core-scala", - libraryDependencies += scalaTest % Test - ) diff --git a/core-scala/pom.xml b/core-scala/pom.xml deleted file mode 100644 index 76b6ee0d22..0000000000 --- a/core-scala/pom.xml +++ /dev/null @@ -1,111 +0,0 @@ - - 4.0.0 - core-scala - 1.0-SNAPSHOT - jar - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - 1.8 - 1.8 - UTF-8 - 2.12.6 - 2.12 - 4.2.0 - - - - - org.scala-lang - scala-library - ${scala.version} - - - - - junit - junit - 4.12 - test - - - org.scalatest - scalatest_${scala.compat.version} - 3.0.5 - test - - - org.specs2 - specs2-core_${scala.compat.version} - ${spec2.version} - test - - - org.specs2 - specs2-junit_${scala.compat.version} - ${spec2.version} - test - - - - - src/main/scala - src/test/scala - - - - net.alchim31.maven - scala-maven-plugin - 3.3.2 - - - - compile - testCompile - - - - -dependencyfile - ${project.build.directory}/.scala_dependencies - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.21.0 - - - true - - - - org.scalatest - scalatest-maven-plugin - 2.0.0 - - ${project.build.directory}/surefire-reports - . - TestSuiteReport.txt - - samples.AppTest - - - - test - - test - - - - - - - diff --git a/core-scala/project/Dependencies.scala b/core-scala/project/Dependencies.scala deleted file mode 100644 index 558929deb6..0000000000 --- a/core-scala/project/Dependencies.scala +++ /dev/null @@ -1,5 +0,0 @@ -import sbt._ - -object Dependencies { - lazy val scalaTest = "org.scalatest" %% "scalatest" % "3.0.5" -} diff --git a/core-scala/project/build.properties b/core-scala/project/build.properties deleted file mode 100644 index d6e35076cc..0000000000 --- a/core-scala/project/build.properties +++ /dev/null @@ -1 +0,0 @@ -sbt.version=1.1.6 diff --git a/core-scala/src/main/scala/com/baeldung/examples/ClassExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/ClassExamples.scala deleted file mode 100644 index 75a37e2bab..0000000000 --- a/core-scala/src/main/scala/com/baeldung/examples/ClassExamples.scala +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.examples - -object ClassExamples extends App { - - import java.time._ - class Customer(val id:Int, val name:String, dob:LocalDate) { - - private var _age = calculateAge(dob) - - def age = _age // getter - def age_= (age:Int) = _age = age //setter - - private def calculateAge(dob:LocalDate) = Period - .between(dob, LocalDate.now) - .getYears - - //override def toString: String = s"(id:${id}, name:${name}, age:${age})" - } - val c = new Customer(1, "Varun Sharma", LocalDate.parse("1980-02-27")) - println(c) - - case class Address(addressLn1:String, area:String, city:String, zip:String) - - val address=Address("102, Raycon Lotus Apartment", "AECS Layout", "Bangalore", "560037") - - val anotherAddress = address.copy(addressLn1="41/2, ITPL Road") - - println(address) - println(anotherAddress) - -} diff --git a/core-scala/src/main/scala/com/baeldung/examples/CollectionExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/CollectionExamples.scala deleted file mode 100644 index 1602516067..0000000000 --- a/core-scala/src/main/scala/com/baeldung/examples/CollectionExamples.scala +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.examples - -object CollectionExamples extends App { - - val aList = List(5, 3, 9, 2) // create a list - val sortedAscList = aList.sorted // sort ascending - val sortedDescList = aList.sortWith(_ > _) // sort descending - val evenList = aList.filter(_%2 == 0) // filter on some condition - - val mySet = Set(10, 20, 5) // create a set - val changedSet = mySet + 50 // add an element - println(changedSet) - val changedSet2 = mySet - 20 // remove an element - println(changedSet2) - - val capitals = Map("Japan" -> "Tokyo", - "England" -> "London", - "India" -> "New Delhi") // create a map - val capitalOfJapan = capitals("Japan") // get from map - println(capitalOfJapan) - -} diff --git a/core-scala/src/main/scala/com/baeldung/examples/ExceptionHandlingExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/ExceptionHandlingExamples.scala deleted file mode 100644 index 16ec7ffdf4..0000000000 --- a/core-scala/src/main/scala/com/baeldung/examples/ExceptionHandlingExamples.scala +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.examples - -object ExceptionHandlingExamples extends App { - import java.io._ - def printLines(filename:String) = { - var reader:Option[BufferedReader] = None - try { - reader = Some(new BufferedReader(new FileReader(new File(filename)))) - reader.get.lines().forEach(println(_)) - } catch { - case e:FileNotFoundException => println(s"There was no file named ${filename}") - case e:Throwable => throw new Exception("Some error occurred", e) - } finally { - if (reader.isDefined) reader.get.close() - } - } - printLines("test.txt") - -} diff --git a/core-scala/src/main/scala/com/baeldung/examples/FirstClassFunctionExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/FirstClassFunctionExamples.scala deleted file mode 100644 index bf925f59c7..0000000000 --- a/core-scala/src/main/scala/com/baeldung/examples/FirstClassFunctionExamples.scala +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.examples - -object FirstClassFunctionExamples extends App { - - def sum(x:Double, y:Double, f:Double => Double) = f(x) + f(y) - - println(sum(3, 4, x => x*x)) // returns 25.0 - - println(sum(3, 4, x => x*x*x)) // returns 91.0 - - println(sum(3, 4, Math.pow(_, 2))) // returns 25.0 - - def max(first:Int, second:Int) = if (first > second) first else second - - println(max(10, -2)) - -} diff --git a/core-scala/src/main/scala/com/baeldung/examples/LoopAndCalculationExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/LoopAndCalculationExamples.scala deleted file mode 100644 index 17091c715d..0000000000 --- a/core-scala/src/main/scala/com/baeldung/examples/LoopAndCalculationExamples.scala +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.examples - -object LoopAndCalculationExamples extends App { - import CalculationUtils._ - println(sumWithWhile(Array(10, 20, 30))) - println(sumWithFor(Array(10, 20, 30))) - println(checkEvenOdd((1 to 10).toArray).toList) - println(filterEvens((1 to 10).toArray).toList) -} - -object CalculationUtils { - - def sumWithWhile(values:Array[Int]) = { - var sum = 0 - var i = 0 - while ( i < values.length) { - sum += values(i) - i+=1 - } - sum - } - - def sumWithFor(values:Array[Int]) = { - var sum = 0 - for (i <- values) { - sum += i - } - sum - } - - def checkEvenOdd(values:Array[Int]) = { - for (i <- values) yield if (i%2 == 0) "Even" else "Odd" - } - - def filterEvens(values:Array[Int]) = - for (i <- values if i%2 == 0) - yield i - -} diff --git a/core-scala/src/main/scala/com/baeldung/examples/MyApp.scala b/core-scala/src/main/scala/com/baeldung/examples/MyApp.scala deleted file mode 100644 index d0861a8727..0000000000 --- a/core-scala/src/main/scala/com/baeldung/examples/MyApp.scala +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.examples - -/** - * @author ${user.name} - */ -object MyApp { - - def foo(x : Array[String]) = x.foldLeft("")((a,b) => a + b) - - def main(args : Array[String]) { - println( "Hello World!" ) - println("Number of arguments passed:" + args.length) - } - -} diff --git a/core-scala/src/main/scala/com/baeldung/examples/ObjectExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/ObjectExamples.scala deleted file mode 100644 index 29db276ebd..0000000000 --- a/core-scala/src/main/scala/com/baeldung/examples/ObjectExamples.scala +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.examples - -object ObjectExamples extends App { - - import java.time._ - class Customer(val id:Int, val name:String, private var _age:Int) { - def age = this._age - def age_= (age:Int) = _age = age - } - object Customer { - def apply(id:Int, name:String, age:Int) = new Customer(id, name, age) - - def apply(id:Int, name:String, dob:LocalDate) = { - val p = Period.between(dob, LocalDate.now) - new Customer(id, name, p.getYears) - } - } - val c = Customer(1, "Varun Sharma", LocalDate.parse("1980-02-27")) - - c.age = 20 - println(c.age) - -} diff --git a/core-scala/src/main/scala/com/baeldung/examples/OptionExample.scala b/core-scala/src/main/scala/com/baeldung/examples/OptionExample.scala deleted file mode 100644 index b0d49af758..0000000000 --- a/core-scala/src/main/scala/com/baeldung/examples/OptionExample.scala +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.examples - -object OptionExample extends App { - - def minimumEvenNumber(data:Array[Int]) = { - val evens = data.filter(_%2 == 0) - if (evens.isEmpty) None else Some(evens.min) - } - - val minEven = minimumEvenNumber(Array(21, 3, 11, 7)).getOrElse(0) - println(minEven) -} diff --git a/core-scala/src/main/scala/com/baeldung/examples/PatternMatchingExample.scala b/core-scala/src/main/scala/com/baeldung/examples/PatternMatchingExample.scala deleted file mode 100644 index d476bed60b..0000000000 --- a/core-scala/src/main/scala/com/baeldung/examples/PatternMatchingExample.scala +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.examples - -object PatternMatchingExample extends App { - - abstract class Item - case class Book(title:String, author:String, price:Double) extends Item - case class MusicCD(title:String, genre:String, price:Double) extends Item - - def describe(item:Item) = item match { - - case b:Book if b.price > 1000 => println(s"The book ${b.title} is expensive") - - case b:Book => println(s"The book ${b.title} is written by ${b.author}.") - - case MusicCD(title, "Jazz", _) => println(s"This is a CD of Jazz music.") - - case _ => println("Unknown Item") - - } - - describe(Book("Half Girlfriend", "Chetan Bhagat", 100)) -} diff --git a/core-scala/src/main/scala/com/baeldung/examples/TraitExample.scala b/core-scala/src/main/scala/com/baeldung/examples/TraitExample.scala deleted file mode 100644 index 0775a2bac2..0000000000 --- a/core-scala/src/main/scala/com/baeldung/examples/TraitExample.scala +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.examples - -import java.io._ - -object TraitExample extends App { - - trait Loggable { - val logger:PrintStream - def getPrefix():String - def log(message:String) = logger.println(s"[${getPrefix()}]:${message}") - } - object CustomerService extends Loggable { - override val logger = System.out - override def getPrefix(): String = "CustomerService" - def retrieve(id:String) = { - log(s"Retrieve with id ${id} called") - // Code to retrieve Customer from DB - } - } - - CustomerService.retrieve("C100") - -} diff --git a/core-scala/src/main/scala/com/baeldung/examples/TupleExamples.scala b/core-scala/src/main/scala/com/baeldung/examples/TupleExamples.scala deleted file mode 100644 index e9ffbd0aca..0000000000 --- a/core-scala/src/main/scala/com/baeldung/examples/TupleExamples.scala +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.examples - -object TupleExamples extends App { - - val empSal:(String, Int) = ("David", 10000) - - def getMaxMinSalary(empSal:Array[(String, Int)]) = { - val minEmpSal = empSal.minBy(empSal => empSal._2) - val maxEmpSal = empSal.maxBy(empSal => empSal._2) - (maxEmpSal._2, minEmpSal._2) - } - val empSalArr = Array(("David", 12000), ("Maria", 15000), - ("Elisa", 11000), ("Adam", 8000)) - - val (maxSalary, minSalary) = getMaxMinSalary(empSalArr) - println("Max Salary: " + maxSalary + " and Min Salary: " + minSalary) - -} diff --git a/core-scala/src/main/scala/com/baeldung/examples/VariableDeclaration.scala b/core-scala/src/main/scala/com/baeldung/examples/VariableDeclaration.scala deleted file mode 100644 index 6050b4f908..0000000000 --- a/core-scala/src/main/scala/com/baeldung/examples/VariableDeclaration.scala +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.examples - -object VariableDeclaration extends App { - - val x:Int = 0 - var friend:String = "David" - lazy val greet = "Hello" + friend - val data = Array(2, 4, 5) - - printHelloWorld() - println(sum(10, 20)) - - def printHelloWorld():Unit = { - println("Hello World") - } - - def sum(x:Int, y:Int) = x + y - - def sayGreeting(to:String, greet:String="Hi", message:String = "How are you?") = println(greet + " " + to + ", " + message) - - sayGreeting(to="David", message="How are you doing?") - sayGreeting(greet="Hello", to="Maria") - -} diff --git a/core-scala/src/test/scala/samples/junit.scala b/core-scala/src/test/scala/samples/junit.scala deleted file mode 100644 index 89513d5bbc..0000000000 --- a/core-scala/src/test/scala/samples/junit.scala +++ /dev/null @@ -1,17 +0,0 @@ -package samples - -import org.junit._ -import Assert._ - -@Test -class AppTest { - - @Test - def testOK() = assertTrue(true) - -// @Test -// def testKO() = assertTrue(false) - -} - - diff --git a/core-scala/src/test/scala/samples/scalatest.scala b/core-scala/src/test/scala/samples/scalatest.scala deleted file mode 100644 index bd10412199..0000000000 --- a/core-scala/src/test/scala/samples/scalatest.scala +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2001-2009 Artima, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package samples - -/* -ScalaTest facilitates different styles of testing by providing traits you can mix -together to get the behavior and syntax you prefer. A few examples are -included here. For more information, visit: - -http://www.scalatest.org/ - -One way to use ScalaTest is to help make JUnit or TestNG tests more -clear and concise. Here's an example: -*/ -import scala.collection._ -import org.scalatest.Assertions -import org.junit.Test - -class StackSuite extends Assertions { - - @Test def stackShouldPopValuesIinLastInFirstOutOrder() { - val stack = new mutable.ArrayStack[Int] - stack.push(1) - stack.push(2) - assert(stack.pop() === 2) - assert(stack.pop() === 1) - } - - @Test def stackShouldThrowRuntimeExceptionIfAnEmptyArrayStackIsPopped() { - val emptyStack = new mutable.ArrayStack[String] - intercept[RuntimeException] { - emptyStack.pop() - } - } -} - -/* -Here's an example of a FunSuite with Matchers mixed in: -*/ -import org.scalatest.FunSuite -import org.scalatest.Matchers - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -@RunWith(classOf[JUnitRunner]) -class ListSuite extends FunSuite with Matchers { - - test("An empty list should be empty") { - List() should be ('empty) - Nil should be ('empty) - } - - test("A non-empty list should not be empty") { - List(1, 2, 3) should not be ('empty) - List("fee", "fie", "foe", "fum") should not be ('empty) - } - - test("A list's length should equal the number of elements it contains") { - List() should have length (0) - List(1, 2) should have length (2) - List("fee", "fie", "foe", "fum") should have length (4) - } -} - -/* -ScalaTest also supports the behavior-driven development style, in which you -combine tests with text that specifies the behavior being tested. Here's -an example whose text output when run looks like: - -A Map -- should only contain keys and values that were added to it -- should report its size as the number of key/value pairs it contains -*/ -import org.scalatest.FunSpec - -class ExampleSpec extends FunSpec { - - describe("An ArrayStack") { - - it("should pop values in last-in-first-out order") { - val stack = new mutable.ArrayStack[Int] - stack.push(1) - stack.push(2) - assert(stack.pop() === 2) - assert(stack.pop() === 1) - } - - it("should throw RuntimeException if an empty array stack is popped") { - val emptyStack = new mutable.ArrayStack[Int] - intercept[RuntimeException] { - emptyStack.pop() - } - } - } -} diff --git a/core-scala/src/test/scala/samples/specs.scala b/core-scala/src/test/scala/samples/specs.scala deleted file mode 100644 index 9e4dfe93bb..0000000000 --- a/core-scala/src/test/scala/samples/specs.scala +++ /dev/null @@ -1,31 +0,0 @@ -package samples - -import org.junit.runner.RunWith -import org.specs2.mutable._ -import org.specs2.runner._ - - -/** - * Sample specification. - * - * This specification can be executed with: scala -cp ${package}.SpecsTest - * Or using maven: mvn test - * - * For more information on how to write or run specifications, please visit: - * http://etorreborre.github.com/specs2/guide/org.specs2.guide.Runners.html - * - */ -@RunWith(classOf[JUnitRunner]) -class MySpecTest extends Specification { - "The 'Hello world' string" should { - "contain 11 characters" in { - "Hello world" must have size(11) - } - "start with 'Hello'" in { - "Hello world" must startWith("Hello") - } - "end with 'world'" in { - "Hello world" must endWith("world") - } - } -} diff --git a/core-scala/test.txt b/core-scala/test.txt deleted file mode 100644 index da431d2039..0000000000 --- a/core-scala/test.txt +++ /dev/null @@ -1,4 +0,0 @@ -Hi, -This is the lines -from the test file. -Thanks. \ No newline at end of file From fcef80587c4f3fd38c77e2055a218b6c11890952 Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Tue, 16 Oct 2018 20:49:12 +0530 Subject: [PATCH 08/12] BAEL-2221 --- .../org/baeldung/web/dto/EmployeeDto.java | 38 ++++++++++ .../java/org/baeldung/web/model/Employee.java | 53 ++++++++++++++ .../baeldung/web/service/EmployeeService.java | 51 ++++++++++++++ .../java/org/baeldung/SpringTestConfig.java | 19 +++++ ...eServiceMockRestServiceServerUnitTest.java | 70 +++++++++++++++++++ .../web/service/EmployeeServiceUnitTest.java | 49 +++++++++++++ .../src/test/resources/logback-test.xml | 23 ++++++ 7 files changed, 303 insertions(+) create mode 100644 spring-resttemplate/src/main/java/org/baeldung/web/dto/EmployeeDto.java create mode 100644 spring-resttemplate/src/main/java/org/baeldung/web/model/Employee.java create mode 100644 spring-resttemplate/src/main/java/org/baeldung/web/service/EmployeeService.java create mode 100644 spring-resttemplate/src/test/java/org/baeldung/SpringTestConfig.java create mode 100644 spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java create mode 100644 spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java create mode 100644 spring-resttemplate/src/test/resources/logback-test.xml diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/dto/EmployeeDto.java b/spring-resttemplate/src/main/java/org/baeldung/web/dto/EmployeeDto.java new file mode 100644 index 0000000000..44c8ba5074 --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/web/dto/EmployeeDto.java @@ -0,0 +1,38 @@ +package org.baeldung.web.dto; + +import java.util.Date; + +public class EmployeeDto { + + private String id; + private String name; + private Double salary; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Double getSalary() { + return salary; + } + + public void setSalary(Double salary) { + this.salary = salary; + } + + @Override public String toString() { + return "EmployeeDto{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", salary=" + salary + '}'; + } +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/model/Employee.java b/spring-resttemplate/src/main/java/org/baeldung/web/model/Employee.java new file mode 100644 index 0000000000..0981cc2da1 --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/web/model/Employee.java @@ -0,0 +1,53 @@ +package org.baeldung.web.model; + +import java.util.Date; +import java.util.Objects; + +public class Employee { + + private String id; + private String name; + private Double salary; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Double getSalary() { + return salary; + } + + public void setSalary(Double salary) { + this.salary = salary; + } + + @Override public String toString() { + return "Employee{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", salary=" + salary + '}'; + } + + @Override public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Employee employee = (Employee) o; + return Objects.equals(id, employee.id) && Objects.equals(name, employee.name) && Objects.equals(salary, employee.salary); + } + + @Override public int hashCode() { + + return Objects.hash(id, name, salary); + } +} diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/service/EmployeeService.java b/spring-resttemplate/src/main/java/org/baeldung/web/service/EmployeeService.java new file mode 100644 index 0000000000..3a0222cb6c --- /dev/null +++ b/spring-resttemplate/src/main/java/org/baeldung/web/service/EmployeeService.java @@ -0,0 +1,51 @@ +package org.baeldung.web.service; + +import org.baeldung.web.dto.EmployeeDto; +import org.baeldung.web.model.Employee; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +@Service +public class EmployeeService { + + static final String EMP_URL_PREFIX = "http://localhost:8080/employee"; + static final String URL_SEP = "/"; + + private static final Logger logger = LoggerFactory.getLogger(EmployeeService.class); + + @Autowired + private RestTemplate restTemplate; + + public EmployeeDto getEmployee(String id) throws Exception { + + Employee emp = null; + try { + + ResponseEntity resp = restTemplate.getForEntity(EMP_URL_PREFIX + + URL_SEP + id, Employee.class); + + if (resp == null || resp.getStatusCode() != HttpStatus.OK + || resp.getBody() == null) { + + throw new Exception("Employee details could not be fetched."); + } + + emp = resp.getBody(); + + EmployeeDto dto = new EmployeeDto(); + dto.setId(emp.getId()); + dto.setName(emp.getName()); + dto.setSalary(emp.getSalary()); + return dto; + + } catch (Exception e) { + logger.error("Error occurred while fetching employee details", e); + throw new Exception("Error occurred while fetching employee details", e); + } + } +} diff --git a/spring-resttemplate/src/test/java/org/baeldung/SpringTestConfig.java b/spring-resttemplate/src/test/java/org/baeldung/SpringTestConfig.java new file mode 100644 index 0000000000..7c4bbb4e5e --- /dev/null +++ b/spring-resttemplate/src/test/java/org/baeldung/SpringTestConfig.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +@Configuration +@EnableAutoConfiguration +@ComponentScan("org.baeldung") +public class SpringTestConfig { + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } + +} diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java new file mode 100644 index 0000000000..7c2f535fae --- /dev/null +++ b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java @@ -0,0 +1,70 @@ +package org.baeldung.web.service; + +import java.net.URI; + +import org.baeldung.SpringTestConfig; +import org.baeldung.web.dto.EmployeeDto; +import org.baeldung.web.model.Employee; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.test.web.client.match.MockRestRequestMatchers; +import org.springframework.test.web.client.response.MockRestResponseCreators; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = SpringTestConfig.class) +public class EmployeeServiceMockRestServiceServerUnitTest { + + private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceMockRestServiceServerUnitTest.class); + + @Autowired + EmployeeService empService; + + @Autowired + RestTemplate restTemplate; + + MockRestServiceServer mockServer; + + ObjectMapper mapper = new ObjectMapper(); + + @Before + public void initMocks() { + mockServer = MockRestServiceServer.createServer(restTemplate); + } + + @Test + public void givenMockingIsDoneByMockRestServiceServer_whenGetIsCalled_shouldReturnMockedObject() throws Exception { + String id = "E001"; + Employee emp = new Employee(); + emp.setId(id); + emp.setName("Eric Simmons"); + emp.setSalary(10000.00d); + //employeeDao.create(emp); + + mockServer.expect(MockRestRequestMatchers.requestTo(new URI(EmployeeService.EMP_URL_PREFIX + + EmployeeService.URL_SEP + id))) + .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) + .andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK) + .contentType(MediaType.APPLICATION_JSON) + .body(mapper.writeValueAsString(emp))); + + EmployeeDto employeeDto = empService.getEmployee(id); + logger.info("Employee received as: {}", employeeDto); + Assert.assertEquals(emp.getName(), employeeDto.getName()); + Assert.assertEquals(emp.getId(), employeeDto.getId()); + } + +} diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java new file mode 100644 index 0000000000..aa323dd685 --- /dev/null +++ b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java @@ -0,0 +1,49 @@ +package org.baeldung.web.service; + +import org.baeldung.web.dto.EmployeeDto; +import org.baeldung.web.model.Employee; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +public class EmployeeServiceUnitTest { + + private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceUnitTest.class); + + @Mock + RestTemplate restTemplate; + + @Spy + @InjectMocks + EmployeeService empService = new EmployeeService(); + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void givenMockingIsDoneByMockito_whenGetIsCalled_shouldReturnMockedObject() throws Exception { + String id = "E001"; + Employee emp = new Employee(); + emp.setId(id); + emp.setName("Eric Simmons"); + emp.setSalary(10000.00d); + Mockito + .when(restTemplate.getForEntity(EmployeeService.EMP_URL_PREFIX + + EmployeeService.URL_SEP + id, Employee.class)) + .thenReturn(new ResponseEntity(emp, HttpStatus.OK)); + + EmployeeDto employeeDto = empService.getEmployee(id); + logger.info("Employee received as: {}", employeeDto); + Assert.assertEquals(emp.getName(), employeeDto.getName()); + Assert.assertEquals(emp.getSalary(), employeeDto.getSalary()); + } + +} diff --git a/spring-resttemplate/src/test/resources/logback-test.xml b/spring-resttemplate/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..9f48d36486 --- /dev/null +++ b/spring-resttemplate/src/test/resources/logback-test.xml @@ -0,0 +1,23 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + \ No newline at end of file From 9713832dc6c5e92a62acf2b454f923f0f35d2731 Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Tue, 16 Oct 2018 21:01:06 +0530 Subject: [PATCH 09/12] BAEL-2221 --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index 9fde092896..beb10b3287 100644 --- a/pom.xml +++ b/pom.xml @@ -361,7 +361,6 @@ core-kotlin kotlin-libraries core-groovy - core-scala core-java-concurrency core-java-concurrency-collections couchbase From da052c96d30997706a49ebca75e1cb05b02136b7 Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Wed, 17 Oct 2018 18:11:30 +0530 Subject: [PATCH 10/12] BAEL-2221 --- ...eServiceMockRestServiceServerUnitTest.java | 33 +++++++++++-------- .../web/service/EmployeeServiceUnitTest.java | 7 ++-- 2 files changed, 23 insertions(+), 17 deletions(-) diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java index 7c2f535fae..f04b0fbc2b 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java @@ -17,9 +17,13 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.client.ExpectedCount; import org.springframework.test.web.client.MockRestServiceServer; -import org.springframework.test.web.client.match.MockRestRequestMatchers; -import org.springframework.test.web.client.response.MockRestResponseCreators; + +import static org.baeldung.web.service.EmployeeService.EMP_URL_PREFIX; +import static org.baeldung.web.service.EmployeeService.URL_SEP; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; +import static org.springframework.test.web.client.response.MockRestResponseCreators.*; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; @@ -31,14 +35,14 @@ public class EmployeeServiceMockRestServiceServerUnitTest { private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceMockRestServiceServerUnitTest.class); @Autowired - EmployeeService empService; + private EmployeeService empService; @Autowired - RestTemplate restTemplate; + private RestTemplate restTemplate; - MockRestServiceServer mockServer; + private MockRestServiceServer mockServer; - ObjectMapper mapper = new ObjectMapper(); + private ObjectMapper mapper = new ObjectMapper(); @Before public void initMocks() { @@ -52,17 +56,20 @@ public class EmployeeServiceMockRestServiceServerUnitTest { emp.setId(id); emp.setName("Eric Simmons"); emp.setSalary(10000.00d); - //employeeDao.create(emp); - mockServer.expect(MockRestRequestMatchers.requestTo(new URI(EmployeeService.EMP_URL_PREFIX - + EmployeeService.URL_SEP + id))) - .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) - .andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK) - .contentType(MediaType.APPLICATION_JSON) - .body(mapper.writeValueAsString(emp))); + String fullUri = new StringBuilder().append(EMP_URL_PREFIX).append(URL_SEP) + .append(id).toString(); + + mockServer.expect(ExpectedCount.once(), requestTo(new URI(fullUri))) + .andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.OK) + .contentType(MediaType.APPLICATION_JSON) + .body(mapper.writeValueAsString(emp))); EmployeeDto employeeDto = empService.getEmployee(id); logger.info("Employee received as: {}", employeeDto); + + mockServer.verify(); Assert.assertEquals(emp.getName(), employeeDto.getName()); Assert.assertEquals(emp.getId(), employeeDto.getId()); } diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java index aa323dd685..ac714bf6db 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java @@ -17,14 +17,13 @@ public class EmployeeServiceUnitTest { private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceUnitTest.class); @Mock - RestTemplate restTemplate; + private RestTemplate restTemplate; - @Spy @InjectMocks - EmployeeService empService = new EmployeeService(); + private EmployeeService empService = new EmployeeService(); @Before - public void initMocks() { + public void setup() { MockitoAnnotations.initMocks(this); } From dbf2721d25e33f63448c7e980b4e80d585bb3b5a Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Mon, 29 Oct 2018 03:14:08 +0530 Subject: [PATCH 11/12] BAEL-2221 --- .../org/baeldung/web/dto/EmployeeDto.java | 38 ------------------ .../java/org/baeldung/web/model/Employee.java | 25 +++++------- .../baeldung/web/service/EmployeeService.java | 30 ++------------ ...eServiceMockRestServiceServerUnitTest.java | 39 +++++++------------ .../web/service/EmployeeServiceUnitTest.java | 25 +++++------- 5 files changed, 38 insertions(+), 119 deletions(-) delete mode 100644 spring-resttemplate/src/main/java/org/baeldung/web/dto/EmployeeDto.java diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/dto/EmployeeDto.java b/spring-resttemplate/src/main/java/org/baeldung/web/dto/EmployeeDto.java deleted file mode 100644 index 44c8ba5074..0000000000 --- a/spring-resttemplate/src/main/java/org/baeldung/web/dto/EmployeeDto.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.baeldung.web.dto; - -import java.util.Date; - -public class EmployeeDto { - - private String id; - private String name; - private Double salary; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Double getSalary() { - return salary; - } - - public void setSalary(Double salary) { - this.salary = salary; - } - - @Override public String toString() { - return "EmployeeDto{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", salary=" + salary + '}'; - } -} diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/model/Employee.java b/spring-resttemplate/src/main/java/org/baeldung/web/model/Employee.java index 0981cc2da1..7cab4a0430 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/web/model/Employee.java +++ b/spring-resttemplate/src/main/java/org/baeldung/web/model/Employee.java @@ -7,7 +7,14 @@ public class Employee { private String id; private String name; - private Double salary; + + public Employee(String id, String name) { + this.id = id; + this.name = name; + } + + public Employee() { + } public String getId() { return id; @@ -25,29 +32,17 @@ public class Employee { this.name = name; } - public Double getSalary() { - return salary; - } - - public void setSalary(Double salary) { - this.salary = salary; - } - - @Override public String toString() { - return "Employee{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", salary=" + salary + '}'; - } - @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Employee employee = (Employee) o; - return Objects.equals(id, employee.id) && Objects.equals(name, employee.name) && Objects.equals(salary, employee.salary); + return Objects.equals(id, employee.id); } @Override public int hashCode() { - return Objects.hash(id, name, salary); + return Objects.hash(id); } } diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/service/EmployeeService.java b/spring-resttemplate/src/main/java/org/baeldung/web/service/EmployeeService.java index 3a0222cb6c..91614e90ad 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/web/service/EmployeeService.java +++ b/spring-resttemplate/src/main/java/org/baeldung/web/service/EmployeeService.java @@ -1,6 +1,5 @@ package org.baeldung.web.service; -import org.baeldung.web.dto.EmployeeDto; import org.baeldung.web.model.Employee; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,31 +20,10 @@ public class EmployeeService { @Autowired private RestTemplate restTemplate; - public EmployeeDto getEmployee(String id) throws Exception { + public Employee getEmployee(String id) { - Employee emp = null; - try { - - ResponseEntity resp = restTemplate.getForEntity(EMP_URL_PREFIX - + URL_SEP + id, Employee.class); - - if (resp == null || resp.getStatusCode() != HttpStatus.OK - || resp.getBody() == null) { - - throw new Exception("Employee details could not be fetched."); - } - - emp = resp.getBody(); - - EmployeeDto dto = new EmployeeDto(); - dto.setId(emp.getId()); - dto.setName(emp.getName()); - dto.setSalary(emp.getSalary()); - return dto; - - } catch (Exception e) { - logger.error("Error occurred while fetching employee details", e); - throw new Exception("Error occurred while fetching employee details", e); - } + ResponseEntity resp = restTemplate.getForEntity("http://localhost:8080/employee/" + id, + Employee.class); + return resp.getStatusCode() == HttpStatus.OK ? resp.getBody() : null; } } diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java index f04b0fbc2b..a45af318f1 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java @@ -1,9 +1,12 @@ package org.baeldung.web.service; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; + import java.net.URI; import org.baeldung.SpringTestConfig; -import org.baeldung.web.dto.EmployeeDto; import org.baeldung.web.model.Employee; import org.junit.Assert; import org.junit.Before; @@ -19,11 +22,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.ExpectedCount; import org.springframework.test.web.client.MockRestServiceServer; - -import static org.baeldung.web.service.EmployeeService.EMP_URL_PREFIX; -import static org.baeldung.web.service.EmployeeService.URL_SEP; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; -import static org.springframework.test.web.client.response.MockRestResponseCreators.*; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; @@ -45,33 +43,24 @@ public class EmployeeServiceMockRestServiceServerUnitTest { private ObjectMapper mapper = new ObjectMapper(); @Before - public void initMocks() { + public void init() { mockServer = MockRestServiceServer.createServer(restTemplate); } @Test public void givenMockingIsDoneByMockRestServiceServer_whenGetIsCalled_shouldReturnMockedObject() throws Exception { - String id = "E001"; - Employee emp = new Employee(); - emp.setId(id); - emp.setName("Eric Simmons"); - emp.setSalary(10000.00d); + Employee emp = new Employee("E001", "Eric Simmons"); - String fullUri = new StringBuilder().append(EMP_URL_PREFIX).append(URL_SEP) - .append(id).toString(); - - mockServer.expect(ExpectedCount.once(), requestTo(new URI(fullUri))) - .andExpect(method(HttpMethod.GET)) - .andRespond(withStatus(HttpStatus.OK) - .contentType(MediaType.APPLICATION_JSON) - .body(mapper.writeValueAsString(emp))); - - EmployeeDto employeeDto = empService.getEmployee(id); - logger.info("Employee received as: {}", employeeDto); + mockServer.expect(ExpectedCount.once(), + requestTo(new URI("http://localhost:8080/employee/E001"))) + .andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.OK) + .contentType(MediaType.APPLICATION_JSON) + .body(mapper.writeValueAsString(emp))); + Employee employee = empService.getEmployee("E001"); mockServer.verify(); - Assert.assertEquals(emp.getName(), employeeDto.getName()); - Assert.assertEquals(emp.getId(), employeeDto.getId()); + Assert.assertEquals(emp, employee); } } diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java index ac714bf6db..ee30c22e9f 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java @@ -1,11 +1,13 @@ package org.baeldung.web.service; -import org.baeldung.web.dto.EmployeeDto; import org.baeldung.web.model.Employee; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.mockito.*; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -29,20 +31,13 @@ public class EmployeeServiceUnitTest { @Test public void givenMockingIsDoneByMockito_whenGetIsCalled_shouldReturnMockedObject() throws Exception { - String id = "E001"; - Employee emp = new Employee(); - emp.setId(id); - emp.setName("Eric Simmons"); - emp.setSalary(10000.00d); - Mockito - .when(restTemplate.getForEntity(EmployeeService.EMP_URL_PREFIX - + EmployeeService.URL_SEP + id, Employee.class)) - .thenReturn(new ResponseEntity(emp, HttpStatus.OK)); + Employee emp = new Employee("E001", "Eric Simmons"); + Mockito.when(restTemplate.getForEntity("http://localhost:8080/employee/E001", Employee.class)) + .thenReturn(new ResponseEntity(emp, HttpStatus.OK)); - EmployeeDto employeeDto = empService.getEmployee(id); - logger.info("Employee received as: {}", employeeDto); - Assert.assertEquals(emp.getName(), employeeDto.getName()); - Assert.assertEquals(emp.getSalary(), employeeDto.getSalary()); + Employee employee = empService.getEmployee("E001"); + + Assert.assertEquals(emp, employee); } } From 5d87e46328fe28ea6255728b3d3b867a93154c73 Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Fri, 2 Nov 2018 03:27:05 +0530 Subject: [PATCH 12/12] BAEL-2221: using MockitoJunitRunner --- .../org/baeldung/web/service/EmployeeServiceUnitTest.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java index ee30c22e9f..23cd9a8fd2 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/web/service/EmployeeServiceUnitTest.java @@ -4,16 +4,19 @@ import org.baeldung.web.model.Employee; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.mockito.runners.MockitoJUnitRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; +@RunWith(MockitoJUnitRunner.class) public class EmployeeServiceUnitTest { private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceUnitTest.class); @@ -24,11 +27,6 @@ public class EmployeeServiceUnitTest { @InjectMocks private EmployeeService empService = new EmployeeService(); - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - @Test public void givenMockingIsDoneByMockito_whenGetIsCalled_shouldReturnMockedObject() throws Exception { Employee emp = new Employee("E001", "Eric Simmons");