From 3e2d766f37f3820a5d0b68d4d6fea12c22087522 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 15 Jul 2017 17:08:56 +0200 Subject: [PATCH 01/43] Refactor TemporalAdjusters (#2266) --- .../CustomTemporalAdjuster.java | 17 +++++---- .../CustomTemporalAdjusterTest.java | 36 +++++++------------ 2 files changed, 20 insertions(+), 33 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java b/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java index ab491bee66..bfb6681f7c 100644 --- a/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java +++ b/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java @@ -10,14 +10,13 @@ public class CustomTemporalAdjuster implements TemporalAdjuster { @Override public Temporal adjustInto(Temporal temporal) { - DayOfWeek dayOfWeek = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK)); - int daysToAdd; - if (dayOfWeek == DayOfWeek.FRIDAY) - daysToAdd = 3; - else if (dayOfWeek == DayOfWeek.SATURDAY) - daysToAdd = 2; - else - daysToAdd = 1; - return temporal.plus(daysToAdd, ChronoUnit.DAYS); + switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) { + case FRIDAY: + return temporal.plus(3, ChronoUnit.DAYS); + case SATURDAY: + return temporal.plus(2, ChronoUnit.DAYS); + default: + return temporal.plus(1, ChronoUnit.DAYS); + } } } 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 a7acc9f743..ad8de82e1f 100644 --- a/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java +++ b/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java @@ -1,34 +1,34 @@ package com.baeldung.temporaladjusters; -import java.time.DayOfWeek; -import java.time.LocalDate; -import java.time.Period; -import java.time.temporal.TemporalAdjuster; -import java.time.temporal.TemporalAdjusters; - +import com.baeldung.temporaladjuster.CustomTemporalAdjuster; import org.junit.Assert; import org.junit.Test; -import com.baeldung.temporaladjuster.CustomTemporalAdjuster; +import java.time.LocalDate; +import java.time.Period; +import java.time.temporal.TemporalAdjuster; + +import static org.junit.Assert.assertEquals; public class CustomTemporalAdjusterTest { + private static final TemporalAdjuster NEXT_WORKING_DAY = new CustomTemporalAdjuster(); + @Test public void whenAdjustAndImplementInterface_thenNextWorkingDay() { LocalDate localDate = LocalDate.of(2017, 07, 8); CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster(); LocalDate nextWorkingDay = localDate.with(temporalAdjuster); - Assert.assertEquals("2017-07-10", nextWorkingDay.toString()); + assertEquals("2017-07-10", nextWorkingDay.toString()); } @Test public void whenAdjust_thenNextWorkingDay() { LocalDate localDate = LocalDate.of(2017, 07, 8); - TemporalAdjuster temporalAdjuster = NEXT_WORKING_DAY; - LocalDate date = localDate.with(temporalAdjuster); + LocalDate date = localDate.with(NEXT_WORKING_DAY); - Assert.assertEquals("2017-07-10", date.toString()); + assertEquals("2017-07-10", date.toString()); } @Test @@ -39,18 +39,6 @@ public class CustomTemporalAdjusterTest { String fourteenDaysAfterDate = "2017-07-22"; - Assert.assertEquals(fourteenDaysAfterDate, result.toString()); + assertEquals(fourteenDaysAfterDate, result.toString()); } - - static TemporalAdjuster NEXT_WORKING_DAY = TemporalAdjusters.ofDateAdjuster(date -> { - DayOfWeek dayOfWeek = date.getDayOfWeek(); - int daysToAdd; - if (dayOfWeek == DayOfWeek.FRIDAY) - daysToAdd = 3; - else if (dayOfWeek == DayOfWeek.SATURDAY) - daysToAdd = 2; - else - daysToAdd = 1; - return date.plusDays(daysToAdd); - }); } From 470ac0c7bb48e8c33b7687ab0243d1eed7fc70c5 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sat, 15 Jul 2017 10:14:47 -0500 Subject: [PATCH 02/43] BAEL-861 README update (#2267) * 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) --- libraries/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/README.md b/libraries/README.md index c7e56db3b8..30f02e5c5a 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -24,6 +24,7 @@ - [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing) - [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map) - [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) +- [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) 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 8739094a161da0817093843d5da04825f44ef676 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Sat, 15 Jul 2017 17:26:13 +0200 Subject: [PATCH 03/43] minor upgrade (#2259) * 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 --- httpclient/pom.xml | 2 +- .../org/baeldung/httpclient/HttpClientPostingLiveTest.java | 2 +- spring-data-mongodb/pom.xml | 2 +- .../org/baeldung/event/CascadeSaveMongoEventListener.java | 4 +++- .../baeldung/event/UserCascadeSaveMongoEventListener.java | 6 ++++-- spring-security-rest/pom.xml | 2 +- 6 files changed, 11 insertions(+), 7 deletions(-) diff --git a/httpclient/pom.xml b/httpclient/pom.xml index 562b3e9bcd..b7567e0c4b 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -147,7 +147,7 @@ 2.5.1 4.4.5 - 4.5.2 + 4.5.3 1.6.1 diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java index ada5667f0b..ad173f9cd8 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java @@ -33,7 +33,7 @@ import org.junit.Test; * NOTE : Need module spring-rest to be running */ public class HttpClientPostingLiveTest { - private static final String SAMPLE_URL = "http://localhost:8080/spring-rest/users"; + private static final String SAMPLE_URL = "http://localhost:8082/spring-rest/users"; private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; private static final String DEFAULT_USER = "test"; private static final String DEFAULT_PASS = "test"; diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 84d49a3e35..7060ec5b36 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -115,7 +115,7 @@ 4.3.4.RELEASE - 1.9.6.RELEASE + 1.10.4.RELEASE 2.9.0 4.1.4 diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java index 79840fb570..acc377011d 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java @@ -3,6 +3,7 @@ package org.baeldung.event; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; +import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent; import org.springframework.util.ReflectionUtils; public class CascadeSaveMongoEventListener extends AbstractMongoEventListener { @@ -11,7 +12,8 @@ public class CascadeSaveMongoEventListener extends AbstractMongoEventListener event) { + final Object source = event.getSource(); ReflectionUtils.doWithFields(source.getClass(), new CascadeCallback(source, mongoOperations)); } } \ No newline at end of file diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java b/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java index 423df59b95..ade20bcc1d 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java @@ -4,14 +4,16 @@ import org.baeldung.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; +import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent; public class UserCascadeSaveMongoEventListener extends AbstractMongoEventListener { @Autowired private MongoOperations mongoOperations; @Override - public void onBeforeConvert(final Object source) { - if (source instanceof User && ((User) source).getEmailAddress() != null) { + public void onBeforeConvert(final BeforeConvertEvent event) { + final Object source = event.getSource(); + if ((source instanceof User) && (((User) source).getEmailAddress() != null)) { mongoOperations.save(((User) source).getEmailAddress()); } } diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 64c0160e1f..13db431ae3 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -307,7 +307,7 @@ 2.9.0 - 2.6.1 + 2.7.0 4.4.5 4.5.2 From d8d1171afa10a839ce81e7f6519f8532ac797f82 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sat, 15 Jul 2017 18:51:14 +0100 Subject: [PATCH 04/43] BAEL-964 - printing directly to standard output --- .../baeldung/commons/collections/MapUtilsTest.java | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java index 470eb46cb0..10d408b467 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java @@ -63,19 +63,7 @@ public class MapUtilsTest { @Test public void whenVerbosePrintMap_thenMustPrintFormattedMap() { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - PrintStream outPrint = new PrintStream(out); - - outPrint.println("Optional Label = "); - outPrint.println("{"); - outPrint.println(" RED = #FF0000"); - outPrint.println(" BLUE = #0000FF"); - outPrint.println(" GREEN = #00FF00"); - outPrint.println("}"); - - out.reset(); - - MapUtils.verbosePrint(outPrint, "Optional Label", this.colorMap); + MapUtils.verbosePrint(System.out, "Optional Label", this.colorMap); } @Test From b4d3e23c3e568e8e25c8786c5de6337bc84035f1 Mon Sep 17 00:00:00 2001 From: Danil Kornishev Date: Sat, 15 Jul 2017 17:53:57 -0400 Subject: [PATCH 05/43] JMH (#2222) * JMH * JMH --- jmh/pom.xml | 100 ++++++++++-------- .../main/java/com/baeldung/Application.java | 14 --- jmh/src/main/java/com/baeldung/BenchMark.java | 46 +++++++- .../java/com/baeldung/BenchmarkRunner.java | 9 ++ jmh/src/test/java/com/baeldung/AppTest.java | 38 ------- 5 files changed, 104 insertions(+), 103 deletions(-) delete mode 100644 jmh/src/main/java/com/baeldung/Application.java create mode 100644 jmh/src/main/java/com/baeldung/BenchmarkRunner.java delete mode 100644 jmh/src/test/java/com/baeldung/AppTest.java diff --git a/jmh/pom.xml b/jmh/pom.xml index 8ecfaa9651..ef5c3f1bbf 100644 --- a/jmh/pom.xml +++ b/jmh/pom.xml @@ -1,52 +1,60 @@ - 4.0.0 - com.baeldung - jmh - jar - 1.0-SNAPSHOT - jmh - http://maven.apache.org + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + com.baeldung + jmh + jar + 1.0-SNAPSHOT + jmh + http://maven.apache.org - - UTF-8 - UTF-8 - 1.8 - + + UTF-8 + UTF-8 + 1.8 + 1.6 + 1.6 + - - - org.openjdk.jmh - jmh-core - 1.19 - - - org.openjdk.jmh - jmh-generator-annprocess - 1.19 - - - junit - junit - 3.8.1 - test - - + + + org.openjdk.jmh + jmh-core + 1.19 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.19 + + + junit + junit + 3.8.1 + test + - - - - org.apache.maven.plugins - maven-jar-plugin - - - - com.baeldung.Application - - - - - - + + com.google.guava + guava + 21.0 + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.baeldung.BenchmarkRunner + + + + + + \ No newline at end of file diff --git a/jmh/src/main/java/com/baeldung/Application.java b/jmh/src/main/java/com/baeldung/Application.java deleted file mode 100644 index 28e70740e0..0000000000 --- a/jmh/src/main/java/com/baeldung/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung; - -import java.io.IOException; - -import org.openjdk.jmh.Main; -import org.openjdk.jmh.runner.RunnerException; - -public class Application { - - public static void main(String[] args) throws RunnerException, IOException { - Main.main(args); - } - -} diff --git a/jmh/src/main/java/com/baeldung/BenchMark.java b/jmh/src/main/java/com/baeldung/BenchMark.java index f2b984d211..b0e1caf4dc 100644 --- a/jmh/src/main/java/com/baeldung/BenchMark.java +++ b/jmh/src/main/java/com/baeldung/BenchMark.java @@ -1,12 +1,48 @@ package com.baeldung; -import org.openjdk.jmh.annotations.Benchmark; +import com.google.common.hash.HashFunction; +import com.google.common.hash.Hasher; +import com.google.common.hash.Hashing; +import org.openjdk.jmh.annotations.*; + +import java.nio.charset.Charset; public class BenchMark { - @Benchmark - public void init() { - - } + @State(Scope.Benchmark) + public static class ExecutionPlan { + + @Param({ "100", "200", "300", "500", "1000" }) + public int iterations; + + public Hasher murmur3; + + public String password = "4v3rys3kur3p455w0rd"; + + @Setup(Level.Invocation) + public void setUp() { + murmur3 = Hashing.murmur3_128().newHasher(); + } + } + + @Fork(value = 1, warmups = 1) + @Benchmark + @BenchmarkMode(Mode.Throughput) + @Warmup(iterations = 5) + public void benchMurmur3_128(ExecutionPlan plan) { + + for (int i = plan.iterations; i > 0; i--) { + plan.murmur3.putString(plan.password, Charset.defaultCharset()); + } + + plan.murmur3.hash(); + } + + @Benchmark + @Fork(value = 1, warmups = 1) + @BenchmarkMode(Mode.Throughput) + public void init() { + // Do nothing + } } diff --git a/jmh/src/main/java/com/baeldung/BenchmarkRunner.java b/jmh/src/main/java/com/baeldung/BenchmarkRunner.java new file mode 100644 index 0000000000..ed6a5bb617 --- /dev/null +++ b/jmh/src/main/java/com/baeldung/BenchmarkRunner.java @@ -0,0 +1,9 @@ +package com.baeldung; + +public class BenchmarkRunner { + + public static void main(String[] args) throws Exception { + org.openjdk.jmh.Main.main(args); + } + +} diff --git a/jmh/src/test/java/com/baeldung/AppTest.java b/jmh/src/test/java/com/baeldung/AppTest.java deleted file mode 100644 index c9f61455bd..0000000000 --- a/jmh/src/test/java/com/baeldung/AppTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} From dc0d802cd905d6c15632524ab2e4ebc3e6bb561f Mon Sep 17 00:00:00 2001 From: dhruba619 Date: Sun, 16 Jul 2017 12:36:17 +0530 Subject: [PATCH 06/43] BAEL-982 Spring-boot mustache initial commit --- spring-mustache/.gitignore | 24 ++++++++ spring-mustache/pom.xml | 60 +++++++++++++++++++ .../SpringMustacheApplication.java | 34 +++++++++++ .../controller/ArticleController.java | 50 ++++++++++++++++ .../springmustache/model/Article.java | 41 +++++++++++++ .../src/main/resources/application.properties | 0 .../main/resources/templates/error/error.html | 9 +++ .../src/main/resources/templates/index.html | 9 +++ .../resources/templates/layout/article.html | 8 +++ .../resources/templates/layout/footer.html | 2 + .../resources/templates/layout/header.html | 11 ++++ .../SpringMustacheApplicationTests.java | 32 ++++++++++ 12 files changed, 280 insertions(+) create mode 100644 spring-mustache/.gitignore create mode 100644 spring-mustache/pom.xml create mode 100644 spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java create mode 100644 spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java create mode 100644 spring-mustache/src/main/java/com/baeldung/springmustache/model/Article.java create mode 100644 spring-mustache/src/main/resources/application.properties create mode 100644 spring-mustache/src/main/resources/templates/error/error.html create mode 100644 spring-mustache/src/main/resources/templates/index.html create mode 100644 spring-mustache/src/main/resources/templates/layout/article.html create mode 100644 spring-mustache/src/main/resources/templates/layout/footer.html create mode 100644 spring-mustache/src/main/resources/templates/layout/header.html create mode 100644 spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java diff --git a/spring-mustache/.gitignore b/spring-mustache/.gitignore new file mode 100644 index 0000000000..2af7cefb0a --- /dev/null +++ b/spring-mustache/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/spring-mustache/pom.xml b/spring-mustache/pom.xml new file mode 100644 index 0000000000..e671672b72 --- /dev/null +++ b/spring-mustache/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + com.baeldung + spring-mustache + 0.0.1-SNAPSHOT + jar + + spring-mustache + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.5.4.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-mustache + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.webjars + bootstrap + 3.3.7 + + + org.fluttercode.datafactory + datafactory + 0.8 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java b/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java new file mode 100644 index 0000000000..d4338ffd7d --- /dev/null +++ b/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java @@ -0,0 +1,34 @@ +package com.baeldung.springmustache; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.mustache.MustacheEnvironmentCollector; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.core.env.Environment; + +import com.samskivert.mustache.Mustache; + +@SpringBootApplication +@ComponentScan(basePackages = { "com.baeldung" }) +public class SpringMustacheApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringMustacheApplication.class, args); + } + + @Bean + public Mustache.Compiler mustacheCompiler(Mustache.TemplateLoader templateLoader, Environment environment) { + + MustacheEnvironmentCollector collector = new MustacheEnvironmentCollector(); + collector.setEnvironment(environment); + + Mustache.Compiler compiler = Mustache.compiler() + .defaultValue("Some Default Value") + .withLoader(templateLoader) + .withCollector(collector); + return compiler; + + } +} + diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java b/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java new file mode 100644 index 0000000000..e0db127d66 --- /dev/null +++ b/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java @@ -0,0 +1,50 @@ +package com.baeldung.springmustache.controller; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.IntStream; + +import org.fluttercode.datafactory.impl.DataFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.baeldung.springmustache.model.Article; + +@Controller +public class ArticleController { + + @RequestMapping("/article") + public ModelAndView displayArticle(Map model) { + + List
articles = new LinkedList<>(); + IntStream.range(0, 10) + .forEach(count -> { + articles.add(generateArticle("Article Title "+count)); + }); + + Map modelMap = new HashMap<>(); + modelMap.put("articles", articles); + + return new ModelAndView("index", modelMap); + } + + private Article generateArticle(String title) { + Article article = new Article(); + DataFactory factory = new DataFactory(); + article.setTitle(title); + article.setBody( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur faucibus tempor diam. In molestie arcu eget ante facilisis sodales. Maecenas porta tellus sapien, eget rutrum nisi blandit in. Mauris tempor auctor ante, ut blandit velit venenatis id. Ut varius, augue aliquet feugiat congue, arcu ipsum finibus purus, dapibus semper velit sapien venenatis magna. Nunc quam ex, aliquet at rutrum sed, vestibulum quis libero. In laoreet libero cursus maximus vulputate. Nullam in fermentum sem. Duis aliquam ullamcorper dui, et dictum justo placerat id. Aliquam pretium orci quis sapien convallis, non blandit est tempus."); + article.setPublishDate(factory.getBirthDate() + .toString()); + article.setAuthor(factory.getName()); + return article; + + } +} + + diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/model/Article.java b/spring-mustache/src/main/java/com/baeldung/springmustache/model/Article.java new file mode 100644 index 0000000000..78b08f877f --- /dev/null +++ b/spring-mustache/src/main/java/com/baeldung/springmustache/model/Article.java @@ -0,0 +1,41 @@ +package com.baeldung.springmustache.model; + +public class Article { + private String title; + private String body; + private String author; + private String publishDate; + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getPublishDate() { + return publishDate; + } + + public void setPublishDate(String publishDate) { + this.publishDate = publishDate; + } + +} diff --git a/spring-mustache/src/main/resources/application.properties b/spring-mustache/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-mustache/src/main/resources/templates/error/error.html b/spring-mustache/src/main/resources/templates/error/error.html new file mode 100644 index 0000000000..fa29db41c4 --- /dev/null +++ b/spring-mustache/src/main/resources/templates/error/error.html @@ -0,0 +1,9 @@ + + + + + + Something went wrong: {{status}} {{error}} + + + \ No newline at end of file diff --git a/spring-mustache/src/main/resources/templates/index.html b/spring-mustache/src/main/resources/templates/index.html new file mode 100644 index 0000000000..bda60f9d8f --- /dev/null +++ b/spring-mustache/src/main/resources/templates/index.html @@ -0,0 +1,9 @@ +{{>layout/header}} + +
{{>layout/article}}
+ + + + +{{>layout/footer}} diff --git a/spring-mustache/src/main/resources/templates/layout/article.html b/spring-mustache/src/main/resources/templates/layout/article.html new file mode 100644 index 0000000000..9d573580d3 --- /dev/null +++ b/spring-mustache/src/main/resources/templates/layout/article.html @@ -0,0 +1,8 @@ +
+ {{#articles}} +

{{title}}

+

{{publishDate}}

+

{{author}}

+

{{body}}

+ {{/articles}} +
\ No newline at end of file diff --git a/spring-mustache/src/main/resources/templates/layout/footer.html b/spring-mustache/src/main/resources/templates/layout/footer.html new file mode 100644 index 0000000000..04f34cac54 --- /dev/null +++ b/spring-mustache/src/main/resources/templates/layout/footer.html @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/spring-mustache/src/main/resources/templates/layout/header.html b/spring-mustache/src/main/resources/templates/layout/header.html new file mode 100644 index 0000000000..d203ef800b --- /dev/null +++ b/spring-mustache/src/main/resources/templates/layout/header.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java b/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java new file mode 100644 index 0000000000..4a72d4156e --- /dev/null +++ b/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java @@ -0,0 +1,32 @@ +package com.baeldung.springmustache; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringMustacheApplicationTests { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void givenIndexPageWhenContainsArticleThenTrue() { + + ResponseEntity entity = this.restTemplate.getForEntity("/article", String.class); + Assert.assertTrue(entity.getStatusCode() + .equals(HttpStatus.OK)); + Assert.assertTrue(entity.getBody() + .contains("Article Title 0")); + + } + +} From f05345112f95e9e282dc4ce169787fbf941d676b Mon Sep 17 00:00:00 2001 From: Sarf Khan Date: Sun, 16 Jul 2017 21:39:35 +0530 Subject: [PATCH 07/43] Spring rest logging Log incoming request --- spring-rest-logging/pom.xml | 64 +++++++++++++++++++ .../baeldung/rest/log/app/Application.java | 18 ++++++ .../log/app/TaxiFareRequestInterceptor.java | 27 ++++++++ .../config/RequestLoggingFilterConfig.java | 23 +++++++ .../rest/log/config/TaxiFareMVCConfig.java | 20 ++++++ .../log/controller/TaxiFareController.java | 40 ++++++++++++ .../com/baeldung/rest/log/data/RateCard.java | 28 ++++++++ .../com/baeldung/rest/log/data/TaxiRide.java | 32 ++++++++++ .../service/TaxiFareCalculatorService.java | 20 ++++++ .../src/main/resources/application.properties | 2 + .../src/main/resources/logback.xml | 21 ++++++ .../controller/TestTaxiFareController.java | 33 ++++++++++ 12 files changed, 328 insertions(+) create mode 100644 spring-rest-logging/pom.xml create mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/app/Application.java create mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/app/TaxiFareRequestInterceptor.java create mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/config/RequestLoggingFilterConfig.java create mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/config/TaxiFareMVCConfig.java create mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/controller/TaxiFareController.java create mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/data/RateCard.java create mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/data/TaxiRide.java create mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/service/TaxiFareCalculatorService.java create mode 100644 spring-rest-logging/src/main/resources/application.properties create mode 100644 spring-rest-logging/src/main/resources/logback.xml create mode 100644 spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java diff --git a/spring-rest-logging/pom.xml b/spring-rest-logging/pom.xml new file mode 100644 index 0000000000..5924650e5f --- /dev/null +++ b/spring-rest-logging/pom.xml @@ -0,0 +1,64 @@ + + 4.0.0 + com.baeldung + spring-rest-logging + 0.1-SNAPSHOT + spring-rest-logging + war + + + org.springframework.boot + spring-boot-starter-parent + 1.4.3.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + org.springframework.boot + spring-boot-test + + + + + org.springframework + spring-web + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + + + + + + javax.servlet + javax.servlet-api + provided + + + + junit + junit + test + + + + org.springframework + spring-test + + + diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/Application.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/Application.java new file mode 100644 index 0000000000..9eb79ee1b1 --- /dev/null +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/Application.java @@ -0,0 +1,18 @@ +package com.baeldung.rest.log.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; + +@EnableAutoConfiguration +@ComponentScan("com.baeldung") +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + public static void main(final String[] args) { + SpringApplication.run(Application.class, args); + } + +} \ No newline at end of file diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/TaxiFareRequestInterceptor.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/TaxiFareRequestInterceptor.java new file mode 100644 index 0000000000..bc011a4db7 --- /dev/null +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/TaxiFareRequestInterceptor.java @@ -0,0 +1,27 @@ +package com.baeldung.rest.log.app; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +@Component +public class TaxiFareRequestInterceptor extends HandlerInterceptorAdapter { + + Logger LOGGER = LoggerFactory.getLogger(TaxiFareRequestInterceptor.class); + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + LOGGER.info("REQUEST URI: " + request.getRequestURI()); + return true; + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + LOGGER.info("RESPONSE: " + response.getStatus()); + } + +} diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/RequestLoggingFilterConfig.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/RequestLoggingFilterConfig.java new file mode 100644 index 0000000000..158ba51f77 --- /dev/null +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/RequestLoggingFilterConfig.java @@ -0,0 +1,23 @@ +package com.baeldung.rest.log.config; + +import javax.servlet.annotation.WebFilter; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.CommonsRequestLoggingFilter; + +@Configuration +@WebFilter +public class RequestLoggingFilterConfig { + + @Bean + public CommonsRequestLoggingFilter logFilter() { + CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter(); + filter.setIncludeQueryString(true); + filter.setIncludePayload(true); + filter.setMaxPayloadLength(10000); + filter.setIncludeHeaders(false); + filter.setAfterMessagePrefix("REQUEST DATA : "); + return filter; + } +} diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/TaxiFareMVCConfig.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/TaxiFareMVCConfig.java new file mode 100644 index 0000000000..71d0fd379f --- /dev/null +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/TaxiFareMVCConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.rest.log.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import com.baeldung.rest.log.app.TaxiFareRequestInterceptor; + +@Configuration +public class TaxiFareMVCConfig extends WebMvcConfigurerAdapter { + + @Autowired + private TaxiFareRequestInterceptor taxiFareRequestInterceptor; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(taxiFareRequestInterceptor).addPathPatterns("/**/taxifare/**/"); + } +} diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/controller/TaxiFareController.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/controller/TaxiFareController.java new file mode 100644 index 0000000000..0d8e4dafa4 --- /dev/null +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/controller/TaxiFareController.java @@ -0,0 +1,40 @@ +package com.baeldung.rest.log.controller; + +import javax.validation.Valid; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.rest.log.data.RateCard; +import com.baeldung.rest.log.data.TaxiRide; +import com.baeldung.rest.log.service.TaxiFareCalculatorService; + +@Controller +public class TaxiFareController { + + @Autowired + private TaxiFareCalculatorService taxiFareCalculatorService; + + private static final Logger LOGGER = LoggerFactory.getLogger(TaxiFareController.class); + + @RequestMapping(method = RequestMethod.GET, value = "/taxifare/get/") + @ResponseBody + public RateCard getTaxiFare() { + LOGGER.debug("getTaxiFare() - START"); + return new RateCard(); + } + + @RequestMapping(method = RequestMethod.POST, value = "/taxifare/calculate/") + @ResponseBody + public String calculateTaxiFare(@RequestBody @Valid TaxiRide taxiRide) { + LOGGER.debug("calculateTaxiFare() - START"); + return taxiFareCalculatorService.calculateFare(taxiRide); + } + +} diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/data/RateCard.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/data/RateCard.java new file mode 100644 index 0000000000..6e0c6d0e38 --- /dev/null +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/data/RateCard.java @@ -0,0 +1,28 @@ +package com.baeldung.rest.log.data; + +public class RateCard { + + private String nightSurcharge; + private String ratePerMile; + + public RateCard(){ + nightSurcharge="Extra $ 100"; + ratePerMile="$ 10 Per Mile"; + } + + + public String getNightSurcharge() { + return nightSurcharge; + } + public void setNightSurcharge(String nightSurcharge) { + this.nightSurcharge = nightSurcharge; + } + public String getRatePerMile() { + return ratePerMile; + } + public void setRatePerMile(String ratePerMile) { + this.ratePerMile = ratePerMile; + } + + +} diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/data/TaxiRide.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/data/TaxiRide.java new file mode 100644 index 0000000000..bcf102e49d --- /dev/null +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/data/TaxiRide.java @@ -0,0 +1,32 @@ +package com.baeldung.rest.log.data; + +public class TaxiRide { + + private Boolean isNightSurcharge; + private Long distanceInMile; + + public TaxiRide(){} + + public TaxiRide(Boolean isNightSurcharge, Long distanceInMile){ + this.isNightSurcharge = isNightSurcharge; + this.distanceInMile = distanceInMile; + } + + + public Boolean getIsNightSurcharge() { + return isNightSurcharge; + } + + public void setIsNightSurcharge(Boolean isNightSurcharge) { + this.isNightSurcharge = isNightSurcharge; + } + + public Long getDistanceInMile() { + return distanceInMile; + } + + public void setDistanceInMile(Long distanceInMile) { + this.distanceInMile = distanceInMile; + } + +} diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/service/TaxiFareCalculatorService.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/service/TaxiFareCalculatorService.java new file mode 100644 index 0000000000..31dfd7ac50 --- /dev/null +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/service/TaxiFareCalculatorService.java @@ -0,0 +1,20 @@ +package com.baeldung.rest.log.service; + +import org.springframework.stereotype.Service; + +import com.baeldung.rest.log.data.TaxiRide; + +@Service +public class TaxiFareCalculatorService { + + public String calculateFare(TaxiRide taxiRide) { + Long fare = 0l; + if (taxiRide.getIsNightSurcharge()) { + fare = taxiRide.getDistanceInMile() * 10 + 100; + } else { + fare = taxiRide.getDistanceInMile() * 10; + } + return String.valueOf(fare); + } + +} diff --git a/spring-rest-logging/src/main/resources/application.properties b/spring-rest-logging/src/main/resources/application.properties new file mode 100644 index 0000000000..ff8a818e66 --- /dev/null +++ b/spring-rest-logging/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port= 9090 +server.context-path=/rest-log diff --git a/spring-rest-logging/src/main/resources/logback.xml b/spring-rest-logging/src/main/resources/logback.xml new file mode 100644 index 0000000000..08117752c7 --- /dev/null +++ b/spring-rest-logging/src/main/resources/logback.xml @@ -0,0 +1,21 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java b/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java new file mode 100644 index 0000000000..61d279a0c5 --- /dev/null +++ b/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java @@ -0,0 +1,33 @@ +package com.baeldung.rest.log.controller; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.Test; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import com.baeldung.rest.log.data.TaxiRide; + +public class TestTaxiFareController { + + private static final String URL = "http://localhost:" + 9090 + "/rest-log/taxifare/"; + + @Test + public void given_taxi_fare_get() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + ResponseEntity response = testRestTemplate.getForEntity(URL + "get/", String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void given_taxi_ride_get_fare() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + TaxiRide taxiRide = new TaxiRide(true,10l); + String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide,String.class); + assertThat(fare, equalTo("200")); + } + + +} From fb7d3fe8f49a896fc10af06f9ea2a095c85161c1 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Mon, 17 Jul 2017 06:10:55 +0200 Subject: [PATCH 08/43] Bael 1010 hll (#2274) * BAEL-1010 HLL article code * BAEL-1010 moved tolerated difference to a variable * Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-1010_hll # Conflicts: # libraries/pom.xml * BAEL-1010 clearer code * use isCloseTo --- .../java/com/baeldung/hll/HLLUnitTest.java | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java b/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java index 2745e1e681..8d09c99f0f 100644 --- a/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java +++ b/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java @@ -4,6 +4,7 @@ package com.baeldung.hll; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import net.agkn.hll.HLL; +import org.assertj.core.data.Offset; import org.junit.Test; import java.util.stream.LongStream; @@ -15,8 +16,8 @@ public class HLLUnitTest { @Test public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() { //given - int numberOfElements = 100_000_000; - int toleratedDifference = 1_000_000; + long numberOfElements = 100_000_000; + long toleratedDifference = 1_000_000; HashFunction hashFunction = Hashing.murmur3_128(); HLL hll = new HLL(14, 5); @@ -29,14 +30,14 @@ public class HLLUnitTest { //then long cardinality = hll.cardinality(); - assertThat(isSimilarTo(cardinality, numberOfElements, toleratedDifference)).isTrue(); + assertThat(cardinality).isCloseTo(numberOfElements, Offset.offset(toleratedDifference)); } @Test public void givenTwoHLLs_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinalityForUnionOfHLLs() { //given - int numberOfElements = 100_000_000; - int toleratedDifference = 1_000_000; + long numberOfElements = 100_000_000; + long toleratedDifference = 1_000_000; HashFunction hashFunction = Hashing.murmur3_128(); HLL firstHll = new HLL(15, 5); HLL secondHLL = new HLL(15, 5); @@ -57,12 +58,6 @@ public class HLLUnitTest { //then firstHll.union(secondHLL); long cardinality = firstHll.cardinality(); - assertThat(isSimilarTo(cardinality, numberOfElements * 2, - toleratedDifference * 2)).isTrue(); - } - - private boolean isSimilarTo(long cardinality, int numberOfElements, int maxToleratedDifference) { - System.out.println(cardinality); - return Math.abs(cardinality - numberOfElements) <= maxToleratedDifference; + assertThat(cardinality).isCloseTo(numberOfElements * 2, Offset.offset(toleratedDifference * 2)); } } From fe39bc6c3d7a6da466d913d6ff1919883a3b20b2 Mon Sep 17 00:00:00 2001 From: baljeet20 Date: Mon, 17 Jul 2017 20:13:22 +0530 Subject: [PATCH 09/43] BAEL-1024 Introduction to MockServer (#2275) --- mockserver/pom.xml | 41 ++++ .../server/ExpectationCallbackHandler.java | 23 +++ .../baeldung/mock/server/TestMockServer.java | 178 ++++++++++++++++++ pom.xml | 1 + 4 files changed, 243 insertions(+) create mode 100644 mockserver/pom.xml create mode 100644 mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java create mode 100644 mockserver/src/test/java/com/baeldung/mock/server/TestMockServer.java diff --git a/mockserver/pom.xml b/mockserver/pom.xml new file mode 100644 index 0000000000..a3ca5459c9 --- /dev/null +++ b/mockserver/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + com.baeldung + mockserver + 1.0.0-SNAPSHOT + + 3.10.8 + 4.4.1 + + + + + org.mock-server + mockserver-netty + ${mock-sever-netty-version} + + + + org.mock-server + mockserver-client-java + ${mock-sever-netty-version} + + + + org.apache.httpcomponents + httpclient + ${apche-http-version} + + + org.apache.httpcomponents + httpcore + ${apche-http-version} + + + + + \ No newline at end of file diff --git a/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java b/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java new file mode 100644 index 0000000000..a74dca28da --- /dev/null +++ b/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java @@ -0,0 +1,23 @@ +package com.baeldung.mock.server; + +import org.mockserver.mock.action.ExpectationCallback; +import org.mockserver.model.HttpRequest; +import org.mockserver.model.HttpResponse; + +import static org.mockserver.model.HttpResponse.notFoundResponse; +import static org.mockserver.model.HttpResponse.response; + + +public class ExpectationCallbackHandler implements ExpectationCallback { + + public HttpResponse handle(HttpRequest httpRequest) { + if (httpRequest.getPath().getValue().endsWith("/callback")) { + return httpResponse; + } else { + return notFoundResponse(); + } + } + + public static HttpResponse httpResponse = response() + .withStatusCode(200); +} diff --git a/mockserver/src/test/java/com/baeldung/mock/server/TestMockServer.java b/mockserver/src/test/java/com/baeldung/mock/server/TestMockServer.java new file mode 100644 index 0000000000..aea1b8b278 --- /dev/null +++ b/mockserver/src/test/java/com/baeldung/mock/server/TestMockServer.java @@ -0,0 +1,178 @@ +package com.baeldung.mock.server; + +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockserver.client.server.MockServerClient; +import org.mockserver.integration.ClientAndProxy; +import org.mockserver.integration.ClientAndServer; +import org.mockserver.model.Header; +import org.mockserver.model.HttpForward; +import org.mockserver.verify.VerificationTimes; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +import static junit.framework.Assert.assertEquals; +import static org.mockserver.integration.ClientAndProxy.startClientAndProxy; +import static org.mockserver.integration.ClientAndServer.startClientAndServer; +import static org.mockserver.matchers.Times.exactly; +import static org.mockserver.model.HttpClassCallback.callback; +import static org.mockserver.model.HttpForward.forward; +import static org.mockserver.model.HttpRequest.request; +import static org.mockserver.model.HttpResponse.response; +import static org.mockserver.model.StringBody.exact; + +public class TestMockServer { + + private ClientAndProxy proxy; + private ClientAndServer mockServer; + + @Before + public void startProxy() { + mockServer = startClientAndServer(1080); + proxy = startClientAndProxy(1090); + } + + + @Test + public void whenPostRequestMockServer_thenServerReceived(){ + createExpectationForInvalidAuth(); + hitTheServerWithPostRequest(); + verifyPostRequest(); + } + + @Test + public void whenPostRequestForInvalidAuth_then401Received(){ + createExpectationForInvalidAuth(); + org.apache.http.HttpResponse response = hitTheServerWithPostRequest(); + assertEquals(401, response.getStatusLine().getStatusCode()); + } + + @Test + public void whenGetRequest_ThenForward(){ + createExpectationForForward(); + hitTheServerWithGetRequest("index.html"); + verifyGetRequest(); + + } + + @Test + public void whenCallbackRequest_ThenCallbackMethodCalled(){ + createExpectationForCallBack(); + org.apache.http.HttpResponse response= hitTheServerWithGetRequest("/callback"); + assertEquals(200,response.getStatusLine().getStatusCode()); + } + + private void verifyPostRequest() { + new MockServerClient("localhost", 1080).verify( + request() + .withMethod("POST") + .withPath("/validate") + .withBody(exact("{username: 'foo', password: 'bar'}")), + VerificationTimes.exactly(1) + ); + } + private void verifyGetRequest() { + new MockServerClient("localhost", 1080).verify( + request() + .withMethod("GET") + .withPath("/index.html"), + VerificationTimes.exactly(1) + ); + } + + private org.apache.http.HttpResponse hitTheServerWithPostRequest() { + String url = "http://127.0.0.1:1080/validate"; + HttpClient client = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost(url); + post.setHeader("Content-type", "application/json"); + org.apache.http.HttpResponse response=null; + + try { + StringEntity stringEntity = new StringEntity("{username: 'foo', password: 'bar'}"); + post.getRequestLine(); + post.setEntity(stringEntity); + response=client.execute(post); + + } catch (Exception e) { + throw new RuntimeException(e); + } + return response; + } + + private org.apache.http.HttpResponse hitTheServerWithGetRequest(String page) { + String url = "http://127.0.0.1:1080/"+page; + HttpClient client = HttpClientBuilder.create().build(); + org.apache.http.HttpResponse response=null; + HttpGet get = new HttpGet(url); + try { + response=client.execute(get); + } catch (IOException e) { + throw new RuntimeException(e); + } + + return response; + } + + private void createExpectationForInvalidAuth() { + new MockServerClient("127.0.0.1", 1080) + .when( + request() + .withMethod("POST") + .withPath("/validate") + .withHeader("\"Content-type\", \"application/json\"") + .withBody(exact("{username: 'foo', password: 'bar'}")), + exactly(1) + ) + .respond( + response() + .withStatusCode(401) + .withHeaders( + new Header("Content-Type", "application/json; charset=utf-8"), + new Header("Cache-Control", "public, max-age=86400") + ) + .withBody("{ message: 'incorrect username and password combination' }") + .withDelay(TimeUnit.SECONDS,1) + ); + } + + private void createExpectationForForward(){ + new MockServerClient("127.0.0.1", 1080) + .when( + request() + .withMethod("GET") + .withPath("/index.html"), + exactly(1) + ) + .forward( + forward() + .withHost("www.mock-server.com") + .withPort(80) + .withScheme(HttpForward.Scheme.HTTP) + ); + } + + private void createExpectationForCallBack(){ + mockServer + .when( + request() + .withPath("/callback") + ) + .callback( + callback() + .withCallbackClass("com.baeldung.mock.server.ExpectationCallbackHandler") + ); + } + + @After + public void stopProxy() { + proxy.stop(); + mockServer.stop(); + } +} diff --git a/pom.xml b/pom.xml index d01134fb30..f0a331e3bd 100644 --- a/pom.xml +++ b/pom.xml @@ -230,6 +230,7 @@ drools liquibase spring-boot-property-exp + mockserver From 59cb7db53e660ac324411476fd18213098d5db88 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Mon, 17 Jul 2017 19:12:24 +0100 Subject: [PATCH 10/43] BAEL-982 - reformatting --- spring-mustache/pom.xml | 97 ++++++++++--------- .../SpringMustacheApplication.java | 8 +- .../controller/ArticleController.java | 12 +-- .../SpringMustacheApplicationTests.java | 6 +- 4 files changed, 60 insertions(+), 63 deletions(-) diff --git a/spring-mustache/pom.xml b/spring-mustache/pom.xml index e671672b72..45fee6b10e 100644 --- a/spring-mustache/pom.xml +++ b/spring-mustache/pom.xml @@ -1,60 +1,61 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - com.baeldung - spring-mustache - 0.0.1-SNAPSHOT - jar + com.baeldung + spring-mustache + 0.0.1-SNAPSHOT + jar - spring-mustache - Demo project for Spring Boot + spring-mustache + Demo project for Spring Boot - - org.springframework.boot - spring-boot-starter-parent - 1.5.4.RELEASE - - + + org.springframework.boot + spring-boot-starter-parent + 1.5.4.RELEASE + + + - - UTF-8 - UTF-8 - 1.8 - + + UTF-8 + UTF-8 + 1.8 + - - - org.springframework.boot - spring-boot-starter-mustache - + + + org.springframework.boot + spring-boot-starter-mustache + - - org.springframework.boot - spring-boot-starter-test - test - - - org.webjars - bootstrap - 3.3.7 - - - org.fluttercode.datafactory - datafactory - 0.8 - - + + org.springframework.boot + spring-boot-starter-test + test + + + org.webjars + bootstrap + 3.3.7 + + + org.fluttercode.datafactory + datafactory + 0.8 + + - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java b/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java index d4338ffd7d..addd1fa088 100644 --- a/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java +++ b/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java @@ -10,7 +10,7 @@ import org.springframework.core.env.Environment; import com.samskivert.mustache.Mustache; @SpringBootApplication -@ComponentScan(basePackages = { "com.baeldung" }) +@ComponentScan(basePackages = {"com.baeldung"}) public class SpringMustacheApplication { public static void main(String[] args) { @@ -24,9 +24,9 @@ public class SpringMustacheApplication { collector.setEnvironment(environment); Mustache.Compiler compiler = Mustache.compiler() - .defaultValue("Some Default Value") - .withLoader(templateLoader) - .withCollector(collector); + .defaultValue("Some Default Value") + .withLoader(templateLoader) + .withCollector(collector); return compiler; } diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java b/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java index e0db127d66..b24625e7d5 100644 --- a/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java +++ b/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java @@ -23,9 +23,9 @@ public class ArticleController { List
articles = new LinkedList<>(); IntStream.range(0, 10) - .forEach(count -> { - articles.add(generateArticle("Article Title "+count)); - }); + .forEach(count -> { + articles.add(generateArticle("Article Title " + count)); + }); Map modelMap = new HashMap<>(); modelMap.put("articles", articles); @@ -38,12 +38,10 @@ public class ArticleController { DataFactory factory = new DataFactory(); article.setTitle(title); article.setBody( - "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur faucibus tempor diam. In molestie arcu eget ante facilisis sodales. Maecenas porta tellus sapien, eget rutrum nisi blandit in. Mauris tempor auctor ante, ut blandit velit venenatis id. Ut varius, augue aliquet feugiat congue, arcu ipsum finibus purus, dapibus semper velit sapien venenatis magna. Nunc quam ex, aliquet at rutrum sed, vestibulum quis libero. In laoreet libero cursus maximus vulputate. Nullam in fermentum sem. Duis aliquam ullamcorper dui, et dictum justo placerat id. Aliquam pretium orci quis sapien convallis, non blandit est tempus."); - article.setPublishDate(factory.getBirthDate() - .toString()); + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur faucibus tempor diam. In molestie arcu eget ante facilisis sodales. Maecenas porta tellus sapien, eget rutrum nisi blandit in. Mauris tempor auctor ante, ut blandit velit venenatis id. Ut varius, augue aliquet feugiat congue, arcu ipsum finibus purus, dapibus semper velit sapien venenatis magna. Nunc quam ex, aliquet at rutrum sed, vestibulum quis libero. In laoreet libero cursus maximus vulputate. Nullam in fermentum sem. Duis aliquam ullamcorper dui, et dictum justo placerat id. Aliquam pretium orci quis sapien convallis, non blandit est tempus."); + article.setPublishDate(factory.getBirthDate().toString()); article.setAuthor(factory.getName()); return article; - } } diff --git a/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java b/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java index 4a72d4156e..9138dfe92b 100644 --- a/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java +++ b/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java @@ -22,11 +22,9 @@ public class SpringMustacheApplicationTests { public void givenIndexPageWhenContainsArticleThenTrue() { ResponseEntity entity = this.restTemplate.getForEntity("/article", String.class); - Assert.assertTrue(entity.getStatusCode() - .equals(HttpStatus.OK)); - Assert.assertTrue(entity.getBody() - .contains("Article Title 0")); + Assert.assertTrue(entity.getStatusCode().equals(HttpStatus.OK)); + Assert.assertTrue(entity.getBody().contains("Article Title 0")); } } From 3671427d5e377fb684b97833a9fac719531b5936 Mon Sep 17 00:00:00 2001 From: Mohit Sinha Date: Tue, 18 Jul 2017 01:53:03 +0530 Subject: [PATCH 11/43] BAEL-969 Apache Commons Chain (#2228) * BAEL 969 Apache Commons Chain - Example with testcase * Made changes for Apache Commons Chain as per recommendation --- libraries/pom.xml | 8 ++- .../chain/AbstractDenominationDispenser.java | 23 ++++++++ .../baeldung/commons/chain/AtmCatalog.java | 13 +++++ .../baeldung/commons/chain/AtmConstants.java | 10 ++++ .../commons/chain/AtmRequestContext.java | 52 +++++++++++++++++++ .../commons/chain/AtmWithdrawalChain.java | 14 +++++ .../baeldung/commons/chain/AuditFilter.java | 18 +++++++ .../chain/FiftyDenominationDispenser.java | 15 ++++++ .../chain/HundredDenominationDispenser.java | 15 ++++++ .../chain/TenDenominationDispenser.java | 15 ++++++ .../baeldung/commons/chain/AtmChainTest.java | 37 +++++++++++++ 11 files changed, 219 insertions(+), 1 deletion(-) create mode 100644 libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java create mode 100644 libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java create mode 100644 libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java create mode 100644 libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java create mode 100644 libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java create mode 100644 libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java create mode 100644 libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java create mode 100644 libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java create mode 100644 libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java create mode 100644 libraries/src/test/java/com/baeldung/commons/chain/AtmChainTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index 9093a2db03..6be4980b93 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -227,11 +227,16 @@ commons-io ${commons.io.version} + + commons-chain + commons-chain + ${commons-chain.version} + commons-dbutils commons-dbutils ${commons.dbutils.version} - + org.apache.flink flink-core @@ -532,6 +537,7 @@ 3.5 1.1 1.9.3 + 1.2 1.9.2 1.2 3.21.0-GA diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java b/libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java new file mode 100644 index 0000000000..cbcf03c7d4 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java @@ -0,0 +1,23 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.Command; +import org.apache.commons.chain.Context; + +import static com.baeldung.commons.chain.AtmConstants.AMOUNT_LEFT_TO_BE_WITHDRAWN; + +public abstract class AbstractDenominationDispenser implements Command { + + @Override + public boolean execute(Context context) throws Exception { + int amountLeftToBeWithdrawn = (int) context.get(AMOUNT_LEFT_TO_BE_WITHDRAWN); + if (amountLeftToBeWithdrawn >= getDenominationValue()) { + context.put(getDenominationString(), amountLeftToBeWithdrawn / getDenominationValue()); + context.put(AMOUNT_LEFT_TO_BE_WITHDRAWN, amountLeftToBeWithdrawn % getDenominationValue()); + } + return false; + } + + protected abstract String getDenominationString(); + + protected abstract int getDenominationValue(); +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java b/libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java new file mode 100644 index 0000000000..768517e19a --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java @@ -0,0 +1,13 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.impl.CatalogBase; + +import static com.baeldung.commons.chain.AtmConstants.ATM_WITHDRAWAL_CHAIN; + +public class AtmCatalog extends CatalogBase { + + public AtmCatalog() { + super(); + addCommand(ATM_WITHDRAWAL_CHAIN, new AtmWithdrawalChain()); + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java b/libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java new file mode 100644 index 0000000000..d9425fcfac --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java @@ -0,0 +1,10 @@ +package com.baeldung.commons.chain; + +public class AtmConstants { + public static final String TOTAL_AMOUNT_TO_BE_WITHDRAWN = "totalAmountToBeWithdrawn"; + public static final String AMOUNT_LEFT_TO_BE_WITHDRAWN = "amountLeftToBeWithdrawn"; + public static final String NO_OF_HUNDREDS_DISPENSED = "noOfHundredsDispensed"; + public static final String NO_OF_FIFTIES_DISPENSED = "noOfFiftiesDispensed"; + public static final String NO_OF_TENS_DISPENSED = "noOfTensDispensed"; + public static final String ATM_WITHDRAWAL_CHAIN = "atmWithdrawalChain"; +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java b/libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java new file mode 100644 index 0000000000..ee089705ad --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java @@ -0,0 +1,52 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.impl.ContextBase; + +public class AtmRequestContext extends ContextBase { + + int totalAmountToBeWithdrawn; + int noOfHundredsDispensed; + int noOfFiftiesDispensed; + int noOfTensDispensed; + int amountLeftToBeWithdrawn; + + public int getTotalAmountToBeWithdrawn() { + return totalAmountToBeWithdrawn; + } + + public void setTotalAmountToBeWithdrawn(int totalAmountToBeWithdrawn) { + this.totalAmountToBeWithdrawn = totalAmountToBeWithdrawn; + } + + public int getNoOfHundredsDispensed() { + return noOfHundredsDispensed; + } + + public void setNoOfHundredsDispensed(int noOfHundredsDispensed) { + this.noOfHundredsDispensed = noOfHundredsDispensed; + } + + public int getNoOfFiftiesDispensed() { + return noOfFiftiesDispensed; + } + + public void setNoOfFiftiesDispensed(int noOfFiftiesDispensed) { + this.noOfFiftiesDispensed = noOfFiftiesDispensed; + } + + public int getNoOfTensDispensed() { + return noOfTensDispensed; + } + + public void setNoOfTensDispensed(int noOfTensDispensed) { + this.noOfTensDispensed = noOfTensDispensed; + } + + public int getAmountLeftToBeWithdrawn() { + return amountLeftToBeWithdrawn; + } + + public void setAmountLeftToBeWithdrawn(int amountLeftToBeWithdrawn) { + this.amountLeftToBeWithdrawn = amountLeftToBeWithdrawn; + } +} diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java b/libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java new file mode 100644 index 0000000000..fdea5e5744 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java @@ -0,0 +1,14 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.impl.ChainBase; + +public class AtmWithdrawalChain extends ChainBase { + + public AtmWithdrawalChain() { + super(); + addCommand(new HundredDenominationDispenser()); + addCommand(new FiftyDenominationDispenser()); + addCommand(new TenDenominationDispenser()); + addCommand(new AuditFilter()); + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java b/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java new file mode 100644 index 0000000000..973e2d498e --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java @@ -0,0 +1,18 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.Context; +import org.apache.commons.chain.Filter; + +public class AuditFilter implements Filter { + + @Override + public boolean postprocess(Context context, Exception exception) { + // Send notification to customer & bank. + return false; + } + + @Override + public boolean execute(Context context) throws Exception { + return false; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java b/libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java new file mode 100644 index 0000000000..f0f5959764 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java @@ -0,0 +1,15 @@ +package com.baeldung.commons.chain; + +import static com.baeldung.commons.chain.AtmConstants.NO_OF_FIFTIES_DISPENSED; + +public class FiftyDenominationDispenser extends AbstractDenominationDispenser { + @Override + protected String getDenominationString() { + return NO_OF_FIFTIES_DISPENSED; + } + + @Override + protected int getDenominationValue() { + return 50; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java b/libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java new file mode 100644 index 0000000000..e65d0d34c9 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java @@ -0,0 +1,15 @@ +package com.baeldung.commons.chain; + +import static com.baeldung.commons.chain.AtmConstants.NO_OF_HUNDREDS_DISPENSED; + +public class HundredDenominationDispenser extends AbstractDenominationDispenser { + @Override + protected String getDenominationString() { + return NO_OF_HUNDREDS_DISPENSED; + } + + @Override + protected int getDenominationValue() { + return 100; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java b/libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java new file mode 100644 index 0000000000..423440bc4d --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java @@ -0,0 +1,15 @@ +package com.baeldung.commons.chain; + +import static com.baeldung.commons.chain.AtmConstants.NO_OF_TENS_DISPENSED; + +public class TenDenominationDispenser extends AbstractDenominationDispenser { + @Override + protected String getDenominationString() { + return NO_OF_TENS_DISPENSED; + } + + @Override + protected int getDenominationValue() { + return 10; + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/commons/chain/AtmChainTest.java b/libraries/src/test/java/com/baeldung/commons/chain/AtmChainTest.java new file mode 100644 index 0000000000..cd9a7baaf3 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/chain/AtmChainTest.java @@ -0,0 +1,37 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.Catalog; +import org.apache.commons.chain.Command; +import org.apache.commons.chain.Context; +import org.junit.Assert; +import org.junit.Test; + +import static com.baeldung.commons.chain.AtmConstants.*; + +public class AtmChainTest { + + public static final int EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN = 460; + public static final int EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN = 0; + public static final int EXPECTED_NO_OF_HUNDREDS_DISPENSED = 4; + public static final int EXPECTED_NO_OF_FIFTIES_DISPENSED = 1; + public static final int EXPECTED_NO_OF_TENS_DISPENSED = 1; + + @Test + public void givenInputsToContext_whenAppliedChain_thenExpectedContext() { + Context context = new AtmRequestContext(); + context.put(TOTAL_AMOUNT_TO_BE_WITHDRAWN, 460); + context.put(AMOUNT_LEFT_TO_BE_WITHDRAWN, 460); + Catalog catalog = new AtmCatalog(); + Command atmWithdrawalChain = catalog.getCommand(ATM_WITHDRAWAL_CHAIN); + try { + atmWithdrawalChain.execute(context); + } catch (Exception e) { + e.printStackTrace(); + } + Assert.assertEquals(EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN, (int) context.get(TOTAL_AMOUNT_TO_BE_WITHDRAWN)); + Assert.assertEquals(EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN, (int) context.get(AMOUNT_LEFT_TO_BE_WITHDRAWN)); + Assert.assertEquals(EXPECTED_NO_OF_HUNDREDS_DISPENSED, (int) context.get(NO_OF_HUNDREDS_DISPENSED)); + Assert.assertEquals(EXPECTED_NO_OF_FIFTIES_DISPENSED, (int) context.get(NO_OF_FIFTIES_DISPENSED)); + Assert.assertEquals(EXPECTED_NO_OF_TENS_DISPENSED, (int) context.get(NO_OF_TENS_DISPENSED)); + } +} \ No newline at end of file From 2ce547d4cdab1a5e4c707d852ca7500c83eff2ae Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Mon, 17 Jul 2017 23:44:10 +0100 Subject: [PATCH 12/43] Complete Example Code for BAEL-782 (#2270) * 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 --- libraries/pom.xml | 11 +++ .../main/java/com/baeldung/bytebuddy/Bar.java | 16 ++++ .../main/java/com/baeldung/bytebuddy/Foo.java | 7 ++ .../baeldung/bytebuddy/ByteBuddyUnitTest.java | 89 +++++++++++++++++++ 4 files changed, 123 insertions(+) create mode 100644 libraries/src/main/java/com/baeldung/bytebuddy/Bar.java create mode 100644 libraries/src/main/java/com/baeldung/bytebuddy/Foo.java create mode 100644 libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index 6be4980b93..c23b6ef912 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -530,6 +530,16 @@ hll ${hll.version} + + net.bytebuddy + byte-buddy + ${bytebuddy.version} + + + net.bytebuddy + byte-buddy-agent + ${bytebuddy.version} + 0.7.0 @@ -572,6 +582,7 @@ mytheme 1.6.0 + 1.7.1 diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java b/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java new file mode 100644 index 0000000000..d0362a6c92 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java @@ -0,0 +1,16 @@ +package com.baeldung.bytebuddy; + +import net.bytebuddy.implementation.bind.annotation.BindingPriority; + +public class Bar { + + @BindingPriority(3) + public static String sayHelloBar() { return "Holla in Bar!"; } + + @BindingPriority(2) + public static String sayBar() { return "bar"; } + + public String bar() { return Bar.class.getSimpleName() + " - Bar"; } + + +} diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java b/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java new file mode 100644 index 0000000000..4be06785b1 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java @@ -0,0 +1,7 @@ +package com.baeldung.bytebuddy; + +public class Foo { + + public String sayHelloFoo() { return "Hello in Foo!"; } + +} diff --git a/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java b/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java new file mode 100644 index 0000000000..6b7364a0a5 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java @@ -0,0 +1,89 @@ +package com.baeldung.bytebuddy; + +import net.bytebuddy.ByteBuddy; +import net.bytebuddy.agent.ByteBuddyAgent; +import net.bytebuddy.dynamic.DynamicType; +import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; +import net.bytebuddy.dynamic.loading.ClassReloadingStrategy; +import net.bytebuddy.implementation.FixedValue; +import net.bytebuddy.implementation.MethodDelegation; +import net.bytebuddy.matcher.ElementMatchers; +import org.junit.Test; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import static net.bytebuddy.matcher.ElementMatchers.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class ByteBuddyUnitTest { + + @Test + public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException { + DynamicType.Unloaded unloadedType = new ByteBuddy() + .subclass(Object.class) + .method(ElementMatchers.isToString()) + .intercept(FixedValue.value("Hello World ByteBuddy!")) + .make(); + + Class dynamicType = unloadedType.load(getClass().getClassLoader()) + .getLoaded(); + + assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!"); + } + + @Test + public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception { + ByteBuddyAgent.install(); + new ByteBuddy() + .redefine(Foo.class) + .method(named("sayHelloFoo")) + .intercept(FixedValue.value("Hello Foo Redefined")) + .make() + .load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent()); + Foo f = new Foo(); + assertEquals(f.sayHelloFoo(), "Hello Foo Redefined"); + } + + @Test + public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException { + + String r = new ByteBuddy() + .subclass(Foo.class) + .method( + named("sayHelloFoo") + .and(isDeclaredBy(Foo.class) + .and(returns(String.class))) + ) + .intercept(MethodDelegation.to(Bar.class)) + .make() + .load(getClass().getClassLoader()) + .getLoaded() + .newInstance() + .sayHelloFoo(); + + assertEquals(r, Bar.sayHelloBar()); + } + + @Test + public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception { + Class type = new ByteBuddy() + .subclass(Object.class) + .name("MyClassName") + .defineMethod("custom", String.class, Modifier.PUBLIC) + .intercept(MethodDelegation.to(Bar.class)) + .defineField("x", String.class, Modifier.PUBLIC) + .make() + .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) + .getLoaded(); + + Method m = type.getDeclaredMethod("custom", null); + + assertEquals(m.invoke(type.newInstance()), Bar.sayHelloBar()); + assertNotNull(type.getDeclaredField("x")); + + } + + +} From afa82c0d28c63703ad977c3a3defb662a8ea48ce Mon Sep 17 00:00:00 2001 From: deep20jain Date: Tue, 18 Jul 2017 09:38:19 +0530 Subject: [PATCH 13/43] BAEL-1029 - deep20jain@gmail.com - An Introduction to Atomic Variables in Java (#2269) * Adding test classes for java atomic variables * Updating counter with atomic integer * Adding reason for ignoring test --- .../atomic/SafeCounterWithLock.java | 13 +++++ .../atomic/SafeCounterWithoutLock.java | 21 +++++++ .../concurrent/atomic/UnsafeCounter.java | 13 +++++ .../concurrent/atomic/CounterTest.java | 58 +++++++++++++++++++ 4 files changed, 105 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java create mode 100644 core-java/src/test/java/com/baeldung/concurrent/atomic/CounterTest.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java new file mode 100644 index 0000000000..b2502018bb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.atomic; + +public class SafeCounterWithLock { + int counter; + + public int getValue() { + return counter; + } + + public synchronized void increment() { + counter++; + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java new file mode 100644 index 0000000000..55226f4f13 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java @@ -0,0 +1,21 @@ +package com.baeldung.concurrent.atomic; + +import java.util.concurrent.atomic.AtomicInteger; + +public class SafeCounterWithoutLock { + AtomicInteger counter = new AtomicInteger(0); + + public int getValue() { + return counter.get(); + } + + public void increment() { + while(true) { + int existingValue = getValue(); + int newValue = existingValue + 1; + if(counter.compareAndSet(existingValue, newValue)) { + return; + } + } + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java b/core-java/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java new file mode 100644 index 0000000000..8a72788842 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.atomic; + +public class UnsafeCounter { + int counter; + + public int getValue() { + return counter; + } + + public void increment() { + counter++; + } +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/atomic/CounterTest.java b/core-java/src/test/java/com/baeldung/concurrent/atomic/CounterTest.java new file mode 100644 index 0000000000..1612c62513 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/atomic/CounterTest.java @@ -0,0 +1,58 @@ +package com.baeldung.concurrent.atomic; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import org.junit.Ignore; +import org.junit.Test; + +public class CounterTest { + + /** + * This test shows the behaviour of a thread-unsafe class in a multithreaded scenario. We are calling + * the increment methods 1000 times from a pool of 3 threads. In most of the cases, the counter will + * less than 1000, because of lost updates, however, occasionally it may reach 1000, when no threads + * called the method simultaneously. This may cause the build to fail occasionally. Hence excluding this + * test by adding Ignore annotation. + */ + @Test + @Ignore + public void givenMultiThread_whenUnsafeCounterIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + UnsafeCounter unsafeCounter = new UnsafeCounter(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(unsafeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, unsafeCounter.getValue()); + } + + @Test + public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + SafeCounterWithLock safeCounter = new SafeCounterWithLock(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(safeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, safeCounter.getValue()); + } + + @Test + public void givenMultiThread_whenSafeCounterWithoutLockIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(safeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, safeCounter.getValue()); + } +} From aba59e88d9e2101a7050b85af3e20112bc2c6888 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Tue, 18 Jul 2017 18:34:06 -0500 Subject: [PATCH 14/43] BAEL-1010: README (#2284) * 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) --- libraries/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/README.md b/libraries/README.md index 30f02e5c5a..7970c0e99e 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -25,7 +25,7 @@ - [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map) - [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) - [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) - +- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) 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 a24e442731b82235ca18451d8eafe44ce58cda02 Mon Sep 17 00:00:00 2001 From: Jesus Boadas Date: Tue, 18 Jul 2017 19:46:02 -0400 Subject: [PATCH 15/43] Vaadin server-push, data binding and validators (#2283) --- libraries/pom.xml | 4 + .../java/com/baeldung/vaadin/BindData.java | 20 ++++ .../java/com/baeldung/vaadin/VaadinUI.java | 102 +++++++++++++++--- 3 files changed, 112 insertions(+), 14 deletions(-) create mode 100644 libraries/src/main/java/com/baeldung/vaadin/BindData.java diff --git a/libraries/pom.xml b/libraries/pom.xml index c23b6ef912..16f70cb171 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -476,6 +476,10 @@ com.vaadin vaadin-themes + + com.vaadin + vaadin-push + org.seleniumhq.selenium selenium-java diff --git a/libraries/src/main/java/com/baeldung/vaadin/BindData.java b/libraries/src/main/java/com/baeldung/vaadin/BindData.java new file mode 100644 index 0000000000..bcdc4eee71 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/vaadin/BindData.java @@ -0,0 +1,20 @@ +package com.baeldung.vaadin; + +public class BindData { + + private String bindName; + + public BindData(String bindName){ + this.bindName = bindName; + } + + public String getBindName() { + return bindName; + } + + public void setBindName(String bindName) { + this.bindName = bindName; + } + + +} diff --git a/libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java b/libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java index e134b501c8..8343d38f6a 100644 --- a/libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java +++ b/libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java @@ -1,7 +1,18 @@ package com.baeldung.vaadin; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.servlet.annotation.WebServlet; + +import com.vaadin.annotations.Push; import com.vaadin.annotations.Theme; import com.vaadin.annotations.VaadinServletConfiguration; +import com.vaadin.data.Validator.InvalidValueException; +import com.vaadin.data.fieldgroup.BeanFieldGroup; +import com.vaadin.data.validator.StringLengthValidator; import com.vaadin.server.ExternalResource; import com.vaadin.server.FontAwesome; import com.vaadin.server.VaadinRequest; @@ -29,14 +40,14 @@ import com.vaadin.ui.TwinColSelect; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; -import javax.servlet.annotation.WebServlet; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - +@SuppressWarnings("serial") +@Push @Theme("mytheme") public class VaadinUI extends UI { + private Label currentTime; + + @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected void init(VaadinRequest vaadinRequest) { final VerticalLayout verticalLayout = new VerticalLayout(); @@ -61,8 +72,7 @@ public class VaadinUI extends UI { label.setCaption("Label"); gridLayout.addComponent(label); - final Link link = new Link("Baeldung", - new ExternalResource("http://www.baeldung.com/")); + final Link link = new Link("Baeldung", new ExternalResource("http://www.baeldung.com/")); link.setId("Link"); link.setTargetName("_blank"); gridLayout.addComponent(link); @@ -118,28 +128,23 @@ public class VaadinUI extends UI { smallButton.addStyleName("small"); buttonLayout.addComponent(smallButton); - Button largeButton = new Button("Large Button"); largeButton.addStyleName("large"); buttonLayout.addComponent(largeButton); - Button hugeButton = new Button("Huge Button"); hugeButton.addStyleName("huge"); buttonLayout.addComponent(hugeButton); - Button disabledButton = new Button("Disabled Button"); disabledButton.setDescription("This button cannot be clicked"); disabledButton.setEnabled(false); buttonLayout.addComponent(disabledButton); - Button dangerButton = new Button("Danger Button"); dangerButton.addStyleName("danger"); buttonLayout.addComponent(dangerButton); - Button friendlyButton = new Button("Friendly Button"); friendlyButton.addStyleName("friendly"); buttonLayout.addComponent(friendlyButton); @@ -171,8 +176,7 @@ public class VaadinUI extends UI { final CheckBox checkbox = new CheckBox("CheckBox"); checkbox.setValue(true); - checkbox.addValueChangeListener(e -> - checkbox.setValue(!checkbox.getValue())); + checkbox.addValueChangeListener(e -> checkbox.setValue(!checkbox.getValue())); formLayout.addComponent(checkbox); List numbers = new ArrayList(); @@ -204,12 +208,62 @@ public class VaadinUI extends UI { panel.setContent(grid); panel.setSizeUndefined(); + Panel serverPushPanel = new Panel("Server Push"); + FormLayout timeLayout = new FormLayout(); + timeLayout.setSpacing(true); + timeLayout.setMargin(true); + currentTime = new Label("No TIME..."); + timeLayout.addComponent(currentTime); + serverPushPanel.setContent(timeLayout); + serverPushPanel.setSizeUndefined(); + new ServerPushThread().start(); + + FormLayout dataBindingLayout = new FormLayout(); + dataBindingLayout.setSpacing(true); + dataBindingLayout.setMargin(true); + + BindData bindData = new BindData("BindData"); + BeanFieldGroup beanFieldGroup = new BeanFieldGroup(BindData.class); + beanFieldGroup.setItemDataSource(bindData); + TextField bindedTextField = (TextField) beanFieldGroup.buildAndBind("BindName", "bindName"); + bindedTextField.setWidth("250px"); + dataBindingLayout.addComponent(bindedTextField); + + FormLayout validatorLayout = new FormLayout(); + validatorLayout.setSpacing(true); + validatorLayout.setMargin(true); + + HorizontalLayout textValidatorLayout = new HorizontalLayout(); + textValidatorLayout.setSpacing(true); + textValidatorLayout.setMargin(true); + + TextField stringValidator = new TextField(); + stringValidator.setNullSettingAllowed(true); + stringValidator.setNullRepresentation(""); + stringValidator.addValidator(new StringLengthValidator("String must have 2-5 characters lenght", 2, 5, true)); + stringValidator.setValidationVisible(false); + textValidatorLayout.addComponent(stringValidator); + Button buttonStringValidator = new Button("Validate String"); + buttonStringValidator.addClickListener(e -> { + try { + stringValidator.setValidationVisible(false); + stringValidator.validate(); + } catch (InvalidValueException err) { + stringValidator.setValidationVisible(true); + } + }); + textValidatorLayout.addComponent(buttonStringValidator); + + validatorLayout.addComponent(textValidatorLayout); verticalLayout.addComponent(gridLayout); verticalLayout.addComponent(richTextPanel); verticalLayout.addComponent(horizontalLayout); verticalLayout.addComponent(formLayout); verticalLayout.addComponent(twinColSelect); verticalLayout.addComponent(panel); + verticalLayout.addComponent(serverPushPanel); + verticalLayout.addComponent(dataBindingLayout); + verticalLayout.addComponent(validatorLayout); setContent(verticalLayout); } @@ -217,4 +271,24 @@ public class VaadinUI extends UI { @VaadinServletConfiguration(ui = VaadinUI.class, productionMode = false) public static class MyUIServlet extends VaadinServlet { } + + class ServerPushThread extends Thread { + @Override + public void run() { + try { + while (true) { + Thread.sleep(1000); + access(new Runnable() { + @Override + public void run() { + currentTime.setValue("Current Time : " + Instant.now()); + } + }); + } + + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } } \ No newline at end of file From 5004fd96a35741bdf036f50ffbdede3d58a5abb5 Mon Sep 17 00:00:00 2001 From: yetanotherallisonf Date: Wed, 19 Jul 2017 03:15:51 -0500 Subject: [PATCH 16/43] Update README.md (#2258) --- vavr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/vavr/README.md b/vavr/README.md index d95e026bde..c4155c2680 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -4,3 +4,4 @@ - [Guide to Pattern Matching in Vavr](http://www.baeldung.com/javaslang-pattern-matching) - [Property Testing Example With Vavr](http://www.baeldung.com/javaslang-property-testing) - [Exceptions in Lambda Expression Using Vavr](http://www.baeldung.com/exceptions-using-vavr) +- [Vavr (ex-Javaslang) Support in Spring Data](http://www.baeldung.com/spring-vavr) From 14456eb92d1afd289ab92fe129a18bac7f442b65 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Wed, 19 Jul 2017 13:46:22 +0530 Subject: [PATCH 17/43] concurrent package description (#2265) * 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 --- .../ScheduledExecutorServiceDemo.java | 46 ++++++++++++++++++ .../cyclicbarrier/CyclicBarrierExample.java | 27 +++++++++++ .../concurrent/cyclicbarrier/Task.java | 25 ++++++++++ .../concurrent/executor/ExecutorDemo.java | 17 +++++++ .../baeldung/concurrent/executor/Invoker.java | 12 +++++ .../executorservice/ExecutorServiceDemo.java | 32 +++++++++++++ .../concurrent/executorservice/Task.java | 10 ++++ .../concurrent/future/FutureDemo.java | 47 +++++++++++++++++++ .../concurrent/semaphore/SemaPhoreDemo.java | 22 +++++++++ .../threadfactory/BaeldungThreadFactory.java | 23 +++++++++ .../concurrent/threadfactory/Demo.java | 13 +++++ .../concurrent/threadfactory/Task.java | 10 ++++ 12 files changed, 284 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/executor/Invoker.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/executorservice/Task.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java create mode 100644 core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java b/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java new file mode 100644 index 0000000000..171f308c16 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java @@ -0,0 +1,46 @@ +package com.baeldung.concurrent.Scheduledexecutorservice; + +import java.util.concurrent.Callable; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +public class ScheduledExecutorServiceDemo { + + public void execute() { + ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + + ScheduledFuture scheduledFuture = executorService.schedule(new Runnable() { + @Override + public void run() { + // task details + } + }, 1, TimeUnit.SECONDS); + + executorService.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + // task details + } + }, 1, 10, TimeUnit.SECONDS); + + executorService.scheduleWithFixedDelay(new Runnable() { + @Override + public void run() { + // task details + } + }, 1, 10, TimeUnit.SECONDS); + + Future future = executorService.schedule(new Callable() { + @Override + public String call() throws Exception { + return "Hello World"; + } + }, 1, TimeUnit.SECONDS); + + executorService.shutdown(); + } + +} 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 new file mode 100644 index 0000000000..e6075c933e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java @@ -0,0 +1,27 @@ +package com.baeldung.concurrent.cyclicbarrier; + +import java.util.concurrent.CyclicBarrier; + +public class CyclicBarrierExample { + + public void start() { + CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() { + @Override + public void run() { + System.out.println("All previous tasks are completed"); + } + }); + + Thread t1 = new Thread(new Task(cyclicBarrier), "T1"); + Thread t2 = new Thread(new Task(cyclicBarrier), "T2"); + Thread t3 = new Thread(new Task(cyclicBarrier), "T3"); + + if (!cyclicBarrier.isBroken()) { + t1.start(); + t2.start(); + t3.start(); + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java new file mode 100644 index 0000000000..4f7801e8c5 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java @@ -0,0 +1,25 @@ +package com.baeldung.concurrent.cyclicbarrier; + +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; + +public class Task implements Runnable { + + private CyclicBarrier barrier; + + public Task(CyclicBarrier barrier) { + this.barrier = barrier; + } + + @Override + public void run() { + try { + System.out.println("Thread : "+ Thread.currentThread().getName() + " is waiting"); + barrier.await(); + System.out.println("Thread : "+ Thread.currentThread().getName() + " is released"); + } catch (InterruptedException | BrokenBarrierException e) { + e.printStackTrace(); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java b/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java new file mode 100644 index 0000000000..9392134bfb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java @@ -0,0 +1,17 @@ +package com.baeldung.concurrent.executor; + +import java.util.concurrent.Executor; + +public class ExecutorDemo { + + public void execute() { + Executor executor = new Invoker(); + executor.execute(new Runnable() { + @Override + public void run() { + // task to be performed + } + }); + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/executor/Invoker.java b/core-java/src/main/java/com/baeldung/concurrent/executor/Invoker.java new file mode 100644 index 0000000000..d9f11986d6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/executor/Invoker.java @@ -0,0 +1,12 @@ +package com.baeldung.concurrent.executor; + +import java.util.concurrent.Executor; + +public class Invoker implements Executor { + + @Override + public void execute(Runnable r) { + r.run(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java b/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java new file mode 100644 index 0000000000..631ae140ab --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java @@ -0,0 +1,32 @@ +package com.baeldung.concurrent.executorservice; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +public class ExecutorServiceDemo { + + ExecutorService executor = Executors.newFixedThreadPool(10); + + public void execute() { + + executor.execute(new Runnable() { + @Override + public void run() { + // task details + } + }); + + executor.submit(new Task()); + + executor.shutdown(); + executor.shutdownNow(); + try { + executor.awaitTermination(20l, TimeUnit.NANOSECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/executorservice/Task.java b/core-java/src/main/java/com/baeldung/concurrent/executorservice/Task.java new file mode 100644 index 0000000000..9a21bca80c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/executorservice/Task.java @@ -0,0 +1,10 @@ +package com.baeldung.concurrent.executorservice; + +public class Task implements Runnable { + + @Override + public void run() { + // task details + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java b/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java new file mode 100644 index 0000000000..89ce1a0a41 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java @@ -0,0 +1,47 @@ +package com.baeldung.concurrent.future; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class FutureDemo { + + public String invoke() { + + String str = null; + + ExecutorService executorService = Executors.newFixedThreadPool(10); + + Future future = executorService.submit(new Callable() { + @Override + public String call() throws Exception { + Thread.sleep(10000l); + return "Hello World"; + } + }); + + future.cancel(false); + + try { + future.get(20, TimeUnit.SECONDS); + } catch (InterruptedException | ExecutionException | TimeoutException e1) { + e1.printStackTrace(); + } + + if (future.isDone() && !future.isCancelled()) { + try { + str = future.get(); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + } + + return str; + + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java b/core-java/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java new file mode 100644 index 0000000000..3a1d8555d3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java @@ -0,0 +1,22 @@ +package com.baeldung.concurrent.semaphore; + +import java.util.concurrent.Semaphore; + +public class SemaPhoreDemo { + + static Semaphore semaphore = new Semaphore(10); + + public void execute() throws InterruptedException { + + System.out.println("Available permit : " + semaphore.availablePermits()); + System.out.println("Number of threads waiting to acquire: " + semaphore.getQueueLength()); + + if (semaphore.tryAcquire()) { + semaphore.acquire(); + // perform some critical operations + semaphore.release(); + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java new file mode 100644 index 0000000000..8744027e40 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadfactory; + +import java.util.concurrent.ThreadFactory; + +public class BaeldungThreadFactory implements ThreadFactory { + + private int threadId; + private String name; + + public BaeldungThreadFactory(String name) { + threadId = 1; + this.name = name; + } + + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r, name + "-Thread_" + threadId); + System.out.println("created new thread with id : " + threadId + " and name : " + t.getName()); + threadId++; + return t; + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java new file mode 100644 index 0000000000..d2af97b761 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.threadfactory; + +public class Demo { + + public void execute() { + BaeldungThreadFactory factory = new BaeldungThreadFactory("BaeldungThreadFactory"); + for (int i = 0; i < 10; i++) { + Thread t = factory.newThread(new Task()); + t.start(); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java new file mode 100644 index 0000000000..04ba62d457 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java @@ -0,0 +1,10 @@ +package com.baeldung.concurrent.threadfactory; + +public class Task implements Runnable { + + @Override + public void run() { + // task details + } + +} From ffd66faa7d4f04946fad20f3fd8991649c82aa3d Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 19 Jul 2017 11:16:44 +0300 Subject: [PATCH 18/43] Refactor HttpClient (#2272) --- .../httpclient/HttpAsyncClientLiveTest.java | 9 +- .../httpclient/HttpClientHeadersLiveTest.java | 23 +---- .../HttpClientMultipartLiveTest.java | 87 +++++++++---------- .../httpclient/HttpClientPostingLiveTest.java | 40 ++++----- .../HttpClientRedirectLiveTest.java | 50 ++++------- .../httpclient/HttpClientTimeoutLiveTest.java | 35 +++----- .../httpclient/HttpsClientSslLiveTest.java | 17 ++-- .../httpclient/ProgressEntityWrapper.java | 6 +- .../org/baeldung/httpclient/ResponseUtil.java | 26 ++++++ ...tAdvancedConfigurationIntegrationTest.java | 43 +++++---- .../base/HttpClientBasicLiveTest.java | 29 ++----- .../base/HttpClientBasicPostLiveTest.java | 28 ++---- .../httpclient/base/HttpClientLiveTest.java | 16 +--- .../base/HttpClientSandboxLiveTest.java | 18 +--- ...ttpClientConnectionManagementLiveTest.java | 20 ++--- .../conn/IdleConnectionMonitorThread.java | 4 +- .../conn/MultiHttpClientConnThread.java | 10 +-- ...sterVersion_MultiHttpClientConnThread.java | 4 +- .../rare/HttpClientUnshortenLiveTest.java | 32 ++++--- .../sec/HttpClientAuthLiveTest.java | 47 ++++------ .../sec/HttpClientCookieLiveTest.java | 36 +++----- 21 files changed, 230 insertions(+), 350 deletions(-) create mode 100644 httpclient/src/test/java/org/baeldung/httpclient/ResponseUtil.java diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java index f2086f2633..d39697c0a9 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java @@ -101,12 +101,7 @@ public class HttpAsyncClientLiveTest { @Test public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception { - final TrustStrategy acceptingTrustStrategy = new TrustStrategy() { - @Override - public final boolean isTrusted(final X509Certificate[] certificate, final String authType) { - return true; - } - }; + final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslContext).build(); @@ -160,7 +155,7 @@ public class HttpAsyncClientLiveTest { private final HttpContext context; private final HttpGet request; - public GetThread(final CloseableHttpAsyncClient client, final HttpGet request) { + GetThread(final CloseableHttpAsyncClient client, final HttpGet request) { this.client = client; context = HttpClientContext.create(); this.request = request; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientHeadersLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientHeadersLiveTest.java index ebd67512e4..51c3817da5 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientHeadersLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientHeadersLiveTest.java @@ -1,11 +1,7 @@ package org.baeldung.httpclient; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - +import com.google.common.collect.Lists; import org.apache.http.Header; -import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; @@ -20,7 +16,8 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.google.common.collect.Lists; +import java.io.IOException; +import java.util.List; public class HttpClientHeadersLiveTest { @@ -37,19 +34,7 @@ public class HttpClientHeadersLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests - headers - deprecated diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java index 954236a56f..9912e73c2b 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java @@ -1,22 +1,7 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; @@ -30,6 +15,20 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + public class HttpClientMultipartLiveTest { // No longer available @@ -48,7 +47,7 @@ public class HttpClientMultipartLiveTest { @Before public final void before() { client = HttpClientBuilder.create() - .build(); + .build(); post = new HttpPost(SERVER); } @@ -67,15 +66,7 @@ public class HttpClientMultipartLiveTest { LOGGER.log(Level.SEVERE, e.getMessage(), e); throw e; } - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @@ -83,8 +74,8 @@ public class HttpClientMultipartLiveTest { @Test public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + TEXTFILENAME); + .getContextClassLoader() + .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); @@ -102,7 +93,7 @@ public class HttpClientMultipartLiveTest { response = client.execute(post); final int statusCode = response.getStatusLine() - .getStatusCode(); + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); @@ -113,10 +104,10 @@ public class HttpClientMultipartLiveTest { } @Test - public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException { + public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + TEXTFILENAME); + .getContextClassLoader() + .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final String message = "This is a multipart post"; final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); @@ -127,7 +118,7 @@ public class HttpClientMultipartLiveTest { post.setEntity(entity); response = client.execute(post); final int statusCode = response.getStatusLine() - .getStatusCode(); + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); @@ -138,13 +129,13 @@ public class HttpClientMultipartLiveTest { } @Test - public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException { + public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + ZIPFILENAME); + .getContextClassLoader() + .getResource("uploads/" + ZIPFILENAME); final URL url2 = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + IMAGEFILENAME); + .getContextClassLoader() + .getResource("uploads/" + IMAGEFILENAME); final InputStream inputStream = new FileInputStream(url.getPath()); final File file = new File(url2.getPath()); final String message = "This is a multipart post"; @@ -157,7 +148,7 @@ public class HttpClientMultipartLiveTest { post.setEntity(entity); response = client.execute(post); final int statusCode = response.getStatusLine() - .getStatusCode(); + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); @@ -169,7 +160,7 @@ public class HttpClientMultipartLiveTest { } @Test - public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException { + public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { final String message = "This is a multipart post"; final byte[] bytes = "binary code".getBytes(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); @@ -180,7 +171,7 @@ public class HttpClientMultipartLiveTest { post.setEntity(entity); response = client.execute(post); final int statusCode = response.getStatusLine() - .getStatusCode(); + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); @@ -192,21 +183,21 @@ public class HttpClientMultipartLiveTest { // UTIL - final String getContent() throws IOException { + private String getContent() throws IOException { rd = new BufferedReader(new InputStreamReader(response.getEntity() - .getContent())); + .getContent())); String body = ""; - String content = ""; + StringBuilder content = new StringBuilder(); while ((body = rd.readLine()) != null) { - content += body + "\n"; + content.append(body).append("\n"); } - return content.trim(); + return content.toString().trim(); } - final String getContentTypeHeader() throws IOException { + private String getContentTypeHeader() throws IOException { return post.getEntity() - .getContentType() - .toString(); + .getContentType() + .toString(); } } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java index ad173f9cd8..39ed8f09ef 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java @@ -1,20 +1,10 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.fluent.Form; import org.apache.http.client.fluent.Request; @@ -29,6 +19,15 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.junit.Test; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + /* * NOTE : Need module spring-rest to be running */ @@ -39,7 +38,7 @@ public class HttpClientPostingLiveTest { private static final String DEFAULT_PASS = "test"; @Test - public void whenSendPostRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL); @@ -54,7 +53,7 @@ public class HttpClientPostingLiveTest { } @Test - public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException, AuthenticationException { + public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION); @@ -68,7 +67,7 @@ public class HttpClientPostingLiveTest { } @Test - public void whenPostJsonUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenPostJsonUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/detail"); @@ -84,14 +83,14 @@ public class HttpClientPostingLiveTest { } @Test - public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws ClientProtocolException, IOException { + public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException { final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse(); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } @Test - public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/multipart"); @@ -109,7 +108,7 @@ public class HttpClientPostingLiveTest { } @Test - public void whenUploadFileUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenUploadFileUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload"); @@ -125,7 +124,7 @@ public class HttpClientPostingLiveTest { } @Test - public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload"); @@ -133,12 +132,7 @@ public class HttpClientPostingLiveTest { builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); final HttpEntity multipart = builder.build(); - final ProgressEntityWrapper.ProgressListener pListener = new ProgressEntityWrapper.ProgressListener() { - @Override - public void progress(final float percentage) { - assertFalse(Float.compare(percentage, 100) > 0); - } - }; + final ProgressEntityWrapper.ProgressListener pListener = percentage -> assertFalse(Float.compare(percentage, 100) > 0); httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener)); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientRedirectLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientRedirectLiveTest.java index 3cb02dc767..a501367a6b 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientRedirectLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientRedirectLiveTest.java @@ -1,13 +1,5 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; @@ -21,6 +13,12 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; +import java.util.Arrays; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + public class HttpClientRedirectLiveTest { private CloseableHttpClient instance; @@ -34,25 +32,13 @@ public class HttpClientRedirectLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @Test - public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException { instance = HttpClients.custom().disableRedirectHandling().build(); final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw"); @@ -62,7 +48,7 @@ public class HttpClientRedirectLiveTest { } @Test - public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException { instance = HttpClientBuilder.create().disableRedirectHandling().build(); response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw")); assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); @@ -71,26 +57,22 @@ public class HttpClientRedirectLiveTest { // redirect with POST @Test - public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { + public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException { instance = HttpClientBuilder.create().build(); response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); } @Test - public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException { final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() { /** Redirectable methods. */ - private final String[] REDIRECT_METHODS = new String[] { HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME }; + private final String[] REDIRECT_METHODS = new String[]{HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME}; @Override protected boolean isRedirectable(final String method) { - for (final String m : REDIRECT_METHODS) { - if (m.equalsIgnoreCase(method)) { - return true; - } - } - return false; + return Arrays.stream(REDIRECT_METHODS) + .anyMatch(m -> m.equalsIgnoreCase(method)); } }).build(); @@ -99,7 +81,7 @@ public class HttpClientRedirectLiveTest { } @Test - public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException { final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build(); response = client.execute(new HttpPost("http://t.co/I5YYd9tddw")); @@ -107,7 +89,7 @@ public class HttpClientRedirectLiveTest { } @Test - public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException { instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientTimeoutLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientTimeoutLiveTest.java index 7e7dbe2146..74255e416c 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientTimeoutLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientTimeoutLiveTest.java @@ -1,13 +1,5 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -18,31 +10,24 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.junit.After; import org.junit.Test; +import java.io.IOException; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + public class HttpClientTimeoutLiveTest { private CloseableHttpResponse response; @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @Test - public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws ClientProtocolException, IOException { + public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws IOException { final int timeout = 2; final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); @@ -56,7 +41,7 @@ public class HttpClientTimeoutLiveTest { } @Test - public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws ClientProtocolException, IOException { + public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws IOException { final int timeout = 2; final SocketConfig config = SocketConfig.custom().setSoTimeout(timeout * 1000).build(); @@ -70,7 +55,7 @@ public class HttpClientTimeoutLiveTest { } @Test - public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws ClientProtocolException, IOException { + public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws IOException { final int timeout = 5; final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); @@ -87,7 +72,7 @@ public class HttpClientTimeoutLiveTest { * This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP) */ @Test(expected = HttpHostConnectException.class) - public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws ClientProtocolException, IOException { + public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException { final int timeout = 3; final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java index 5dfecb85aa..4eadfe24d5 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java @@ -1,14 +1,5 @@ package org.baeldung.httpclient; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.security.GeneralSecurityException; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLHandshakeException; - import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ClientConnectionManager; @@ -28,6 +19,14 @@ import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.junit.Test; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; +import java.io.IOException; +import java.security.GeneralSecurityException; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + /** * This test requires a localhost server over HTTPS
* It should only be manually run, not part of the automated build diff --git a/httpclient/src/test/java/org/baeldung/httpclient/ProgressEntityWrapper.java b/httpclient/src/test/java/org/baeldung/httpclient/ProgressEntityWrapper.java index f0b7e0e559..cd00d8711a 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/ProgressEntityWrapper.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/ProgressEntityWrapper.java @@ -10,7 +10,7 @@ import org.apache.http.entity.HttpEntityWrapper; public class ProgressEntityWrapper extends HttpEntityWrapper { private final ProgressListener listener; - public ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) { + ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) { super(entity); this.listener = listener; } @@ -20,7 +20,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper { super.writeTo(new CountingOutputStream(outstream, listener, getContentLength())); } - public static interface ProgressListener { + public interface ProgressListener { void progress(float percentage); } @@ -30,7 +30,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper { private long transferred; private long totalBytes; - public CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) { + CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) { super(out); this.listener = listener; transferred = 0; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/ResponseUtil.java b/httpclient/src/test/java/org/baeldung/httpclient/ResponseUtil.java new file mode 100644 index 0000000000..fd38b95cbe --- /dev/null +++ b/httpclient/src/test/java/org/baeldung/httpclient/ResponseUtil.java @@ -0,0 +1,26 @@ +package org.baeldung.httpclient; + +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; + +import java.io.IOException; + +public final class ResponseUtil { + private ResponseUtil() { + } + + public static void closeResponse(CloseableHttpResponse response) throws IOException { + if (response == null) { + return; + } + + try { + final HttpEntity entity = response.getEntity(); + if (entity != null) { + entity.getContent().close(); + } + } finally { + response.close(); + } + } +} diff --git a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java index b5a76241d1..77d5a298c1 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java @@ -24,7 +24,14 @@ import org.junit.Test; import java.io.IOException; -import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static org.junit.Assert.assertEquals; public class HttpClientAdvancedConfigurationIntegrationTest { @@ -40,9 +47,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest { //given String userAgent = "BaeldungAgent/1.0"; serviceMock.stubFor(get(urlEqualTo("/detail")) - .withHeader("User-Agent", equalTo(userAgent)) - .willReturn(aResponse() - .withStatus(200))); + .withHeader("User-Agent", equalTo(userAgent)) + .willReturn(aResponse() + .withStatus(200))); HttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://localhost:8089/detail"); @@ -60,10 +67,10 @@ public class HttpClientAdvancedConfigurationIntegrationTest { //given String xmlBody = "1"; serviceMock.stubFor(post(urlEqualTo("/person")) - .withHeader("Content-Type", equalTo("application/xml")) - .withRequestBody(equalTo(xmlBody)) - .willReturn(aResponse() - .withStatus(200))); + .withHeader("Content-Type", equalTo("application/xml")) + .withRequestBody(equalTo(xmlBody)) + .willReturn(aResponse() + .withStatus(200))); HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:8089/person"); @@ -83,17 +90,17 @@ public class HttpClientAdvancedConfigurationIntegrationTest { public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException { //given proxyMock.stubFor(get(urlMatching(".*")) - .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); + .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); serviceMock.stubFor(get(urlEqualTo("/private")) - .willReturn(aResponse().withStatus(200))); + .willReturn(aResponse().withStatus(200))); HttpHost proxy = new HttpHost("localhost", 8090); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); HttpClient httpclient = HttpClients.custom() - .setRoutePlanner(routePlanner) - .build(); + .setRoutePlanner(routePlanner) + .build(); //when final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); @@ -109,9 +116,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest { public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException { //given proxyMock.stubFor(get(urlMatching("/private")) - .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); + .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); serviceMock.stubFor(get(urlEqualTo("/private")) - .willReturn(aResponse().withStatus(200))); + .willReturn(aResponse().withStatus(200))); HttpHost proxy = new HttpHost("localhost", 8090); @@ -120,7 +127,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest { // Client credentials CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxy), - new UsernamePasswordCredentials("username_admin", "secret_password")); + new UsernamePasswordCredentials("username_admin", "secret_password")); // Create AuthCache instance @@ -135,9 +142,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpClient httpclient = HttpClients.custom() - .setRoutePlanner(routePlanner) - .setDefaultCredentialsProvider(credentialsProvider) - .build(); + .setRoutePlanner(routePlanner) + .setDefaultCredentialsProvider(credentialsProvider) + .build(); //when diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicLiveTest.java index 2a101ec816..fee9dc4343 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicLiveTest.java @@ -1,13 +1,5 @@ package org.baeldung.httpclient.base; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; @@ -16,10 +8,17 @@ import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + public class HttpClientBasicLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; @@ -35,19 +34,7 @@ public class HttpClientBasicLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java index 7eb078b18b..fe275be082 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java @@ -1,22 +1,20 @@ package org.baeldung.httpclient.base; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + public class HttpClientBasicPostLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; @@ -32,37 +30,25 @@ public class HttpClientBasicPostLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests - non-GET @Test - public final void whenExecutingPostRequest_thenNoExceptions() throws ClientProtocolException, IOException { + public final void whenExecutingPostRequest_thenNoExceptions() throws IOException { instance.execute(new HttpPost(SAMPLE_URL)); } @Test - public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException { + public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException { final HttpPost request = new HttpPost(SAMPLE_URL); request.setEntity(new StringEntity("in the body of the POST")); instance.execute(request); } @Test - public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException, AuthenticationException { + public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException { final HttpPost request = new HttpPost(SAMPLE_URL); request.setEntity(new StringEntity("in the body of the POST")); final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password"); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java index 878d220f67..78097227e7 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java @@ -11,12 +11,12 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; -import java.io.InputStream; import static org.hamcrest.Matchers.emptyArray; import static org.hamcrest.Matchers.not; @@ -37,19 +37,7 @@ public class HttpClientLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java index 40216a70a5..d945d075f2 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java @@ -1,9 +1,5 @@ package org.baeldung.httpclient.base; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; @@ -12,8 +8,11 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; +import org.baeldung.httpclient.ResponseUtil; import org.junit.Test; +import java.io.IOException; + /* * NOTE : Need module spring-security-rest-basic-auth to be running */ @@ -32,15 +31,6 @@ public class HttpClientSandboxLiveTest { System.out.println(response.getStatusLine()); - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - // EntityUtils.consume(entity); - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java index e04cd32d65..0f8ebefe6c 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java @@ -1,11 +1,5 @@ package org.baeldung.httpclient.conn; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; - import org.apache.http.HeaderElement; import org.apache.http.HeaderElementIterator; import org.apache.http.HttpClientConnection; @@ -36,6 +30,12 @@ import org.junit.Before; import org.junit.Ignore; import org.junit.Test; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertTrue; + public class HttpClientConnectionManagementLiveTest { private static final String SERVER1 = "http://www.petrikainulainen.net/"; private static final String SERVER7 = "http://www.baeldung.com/"; @@ -129,7 +129,7 @@ public class HttpClientConnectionManagementLiveTest { @Test // @Ignore // Example 3.2. TESTER VERSION - /*tester*/public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException { + /*tester*/ public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException { poolingConnManager = new PoolingHttpClientConnectionManager(); final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); @@ -173,7 +173,7 @@ public class HttpClientConnectionManagementLiveTest { @Test // @Ignore // 4.2 Tester Version - /*tester*/public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException { + /*tester*/ public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException { poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager); @@ -266,7 +266,7 @@ public class HttpClientConnectionManagementLiveTest { @Test // @Ignore // 6.2 TESTER VERSION - /*tester*/public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { + /*tester*/ public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager.setDefaultMaxPerRoute(5); poolingConnManager.setMaxTotal(5); @@ -333,7 +333,7 @@ public class HttpClientConnectionManagementLiveTest { @Test @Ignore("Very Long Running") // 8.2 TESTER VERSION - /*tester*/public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException { + /*tester*/ public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException { poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java index 2a1c419e41..ffe4155a78 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java @@ -9,7 +9,7 @@ public class IdleConnectionMonitorThread extends Thread { private final HttpClientConnectionManager connMgr; private volatile boolean shutdown; - public IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) { + IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) { super(); this.connMgr = connMgr; } @@ -31,7 +31,7 @@ public class IdleConnectionMonitorThread extends Thread { } } - public final void shutdown() { + private void shutdown() { shutdown = true; synchronized (this) { notifyAll(); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java index 071b964710..3794943f02 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java @@ -18,23 +18,23 @@ public class MultiHttpClientConnThread extends Thread { private final HttpGet get; private PoolingHttpClientConnectionManager connManager; - public int leasedConn; + private int leasedConn; - public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { + MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { this.client = client; this.get = get; this.connManager = connManager; leasedConn = 0; } - public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) { + MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) { this.client = client; this.get = get; } // API - public final int getLeasedConn() { + final int getLeasedConn() { return leasedConn; } @@ -61,8 +61,6 @@ public class MultiHttpClientConnThread extends Thread { } EntityUtils.consume(response.getEntity()); - } catch (final ClientProtocolException ex) { - logger.error("", ex); } catch (final IOException ex) { logger.error("", ex); } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java index 62cd466596..9cc6480e74 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java @@ -18,7 +18,7 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread { private final HttpGet get; private PoolingHttpClientConnectionManager connManager; - public TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { + TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { this.client = client; this.get = get; this.connManager = Preconditions.checkNotNull(connManager); @@ -38,8 +38,6 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread { logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased()); logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable()); - } catch (final ClientProtocolException ex) { - logger.error("", ex); } catch (final IOException ex) { logger.error("", ex); } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java index a185e99639..8fc79baed9 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java @@ -1,12 +1,7 @@ package org.baeldung.httpclient.rare; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.http.Header; @@ -20,8 +15,12 @@ import org.apache.http.util.EntityUtils; import org.junit.Before; import org.junit.Test; -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; public class HttpClientUnshortenLiveTest { @@ -52,7 +51,7 @@ public class HttpClientUnshortenLiveTest { // API - final String expand(final String urlArg) throws IOException { + private String expand(final String urlArg) throws IOException { String originalUrl = urlArg; String newUrl = expandSingleLevel(originalUrl); while (!originalUrl.equals(newUrl)) { @@ -81,7 +80,7 @@ public class HttpClientUnshortenLiveTest { return newUrl; } - final Pair expandSingleLevelSafe(final String url) throws IOException { + private Pair expandSingleLevelSafe(final String url) throws IOException { HttpHead request = null; HttpEntity httpEntity = null; InputStream entityContentStream = null; @@ -95,15 +94,15 @@ public class HttpClientUnshortenLiveTest { final int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != 301 && statusCode != 302) { - return new ImmutablePair(statusCode, url); + return new ImmutablePair<>(statusCode, url); } final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); Preconditions.checkState(headers.length == 1); final String newUrl = headers[0].getValue(); - return new ImmutablePair(statusCode, newUrl); + return new ImmutablePair<>(statusCode, newUrl); } catch (final IllegalArgumentException uriEx) { - return new ImmutablePair(500, url); + return new ImmutablePair<>(500, url); } finally { if (request != null) { request.releaseConnection(); @@ -117,7 +116,7 @@ public class HttpClientUnshortenLiveTest { } } - final String expandSingleLevel(final String url) throws IOException { + private String expandSingleLevel(final String url) throws IOException { HttpHead request = null; try { @@ -130,9 +129,8 @@ public class HttpClientUnshortenLiveTest { } final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); Preconditions.checkState(headers.length == 1); - final String newUrl = headers[0].getValue(); - return newUrl; + return headers[0].getValue(); } catch (final IllegalArgumentException uriEx) { return url; } finally { diff --git a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java index e98dd4d14f..7a75729ea5 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java @@ -1,21 +1,12 @@ package org.baeldung.httpclient.sec; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; - import org.apache.commons.codec.binary.Base64; -import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -26,10 +17,17 @@ import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpContext; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; +import java.nio.charset.Charset; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + /* * NOTE : Need module spring-security-rest-basic-auth to be running */ @@ -51,25 +49,13 @@ public class HttpClientAuthLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @Test - public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException { + public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException { client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build(); response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION)); @@ -79,7 +65,7 @@ public class HttpClientAuthLiveTest { } @Test - public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException { + public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException { client = HttpClientBuilder.create().build(); response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context()); @@ -88,7 +74,7 @@ public class HttpClientAuthLiveTest { } @Test - public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws ClientProtocolException, IOException { + public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws IOException { client = HttpClientBuilder.create().build(); final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); @@ -100,7 +86,7 @@ public class HttpClientAuthLiveTest { } @Test - public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws ClientProtocolException, IOException { + public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException { final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); final String auth = DEFAULT_USER + ":" + DEFAULT_PASS; final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); @@ -116,14 +102,14 @@ public class HttpClientAuthLiveTest { // UTILS - private final CredentialsProvider provider() { + private CredentialsProvider provider() { final CredentialsProvider provider = new BasicCredentialsProvider(); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS); provider.setCredentials(AuthScope.ANY, credentials); return provider; } - private final HttpContext context() { + private HttpContext context() { final HttpHost targetHost = new HttpHost("localhost", 8080, "http"); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS)); @@ -141,12 +127,11 @@ public class HttpClientAuthLiveTest { return context; } - private final String authorizationHeader(final String username, final String password) { + private String authorizationHeader(final String username, final String password) { final String auth = username + ":" + password; final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); - final String authHeader = "Basic " + new String(encodedAuth); - return authHeader; + return "Basic " + new String(encodedAuth); } } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientCookieLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientCookieLiveTest.java index 7da9ad04e4..ba27aca08d 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientCookieLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientCookieLiveTest.java @@ -1,13 +1,5 @@ package org.baeldung.httpclient.sec; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -18,10 +10,16 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + public class HttpClientCookieLiveTest { private CloseableHttpClient instance; @@ -35,25 +33,13 @@ public class HttpClientCookieLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @Test - public final void whenSettingCookiesOnARequest_thenCorrect() throws ClientProtocolException, IOException { + public final void whenSettingCookiesOnARequest_thenCorrect() throws IOException { instance = HttpClientBuilder.create().build(); final HttpGet request = new HttpGet("http://www.github.com"); request.setHeader("Cookie", "JSESSIONID=1234"); @@ -64,7 +50,7 @@ public class HttpClientCookieLiveTest { } @Test - public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); cookie.setDomain(".github.com"); @@ -80,7 +66,7 @@ public class HttpClientCookieLiveTest { } @Test - public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws ClientProtocolException, IOException { + public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); cookie.setDomain(".github.com"); @@ -96,7 +82,7 @@ public class HttpClientCookieLiveTest { } @Test - public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws ClientProtocolException, IOException { + public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); cookie.setDomain(".github.com"); From 600d610ddfef9390ff90b8532c76ff3e4c7867db Mon Sep 17 00:00:00 2001 From: lor6 Date: Wed, 19 Jul 2017 23:46:42 +0300 Subject: [PATCH 19/43] add libs repo (#2288) --- vavr/pom.xml | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/vavr/pom.xml b/vavr/pom.xml index cbf2a37ec9..d35a408389 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -51,8 +51,20 @@ true + + snapshots + libs-snapshot + https://repo.spring.io/libs-snapshot + - + + + + spring-snapshots + http://repo.spring.io/snapshot + + + 1.8 0.9.0 From b558adec06cf97a63a4474e63c57b651b003abbe Mon Sep 17 00:00:00 2001 From: Nikhil Khatwani Date: Thu, 20 Jul 2017 08:24:43 +0530 Subject: [PATCH 20/43] Changes for BAEL-1050: Added new field (#2282) --- .../com/baeldung/deserialization/AppleProduct.java | 10 +++++++--- .../deserialization/DeserializationUtility.java | 3 ++- .../deserialization/SerializationUtility.java | 1 + .../deserialization/DeserializationUnitTest.java | 13 +++++++------ 4 files changed, 17 insertions(+), 10 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java b/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java index d672b9a4f5..a10499b362 100644 --- a/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java +++ b/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java @@ -4,12 +4,12 @@ import java.io.Serializable; public class AppleProduct implements Serializable { - private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated) -// private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated) + private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated) + // private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated) public String headphonePort; public String thunderboltPort; - public String lighteningPort; + public String lightningPort; public String getHeadphonePort() { return headphonePort; @@ -23,4 +23,8 @@ public class AppleProduct implements Serializable { return serialVersionUID; } + public String getLightningPort() { + return lightningPort; + } + } \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java b/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java index 3ed2b8be1d..ad8e929898 100644 --- a/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java +++ b/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java @@ -9,11 +9,12 @@ public class DeserializationUtility { public static void main(String[] args) throws ClassNotFoundException, IOException { - String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA=="; + String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA=="; System.out.println("Deserializing AppleProduct..."); AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj); System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort()); System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort()); + System.out.println("LightningPort port of AppleProduct:" + deserializedObj.getLightningPort()); } public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException { diff --git a/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java b/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java index 1dbcc40e6b..aa7f66659a 100644 --- a/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java +++ b/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java @@ -13,6 +13,7 @@ public class SerializationUtility { AppleProduct macBook = new AppleProduct(); macBook.headphonePort = "headphonePort2020"; macBook.thunderboltPort = "thunderboltPort2020"; + macBook.lightningPort = "lightningPort2020"; String serializedObj = serializeObjectToString(macBook); System.out.println("Serialized AppleProduct object to string:"); diff --git a/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java b/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java index 887e7e41da..d7c1ee17d4 100644 --- a/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java +++ b/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java @@ -12,7 +12,7 @@ import org.junit.Test; public class DeserializationUnitTest { - private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA=="; + private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAdMuxAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA"; private static long userDefinedSerialVersionUID = 1234567L; @@ -25,20 +25,22 @@ public class DeserializationUnitTest { public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException { assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID()); - + AppleProduct macBook = new AppleProduct(); macBook.headphonePort = "headphonePort2020"; macBook.thunderboltPort = "thunderboltPort2020"; - + macBook.lightningPort = "lightningPort2020"; + // serializes the "AppleProduct" object String serializedProduct = SerializationUtility.serializeObjectToString(macBook); // deserializes the "AppleProduct" object AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct); - + assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort)); assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort)); - + assertTrue(deserializedProduct.lightningPort.equalsIgnoreCase(macBook.lightningPort)); + } /** @@ -59,7 +61,6 @@ public class DeserializationUnitTest { public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException { assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID()); - // attempts to deserialize the "AppleProduct" object DeserializationUtility.deSerializeObjectFromString(serializedObj); } From 7d369725709350a7278bee5d119375c5fba9e2dd Mon Sep 17 00:00:00 2001 From: Jesus Boadas Date: Thu, 20 Jul 2017 10:13:42 -0400 Subject: [PATCH 21/43] changed thread for ScheduledExecutorService (#2297) --- .../java/com/baeldung/vaadin/VaadinUI.java | 29 +++++-------------- 1 file changed, 8 insertions(+), 21 deletions(-) diff --git a/libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java b/libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java index 8343d38f6a..68e2ca7944 100644 --- a/libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java +++ b/libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java @@ -4,6 +4,9 @@ import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import javax.servlet.annotation.WebServlet; @@ -216,7 +219,11 @@ public class VaadinUI extends UI { timeLayout.addComponent(currentTime); serverPushPanel.setContent(timeLayout); serverPushPanel.setSizeUndefined(); - new ServerPushThread().start(); + ScheduledExecutorService scheduleExecutor = Executors.newScheduledThreadPool(1); + Runnable task = () -> { + currentTime.setValue("Current Time : " + Instant.now()); + }; + scheduleExecutor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS); FormLayout dataBindingLayout = new FormLayout(); dataBindingLayout.setSpacing(true); @@ -271,24 +278,4 @@ public class VaadinUI extends UI { @VaadinServletConfiguration(ui = VaadinUI.class, productionMode = false) public static class MyUIServlet extends VaadinServlet { } - - class ServerPushThread extends Thread { - @Override - public void run() { - try { - while (true) { - Thread.sleep(1000); - access(new Runnable() { - @Override - public void run() { - currentTime.setValue("Current Time : " + Instant.now()); - } - }); - } - - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } } \ No newline at end of file From 318d0790f58198475a44efbda4a5ac666f1c0b8a Mon Sep 17 00:00:00 2001 From: amilabanuka Date: Fri, 21 Jul 2017 00:06:28 +0800 Subject: [PATCH 22/43] BAEL-281: Static Analysis tools with Eclipse (#2298) --- .../src/test/java/com/baeldung/pmd/CntTest.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 static-analysis/src/test/java/com/baeldung/pmd/CntTest.java diff --git a/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java b/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java new file mode 100644 index 0000000000..ed72602f99 --- /dev/null +++ b/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java @@ -0,0 +1,17 @@ +package com.baeldung.pmd; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class CntTest { + + private Cnt service; + + @Test + public void whenSecondParamIsZeroShouldReturnIntMax(){ + service = new Cnt(); + int answer = service.d(100,0); + assertEquals(Integer.MAX_VALUE, answer); + } +} From eab110d0d00d0d713acea2230d2de0715bebb6b6 Mon Sep 17 00:00:00 2001 From: ramansahasi Date: Thu, 20 Jul 2017 21:36:54 +0530 Subject: [PATCH 23/43] BAEL-787 (updated) - AWS S3 with Java (#2296) * Replacing manual handling of stream Replacing manual handling of stream apache commons FileUtils library. * Replacing manual handling of stream Replacing manual handling of stream apache commons FileUtils library. * Update S3Application.java --- .../main/java/com/baeldung/s3/S3Application.java | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/aws/src/main/java/com/baeldung/s3/S3Application.java b/aws/src/main/java/com/baeldung/s3/S3Application.java index fcbd7811b5..fdfb909f73 100644 --- a/aws/src/main/java/com/baeldung/s3/S3Application.java +++ b/aws/src/main/java/com/baeldung/s3/S3Application.java @@ -1,9 +1,10 @@ package com.baeldung.s3; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; +import org.apache.commons.io.FileUtils; + import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; @@ -28,7 +29,7 @@ public class S3Application { "", "" ); - } + } public static void main(String[] args) throws IOException { //set-up the client @@ -74,15 +75,7 @@ public class S3Application { //downloading an object S3Object s3object = awsService.getObject(bucketName, "Document/hello.txt"); S3ObjectInputStream inputStream = s3object.getObjectContent(); - FileOutputStream fos = new FileOutputStream(new File("/Users/user/Desktop/hello.txt")); - - int read = 0; - byte[] bytes = new byte[1024]; - while ((read = inputStream.read(bytes)) != -1) { - fos.write(bytes, 0, read); - } - inputStream.close(); - fos.close(); + FileUtils.copyInputStreamToFile(inputStream, new File("/Users/user/Desktop/hello.txt")); //copying an object awsService.copyObject( From c910f2533418fe50d02af484bdcb13f663e0aaff Mon Sep 17 00:00:00 2001 From: baljeet20 Date: Thu, 20 Jul 2017 22:47:55 +0530 Subject: [PATCH 24/43] review changes (#2299) --- mockserver/pom.xml | 13 +++++++++++++ ...MockServer.java => MockServerLiveTest.java} | 18 ++++++++---------- 2 files changed, 21 insertions(+), 10 deletions(-) rename mockserver/src/test/java/com/baeldung/mock/server/{TestMockServer.java => MockServerLiveTest.java} (95%) diff --git a/mockserver/pom.xml b/mockserver/pom.xml index a3ca5459c9..8d3e97f129 100644 --- a/mockserver/pom.xml +++ b/mockserver/pom.xml @@ -37,5 +37,18 @@
+ + + + maven-surefire-plugin + 2.20 + + + **/**LiveTest.java + + + + + \ No newline at end of file diff --git a/mockserver/src/test/java/com/baeldung/mock/server/TestMockServer.java b/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java similarity index 95% rename from mockserver/src/test/java/com/baeldung/mock/server/TestMockServer.java rename to mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java index aea1b8b278..56d354be7f 100644 --- a/mockserver/src/test/java/com/baeldung/mock/server/TestMockServer.java +++ b/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java @@ -5,9 +5,7 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockserver.client.server.MockServerClient; import org.mockserver.integration.ClientAndProxy; import org.mockserver.integration.ClientAndServer; @@ -28,13 +26,13 @@ import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.StringBody.exact; -public class TestMockServer { +public class MockServerLiveTest { - private ClientAndProxy proxy; - private ClientAndServer mockServer; + private static ClientAndProxy proxy; + private static ClientAndServer mockServer; - @Before - public void startProxy() { + @BeforeClass + public static void startProxy() { mockServer = startClientAndServer(1080); proxy = startClientAndProxy(1090); } @@ -170,8 +168,8 @@ public class TestMockServer { ); } - @After - public void stopProxy() { + @AfterClass + public static void stopProxy() { proxy.stop(); mockServer.stop(); } From 292d9f802f685745f5e9972eec2cc5c81254f85a Mon Sep 17 00:00:00 2001 From: Daniel Cassiani Date: Thu, 20 Jul 2017 19:40:13 -0300 Subject: [PATCH 25/43] PR for BAEL-798 - Apache Camel with Spring Boot (#2280) * initial import * simplified to rest only * simplifications * update * Create ExampleServices.java * Update Application.java * simple readme * strip of dependency management * setting Camel versions apart where affected * Update README.md * update comments * Update pom.xml * delete of fabri8 deployment.yml * remove extends --- .../main/java/com/baeldung/camel/Application.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/camel-api/src/main/java/com/baeldung/camel/Application.java b/camel-api/src/main/java/com/baeldung/camel/Application.java index f805385ff9..aadd37a3b4 100644 --- a/camel-api/src/main/java/com/baeldung/camel/Application.java +++ b/camel-api/src/main/java/com/baeldung/camel/Application.java @@ -13,14 +13,13 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; @SpringBootApplication @ComponentScan(basePackages="com.baeldung.camel") -public class Application extends SpringBootServletInitializer { +public class Application{ @Value("${server.port}") String serverPort; @@ -62,10 +61,12 @@ public class Application extends SpringBootServletInitializer { .bindingMode(RestBindingMode.json) .dataFormatProperty("prettyPrint", "true"); /** -The Rest DSL supports automatic binding json/xml contents to/from POJOs using Camels Data Format. -By default the binding mode is off, meaning there is no automatic binding happening for incoming and outgoing messages. -You may want to use binding if you develop POJOs that maps to your REST services request and response types. -This allows you, as a developer, to work with the POJOs in Java code. +The Rest DSL supports automatic binding json/xml contents to/from +POJOs using Camels Data Format. +By default the binding mode is off, meaning there is no automatic +binding happening for incoming and outgoing messages. +You may want to use binding if you develop POJOs that maps to +your REST services request and response types. */ rest("/api/").description("Teste REST Service") From 64212862bf2566db43daa44ba0d1c54cf5ac2f9e Mon Sep 17 00:00:00 2001 From: deep20jain Date: Fri, 21 Jul 2017 04:13:49 +0530 Subject: [PATCH 26/43] BAEL-1029 - deep20jain@gmail.com - Addressing review comment (#2294) * Adding test classes for java atomic variables * Updating counter with atomic integer * Adding reason for ignoring test * Removing ignore annotation and moving test to manual test * Removing counter test --- ...erTest.java => ThreadSafeCounterTest.java} | 24 ++------------ .../atomic/ThreadUnsafeCounterManualTest.java | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 22 deletions(-) rename core-java/src/test/java/com/baeldung/concurrent/atomic/{CounterTest.java => ThreadSafeCounterTest.java} (53%) create mode 100644 core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java diff --git a/core-java/src/test/java/com/baeldung/concurrent/atomic/CounterTest.java b/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java similarity index 53% rename from core-java/src/test/java/com/baeldung/concurrent/atomic/CounterTest.java rename to core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java index 1612c62513..e9b2e164ae 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/atomic/CounterTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java @@ -7,31 +7,10 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; -import org.junit.Ignore; import org.junit.Test; -public class CounterTest { +public class ThreadSafeCounterTest { - /** - * This test shows the behaviour of a thread-unsafe class in a multithreaded scenario. We are calling - * the increment methods 1000 times from a pool of 3 threads. In most of the cases, the counter will - * less than 1000, because of lost updates, however, occasionally it may reach 1000, when no threads - * called the method simultaneously. This may cause the build to fail occasionally. Hence excluding this - * test by adding Ignore annotation. - */ - @Test - @Ignore - public void givenMultiThread_whenUnsafeCounterIncrement() throws InterruptedException { - ExecutorService service = Executors.newFixedThreadPool(3); - UnsafeCounter unsafeCounter = new UnsafeCounter(); - - IntStream.range(0, 1000) - .forEach(count -> service.submit(unsafeCounter::increment)); - service.awaitTermination(100, TimeUnit.MILLISECONDS); - - assertEquals(1000, unsafeCounter.getValue()); - } - @Test public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(3); @@ -55,4 +34,5 @@ public class CounterTest { assertEquals(1000, safeCounter.getValue()); } + } diff --git a/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java b/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java new file mode 100644 index 0000000000..cc7cc18bb5 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java @@ -0,0 +1,33 @@ +package com.baeldung.concurrent.atomic; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import org.junit.Test; + +/** + * This test shows the behaviour of a thread-unsafe class in a multithreaded scenario. We are calling + * the increment methods 1000 times from a pool of 3 threads. In most of the cases, the counter will + * less than 1000, because of lost updates, however, occasionally it may reach 1000, when no threads + * called the method simultaneously. This may cause the build to fail occasionally. Hence excluding this + * test from build by adding this in manual test + */ +public class ThreadUnsafeCounterManualTest { + + @Test + public void givenMultiThread_whenUnsafeCounterIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + UnsafeCounter unsafeCounter = new UnsafeCounter(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(unsafeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, unsafeCounter.getValue()); + } + +} From 4e95722017879aabade12999a1322fbcd4e0effa Mon Sep 17 00:00:00 2001 From: Naresh Babu P B Date: Fri, 21 Jul 2017 04:29:46 +0530 Subject: [PATCH 27/43] BAEL-422 Examples for tutorial on Vavr Collection API (#2293) --- .../collections/CollectionAPIUnitTest.java | 261 ++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java diff --git a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java new file mode 100644 index 0000000000..48c0cb7305 --- /dev/null +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java @@ -0,0 +1,261 @@ +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 org.junit.Test; + +import io.vavr.Tuple; +import io.vavr.Tuple2; +import io.vavr.collection.Array; +import io.vavr.collection.CharSeq; +import io.vavr.collection.HashSet; +import io.vavr.collection.Iterator; +import io.vavr.collection.List; +import io.vavr.collection.Map; +import io.vavr.collection.Queue; +import io.vavr.collection.Set; +import io.vavr.collection.SortedMap; +import io.vavr.collection.SortedSet; +import io.vavr.collection.Stream; +import io.vavr.collection.TreeMap; +import io.vavr.collection.TreeSet; +import io.vavr.collection.Vector; + +public class CollectionAPIUnitTest { + + @Test + public void givenEmptyList_whenStacked_thenCorrect() { + List intList = List.empty(); + + List anotherList = intList.push(4) + .push(0); + Iterator iterator = anotherList.iterator(); + + assertEquals(new Integer(0), iterator.next()); + assertEquals(new Integer(4), iterator.next()); + } + + @Test + public void givenList_whenPrependTail_thenCorrect() { + List intList = List.of(1, 2, 3); + + List newList = intList.tail() + .prepend(0); + + assertEquals(new Integer(1), intList.get(0)); + assertEquals(new Integer(2), intList.get(1)); + assertEquals(new Integer(3), intList.get(2)); + + assertNotSame(intList.get(0), newList.get(0)); + assertEquals(new Integer(0), newList.get(0)); + assertSame(intList.get(1), newList.get(1)); + assertSame(intList.get(2), newList.get(2)); + } + + @Test + public void givenQueue_whenEnqueued_thenCorrect() { + Queue queue = Queue.of(1, 2, 3); + Queue secondQueue = queue.enqueue(4) + .enqueue(5); + + assertEquals(3, queue.size()); + assertEquals(5, secondQueue.size()); + + secondQueue.dequeue() + .map((k, v) -> { + assertEquals(new Integer(1), k); + return v.dequeue(); + }) + .map((k, v) -> { + assertEquals(new Integer(2), k); + return v.dequeue(); + }) + .map((k, v) -> { + assertEquals(new Integer(3), k); + return v.dequeue(); + }) + .map((k, v) -> { + assertEquals(new Integer(4), k); + return v.dequeue(); + }) + .map((k, v) -> { + assertEquals(new Integer(5), k); + assertTrue(v.isEmpty()); + return null; + }); + } + + @Test + public void givenStream_whenProcessed_thenCorrect() { + Stream intStream = Stream.iterate(0, i -> i + 1) + .take(10); + + assertEquals(10, intStream.size()); + + long evenSum = intStream.filter(i -> i % 2 == 0) + .sum() + .longValue(); + + assertEquals(20L, evenSum); + assertEquals(new Integer(5), intStream.get(5)); + } + + @Test + public void givenArray_whenQueried_thenCorrect() { + Array intArray = Array.of(1, 2, 3); + Array newArray = intArray.removeAt(1); + + assertEquals(3, intArray.size()); + assertEquals(2, newArray.size()); + + assertEquals(new Integer(1), intArray.get(0)); + assertEquals(new Integer(2), intArray.get(1)); + assertEquals(new Integer(3), intArray.get(2)); + assertEquals(new Integer(3), newArray.get(1)); + } + + @Test + public void givenVector_whenQueried_thenCorrect() { + Vector intVector = Vector.range(1, 5); + Vector newVector = intVector.replace(2, 6); + + assertEquals(4, intVector.size()); + assertEquals(4, newVector.size()); + + assertEquals(new Integer(1), intVector.get(0)); + assertEquals(new Integer(2), intVector.get(1)); + assertEquals(new Integer(3), intVector.get(2)); + assertEquals(new Integer(6), newVector.get(1)); + } + + @Test + public void givenCharSeq_whenProcessed_thenCorrect() { + CharSeq chars = CharSeq.of("vavr"); + CharSeq newChars = chars.replace('v', 'V'); + + assertEquals(4, chars.size()); + assertEquals(4, newChars.size()); + + assertEquals('v', chars.charAt(0)); + assertEquals('V', newChars.charAt(0)); + assertEquals("Vavr", newChars.mkString()); + } + + @Test + public void givenHashSet_whenModified_thenCorrect() { + HashSet set = HashSet.of("Red", "Green", "Blue"); + HashSet newSet = set.add("Yellow"); + + assertEquals(3, set.size()); + assertEquals(4, newSet.size()); + assertFalse(set.contains("Yellow")); + assertTrue(newSet.contains("Yellow")); + } + + @Test + public void givenSortedSet_whenIterated_thenCorrect() { + SortedSet set = TreeSet.of("Red", "Green", "Blue"); + + Iterator iterator = set.iterator(); + assertEquals("Blue", iterator.next()); + assertEquals("Green", iterator.next()); + assertEquals("Red", iterator.next()); + } + + @Test + public void givenSortedSet_whenReversed_thenCorrect() { + Comparator reverseCompare = (a, b) -> b.compareTo(a); + SortedSet set = TreeSet.of(reverseCompare, "Green", "Red", "Blue"); + + Iterator iterator = set.iterator(); + assertEquals("Red", iterator.next()); + assertEquals("Green", iterator.next()); + assertEquals("Blue", iterator.next()); + } + + @Test + public void givenMap_whenIterated_thenCorrect() { + Map> map = List.rangeClosed(0, 10) + .groupBy(i -> i % 2); + + assertEquals(2, map.size()); + + Iterator>> iterator = map.iterator(); + assertEquals(6, iterator.next() + ._2() + .size()); + assertEquals(5, iterator.next() + ._2() + .size()); + } + + @Test + public void givenTreeMap_whenIterated_thenCorrect() { + SortedMap map = TreeMap.of(3, "Three", 2, "Two", 4, "Four", 1, "One"); + + Iterator> iterator = map.iterator(); + assertEquals(new Integer(1), iterator.next() + ._1()); + assertEquals(new Integer(2), iterator.next() + ._1()); + assertEquals(new Integer(3), iterator.next() + ._1()); + } + + @Test + public void givenJavaList_whenConverted_thenCorrect() { + java.util.List javaList = java.util.Arrays.asList(1, 2, 3, 4); + List vavrList = List.ofAll(javaList); + + assertTrue(vavrList instanceof io.vavr.collection.List); + + java.util.stream.Stream javaStream = javaList.stream(); + Set vavrSet = HashSet.ofAll(javaStream); + + assertTrue(vavrSet instanceof io.vavr.collection.Set); + } + + @Test + public void givenVavrList_whenConverted_thenCorrect() { + Integer[] array = List.of(1, 2, 3) + .toJavaArray(Integer.class); + assertEquals(3, array.length); + + java.util.Map map = List.of("1", "2", "3") + .toJavaMap(i -> Tuple.of(i, Integer.valueOf(i))); + assertEquals(new Integer(2), map.get("2")); + } + + @Test + public void givenVavrList_whenConvertedView_thenCorrect() { + java.util.List javaList = List.of(1, 2, 3) + .asJavaMutable(); + javaList.add(4); + + assertEquals(new Integer(4), javaList.get(3)); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenVavrList_whenConvertedView_thenException() { + java.util.List javaList = List.of(1, 2, 3) + .asJava(); + + assertEquals(new Integer(3), javaList.get(2)); + javaList.add(4); + } + + @Test + public void givenList_whenSquared_thenCorrect() { + List vavrList = List.of(1, 2, 3); + Number sum = vavrList.map(i -> i * i) + .sum(); + + assertEquals(new Long(14), sum); + } +} From f8bf4038f1dc0a109f1024c7b7b274a3e72b932d Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Fri, 21 Jul 2017 13:37:49 +0300 Subject: [PATCH 28/43] Optimize and refactor (#2302) --- ...otWithServletComponentIntegrationTest.java | 13 ++- ...ithoutServletComponentIntegrationTest.java | 12 +- .../AutoconfigurationIntegrationTest.java | 9 +- .../DisplayBeanIntegrationTest.java | 32 +++-- .../java/com/baeldung/intro/AppLiveTest.java | 10 +- .../toggle/ToggleIntegrationTest.java | 8 +- .../utils/UtilsControllerIntegrationTest.java | 28 +++-- .../MyStompSessionHandlerIntegrationTest.java | 5 - .../EmployeeControllerIntegrationTest.java | 16 +-- .../EmployeeRepositoryIntegrationTest.java | 12 +- ...EmployeeRestControllerIntegrationTest.java | 44 +++---- .../EmployeeServiceImplIntegrationTest.java | 38 +++--- .../org/baeldung/boot/boottest/JsonUtil.java | 4 +- .../ApiDocumentationIntegrationTest.java | 14 ++- ...ngStartedDocumentationIntegrationTest.java | 20 ++-- .../web/AbstractDiscoverabilityLiveTest.java | 2 +- .../csrf/CsrfAbstractIntegrationTest.java | 8 +- .../org/baeldung/test/JacksonMarshaller.java | 12 -- .../test/java/org/baeldung/util/IDUtil.java | 8 +- .../LoggerInterceptorIntegrationTest.java | 1 + .../baeldung/web/util/HTTPLinkHeaderUtil.java | 37 +----- ...ilityObjectsControllerIntegrationTest.java | 2 +- ...ayoutDialectControllerIntegrationTest.java | 2 +- .../csrf/CsrfEnabledIntegrationTest.java | 2 +- .../junitparams/SafeAdditionUtilTest.java | 10 +- .../junitparams/TestDataProvider.java | 4 +- .../calculator/CalculatorIntegrationTest.java | 9 +- .../collections/CollectionAPIUnitTest.java | 110 +++++++++--------- .../jsoncreator/JsonCreatorUnitTest.java | 8 +- .../jsonfilter/JsonFilterUnitTest.java | 2 +- .../jsonformat/JsonFormatUnitTest.java | 4 +- .../jsonproperty/JsonPropertyUnitTest.java | 4 +- 32 files changed, 220 insertions(+), 270 deletions(-) diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index 8d5eb56bf4..660b461ab6 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -14,15 +14,18 @@ import org.springframework.test.context.junit4.SpringRunner; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) @AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false" }) +@TestPropertySource(properties = {"security.basic.enabled=false"}) public class SpringBootWithServletComponentIntegrationTest { - @Autowired private ServletContext servletContext; + @Autowired + private ServletContext servletContext; @Test public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() { @@ -42,7 +45,8 @@ public class SpringBootWithServletComponentIntegrationTest { .contains("echo servlet")); } - @Autowired private TestRestTemplate restTemplate; + @Autowired + private TestRestTemplate restTemplate; @Test public void givenServletFilter_whenGetHello_thenRequestFiltered() { @@ -59,7 +63,6 @@ public class SpringBootWithServletComponentIntegrationTest { } - } diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java index 64507ad02c..31bb2ab195 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java @@ -14,17 +14,21 @@ import org.springframework.test.context.junit4.SpringRunner; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class) @AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false" }) +@TestPropertySource(properties = {"security.basic.enabled=false"}) public class SpringBootWithoutServletComponentIntegrationTest { - @Autowired private ServletContext servletContext; + @Autowired + private ServletContext servletContext; - @Autowired private TestRestTemplate restTemplate; + @Autowired + private TestRestTemplate restTemplate; @Test public void givenServletContext_whenAccessAttrs_thenNotFound() { diff --git a/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java index dda9d69edd..e886042c8d 100644 --- a/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java @@ -1,5 +1,8 @@ package com.baeldung.autoconfiguration; +import com.baeldung.autoconfiguration.example.AutoconfigurationApplication; +import com.baeldung.autoconfiguration.example.MyUser; +import com.baeldung.autoconfiguration.example.MyUserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -7,13 +10,9 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.baeldung.autoconfiguration.example.AutoconfigurationApplication; -import com.baeldung.autoconfiguration.example.MyUser; -import com.baeldung.autoconfiguration.example.MyUserRepository; - @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AutoconfigurationApplication.class) -@EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" }) +@EnableJpaRepositories(basePackages = {"com.baeldung.autoconfiguration.example"}) public class AutoconfigurationIntegrationTest { @Autowired diff --git a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java index 530b8e9cb3..413f6980ce 100644 --- a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java @@ -1,15 +1,5 @@ package com.baeldung.displayallbeans; -import static org.assertj.core.api.BDDAssertions.then; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -23,7 +13,15 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.displayallbeans.Application; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @@ -46,10 +44,10 @@ public class DisplayBeanIntegrationTest { public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception { ResponseEntity entity = this.testRestTemplate.getForEntity( "http://localhost:" + this.port + "/displayallbeans", String.class); - + then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } - + @Test public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception { @SuppressWarnings("rawtypes") @@ -68,14 +66,14 @@ public class DisplayBeanIntegrationTest { List> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans"); List beanNamesList = allBeans.stream().map(x -> (String) x.get("bean")).collect(Collectors.toList()); - assertThat( beanNamesList, hasItem("fooController")); - assertThat( beanNamesList, hasItem("fooService")); + assertThat(beanNamesList, hasItem("fooController")); + assertThat(beanNamesList, hasItem("fooService")); } - + @Test public void givenWebApplicationContext_whenAccessGetBeanDefinitionNames_thenReturnsBeanNames() throws Exception { String[] beanNames = context.getBeanDefinitionNames(); - + List beanNamesList = Arrays.asList(beanNames); assertTrue(beanNamesList.contains("fooController")); assertTrue(beanNamesList.contains("fooService")); diff --git a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java index af46fe0423..fa05dbab66 100644 --- a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -18,7 +18,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false" }) +@TestPropertySource(properties = {"security.basic.enabled=false"}) public class AppLiveTest { @Autowired @@ -27,15 +27,15 @@ public class AppLiveTest { @Test public void getIndex() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("Index Page"))); + .andExpect(status().isOk()) + .andExpect(content().string(equalTo("Index Page"))); } @Test public void getLocal() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("/local"))); + .andExpect(status().isOk()) + .andExpect(content().string(equalTo("/local"))); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java index e40678603b..ca6230e8f5 100644 --- a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java @@ -1,9 +1,5 @@ package com.baeldung.toggle; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,6 +12,10 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import static org.junit.Assert.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ToggleApplication.class) @AutoConfigureMockMvc diff --git a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java index 829c0a6ac4..edb40e9a1f 100644 --- a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.utils; +import com.baeldung.utils.controller.UtilsController; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -10,32 +11,29 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import com.baeldung.utils.controller.UtilsController; - public class UtilsControllerIntegrationTest { - @InjectMocks + @InjectMocks private UtilsController utilsController; - + private MockMvc mockMvc; - + @Before public void setup() { MockitoAnnotations.initMocks(this); this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController) - .build(); + .build(); } - + @Test public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception { - String param = "testparam"; - this.mockMvc.perform( - post("/setParam") - .param("param", param) - .sessionAttr("parameter", param)) - .andExpect(status().isOk()); + String param = "testparam"; + this.mockMvc.perform( + post("/setParam") + .param("param", param) + .sessionAttr("parameter", param)) + .andExpect(status().isOk()); } - + } diff --git a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java index f30c8ee4e7..b52ab5b1d3 100644 --- a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java @@ -6,11 +6,6 @@ import org.mockito.Mockito; import org.springframework.messaging.simp.stomp.StompHeaders; import org.springframework.messaging.simp.stomp.StompSession; -/** - * Test class for MyStompSessionHandler - * @author Kalyan - * - */ public class MyStompSessionHandlerIntegrationTest { @Test diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java index 2146fc09bc..6623a6396f 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java @@ -45,9 +45,9 @@ public class EmployeeControllerIntegrationTest { given(service.save(Mockito.anyObject())).willReturn(alex); mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON) - .content(JsonUtil.toJson(alex))) - .andExpect(status().isCreated()) - .andExpect(jsonPath("$.name", is("alex"))); + .content(JsonUtil.toJson(alex))) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name", is("alex"))); verify(service, VerificationModeFactory.times(1)).save(Mockito.anyObject()); reset(service); } @@ -63,11 +63,11 @@ public class EmployeeControllerIntegrationTest { given(service.getAllEmployees()).willReturn(allEmployees); mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$", hasSize(3))) - .andExpect(jsonPath("$[0].name", is(alex.getName()))) - .andExpect(jsonPath("$[1].name", is(john.getName()))) - .andExpect(jsonPath("$[2].name", is(bob.getName()))); + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(3))) + .andExpect(jsonPath("$[0].name", is(alex.getName()))) + .andExpect(jsonPath("$[1].name", is(john.getName()))) + .andExpect(jsonPath("$[2].name", is(bob.getName()))); verify(service, VerificationModeFactory.times(1)).getAllEmployees(); reset(service); } diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java index ec599beedf..952ff19707 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java @@ -1,9 +1,5 @@ package org.baeldung.boot.boottest; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.List; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -11,6 +7,10 @@ import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringRunner.class) @DataJpaTest public class EmployeeRepositoryIntegrationTest { @@ -65,7 +65,7 @@ public class EmployeeRepositoryIntegrationTest { List allEmployees = employeeRepository.findAll(); assertThat(allEmployees).hasSize(3) - .extracting(Employee::getName) - .containsOnly(alex.getName(), ron.getName(), bob.getName()); + .extracting(Employee::getName) + .containsOnly(alex.getName(), ron.getName(), bob.getName()); } } diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java index 4c3a50f933..c1d8c52eb9 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java @@ -1,19 +1,5 @@ package org.baeldung.boot.boottest; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.hasSize; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.io.IOException; -import java.util.List; - import org.baeldung.boot.DemoApplication; import org.junit.After; import org.junit.Test; @@ -27,6 +13,20 @@ import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasSize; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class) @AutoConfigureMockMvc @@ -49,11 +49,11 @@ public class EmployeeRestControllerIntegrationTest { public void whenValidInput_thenCreateEmployee() throws IOException, Exception { Employee bob = new Employee("bob"); mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON) - .content(JsonUtil.toJson(bob))); + .content(JsonUtil.toJson(bob))); List found = repository.findAll(); assertThat(found).extracting(Employee::getName) - .containsOnly("bob"); + .containsOnly("bob"); } @Test @@ -63,12 +63,12 @@ public class EmployeeRestControllerIntegrationTest { createTestEmployee("alex"); mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2)))) - .andExpect(jsonPath("$[0].name", is("bob"))) - .andExpect(jsonPath("$[1].name", is("alex"))); + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2)))) + .andExpect(jsonPath("$[0].name", is("bob"))) + .andExpect(jsonPath("$[1].name", is("alex"))); } private void createTestEmployee(String name) { diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java index 8038ae4373..5bd6b34c40 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java @@ -1,10 +1,5 @@ package org.baeldung.boot.boottest; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.List; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,6 +11,11 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringRunner.class) public class EmployeeServiceImplIntegrationTest { @@ -44,27 +44,27 @@ public class EmployeeServiceImplIntegrationTest { List allEmployees = Arrays.asList(john, bob, alex); Mockito.when(employeeRepository.findByName(john.getName())) - .thenReturn(john); + .thenReturn(john); Mockito.when(employeeRepository.findByName(alex.getName())) - .thenReturn(alex); + .thenReturn(alex); Mockito.when(employeeRepository.findByName("wrong_name")) - .thenReturn(null); + .thenReturn(null); Mockito.when(employeeRepository.findById(john.getId())) - .thenReturn(john); + .thenReturn(john); Mockito.when(employeeRepository.findAll()) - .thenReturn(allEmployees); + .thenReturn(allEmployees); Mockito.when(employeeRepository.findById(-99L)) - .thenReturn(null); + .thenReturn(null); } @Test public void whenValidName_thenEmployeeShouldBeFound() { String name = "alex"; Employee found = employeeService.getEmployeeByName(name); - - assertThat(found.getName()) + + assertThat(found.getName()) .isEqualTo(name); - } + } @Test public void whenInValidName_thenEmployeeShouldNotBeFound() { @@ -114,25 +114,25 @@ public class EmployeeServiceImplIntegrationTest { List allEmployees = employeeService.getAllEmployees(); verifyFindAllEmployeesIsCalledOnce(); assertThat(allEmployees).hasSize(3) - .extracting(Employee::getName) - .contains(alex.getName(), john.getName(), bob.getName()); + .extracting(Employee::getName) + .contains(alex.getName(), john.getName(), bob.getName()); } private void verifyFindByNameIsCalledOnce(String name) { Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findByName(name); + .findByName(name); Mockito.reset(employeeRepository); } private void verifyFindByIdIsCalledOnce() { Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findById(Mockito.anyLong()); + .findById(Mockito.anyLong()); Mockito.reset(employeeRepository); } private void verifyFindAllEmployeesIsCalledOnce() { Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findAll(); + .findAll(); Mockito.reset(employeeRepository); } } diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java index 8c7e5576ce..36d07164b2 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java @@ -1,10 +1,10 @@ package org.baeldung.boot.boottest; -import java.io.IOException; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; + class JsonUtil { static byte[] toJson(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); diff --git a/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java b/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java index 0912023fb7..f2ac9d0f82 100644 --- a/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java +++ b/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java @@ -28,9 +28,17 @@ import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.li import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; -import static org.springframework.restdocs.payload.PayloadDocumentation.*; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; +import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; +import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; +import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.restdocs.snippet.Attributes.key; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.util.StringUtils.collectionToDelimitedString; diff --git a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java index 1af626d03b..c02c0c27f8 100644 --- a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java +++ b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java @@ -1,8 +1,6 @@ package com.example; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.jayway.jsonpath.JsonPath; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -14,21 +12,19 @@ import org.springframework.restdocs.RestDocumentation; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import java.io.UnsupportedEncodingException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SpringRestDocsApplication.class) diff --git a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java index 2d3ad7b13f..e7456f1667 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java @@ -37,7 +37,7 @@ public abstract class AbstractDiscoverabilityLiveTest ex // Then final String allowHeader = res.getHeader(HttpHeaders.ALLOW); - assertThat(allowHeader, AnyOf. anyOf(containsString("GET"), containsString("PUT"), containsString("DELETE"))); + assertThat(allowHeader, AnyOf.anyOf(containsString("GET"), containsString("PUT"), containsString("DELETE"))); } @Test diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java index be9b7cf27e..6e70f979c8 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java @@ -31,7 +31,7 @@ public abstract class CsrfAbstractIntegrationTest { @Autowired private Filter springSecurityFilterChain; - protected MockMvc mvc; + MockMvc mvc; // @@ -40,15 +40,15 @@ public abstract class CsrfAbstractIntegrationTest { mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); } - protected RequestPostProcessor testUser() { + RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } - protected RequestPostProcessor testAdmin() { + RequestPostProcessor testAdmin() { return user("admin").password("adminPass").roles("USER", "ADMIN"); } - protected String createFoo() throws JsonProcessingException { + String createFoo() throws JsonProcessingException { return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6))); } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java b/spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java index 392e101193..a899d387ab 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java @@ -33,10 +33,6 @@ public final class JacksonMarshaller implements IMarshaller { String entityAsJSON = null; try { entityAsJSON = objectMapper.writeValueAsString(resource); - } catch (final JsonParseException parseEx) { - logger.error("", parseEx); - } catch (final JsonMappingException mappingEx) { - logger.error("", mappingEx); } catch (final IOException ioEx) { logger.error("", ioEx); } @@ -51,10 +47,6 @@ public final class JacksonMarshaller implements IMarshaller { T entity = null; try { entity = objectMapper.readValue(resourceAsString, clazz); - } catch (final JsonParseException parseEx) { - logger.error("", parseEx); - } catch (final JsonMappingException mappingEx) { - logger.error("", mappingEx); } catch (final IOException ioEx) { logger.error("", ioEx); } @@ -76,10 +68,6 @@ public final class JacksonMarshaller implements IMarshaller { } else { entities = objectMapper.readValue(resourcesAsString, List.class); } - } catch (final JsonParseException parseEx) { - logger.error("", parseEx); - } catch (final JsonMappingException mappingEx) { - logger.error("", mappingEx); } catch (final IOException ioEx) { logger.error("", ioEx); } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java b/spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java index 84fb63a321..85ab623e5f 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java @@ -10,21 +10,21 @@ public final class IDUtil { // API - public final static String randomPositiveLongAsString() { + public static String randomPositiveLongAsString() { return Long.toString(randomPositiveLong()); } - public final static String randomNegativeLongAsString() { + public static String randomNegativeLongAsString() { return Long.toString(randomNegativeLong()); } - public final static long randomPositiveLong() { + public static long randomPositiveLong() { long id = new Random().nextLong() * 10000; id = (id < 0) ? (-1 * id) : id; return id; } - public final static long randomNegativeLong() { + private static long randomNegativeLong() { long id = new Random().nextLong() * 10000; id = (id > 0) ? (-1 * id) : id; return id; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java index 7dcaec5a12..44dc860e62 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java @@ -27,6 +27,7 @@ public class LoggerInterceptorIntegrationTest { @Autowired WebApplicationContext wac; + @Autowired MockHttpSession session; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java b/spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java index bb3919eacc..29f1c91ca3 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java @@ -1,10 +1,5 @@ package org.baeldung.web.util; -import java.util.List; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; - public final class HTTPLinkHeaderUtil { private HTTPLinkHeaderUtil() { @@ -13,23 +8,6 @@ public final class HTTPLinkHeaderUtil { // - /** - * ex.
- * https://api.github.com/users/steveklabnik/gists?page=2>; rel="next", ; rel="last" - */ - public static List extractAllURIs(final String linkHeader) { - Preconditions.checkNotNull(linkHeader); - - final List linkHeaders = Lists.newArrayList(); - final String[] links = linkHeader.split(", "); - for (final String link : links) { - final int positionOfSeparator = link.indexOf(';'); - linkHeaders.add(link.substring(1, positionOfSeparator - 1)); - } - - return linkHeaders; - } - public static String extractURIByRel(final String linkHeader, final String rel) { if (linkHeader == null) { return null; @@ -37,7 +15,7 @@ public final class HTTPLinkHeaderUtil { String uriWithSpecifiedRel = null; final String[] links = linkHeader.split(", "); - String linkRelation = null; + String linkRelation; for (final String link : links) { final int positionOfSeparator = link.indexOf(';'); linkRelation = link.substring(positionOfSeparator + 1, link.length()).trim(); @@ -50,20 +28,9 @@ public final class HTTPLinkHeaderUtil { return uriWithSpecifiedRel; } - static Object extractTypeOfRelation(final String linkRelation) { + private static Object extractTypeOfRelation(final String linkRelation) { final int positionOfEquals = linkRelation.indexOf('='); return linkRelation.substring(positionOfEquals + 2, linkRelation.length() - 1).trim(); } - /** - * ex.
- * https://api.github.com/users/steveklabnik/gists?page=2>; rel="next" - */ - public static String extractSingleURI(final String linkHeader) { - Preconditions.checkNotNull(linkHeader); - final int positionOfSeparator = linkHeader.indexOf(';'); - - return linkHeader.substring(1, positionOfSeparator - 1); - } - } diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java index 6c551b53b2..462e9e8c21 100644 --- a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java @@ -41,7 +41,7 @@ public class ExpressionUtilityObjectsControllerIntegrationTest { @Autowired private Filter springSecurityFilterChain; - protected RequestPostProcessor testUser() { + private RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java index 62c364f864..9c5efdbfc2 100644 --- a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java @@ -41,7 +41,7 @@ public class LayoutDialectControllerIntegrationTest { @Autowired private Filter springSecurityFilterChain; - protected RequestPostProcessor testUser() { + private RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } diff --git a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java index 3d8ddfdd5c..4f6480e3b2 100644 --- a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -41,7 +41,7 @@ public class CsrfEnabledIntegrationTest { @Autowired private Filter springSecurityFilterChain; - protected RequestPostProcessor testUser() { + private RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } diff --git a/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java b/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java index 8ab49309cd..f1659437ec 100644 --- a/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java +++ b/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java @@ -1,20 +1,20 @@ package com.baeldung.junitparams; -import static org.junit.Assert.assertEquals; - import junitparams.FileParameters; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Test; import org.junit.runner.RunWith; +import static org.junit.Assert.assertEquals; + @RunWith(JUnitParamsRunner.class) public class SafeAdditionUtilTest { private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil(); @Test - @Parameters({ "1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15" }) + @Parameters({"1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15"}) public void whenWithAnnotationProvidedParams_thenSafeAdd(int a, int b, int expectedValue) { assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); } @@ -26,7 +26,7 @@ public class SafeAdditionUtilTest { } private Object[] parametersToTestAdd() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; } @Test @@ -36,7 +36,7 @@ public class SafeAdditionUtilTest { } private Object[] parametersForWhenWithnoParam_thenLoadByNameSafeAdd() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; } @Test diff --git a/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java b/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java index d318345a56..08a472502e 100644 --- a/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java +++ b/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java @@ -3,11 +3,11 @@ package com.baeldung.junitparams; public class TestDataProvider { public static Object[] provideBasicData() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { 15, -5, 10 }, new Object[] { -5, -10, -15 } }; + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{15, -5, 10}, new Object[]{-5, -10, -15}}; } public static Object[] provideEdgeCaseData() { - return new Object[] { new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -2, Integer.MIN_VALUE }, }; + return new Object[]{new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -2, Integer.MIN_VALUE},}; } } diff --git a/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java b/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java index 1cdb92090a..20bd62396c 100644 --- a/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java +++ b/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java @@ -1,15 +1,14 @@ package com.baeldung.testing.calculator; -import org.junit.runner.RunWith; - import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; +import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions( - features={"classpath:features/calculator.feature", "classpath:features/calculator-scenario-outline.feature"} - , plugin = { "pretty", "json:target/reports/json/calculator.json" } - , glue = {"com.baeldung.cucumber.calculator"} + features = {"classpath:features/calculator.feature", "classpath:features/calculator-scenario-outline.feature"} + , plugin = {"pretty", "json:target/reports/json/calculator.json"} + , glue = {"com.baeldung.cucumber.calculator"} ) public class CalculatorIntegrationTest { } 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 48c0cb7305..8b05b5a230 100644 --- a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java @@ -1,16 +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 org.junit.Test; - -import io.vavr.Tuple; import io.vavr.Tuple2; import io.vavr.collection.Array; import io.vavr.collection.CharSeq; @@ -26,6 +15,16 @@ 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 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 { @@ -34,7 +33,7 @@ public class CollectionAPIUnitTest { List intList = List.empty(); List anotherList = intList.push(4) - .push(0); + .push(0); Iterator iterator = anotherList.iterator(); assertEquals(new Integer(0), iterator.next()); @@ -46,7 +45,7 @@ public class CollectionAPIUnitTest { List intList = List.of(1, 2, 3); List newList = intList.tail() - .prepend(0); + .prepend(0); assertEquals(new Integer(1), intList.get(0)); assertEquals(new Integer(2), intList.get(1)); @@ -62,45 +61,45 @@ public class CollectionAPIUnitTest { public void givenQueue_whenEnqueued_thenCorrect() { Queue queue = Queue.of(1, 2, 3); Queue secondQueue = queue.enqueue(4) - .enqueue(5); + .enqueue(5); assertEquals(3, queue.size()); assertEquals(5, secondQueue.size()); secondQueue.dequeue() - .map((k, v) -> { - assertEquals(new Integer(1), k); - return v.dequeue(); - }) - .map((k, v) -> { - assertEquals(new Integer(2), k); - return v.dequeue(); - }) - .map((k, v) -> { - assertEquals(new Integer(3), k); - return v.dequeue(); - }) - .map((k, v) -> { - assertEquals(new Integer(4), k); - return v.dequeue(); - }) - .map((k, v) -> { - assertEquals(new Integer(5), k); - assertTrue(v.isEmpty()); - return null; - }); + .map((k, v) -> { + assertEquals(new Integer(1), k); + return v.dequeue(); + }) + .map((k, v) -> { + assertEquals(new Integer(2), k); + return v.dequeue(); + }) + .map((k, v) -> { + assertEquals(new Integer(3), k); + return v.dequeue(); + }) + .map((k, v) -> { + assertEquals(new Integer(4), k); + return v.dequeue(); + }) + .map((k, v) -> { + assertEquals(new Integer(5), k); + assertTrue(v.isEmpty()); + return null; + }); } @Test public void givenStream_whenProcessed_thenCorrect() { Stream intStream = Stream.iterate(0, i -> i + 1) - .take(10); + .take(10); assertEquals(10, intStream.size()); long evenSum = intStream.filter(i -> i % 2 == 0) - .sum() - .longValue(); + .sum() + .longValue(); assertEquals(20L, evenSum); assertEquals(new Integer(5), intStream.get(5)); @@ -170,7 +169,7 @@ public class CollectionAPIUnitTest { @Test public void givenSortedSet_whenReversed_thenCorrect() { - Comparator reverseCompare = (a, b) -> b.compareTo(a); + Comparator reverseCompare = Comparator.reverseOrder(); SortedSet set = TreeSet.of(reverseCompare, "Green", "Red", "Blue"); Iterator iterator = set.iterator(); @@ -182,17 +181,17 @@ public class CollectionAPIUnitTest { @Test public void givenMap_whenIterated_thenCorrect() { Map> map = List.rangeClosed(0, 10) - .groupBy(i -> i % 2); + .groupBy(i -> i % 2); assertEquals(2, map.size()); Iterator>> iterator = map.iterator(); assertEquals(6, iterator.next() - ._2() - .size()); + ._2() + .size()); assertEquals(5, iterator.next() - ._2() - .size()); + ._2() + .size()); } @Test @@ -201,11 +200,11 @@ public class CollectionAPIUnitTest { Iterator> iterator = map.iterator(); assertEquals(new Integer(1), iterator.next() - ._1()); + ._1()); assertEquals(new Integer(2), iterator.next() - ._1()); + ._1()); assertEquals(new Integer(3), iterator.next() - ._1()); + ._1()); } @Test @@ -223,19 +222,14 @@ public class CollectionAPIUnitTest { @Test public void givenVavrList_whenConverted_thenCorrect() { - Integer[] array = List.of(1, 2, 3) - .toJavaArray(Integer.class); - assertEquals(3, array.length); - - java.util.Map map = List.of("1", "2", "3") - .toJavaMap(i -> Tuple.of(i, Integer.valueOf(i))); - assertEquals(new Integer(2), map.get("2")); + java.util.Set collect = List.of(1, 2, 3) + .collect(Collectors.toSet()); } @Test public void givenVavrList_whenConvertedView_thenCorrect() { java.util.List javaList = List.of(1, 2, 3) - .asJavaMutable(); + .asJavaMutable(); javaList.add(4); assertEquals(new Integer(4), javaList.get(3)); @@ -244,7 +238,7 @@ public class CollectionAPIUnitTest { @Test(expected = UnsupportedOperationException.class) public void givenVavrList_whenConvertedView_thenException() { java.util.List javaList = List.of(1, 2, 3) - .asJava(); + .asJava(); assertEquals(new Integer(3), javaList.get(2)); javaList.add(4); @@ -254,8 +248,8 @@ public class CollectionAPIUnitTest { public void givenList_whenSquared_thenCorrect() { List vavrList = List.of(1, 2, 3); Number sum = vavrList.map(i -> i * i) - .sum(); + .sum(); - assertEquals(new Long(14), sum); + assertEquals(14L, sum); } } diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorUnitTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorUnitTest.java index 1b1986417d..33c96acf52 100644 --- a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorUnitTest.java +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorUnitTest.java @@ -21,10 +21,10 @@ public class JsonCreatorUnitTest { // arrange String authorJson = - "{" + - " \"christianName\": \"Alex\"," + - " \"surname\": \"Theedom\"" + - "}"; + "{" + + " \"christianName\": \"Alex\"," + + " \"surname\": \"Theedom\"" + + "}"; // act final Author author = new ObjectMapper().readerFor(Author.class).readValue(authorJson); diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterUnitTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterUnitTest.java index 133f8b1f21..5491168f9b 100644 --- a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterUnitTest.java +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterUnitTest.java @@ -24,7 +24,7 @@ public class JsonFilterUnitTest { // arrange Author author = new Author("Alex", "Theedom"); FilterProvider filters = new SimpleFilterProvider() - .addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); + .addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); // act String result = new ObjectMapper().writer(filters).writeValueAsString(author); diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatUnitTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatUnitTest.java index 373e8d716a..6801516dfd 100644 --- a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatUnitTest.java +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatUnitTest.java @@ -32,8 +32,8 @@ public class JsonFormatUnitTest { Date date = df.parse(toParse); Book book = new Book( - "Design Patterns: Elements of Reusable Object-oriented Software", - new Author("The", "GoF") + "Design Patterns: Elements of Reusable Object-oriented Software", + new Author("The", "GoF") ); book.setPublished(date); diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyUnitTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyUnitTest.java index 191330be86..62f9b498ac 100644 --- a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyUnitTest.java +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyUnitTest.java @@ -22,8 +22,8 @@ public class JsonPropertyUnitTest { // arrange Book book = new Book( - "Design Patterns: Elements of Reusable Object-oriented Software", - new Author("The", "GoF") + "Design Patterns: Elements of Reusable Object-oriented Software", + new Author("The", "GoF") ); book.configureBinding("Hardback"); From 75ac7de5cde3ac424af9e9f145f258fb4a237703 Mon Sep 17 00:00:00 2001 From: mokhan Date: Fri, 21 Jul 2017 22:12:27 +0530 Subject: [PATCH 29/43] Updated custom logging implementation --- spring-rest-logging/pom.xml | 11 ++++++++++- .../log/app/TaxiFareRequestInterceptor.java | 19 ++++++++++++++++++- .../config/RequestLoggingFilterConfig.java | 3 --- .../log/controller/TaxiFareController.java | 5 ++++- 4 files changed, 32 insertions(+), 6 deletions(-) diff --git a/spring-rest-logging/pom.xml b/spring-rest-logging/pom.xml index 5924650e5f..799a746b63 100644 --- a/spring-rest-logging/pom.xml +++ b/spring-rest-logging/pom.xml @@ -12,7 +12,7 @@ spring-boot-starter-parent 1.4.3.RELEASE - + @@ -60,5 +60,14 @@ org.springframework spring-test + + + + commons-io + commons-io + 2.4 + + + diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/TaxiFareRequestInterceptor.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/TaxiFareRequestInterceptor.java index bc011a4db7..4c187772cc 100644 --- a/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/TaxiFareRequestInterceptor.java +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/TaxiFareRequestInterceptor.java @@ -7,6 +7,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; +import org.springframework.web.util.ContentCachingRequestWrapper; + +import com.baeldung.rest.log.util.RequestLoggingUtil; @Component public class TaxiFareRequestInterceptor extends HandlerInterceptorAdapter { @@ -15,7 +18,21 @@ public class TaxiFareRequestInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - LOGGER.info("REQUEST URI: " + request.getRequestURI()); + String postData = null; + HttpServletRequest requestCacheWrapperObject = null; + try { + // Uncomment to produce the stream closed issue + // postData = RequestLoggingUtil.getStringFromInputStream(request.getInputStream()); + + // To overcome request stream closed issue + requestCacheWrapperObject = new ContentCachingRequestWrapper(request); + requestCacheWrapperObject.getParameterMap(); + } catch (Exception exception) { + exception.printStackTrace(); + } finally { + postData = RequestLoggingUtil.readPayload(requestCacheWrapperObject); + LOGGER.info("REQUEST DATA: " + postData); + } return true; } diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/RequestLoggingFilterConfig.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/RequestLoggingFilterConfig.java index 158ba51f77..7afb34dd11 100644 --- a/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/RequestLoggingFilterConfig.java +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/RequestLoggingFilterConfig.java @@ -1,13 +1,10 @@ package com.baeldung.rest.log.config; -import javax.servlet.annotation.WebFilter; - import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.CommonsRequestLoggingFilter; @Configuration -@WebFilter public class RequestLoggingFilterConfig { @Bean diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/controller/TaxiFareController.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/controller/TaxiFareController.java index 0d8e4dafa4..1ef9ece0b2 100644 --- a/spring-rest-logging/src/main/java/com/baeldung/rest/log/controller/TaxiFareController.java +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/controller/TaxiFareController.java @@ -34,7 +34,10 @@ public class TaxiFareController { @ResponseBody public String calculateTaxiFare(@RequestBody @Valid TaxiRide taxiRide) { LOGGER.debug("calculateTaxiFare() - START"); - return taxiFareCalculatorService.calculateFare(taxiRide); + String totalFare = taxiFareCalculatorService.calculateFare(taxiRide); + LOGGER.debug("calculateTaxiFare() - Total Fare : {}",totalFare); + LOGGER.debug("calculateTaxiFare() - END"); + return totalFare; } } From e96690ef203ddfd2e8d0202d41faebdeb96aa833 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sat, 22 Jul 2017 07:05:12 +0100 Subject: [PATCH 30/43] BAEL-964 - Changing assertions within invert test --- .../commons/collections/MapUtilsTest.java | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java index 10d408b467..4685d84781 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java @@ -4,14 +4,19 @@ import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.MapUtils; import org.apache.commons.collections4.PredicateUtils; import org.apache.commons.collections4.TransformerUtils; +import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import java.util.Collection; import java.util.HashMap; import java.util.Map; +import java.util.Set; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.collection.IsMapWithSize.aMapWithSize; @@ -85,19 +90,12 @@ public class MapUtilsTest { @Test public void whenInvertMap_thenMustReturnInvertedMap() { Map invColorMap = MapUtils.invertMap(this.colorMap); - assertEquals(this.colorMap.size(), invColorMap.size()); - MapIterator itColorMap - = MapUtils.iterableMap(this.colorMap).mapIterator(); - - while (itColorMap.hasNext()) { - String colorMapKey = itColorMap.next(); - String colorMapValue = itColorMap.getValue(); - - String invColorMapValue = MapUtils.getString(invColorMap, colorMapValue); - - assertTrue(invColorMapValue.equals(colorMapKey)); - } + int size = invColorMap.size(); + Assertions.assertThat(invColorMap) + .hasSameSizeAs(colorMap) + .containsKeys(this.colorMap.values().toArray(new String[size])) + .containsValues(this.colorMap.keySet().toArray(new String[size])); } @Test(expected = IllegalArgumentException.class) From 226acd5a195a3173d19a7c520fb778bb95512db8 Mon Sep 17 00:00:00 2001 From: Naresh Babu P B Date: Sat, 22 Jul 2017 19:08:37 +0530 Subject: [PATCH 31/43] Bael-422 Vavr Collections (#2304) * BAEL-422 Examples for tutorial on Vavr Collection API * Fixed as per review comments --- .../collections/CollectionAPIUnitTest.java | 95 +++++++++++-------- 1 file changed, 57 insertions(+), 38 deletions(-) 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 8b05b5a230..9f0c48e3ee 100644 --- a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java @@ -1,5 +1,18 @@ 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; import io.vavr.collection.CharSeq; @@ -15,16 +28,6 @@ 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 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 { @@ -66,28 +69,16 @@ public class CollectionAPIUnitTest { assertEquals(3, queue.size()); assertEquals(5, secondQueue.size()); - secondQueue.dequeue() - .map((k, v) -> { - assertEquals(new Integer(1), k); - return v.dequeue(); - }) - .map((k, v) -> { - assertEquals(new Integer(2), k); - return v.dequeue(); - }) - .map((k, v) -> { - assertEquals(new Integer(3), k); - return v.dequeue(); - }) - .map((k, v) -> { - assertEquals(new Integer(4), k); - return v.dequeue(); - }) - .map((k, v) -> { - assertEquals(new Integer(5), k); - assertTrue(v.isEmpty()); - return null; - }); + Tuple2> result = secondQueue.dequeue(); + Integer headValue = result.apply((head, tail) -> head); + assertEquals(new Integer(1), headValue); + + Iterator iterator = result.apply((head, tail) -> tail.iterator()); + + assertEquals(new Integer(2), iterator.next()); + assertEquals(new Integer(3), iterator.next()); + assertEquals(new Integer(4), iterator.next()); + assertEquals(new Integer(5), iterator.next()); } @Test @@ -101,7 +92,7 @@ public class CollectionAPIUnitTest { .sum() .longValue(); - assertEquals(20L, evenSum); + assertEquals(20, evenSum); assertEquals(new Integer(5), intStream.get(5)); } @@ -169,8 +160,7 @@ public class CollectionAPIUnitTest { @Test public void givenSortedSet_whenReversed_thenCorrect() { - Comparator reverseCompare = Comparator.reverseOrder(); - SortedSet set = TreeSet.of(reverseCompare, "Green", "Red", "Blue"); + SortedSet set = TreeSet.of(Comparator.reverseOrder(), "Green", "Red", "Blue"); Iterator iterator = set.iterator(); assertEquals("Red", iterator.next()); @@ -212,18 +202,47 @@ public class CollectionAPIUnitTest { java.util.List javaList = java.util.Arrays.asList(1, 2, 3, 4); List vavrList = List.ofAll(javaList); - assertTrue(vavrList instanceof io.vavr.collection.List); + assertEquals(4, vavrList.size()); + assertEquals(new Integer(1), vavrList.head()); java.util.stream.Stream javaStream = javaList.stream(); Set vavrSet = HashSet.ofAll(javaStream); - assertTrue(vavrSet instanceof io.vavr.collection.Set); + assertEquals(4, vavrSet.size()); + assertEquals(new Integer(2), vavrSet.tail() + .head()); + } + + @Test + public void givenJavaStream_whenCollected_thenCorrect() { + List vavrList = IntStream.range(1, 10) + .boxed() + .filter(i -> i % 2 == 0) + .collect(List.collector()); + + assertEquals(4, vavrList.size()); + assertEquals(new Integer(2), vavrList.head()); } @Test public void givenVavrList_whenConverted_thenCorrect() { - java.util.Set collect = List.of(1, 2, 3) + Integer[] array = List.of(1, 2, 3) + .toJavaArray(Integer.class); + assertEquals(3, array.length); + + java.util.Map map = List.of("1", "2", "3") + .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) .collect(Collectors.toSet()); + + assertEquals(3, javaSet.size()); + assertEquals(new Integer(1), javaSet.iterator() + .next()); } @Test From 101f6fd163f23cd825eb9d06dcda318ea620fbcc Mon Sep 17 00:00:00 2001 From: mokhan Date: Sun, 23 Jul 2017 14:44:52 +0530 Subject: [PATCH 32/43] Comment incorporation Missing file commit --- .../rest/log/util/RequestLoggingUtil.java | 38 +++++++++++++++++++ .../controller/TestTaxiFareController.java | 4 +- 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java new file mode 100644 index 0000000000..3c9eebf34e --- /dev/null +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java @@ -0,0 +1,38 @@ +package com.baeldung.rest.log.util; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.springframework.web.util.ContentCachingRequestWrapper; +import org.springframework.web.util.WebUtils; + +public class RequestLoggingUtil { + + public static String getStringFromInputStream(InputStream is) { + StringWriter writer = new StringWriter(); + String encoding = "UTF-8"; + try { + IOUtils.copy(is, writer, encoding); + } catch (IOException e) { + e.printStackTrace(); + } + return writer.toString(); + } + + public static String readPayload(final HttpServletRequest request) throws IOException { + String payloadData = null; + ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class); + if (null != contentCachingRequestWrapper) { + byte[] buf = contentCachingRequestWrapper.getContentAsByteArray(); + if (buf.length > 0) { + payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding()); + } + } + return payloadData; + } + +} diff --git a/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java b/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java index 61d279a0c5..ed3cdda7ad 100644 --- a/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java +++ b/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java @@ -15,14 +15,14 @@ public class TestTaxiFareController { private static final String URL = "http://localhost:" + 9090 + "/rest-log/taxifare/"; @Test - public void given_taxi_fare_get() { + public void givenRequest_thenfetchTaxiFareRateCard() { TestRestTemplate testRestTemplate = new TestRestTemplate(); ResponseEntity response = testRestTemplate.getForEntity(URL + "get/", String.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } @Test - public void given_taxi_ride_get_fare() { + public void givenTaxiRide_thenGetCalculatedFare() { TestRestTemplate testRestTemplate = new TestRestTemplate(); TaxiRide taxiRide = new TaxiRide(true,10l); String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide,String.class); From 879bedf205e7609cd5d792d21d0ba680d681f545 Mon Sep 17 00:00:00 2001 From: mokhan Date: Sun, 23 Jul 2017 14:44:52 +0530 Subject: [PATCH 33/43] Comment incorporation Missing file commit --- pom.xml | 1 + .../rest/log/util/RequestLoggingUtil.java | 38 +++++++++++++++++++ .../controller/TestTaxiFareController.java | 4 +- 3 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java diff --git a/pom.xml b/pom.xml index 818d131359..9bfadc01a5 100644 --- a/pom.xml +++ b/pom.xml @@ -208,6 +208,7 @@ spring-zuul spring-reactor spring-vertx + spring-rest-logging testing testng diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java new file mode 100644 index 0000000000..3c9eebf34e --- /dev/null +++ b/spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java @@ -0,0 +1,38 @@ +package com.baeldung.rest.log.util; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.springframework.web.util.ContentCachingRequestWrapper; +import org.springframework.web.util.WebUtils; + +public class RequestLoggingUtil { + + public static String getStringFromInputStream(InputStream is) { + StringWriter writer = new StringWriter(); + String encoding = "UTF-8"; + try { + IOUtils.copy(is, writer, encoding); + } catch (IOException e) { + e.printStackTrace(); + } + return writer.toString(); + } + + public static String readPayload(final HttpServletRequest request) throws IOException { + String payloadData = null; + ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class); + if (null != contentCachingRequestWrapper) { + byte[] buf = contentCachingRequestWrapper.getContentAsByteArray(); + if (buf.length > 0) { + payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding()); + } + } + return payloadData; + } + +} diff --git a/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java b/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java index 61d279a0c5..ed3cdda7ad 100644 --- a/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java +++ b/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java @@ -15,14 +15,14 @@ public class TestTaxiFareController { private static final String URL = "http://localhost:" + 9090 + "/rest-log/taxifare/"; @Test - public void given_taxi_fare_get() { + public void givenRequest_thenfetchTaxiFareRateCard() { TestRestTemplate testRestTemplate = new TestRestTemplate(); ResponseEntity response = testRestTemplate.getForEntity(URL + "get/", String.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } @Test - public void given_taxi_ride_get_fare() { + public void givenTaxiRide_thenGetCalculatedFare() { TestRestTemplate testRestTemplate = new TestRestTemplate(); TaxiRide taxiRide = new TaxiRide(true,10l); String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide,String.class); From ef5013ce24fd38c6758ad608b4953ef757913544 Mon Sep 17 00:00:00 2001 From: Jesus Boadas Date: Sun, 23 Jul 2017 16:10:39 -0400 Subject: [PATCH 34/43] Delete Vaadin from libraries (#2309) * Delete Vaadin from libraries * Add Vaadin to tutorials --- libraries/pom.xml | 183 ------------------ .../webapp/VAADIN/themes/valo/addons.scss | 7 - vaadin/pom.xml | 173 +++++++++++++++++ .../com/baeldung/introduction}/BindData.java | 2 +- .../com/baeldung/introduction}/VaadinUI.java | 4 +- vaadin/src/main/resources/README | 1 + .../webapp/VAADIN/themes/mytheme/addons.scss | 0 .../webapp/VAADIN/themes/mytheme/favicon.ico | Bin .../webapp/VAADIN/themes/mytheme/mytheme.scss | 0 .../webapp/VAADIN/themes/mytheme/styles.css | 0 .../webapp/VAADIN/themes/mytheme/styles.scss | 0 11 files changed, 177 insertions(+), 193 deletions(-) delete mode 100644 libraries/src/main/webapp/VAADIN/themes/valo/addons.scss create mode 100644 vaadin/pom.xml rename {libraries/src/main/java/com/baeldung/vaadin => vaadin/src/main/java/com/baeldung/introduction}/BindData.java (89%) rename {libraries/src/main/java/com/baeldung/vaadin => vaadin/src/main/java/com/baeldung/introduction}/VaadinUI.java (99%) create mode 100644 vaadin/src/main/resources/README rename {libraries => vaadin}/src/main/webapp/VAADIN/themes/mytheme/addons.scss (100%) rename {libraries => vaadin}/src/main/webapp/VAADIN/themes/mytheme/favicon.ico (100%) rename {libraries => vaadin}/src/main/webapp/VAADIN/themes/mytheme/mytheme.scss (100%) rename {libraries => vaadin}/src/main/webapp/VAADIN/themes/mytheme/styles.css (100%) rename {libraries => vaadin}/src/main/webapp/VAADIN/themes/mytheme/styles.scss (100%) diff --git a/libraries/pom.xml b/libraries/pom.xml index 16f70cb171..d80c9ffdae 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -71,78 +71,8 @@ - - - org.apache.maven.plugins - maven-war-plugin - 3.0.0 - - false - WEB-INF/classes/VAADIN/widgetsets/WEB-INF/** - - - - com.vaadin - vaadin-maven-plugin - ${vaadin.plugin.version} - - - - update-theme - update-widgetset - compile - compile-theme - - - - - - org.apache.maven.plugins - maven-clean-plugin - 3.0.0 - - - - src/main/webapp/VAADIN/themes - - **/styles.css - **/styles.scss.cache - - - - - - - org.eclipse.jetty - jetty-maven-plugin - ${jetty.version} - - 2 - true - - - - - - - vaadin-addons - http://maven.vaadin.com/vaadin-addons - - - - - - com.vaadin - vaadin-bom - ${vaadin.version} - pom - import - - - - @@ -463,72 +393,6 @@ ${org.hamcrest.java-hamcrest.version} test - - - com.vaadin - vaadin-server - - - com.vaadin - vaadin-client-compiled - - - com.vaadin - vaadin-themes - - - com.vaadin - vaadin-push - - - org.seleniumhq.selenium - selenium-java - test - 3.4.0 - - - org.seleniumhq.selenium - htmlunit-driver - 2.27 - - - org.eclipse.jetty.websocket - websocket-server - ${jetty.version} - - - org.eclipse.jetty.websocket - websocket-client - ${jetty.version} - - - org.eclipse.jetty.websocket - websocket-api - ${jetty.version} - - - org.eclipse.jetty.websocket - websocket-common - ${jetty.version} - - - org.eclipse.jetty - jetty-continuation - ${jetty.version} - - - org.eclipse.jetty - jetty-util - ${jetty.version} - - - org.seleniumhq.selenium - selenium-api - 3.4.0 - test - jar - - net.agkn hll @@ -580,54 +444,7 @@ 3.5.0 3.0.0 2.0.0.0 - - 7.7.10 - 8.0.6 - mytheme - 1.6.0 1.7.1 - - - - vaadin-prerelease - - false - - - - vaadin-prereleases - http://maven.vaadin.com/vaadin-prereleases - - - vaadin-snapshots - https://oss.sonatype.org/content/repositories/vaadin-snapshots/ - - false - - - true - - - - - - vaadin-prereleases - http://maven.vaadin.com/vaadin-prereleases - - - vaadin-snapshots - https://oss.sonatype.org/content/repositories/vaadin-snapshots/ - - false - - - true - - - - - - diff --git a/libraries/src/main/webapp/VAADIN/themes/valo/addons.scss b/libraries/src/main/webapp/VAADIN/themes/valo/addons.scss deleted file mode 100644 index a5670b70c7..0000000000 --- a/libraries/src/main/webapp/VAADIN/themes/valo/addons.scss +++ /dev/null @@ -1,7 +0,0 @@ -/* This file is automatically managed and will be overwritten from time to time. */ -/* Do not manually edit this file. */ - -/* Import and include this mixin into your project theme to include the addon themes */ -@mixin addons { -} - diff --git a/vaadin/pom.xml b/vaadin/pom.xml new file mode 100644 index 0000000000..6d3512ba2d --- /dev/null +++ b/vaadin/pom.xml @@ -0,0 +1,173 @@ + + + 4.0.0 + + org.test + vaadin-app + war + 1.0-SNAPSHOT + vaadin-app + + + 3 + + + + 7.7.10 + 8.0.6 + 9.3.9.v20160517 + UTF-8 + 1.8 + 1.8 + local + mytheme + + + + + vaadin-addons + http://maven.vaadin.com/vaadin-addons + + + + + + + com.vaadin + vaadin-bom + ${vaadin.version} + pom + import + + + + + + + javax.servlet + javax.servlet-api + 3.0.1 + provided + + + com.vaadin + vaadin-server + + + com.vaadin + vaadin-push + + + com.vaadin + vaadin-client-compiled + + + com.vaadin + vaadin-themes + + + + + + + org.apache.maven.plugins + maven-war-plugin + 3.0.0 + + false + + WEB-INF/classes/VAADIN/widgetsets/WEB-INF/** + + + + com.vaadin + vaadin-maven-plugin + ${vaadin.plugin.version} + + + + update-theme + update-widgetset + compile + + compile-theme + + + + + + org.apache.maven.plugins + maven-clean-plugin + 3.0.0 + + + + + src/main/webapp/VAADIN/themes + + **/styles.css + **/styles.scss.cache + + + + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty.plugin.version} + + 2 + + + + + + + + + vaadin-prerelease + + false + + + + + vaadin-prereleases + http://maven.vaadin.com/vaadin-prereleases + + + vaadin-snapshots + https://oss.sonatype.org/content/repositories/vaadin-snapshots/ + + false + + + true + + + + + + vaadin-prereleases + http://maven.vaadin.com/vaadin-prereleases + + + vaadin-snapshots + https://oss.sonatype.org/content/repositories/vaadin-snapshots/ + + false + + + true + + + + + + + diff --git a/libraries/src/main/java/com/baeldung/vaadin/BindData.java b/vaadin/src/main/java/com/baeldung/introduction/BindData.java similarity index 89% rename from libraries/src/main/java/com/baeldung/vaadin/BindData.java rename to vaadin/src/main/java/com/baeldung/introduction/BindData.java index bcdc4eee71..299554c039 100644 --- a/libraries/src/main/java/com/baeldung/vaadin/BindData.java +++ b/vaadin/src/main/java/com/baeldung/introduction/BindData.java @@ -1,4 +1,4 @@ -package com.baeldung.vaadin; +package com.baeldung.introduction; public class BindData { diff --git a/libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java similarity index 99% rename from libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java rename to vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java index 68e2ca7944..1b3733ad74 100644 --- a/libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java +++ b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java @@ -1,4 +1,4 @@ -package com.baeldung.vaadin; +package com.baeldung.introduction; import java.time.Instant; import java.util.ArrayList; @@ -278,4 +278,4 @@ public class VaadinUI extends UI { @VaadinServletConfiguration(ui = VaadinUI.class, productionMode = false) public static class MyUIServlet extends VaadinServlet { } -} \ No newline at end of file +} diff --git a/vaadin/src/main/resources/README b/vaadin/src/main/resources/README new file mode 100644 index 0000000000..faabc74ad5 --- /dev/null +++ b/vaadin/src/main/resources/README @@ -0,0 +1 @@ +Please add your static resources here diff --git a/libraries/src/main/webapp/VAADIN/themes/mytheme/addons.scss b/vaadin/src/main/webapp/VAADIN/themes/mytheme/addons.scss similarity index 100% rename from libraries/src/main/webapp/VAADIN/themes/mytheme/addons.scss rename to vaadin/src/main/webapp/VAADIN/themes/mytheme/addons.scss diff --git a/libraries/src/main/webapp/VAADIN/themes/mytheme/favicon.ico b/vaadin/src/main/webapp/VAADIN/themes/mytheme/favicon.ico similarity index 100% rename from libraries/src/main/webapp/VAADIN/themes/mytheme/favicon.ico rename to vaadin/src/main/webapp/VAADIN/themes/mytheme/favicon.ico diff --git a/libraries/src/main/webapp/VAADIN/themes/mytheme/mytheme.scss b/vaadin/src/main/webapp/VAADIN/themes/mytheme/mytheme.scss similarity index 100% rename from libraries/src/main/webapp/VAADIN/themes/mytheme/mytheme.scss rename to vaadin/src/main/webapp/VAADIN/themes/mytheme/mytheme.scss diff --git a/libraries/src/main/webapp/VAADIN/themes/mytheme/styles.css b/vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.css similarity index 100% rename from libraries/src/main/webapp/VAADIN/themes/mytheme/styles.css rename to vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.css diff --git a/libraries/src/main/webapp/VAADIN/themes/mytheme/styles.scss b/vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.scss similarity index 100% rename from libraries/src/main/webapp/VAADIN/themes/mytheme/styles.scss rename to vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.scss From 9c4042eb88480cc4f9ca64179c264ce714fb173c Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 24 Jul 2017 08:49:36 +0200 Subject: [PATCH 35/43] Add missing "volatile"s (#2307) * Add volatile keywords * Update SafeCounterWithoutLock.java --- .../com/baeldung/concurrent/atomic/SafeCounterWithLock.java | 2 +- .../com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java index b2502018bb..38633011bf 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java +++ b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java @@ -1,7 +1,7 @@ package com.baeldung.concurrent.atomic; public class SafeCounterWithLock { - int counter; + private volatile int counter; public int getValue() { return counter; diff --git a/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java index 55226f4f13..41e10789a6 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java +++ b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java @@ -3,7 +3,7 @@ package com.baeldung.concurrent.atomic; import java.util.concurrent.atomic.AtomicInteger; public class SafeCounterWithoutLock { - AtomicInteger counter = new AtomicInteger(0); + private final AtomicInteger counter = new AtomicInteger(0); public int getValue() { return counter.get(); From f58c41de4db4c0d82680689128332c40b2717262 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Mon, 24 Jul 2017 09:23:18 +0200 Subject: [PATCH 36/43] cucumber java8 (#2306) * 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 --- testing/pom.xml | 6 +++++ .../shopping/ShoppingIntegrationTest.java | 12 ++++++++++ .../testing/shopping/ShoppingStepsDef.java | 22 +++++++++++++++++++ .../test/resources/features/shopping.feature | 11 ++++++++++ 4 files changed, 51 insertions(+) create mode 100644 testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java create mode 100644 testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java create mode 100644 testing/src/test/resources/features/shopping.feature diff --git a/testing/pom.xml b/testing/pom.xml index aa10392aa8..bfd47dbc4a 100644 --- a/testing/pom.xml +++ b/testing/pom.xml @@ -45,6 +45,12 @@ test + + info.cukes + cucumber-java8 + ${cucumber.version} + test + org.pitest diff --git a/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java b/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java new file mode 100644 index 0000000000..7bf8641ed6 --- /dev/null +++ b/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java @@ -0,0 +1,12 @@ +package com.baeldung.testing.shopping; + +import org.junit.runner.RunWith; + +import cucumber.api.CucumberOptions; +import cucumber.api.junit.Cucumber; + +@RunWith(Cucumber.class) +@CucumberOptions(features = { "classpath:features/shopping.feature" }) +public class ShoppingIntegrationTest { + +} diff --git a/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java b/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java new file mode 100644 index 0000000000..2c4bf2eeae --- /dev/null +++ b/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java @@ -0,0 +1,22 @@ +package com.baeldung.testing.shopping; + +import static org.junit.Assert.assertEquals; +import cucumber.api.java8.En; + +public class ShoppingStepsDef implements En { + + private int budget = 0; + + public ShoppingStepsDef() { + + Given("I have (\\d+) in my wallet", (Integer money) -> budget = money); + + When("I buy .* with (\\d+)", (Integer price) -> budget -= price); + + Then("I should have (\\d+) in my wallet", (Integer finalBudget) -> { + assertEquals(budget, finalBudget.intValue()); + }); + + } + +} \ No newline at end of file diff --git a/testing/src/test/resources/features/shopping.feature b/testing/src/test/resources/features/shopping.feature new file mode 100644 index 0000000000..d1ce43df75 --- /dev/null +++ b/testing/src/test/resources/features/shopping.feature @@ -0,0 +1,11 @@ +Feature: Shopping + + Scenario: Track my budget + Given I have 100 in my wallet + When I buy milk with 10 + Then I should have 90 in my wallet + + Scenario: Track my budget + Given I have 200 in my wallet + When I buy rice with 20 + Then I should have 180 in my wallet From 1be49ebc7ff3cd3874fbd9a801a5b52334a864f4 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Mon, 24 Jul 2017 12:58:10 +0530 Subject: [PATCH 37/43] introducing lambda (#2305) * 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 --- .../ScheduledExecutorServiceDemo.java | 30 ++++++------------- .../cyclicbarrier/CyclicBarrierExample.java | 8 ++--- .../concurrent/executor/ExecutorDemo.java | 7 ++--- .../executorservice/ExecutorServiceDemo.java | 9 ++---- .../concurrent/future/FutureDemo.java | 11 +++---- 5 files changed, 20 insertions(+), 45 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java b/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java index 171f308c16..b77019eea5 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java @@ -1,6 +1,5 @@ package com.baeldung.concurrent.Scheduledexecutorservice; -import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; @@ -12,32 +11,21 @@ public class ScheduledExecutorServiceDemo { public void execute() { ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); - ScheduledFuture scheduledFuture = executorService.schedule(new Runnable() { - @Override - public void run() { - // task details - } + ScheduledFuture scheduledFuture = executorService.schedule(() -> { + // Task }, 1, TimeUnit.SECONDS); - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - // task details - } + executorService.scheduleAtFixedRate(() -> { + // Task }, 1, 10, TimeUnit.SECONDS); - executorService.scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { - // task details - } + executorService.scheduleWithFixedDelay(() -> { + // Task }, 1, 10, TimeUnit.SECONDS); - Future future = executorService.schedule(new Callable() { - @Override - public String call() throws Exception { - return "Hello World"; - } + Future future = executorService.schedule(() -> { + // Task + return "Hellow world"; }, 1, TimeUnit.SECONDS); executorService.shutdown(); 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 e6075c933e..85c0cf7680 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 @@ -5,11 +5,9 @@ import java.util.concurrent.CyclicBarrier; public class CyclicBarrierExample { public void start() { - CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() { - @Override - public void run() { - System.out.println("All previous tasks are completed"); - } + CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> { + // Task + System.out.println("All previous tasks are completed"); }); Thread t1 = new Thread(new Task(cyclicBarrier), "T1"); diff --git a/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java b/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java index 9392134bfb..84998cb489 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java @@ -6,11 +6,8 @@ public class ExecutorDemo { public void execute() { Executor executor = new Invoker(); - executor.execute(new Runnable() { - @Override - public void run() { - // task to be performed - } + executor.execute(()->{ + // task to be performed }); } diff --git a/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java b/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java index 631ae140ab..ae2b279d9a 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java @@ -10,15 +10,10 @@ public class ExecutorServiceDemo { public void execute() { - executor.execute(new Runnable() { - @Override - public void run() { - // task details - } + executor.submit(() -> { + new Task(); }); - executor.submit(new Task()); - executor.shutdown(); executor.shutdownNow(); try { diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java b/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java index 89ce1a0a41..7cb611be0f 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java @@ -1,6 +1,5 @@ package com.baeldung.concurrent.future; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -16,12 +15,10 @@ public class FutureDemo { ExecutorService executorService = Executors.newFixedThreadPool(10); - Future future = executorService.submit(new Callable() { - @Override - public String call() throws Exception { - Thread.sleep(10000l); - return "Hello World"; - } + Future future = executorService.submit(() -> { + // Task + Thread.sleep(10000l); + return "Hellow world"; }); future.cancel(false); From 29b0da9960184906702a49ce5ee2aadde4b3c681 Mon Sep 17 00:00:00 2001 From: mokhan Date: Mon, 24 Jul 2017 23:03:24 +0530 Subject: [PATCH 38/43] Web Logging code included in exisitng module namely "spring-rest" --- spring-rest/pom.xml | 558 +++++++++--------- .../com/baeldung/web/log/app/Application.java | 18 + .../log/app/TaxiFareRequestInterceptor.java | 44 ++ .../config/RequestLoggingFilterConfig.java | 20 + .../web/log/config/TaxiFareMVCConfig.java | 20 + .../log/controller/TaxiFareController.java | 43 ++ .../com/baeldung/web/log/data/RateCard.java | 28 + .../com/baeldung/web/log/data/TaxiRide.java | 32 + .../service/TaxiFareCalculatorService.java | 20 + .../web/log/util/RequestLoggingUtil.java | 38 ++ spring-rest/src/main/resources/logback.xml | 4 + .../web/log/test/TestTaxiFareController.java | 33 ++ 12 files changed, 583 insertions(+), 275 deletions(-) create mode 100644 spring-rest/src/main/java/com/baeldung/web/log/app/Application.java create mode 100644 spring-rest/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java create mode 100644 spring-rest/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java create mode 100644 spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java create mode 100644 spring-rest/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java create mode 100644 spring-rest/src/main/java/com/baeldung/web/log/data/RateCard.java create mode 100644 spring-rest/src/main/java/com/baeldung/web/log/data/TaxiRide.java create mode 100644 spring-rest/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java create mode 100644 spring-rest/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java create mode 100644 spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index c12028149d..6065d7e529 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -1,321 +1,329 @@ - 4.0.0 - com.baeldung - spring-rest - 0.1-SNAPSHOT - spring-rest - war + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + spring-rest + 0.1-SNAPSHOT + spring-rest + war - - parent-boot-4 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-4 - + + parent-boot-4 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-4 + - + - + - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-devtools - - - org.springframework.boot - spring-boot-test - + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-devtools + + + org.springframework.boot + spring-boot-test + - + - - org.springframework - spring-web - - - commons-logging - commons-logging - - - - - org.springframework - spring-webmvc - - - org.springframework - spring-oxm - + + org.springframework + spring-web + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + + + org.springframework + spring-oxm + - - commons-fileupload - commons-fileupload - ${commons-fileupload.version} - - + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + + - - javax.servlet - javax.servlet-api - provided - + + javax.servlet + javax.servlet-api + provided + - - javax.servlet - jstl - runtime - + + javax.servlet + jstl + runtime + - + - - com.fasterxml.jackson.core - jackson-databind - + + com.fasterxml.jackson.core + jackson-databind + - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + - - com.thoughtworks.xstream - xstream - ${xstream.version} - + + com.thoughtworks.xstream + xstream + ${xstream.version} + - + - - com.google.guava - guava - ${guava.version} - + + com.google.guava + guava + ${guava.version} + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - + - - com.squareup.okhttp3 - okhttp - ${com.squareup.okhttp3.version} - + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + - + - - org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library - test - + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + - - org.mockito - mockito-core - test - + + org.mockito + mockito-core + test + - - org.springframework - spring-test - + + org.springframework + spring-test + - - - com.google.protobuf - protobuf-java - ${protobuf-java.version} - - - com.googlecode.protobuf-java-format - protobuf-java-format - ${protobuf-java-format.version} - + + + com.google.protobuf + protobuf-java + ${protobuf-java.version} + + + com.googlecode.protobuf-java-format + protobuf-java-format + ${protobuf-java-format.version} + - - com.esotericsoftware - kryo - ${kryo.version} - + + com.esotericsoftware + kryo + ${kryo.version} + - - com.jayway.jsonpath - json-path - + + com.jayway.jsonpath + json-path + - - - spring-rest - - - src/main/resources - true - - + + + commons-io + commons-io + 2.4 + - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - org.apache.maven.plugins - maven-war-plugin - + - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - tomcat8x - embedded - - - - - - - 8082 - - - - + + spring-rest + + + src/main/resources + true + + - + + + org.springframework.boot + spring-boot-maven-plugin + + true + + + + org.apache.maven.plugins + maven-war-plugin + - + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + tomcat8x + embedded + + + + + + + 8082 + + + + - + - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*IntegrationTest.java - - - - - + - - - + - - live - - - - org.codehaus.cargo - cargo-maven2-plugin - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*IntegrationTest.java + + + + + - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*LiveTest.java - - - cargo - - - - - + + + - - - + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + - + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + - - 1.3.2 - 4.0.0 - 1.4 - 3.1.0 - 3.5 - 1.4.9 + + + - - 20.0 + - - 1.6.0 - 3.0.4 + + 1.3.2 + 4.0.0 + 1.4 + 3.1.0 + 3.5 + 1.4.9 - - 3.4.1 + + 20.0 - 2.2.0 - + + 1.6.0 + 3.0.4 + + + 3.4.1 + + 2.2.0 + diff --git a/spring-rest/src/main/java/com/baeldung/web/log/app/Application.java b/spring-rest/src/main/java/com/baeldung/web/log/app/Application.java new file mode 100644 index 0000000000..9bdbbd0d9f --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/app/Application.java @@ -0,0 +1,18 @@ +package com.baeldung.web.log.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; + +@EnableAutoConfiguration +@ComponentScan("com.baeldung.web.log") +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + public static void main(final String[] args) { + SpringApplication.run(Application.class, args); + } + +} \ No newline at end of file diff --git a/spring-rest/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java b/spring-rest/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java new file mode 100644 index 0000000000..831d236edd --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java @@ -0,0 +1,44 @@ +package com.baeldung.web.log.app; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; +import org.springframework.web.util.ContentCachingRequestWrapper; + +import com.baeldung.web.log.util.RequestLoggingUtil; + +@Component +public class TaxiFareRequestInterceptor extends HandlerInterceptorAdapter { + + Logger LOGGER = LoggerFactory.getLogger(TaxiFareRequestInterceptor.class); + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String postData = null; + HttpServletRequest requestCacheWrapperObject = null; + try { + // Uncomment to produce the stream closed issue + // postData = RequestLoggingUtil.getStringFromInputStream(request.getInputStream()); + + // To overcome request stream closed issue + requestCacheWrapperObject = new ContentCachingRequestWrapper(request); + requestCacheWrapperObject.getParameterMap(); + } catch (Exception exception) { + exception.printStackTrace(); + } finally { + postData = RequestLoggingUtil.readPayload(requestCacheWrapperObject); + LOGGER.info("REQUEST DATA: " + postData); + } + return true; + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + LOGGER.info("RESPONSE: " + response.getStatus()); + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java b/spring-rest/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java new file mode 100644 index 0000000000..bc9ad1cf84 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.web.log.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.CommonsRequestLoggingFilter; + +@Configuration +public class RequestLoggingFilterConfig { + + @Bean + public CommonsRequestLoggingFilter logFilter() { + CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter(); + filter.setIncludeQueryString(true); + filter.setIncludePayload(true); + filter.setMaxPayloadLength(10000); + filter.setIncludeHeaders(false); + filter.setAfterMessagePrefix("REQUEST DATA : "); + return filter; + } +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java b/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java new file mode 100644 index 0000000000..fa26706ff0 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.web.log.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import com.baeldung.web.log.app.TaxiFareRequestInterceptor; + +@Configuration +public class TaxiFareMVCConfig extends WebMvcConfigurerAdapter { + + @Autowired + private TaxiFareRequestInterceptor taxiFareRequestInterceptor; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(taxiFareRequestInterceptor).addPathPatterns("/**/taxifare/**/"); + } +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java b/spring-rest/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java new file mode 100644 index 0000000000..28bf07e8a6 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java @@ -0,0 +1,43 @@ +package com.baeldung.web.log.controller; + +import javax.validation.Valid; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.web.log.data.RateCard; +import com.baeldung.web.log.data.TaxiRide; +import com.baeldung.web.log.service.TaxiFareCalculatorService; + +@Controller +public class TaxiFareController { + + @Autowired + private TaxiFareCalculatorService taxiFareCalculatorService; + + private static final Logger LOGGER = LoggerFactory.getLogger(TaxiFareController.class); + + @RequestMapping(method = RequestMethod.GET, value = "/taxifare/get/") + @ResponseBody + public RateCard getTaxiFare() { + LOGGER.debug("getTaxiFare() - START"); + return new RateCard(); + } + + @RequestMapping(method = RequestMethod.POST, value = "/taxifare/calculate/") + @ResponseBody + public String calculateTaxiFare(@RequestBody @Valid TaxiRide taxiRide) { + LOGGER.debug("calculateTaxiFare() - START"); + String totalFare = taxiFareCalculatorService.calculateFare(taxiRide); + LOGGER.debug("calculateTaxiFare() - Total Fare : {}",totalFare); + LOGGER.debug("calculateTaxiFare() - END"); + return totalFare; + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/data/RateCard.java b/spring-rest/src/main/java/com/baeldung/web/log/data/RateCard.java new file mode 100644 index 0000000000..35ae38fd11 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/data/RateCard.java @@ -0,0 +1,28 @@ +package com.baeldung.web.log.data; + +public class RateCard { + + private String nightSurcharge; + private String ratePerMile; + + public RateCard(){ + nightSurcharge="Extra $ 100"; + ratePerMile="$ 10 Per Mile"; + } + + + public String getNightSurcharge() { + return nightSurcharge; + } + public void setNightSurcharge(String nightSurcharge) { + this.nightSurcharge = nightSurcharge; + } + public String getRatePerMile() { + return ratePerMile; + } + public void setRatePerMile(String ratePerMile) { + this.ratePerMile = ratePerMile; + } + + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/data/TaxiRide.java b/spring-rest/src/main/java/com/baeldung/web/log/data/TaxiRide.java new file mode 100644 index 0000000000..0877cdced4 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/data/TaxiRide.java @@ -0,0 +1,32 @@ +package com.baeldung.web.log.data; + +public class TaxiRide { + + private Boolean isNightSurcharge; + private Long distanceInMile; + + public TaxiRide(){} + + public TaxiRide(Boolean isNightSurcharge, Long distanceInMile){ + this.isNightSurcharge = isNightSurcharge; + this.distanceInMile = distanceInMile; + } + + + public Boolean getIsNightSurcharge() { + return isNightSurcharge; + } + + public void setIsNightSurcharge(Boolean isNightSurcharge) { + this.isNightSurcharge = isNightSurcharge; + } + + public Long getDistanceInMile() { + return distanceInMile; + } + + public void setDistanceInMile(Long distanceInMile) { + this.distanceInMile = distanceInMile; + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java b/spring-rest/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java new file mode 100644 index 0000000000..ec9c81187a --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java @@ -0,0 +1,20 @@ +package com.baeldung.web.log.service; + +import org.springframework.stereotype.Service; + +import com.baeldung.web.log.data.TaxiRide; + +@Service +public class TaxiFareCalculatorService { + + public String calculateFare(TaxiRide taxiRide) { + Long fare = 0l; + if (taxiRide.getIsNightSurcharge()) { + fare = taxiRide.getDistanceInMile() * 10 + 100; + } else { + fare = taxiRide.getDistanceInMile() * 10; + } + return String.valueOf(fare); + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java b/spring-rest/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java new file mode 100644 index 0000000000..c13d35b55c --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java @@ -0,0 +1,38 @@ +package com.baeldung.web.log.util; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.springframework.web.util.ContentCachingRequestWrapper; +import org.springframework.web.util.WebUtils; + +public class RequestLoggingUtil { + + public static String getStringFromInputStream(InputStream is) { + StringWriter writer = new StringWriter(); + String encoding = "UTF-8"; + try { + IOUtils.copy(is, writer, encoding); + } catch (IOException e) { + e.printStackTrace(); + } + return writer.toString(); + } + + public static String readPayload(final HttpServletRequest request) throws IOException { + String payloadData = null; + ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class); + if (null != contentCachingRequestWrapper) { + byte[] buf = contentCachingRequestWrapper.getContentAsByteArray(); + if (buf.length > 0) { + payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding()); + } + } + return payloadData; + } + +} diff --git a/spring-rest/src/main/resources/logback.xml b/spring-rest/src/main/resources/logback.xml index ec0dc2469a..3496a4a03c 100644 --- a/spring-rest/src/main/resources/logback.xml +++ b/spring-rest/src/main/resources/logback.xml @@ -6,6 +6,10 @@ + + + + diff --git a/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java b/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java new file mode 100644 index 0000000000..935275983f --- /dev/null +++ b/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java @@ -0,0 +1,33 @@ +package com.baeldung.web.log.test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.Test; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import com.baeldung.web.log.data.TaxiRide; + +public class TestTaxiFareController { + + private static final String URL = "http://localhost:" + 8082 + "/spring-rest/taxifare/"; + + @Test + public void givenRequest_thenfetchTaxiFareRateCard() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + ResponseEntity response = testRestTemplate.getForEntity(URL + "get/", String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenTaxiRide_thenGetCalculatedFare() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + TaxiRide taxiRide = new TaxiRide(true,10l); + String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide,String.class); + assertThat(fare, equalTo("200")); + } + + +} From 553c26c1a2a96b80012cfa8e9cd64a6e35af8762 Mon Sep 17 00:00:00 2001 From: mokhan Date: Mon, 24 Jul 2017 23:08:43 +0530 Subject: [PATCH 39/43] deleted the new module --- pom.xml | 2 +- spring-rest-logging/pom.xml | 73 ------------------- .../baeldung/rest/log/app/Application.java | 18 ----- .../log/app/TaxiFareRequestInterceptor.java | 44 ----------- .../config/RequestLoggingFilterConfig.java | 20 ----- .../rest/log/config/TaxiFareMVCConfig.java | 20 ----- .../log/controller/TaxiFareController.java | 43 ----------- .../com/baeldung/rest/log/data/RateCard.java | 28 ------- .../com/baeldung/rest/log/data/TaxiRide.java | 32 -------- .../service/TaxiFareCalculatorService.java | 20 ----- .../rest/log/util/RequestLoggingUtil.java | 38 ---------- .../src/main/resources/application.properties | 2 - .../src/main/resources/logback.xml | 21 ------ .../controller/TestTaxiFareController.java | 33 --------- 14 files changed, 1 insertion(+), 393 deletions(-) delete mode 100644 spring-rest-logging/pom.xml delete mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/app/Application.java delete mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/app/TaxiFareRequestInterceptor.java delete mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/config/RequestLoggingFilterConfig.java delete mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/config/TaxiFareMVCConfig.java delete mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/controller/TaxiFareController.java delete mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/data/RateCard.java delete mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/data/TaxiRide.java delete mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/service/TaxiFareCalculatorService.java delete mode 100644 spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java delete mode 100644 spring-rest-logging/src/main/resources/application.properties delete mode 100644 spring-rest-logging/src/main/resources/logback.xml delete mode 100644 spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java diff --git a/pom.xml b/pom.xml index 9bfadc01a5..7e87d4fd8c 100644 --- a/pom.xml +++ b/pom.xml @@ -208,7 +208,7 @@ spring-zuul spring-reactor spring-vertx - spring-rest-logging + testing testng diff --git a/spring-rest-logging/pom.xml b/spring-rest-logging/pom.xml deleted file mode 100644 index 799a746b63..0000000000 --- a/spring-rest-logging/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - 4.0.0 - com.baeldung - spring-rest-logging - 0.1-SNAPSHOT - spring-rest-logging - war - - - org.springframework.boot - spring-boot-starter-parent - 1.4.3.RELEASE - - - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - - - org.springframework.boot - spring-boot-test - - - - - org.springframework - spring-web - - - commons-logging - commons-logging - - - - - org.springframework - spring-webmvc - - - - - - javax.servlet - javax.servlet-api - provided - - - - junit - junit - test - - - - org.springframework - spring-test - - - - - commons-io - commons-io - 2.4 - - - - - diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/Application.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/Application.java deleted file mode 100644 index 9eb79ee1b1..0000000000 --- a/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/Application.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.rest.log.app; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; -import org.springframework.context.annotation.ComponentScan; - -@EnableAutoConfiguration -@ComponentScan("com.baeldung") -@SpringBootApplication -public class Application extends SpringBootServletInitializer { - - public static void main(final String[] args) { - SpringApplication.run(Application.class, args); - } - -} \ No newline at end of file diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/TaxiFareRequestInterceptor.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/TaxiFareRequestInterceptor.java deleted file mode 100644 index 4c187772cc..0000000000 --- a/spring-rest-logging/src/main/java/com/baeldung/rest/log/app/TaxiFareRequestInterceptor.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.rest.log.app; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; -import org.springframework.web.util.ContentCachingRequestWrapper; - -import com.baeldung.rest.log.util.RequestLoggingUtil; - -@Component -public class TaxiFareRequestInterceptor extends HandlerInterceptorAdapter { - - Logger LOGGER = LoggerFactory.getLogger(TaxiFareRequestInterceptor.class); - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - String postData = null; - HttpServletRequest requestCacheWrapperObject = null; - try { - // Uncomment to produce the stream closed issue - // postData = RequestLoggingUtil.getStringFromInputStream(request.getInputStream()); - - // To overcome request stream closed issue - requestCacheWrapperObject = new ContentCachingRequestWrapper(request); - requestCacheWrapperObject.getParameterMap(); - } catch (Exception exception) { - exception.printStackTrace(); - } finally { - postData = RequestLoggingUtil.readPayload(requestCacheWrapperObject); - LOGGER.info("REQUEST DATA: " + postData); - } - return true; - } - - @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { - LOGGER.info("RESPONSE: " + response.getStatus()); - } - -} diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/RequestLoggingFilterConfig.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/RequestLoggingFilterConfig.java deleted file mode 100644 index 7afb34dd11..0000000000 --- a/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/RequestLoggingFilterConfig.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.rest.log.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.filter.CommonsRequestLoggingFilter; - -@Configuration -public class RequestLoggingFilterConfig { - - @Bean - public CommonsRequestLoggingFilter logFilter() { - CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter(); - filter.setIncludeQueryString(true); - filter.setIncludePayload(true); - filter.setMaxPayloadLength(10000); - filter.setIncludeHeaders(false); - filter.setAfterMessagePrefix("REQUEST DATA : "); - return filter; - } -} diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/TaxiFareMVCConfig.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/TaxiFareMVCConfig.java deleted file mode 100644 index 71d0fd379f..0000000000 --- a/spring-rest-logging/src/main/java/com/baeldung/rest/log/config/TaxiFareMVCConfig.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.rest.log.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -import com.baeldung.rest.log.app.TaxiFareRequestInterceptor; - -@Configuration -public class TaxiFareMVCConfig extends WebMvcConfigurerAdapter { - - @Autowired - private TaxiFareRequestInterceptor taxiFareRequestInterceptor; - - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(taxiFareRequestInterceptor).addPathPatterns("/**/taxifare/**/"); - } -} diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/controller/TaxiFareController.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/controller/TaxiFareController.java deleted file mode 100644 index 1ef9ece0b2..0000000000 --- a/spring-rest-logging/src/main/java/com/baeldung/rest/log/controller/TaxiFareController.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.rest.log.controller; - -import javax.validation.Valid; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.baeldung.rest.log.data.RateCard; -import com.baeldung.rest.log.data.TaxiRide; -import com.baeldung.rest.log.service.TaxiFareCalculatorService; - -@Controller -public class TaxiFareController { - - @Autowired - private TaxiFareCalculatorService taxiFareCalculatorService; - - private static final Logger LOGGER = LoggerFactory.getLogger(TaxiFareController.class); - - @RequestMapping(method = RequestMethod.GET, value = "/taxifare/get/") - @ResponseBody - public RateCard getTaxiFare() { - LOGGER.debug("getTaxiFare() - START"); - return new RateCard(); - } - - @RequestMapping(method = RequestMethod.POST, value = "/taxifare/calculate/") - @ResponseBody - public String calculateTaxiFare(@RequestBody @Valid TaxiRide taxiRide) { - LOGGER.debug("calculateTaxiFare() - START"); - String totalFare = taxiFareCalculatorService.calculateFare(taxiRide); - LOGGER.debug("calculateTaxiFare() - Total Fare : {}",totalFare); - LOGGER.debug("calculateTaxiFare() - END"); - return totalFare; - } - -} diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/data/RateCard.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/data/RateCard.java deleted file mode 100644 index 6e0c6d0e38..0000000000 --- a/spring-rest-logging/src/main/java/com/baeldung/rest/log/data/RateCard.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.rest.log.data; - -public class RateCard { - - private String nightSurcharge; - private String ratePerMile; - - public RateCard(){ - nightSurcharge="Extra $ 100"; - ratePerMile="$ 10 Per Mile"; - } - - - public String getNightSurcharge() { - return nightSurcharge; - } - public void setNightSurcharge(String nightSurcharge) { - this.nightSurcharge = nightSurcharge; - } - public String getRatePerMile() { - return ratePerMile; - } - public void setRatePerMile(String ratePerMile) { - this.ratePerMile = ratePerMile; - } - - -} diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/data/TaxiRide.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/data/TaxiRide.java deleted file mode 100644 index bcf102e49d..0000000000 --- a/spring-rest-logging/src/main/java/com/baeldung/rest/log/data/TaxiRide.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.rest.log.data; - -public class TaxiRide { - - private Boolean isNightSurcharge; - private Long distanceInMile; - - public TaxiRide(){} - - public TaxiRide(Boolean isNightSurcharge, Long distanceInMile){ - this.isNightSurcharge = isNightSurcharge; - this.distanceInMile = distanceInMile; - } - - - public Boolean getIsNightSurcharge() { - return isNightSurcharge; - } - - public void setIsNightSurcharge(Boolean isNightSurcharge) { - this.isNightSurcharge = isNightSurcharge; - } - - public Long getDistanceInMile() { - return distanceInMile; - } - - public void setDistanceInMile(Long distanceInMile) { - this.distanceInMile = distanceInMile; - } - -} diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/service/TaxiFareCalculatorService.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/service/TaxiFareCalculatorService.java deleted file mode 100644 index 31dfd7ac50..0000000000 --- a/spring-rest-logging/src/main/java/com/baeldung/rest/log/service/TaxiFareCalculatorService.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.rest.log.service; - -import org.springframework.stereotype.Service; - -import com.baeldung.rest.log.data.TaxiRide; - -@Service -public class TaxiFareCalculatorService { - - public String calculateFare(TaxiRide taxiRide) { - Long fare = 0l; - if (taxiRide.getIsNightSurcharge()) { - fare = taxiRide.getDistanceInMile() * 10 + 100; - } else { - fare = taxiRide.getDistanceInMile() * 10; - } - return String.valueOf(fare); - } - -} diff --git a/spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java b/spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java deleted file mode 100644 index 3c9eebf34e..0000000000 --- a/spring-rest-logging/src/main/java/com/baeldung/rest/log/util/RequestLoggingUtil.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.rest.log.util; - -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.io.IOUtils; -import org.springframework.web.util.ContentCachingRequestWrapper; -import org.springframework.web.util.WebUtils; - -public class RequestLoggingUtil { - - public static String getStringFromInputStream(InputStream is) { - StringWriter writer = new StringWriter(); - String encoding = "UTF-8"; - try { - IOUtils.copy(is, writer, encoding); - } catch (IOException e) { - e.printStackTrace(); - } - return writer.toString(); - } - - public static String readPayload(final HttpServletRequest request) throws IOException { - String payloadData = null; - ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class); - if (null != contentCachingRequestWrapper) { - byte[] buf = contentCachingRequestWrapper.getContentAsByteArray(); - if (buf.length > 0) { - payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding()); - } - } - return payloadData; - } - -} diff --git a/spring-rest-logging/src/main/resources/application.properties b/spring-rest-logging/src/main/resources/application.properties deleted file mode 100644 index ff8a818e66..0000000000 --- a/spring-rest-logging/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -server.port= 9090 -server.context-path=/rest-log diff --git a/spring-rest-logging/src/main/resources/logback.xml b/spring-rest-logging/src/main/resources/logback.xml deleted file mode 100644 index 08117752c7..0000000000 --- a/spring-rest-logging/src/main/resources/logback.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java b/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java deleted file mode 100644 index ed3cdda7ad..0000000000 --- a/spring-rest-logging/src/test/java/com/baeldung/rest/log/controller/TestTaxiFareController.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.rest.log.controller; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; - -import org.junit.Test; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - -import com.baeldung.rest.log.data.TaxiRide; - -public class TestTaxiFareController { - - private static final String URL = "http://localhost:" + 9090 + "/rest-log/taxifare/"; - - @Test - public void givenRequest_thenfetchTaxiFareRateCard() { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - ResponseEntity response = testRestTemplate.getForEntity(URL + "get/", String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - } - - @Test - public void givenTaxiRide_thenGetCalculatedFare() { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - TaxiRide taxiRide = new TaxiRide(true,10l); - String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide,String.class); - assertThat(fare, equalTo("200")); - } - - -} From 34dc899c9b2df10ac03b3cc6e29f50af5cf69799 Mon Sep 17 00:00:00 2001 From: Alejandro Gervasio Date: Mon, 24 Jul 2017 18:15:09 -0300 Subject: [PATCH 40/43] Custom Efficient hashCode() Implementations - Alejandro Gervasio - alejandro.gervasio@gmail.com (#2301) * Initial Commit * Updated pom.xml * Updated User class * Updated pom.xml * Updated Application class --- core-java/hashcode/pom.xml | 39 +++++++++++++++++++ .../com/baeldung/application/Application.java | 23 +++++++++++ .../main/java/com/baeldung/entities/User.java | 38 ++++++++++++++++++ .../baeldung/application/ApplicationTest.java | 30 ++++++++++++++ .../java/com/baeldung/entities/UserTest.java | 34 ++++++++++++++++ 5 files changed, 164 insertions(+) create mode 100644 core-java/hashcode/pom.xml create mode 100644 core-java/hashcode/src/main/java/com/baeldung/application/Application.java create mode 100644 core-java/hashcode/src/main/java/com/baeldung/entities/User.java create mode 100644 core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java create mode 100644 core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java diff --git a/core-java/hashcode/pom.xml b/core-java/hashcode/pom.xml new file mode 100644 index 0000000000..393aa69153 --- /dev/null +++ b/core-java/hashcode/pom.xml @@ -0,0 +1,39 @@ + + + 4.0.0 + com.baeldung.hashcode + hashcode + 1.0 + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + junit + junit + 4.12 + test + + + org.slf4j + slf4j-api + 1.7.25 + + + org.slf4j + slf4j-simple + 1.7.25 + + + \ No newline at end of file diff --git a/core-java/hashcode/src/main/java/com/baeldung/application/Application.java b/core-java/hashcode/src/main/java/com/baeldung/application/Application.java new file mode 100644 index 0000000000..08c670c82f --- /dev/null +++ b/core-java/hashcode/src/main/java/com/baeldung/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/hashcode/src/main/java/com/baeldung/entities/User.java b/core-java/hashcode/src/main/java/com/baeldung/entities/User.java new file mode 100644 index 0000000000..a976233562 --- /dev/null +++ b/core-java/hashcode/src/main/java/com/baeldung/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/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java b/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java new file mode 100644 index 0000000000..dcd853f451 --- /dev/null +++ b/core-java/hashcode/src/test/java/com/baeldung/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/hashcode/src/test/java/com/baeldung/entities/UserTest.java b/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java new file mode 100644 index 0000000000..01f6085d7e --- /dev/null +++ b/core-java/hashcode/src/test/java/com/baeldung/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 7fdab0e191fb709e4481198caad1ad73baba9479 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Tue, 25 Jul 2017 15:42:57 +0100 Subject: [PATCH 41/43] BAEL-554 - Logging Spring Web Request --- .../web/log/test/TestTaxiFareController.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java b/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java index 935275983f..398e3c04e9 100644 --- a/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java +++ b/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java @@ -13,21 +13,21 @@ import com.baeldung.web.log.data.TaxiRide; public class TestTaxiFareController { private static final String URL = "http://localhost:" + 8082 + "/spring-rest/taxifare/"; - + @Test - public void givenRequest_thenfetchTaxiFareRateCard() { + public void givenRequest_whenFetchTaxiFareRateCard_thanOK() { TestRestTemplate testRestTemplate = new TestRestTemplate(); ResponseEntity response = testRestTemplate.getForEntity(URL + "get/", String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } - + @Test - public void givenTaxiRide_thenGetCalculatedFare() { + public void givenTaxiRide_whenCalculatedFare_thanStatus200() { TestRestTemplate testRestTemplate = new TestRestTemplate(); - TaxiRide taxiRide = new TaxiRide(true,10l); - String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide,String.class); + TaxiRide taxiRide = new TaxiRide(true, 10l); + String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide, String.class); + assertThat(fare, equalTo("200")); } - - } From d4f245a275e016386562d7d7f4bb2b40b5cc74cb Mon Sep 17 00:00:00 2001 From: Adam InTae Gerard Date: Tue, 25 Jul 2017 15:11:02 -0700 Subject: [PATCH 42/43] BAEL-771 (#2286) * BAEL-771 * Corrected XOR from mislabeled AND * Unit tests added * Merged into libraries module - removed Neuroph module * Merged into libraries module - removed Neuroph module * Merged pom.xml * Merged pom.xml * libraries pom.xml - I removed a white space during merge so conflict persisted - here's the temporary reversion --- libraries/README.md | 1 + libraries/pom.xml | 45 +++++++++++- .../java/com/baeldung/neuroph/NeurophXOR.java | 73 +++++++++++++++++++ .../java/com/baeldung/neuroph/XORTest.java | 50 +++++++++++++ 4 files changed, 167 insertions(+), 2 deletions(-) create mode 100644 libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java create mode 100644 libraries/src/test/java/com/baeldung/neuroph/XORTest.java diff --git a/libraries/README.md b/libraries/README.md index 7970c0e99e..f0484ec710 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -26,6 +26,7 @@ - [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) - [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) - [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) +- [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index d80c9ffdae..c5e1f64594 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -7,7 +7,6 @@ 1.0.0-SNAPSHOT 4.0.0 - libraries libraries @@ -71,9 +70,51 @@ + + + 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 @@ -327,7 +368,6 @@ quartz 2.3.0 - one.util streamex @@ -432,6 +472,7 @@ 2.5 1.2.0 2.8.5 + 2.92 1.4.0 1.24.0 1.1.3-rc.5 diff --git a/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java new file mode 100644 index 0000000000..fb6a01d4c1 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java @@ -0,0 +1,73 @@ +package com.baeldung.neuroph; + +import org.neuroph.core.Layer; +import org.neuroph.core.NeuralNetwork; +import org.neuroph.core.Neuron; +import org.neuroph.core.data.DataSet; +import org.neuroph.core.data.DataSetRow; +import org.neuroph.nnet.learning.BackPropagation; +import org.neuroph.util.ConnectionFactory; +import org.neuroph.util.NeuralNetworkType; + +public class NeurophXOR { + + public static NeuralNetwork assembleNeuralNetwork() { + + Layer inputLayer = new Layer(); + inputLayer.addNeuron(new Neuron()); + inputLayer.addNeuron(new Neuron()); + + Layer hiddenLayerOne = new Layer(); + hiddenLayerOne.addNeuron(new Neuron()); + hiddenLayerOne.addNeuron(new Neuron()); + hiddenLayerOne.addNeuron(new Neuron()); + hiddenLayerOne.addNeuron(new Neuron()); + + Layer hiddenLayerTwo = new Layer(); + hiddenLayerTwo.addNeuron(new Neuron()); + hiddenLayerTwo.addNeuron(new Neuron()); + hiddenLayerTwo.addNeuron(new Neuron()); + hiddenLayerTwo.addNeuron(new Neuron()); + + Layer outputLayer = new Layer(); + outputLayer.addNeuron(new Neuron()); + + NeuralNetwork ann = new NeuralNetwork(); + + ann.addLayer(0, inputLayer); + ann.addLayer(1, hiddenLayerOne); + ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(1)); + ann.addLayer(2, hiddenLayerTwo); + ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2)); + ann.addLayer(3, outputLayer); + ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3)); + ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount()-1), false); + + ann.setInputNeurons(inputLayer.getNeurons()); + ann.setOutputNeurons(outputLayer.getNeurons()); + + ann.setNetworkType(NeuralNetworkType.MULTI_LAYER_PERCEPTRON); + return ann; + } + + public static NeuralNetwork trainNeuralNetwork(NeuralNetwork ann) { + int inputSize = 2; + int outputSize = 1; + DataSet ds = new DataSet(inputSize, outputSize); + + DataSetRow rOne = new DataSetRow(new double[] {0, 1}, new double[] {1}); + ds.addRow(rOne); + DataSetRow rTwo = new DataSetRow(new double[] {1, 1}, new double[] {0}); + ds.addRow(rTwo); + DataSetRow rThree = new DataSetRow(new double[] {0, 0}, new double[] {0}); + ds.addRow(rThree); + DataSetRow rFour = new DataSetRow(new double[] {1, 0}, new double[] {1}); + ds.addRow(rFour); + + BackPropagation backPropagation = new BackPropagation(); + backPropagation.setMaxIterations(1000); + + ann.learn(ds, backPropagation); + return ann; + } +} diff --git a/libraries/src/test/java/com/baeldung/neuroph/XORTest.java b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java new file mode 100644 index 0000000000..063c57195b --- /dev/null +++ b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java @@ -0,0 +1,50 @@ +package com.baeldung.neuroph; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.neuroph.core.NeuralNetwork; + +import static org.junit.Assert.*; + +public class XORTest { + private NeuralNetwork ann = null; + + @Before + public void annInit() { + ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork()); + } + + @Test + public void leftDisjunctTest() { + ann.setInput(0, 1); + ann.calculate(); + 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); + } + + @Test + public void bothFalseConjunctTest() { + ann.setInput(0, 0); + ann.calculate(); + 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); + } + + @After + public void annClose() { + ann = null; + } +} From 7ffd8ecb12dd24a12ae92e7d759192453e509f7d Mon Sep 17 00:00:00 2001 From: cleversonzanon Date: Thu, 27 Jul 2017 03:20:04 -0300 Subject: [PATCH 43/43] Cleverson Zanon | cleverson.ssantos1008@gmail.com (#2315) * Different Types of Bean Injection in Spring code * Dataclasses in Kotlin * Revert "Different Types of Bean Injection in Spring code" This reverts commit 4b747726b93a9f6bf76d6518792fc77e0d5c2fc9. * Destructuring Declarations in Kotlin --- .../destructuringdeclarations/Person.kt | 3 + .../destructuringdeclarations/Result.kt | 3 + .../destructuringdeclarations/Sandbox.kt | 55 +++++++++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt create mode 100644 kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt create mode 100644 kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt diff --git a/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt new file mode 100644 index 0000000000..d3167ce033 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt @@ -0,0 +1,3 @@ +package com.baeldung.destructuringdeclarations + +data class Person(var id: Int, var name: String, var age: Int) \ No newline at end of file diff --git a/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt new file mode 100644 index 0000000000..e3da9b46a4 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt @@ -0,0 +1,3 @@ +package com.baeldung.destructuringdeclarations + +data class Result(val result: Int, val status: String) \ No newline at end of file diff --git a/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt new file mode 100644 index 0000000000..87775f9378 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt @@ -0,0 +1,55 @@ +package com.baeldung.destructuringdeclarations + +import com.baeldung.destructuringdeclarations.Person +import com.baeldung.destructuringdeclarations.Result + +fun main(args: Array) { + + //2.1. Objects + val person = Person(1, "Jon Snow", 20) + val(id, name, age) = person + + println(id) //1 + println(name) //Jon Snow + println(age) //20 + + //The equivalent of line 10 +/* val id = person.component1(); + val name = person.component2(); + val age = person.component3();*/ + + //2.2. Functions + fun getPersonInfo() = Person(2, "Ned Stark", 45) + val(idf, namef, agef) = getPersonInfo() + + fun twoValuesReturn(): Result { + + // needed code + + return Result(1, "success") + } + + // Now, to use this function: + val (result, status) = twoValuesReturn() + + //2.3. Collections and For-loops + var map: HashMap = HashMap() + map.put(1, person) + + for((key, value) in map){ + println("Key: $key, Value: $value") + } + + //2.4. Underscore and Destructuring in Lambdas + val (_, status2) = twoValuesReturn() + + map.mapValues { entry -> "${entry.value}!" } + map.mapValues { (key, value) -> "$value!" } + + //A pair of parameters vs. a destructuring pair +/* { a -> ... } // one parameter + { a, b -> ... } // two parameters + { (a, b) -> ... } // a destructured pair + { (a, b), c -> ... } // a destructured pair and another parameter*/ + +} \ No newline at end of file