From d1b8f9b9b35ee84409571844317474295e7a6b4f Mon Sep 17 00:00:00 2001 From: tritty Date: Wed, 9 May 2018 03:58:04 +0530 Subject: [PATCH 01/69] Bean Object, server side and client side example for event streaming example --- .../controller/StockBrokerController.java | 26 ++++++++++++ .../com/baeldung/reactive/model/Stock.java | 18 ++++++++ .../reactive/webclient/StockClient.java | 42 +++++++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/controller/StockBrokerController.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/model/Stock.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/webclient/StockClient.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/StockBrokerController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/StockBrokerController.java new file mode 100644 index 0000000000..f904943a02 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/StockBrokerController.java @@ -0,0 +1,26 @@ +package com.baeldung.reactive.controller; + +import java.time.Duration; +import java.util.Date; +import java.util.Random; +import java.util.stream.Stream; + +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.reactive.model.Stock; + +import reactor.core.publisher.Flux; + +@RestController +public class StockBrokerController { + + @GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE, value = "/getStockPrice") + public Flux getStockUpdates() { + final Flux stockFlux = Flux.fromStream(Stream.generate(() -> new Stock(new Random().nextFloat(), "WebFluxStock", new Date()))); + final Flux intervalFlux = Flux.interval(Duration.ofSeconds(1)); + return Flux.zip(stockFlux, intervalFlux) + .map(t1 -> t1.getT1()); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/model/Stock.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/model/Stock.java new file mode 100644 index 0000000000..959c8de685 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/model/Stock.java @@ -0,0 +1,18 @@ +package com.baeldung.reactive.model; + +import java.util.Date; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@AllArgsConstructor +@Data +@NoArgsConstructor +public class Stock { + + private float price; + private String name; + private Date date; + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webclient/StockClient.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webclient/StockClient.java new file mode 100644 index 0000000000..d86660dd90 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/webclient/StockClient.java @@ -0,0 +1,42 @@ +package com.baeldung.reactive.webclient; + +import java.util.Collections; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.http.MediaType; +import org.springframework.web.reactive.function.client.WebClient; + +import com.baeldung.reactive.model.Stock; + +@SpringBootApplication +public class StockClient { + + @Bean + WebClient webClient() { + return WebClient.builder() + .baseUrl("http://localhost:8080/getStockPrice") + .build(); + } + + @Bean + CommandLineRunner runner(WebClient webClient) { + return args -> { + webClient.get() + .accept(MediaType.TEXT_EVENT_STREAM) + .retrieve() + .bodyToFlux(Stock.class) + .log() + .subscribe(System.out::println); + }; + } + + public static void main(String args[]) throws InterruptedException { + new SpringApplicationBuilder(StockClient.class).properties(Collections.singletonMap("server.port", "9090")) + .run(args); + + } + +} From 3623391466fc1999629d1a2edac10025abc909e0 Mon Sep 17 00:00:00 2001 From: tritty Date: Mon, 28 May 2018 00:21:44 +0530 Subject: [PATCH 02/69] BAEL-1628 Access a File from the Classpath in a Spring Application --- .../java/com/baeldung/resource/AppConfig.java | 10 ++ .../resource/ClassPathResourceReader.java | 98 +++++++++++++++++++ .../src/main/resources/data/resource-data.txt | 1 + .../baeldung/resource/SpringResourceTest.java | 57 +++++++++++ .../src/test/resources/data/resource-data.txt | 1 + 5 files changed, 167 insertions(+) create mode 100644 spring-core/src/main/java/com/baeldung/resource/AppConfig.java create mode 100644 spring-core/src/main/java/com/baeldung/resource/ClassPathResourceReader.java create mode 100644 spring-core/src/main/resources/data/resource-data.txt create mode 100644 spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java create mode 100644 spring-core/src/test/resources/data/resource-data.txt diff --git a/spring-core/src/main/java/com/baeldung/resource/AppConfig.java b/spring-core/src/main/java/com/baeldung/resource/AppConfig.java new file mode 100644 index 0000000000..5b266cb5cf --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/resource/AppConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.resource; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.resource") +public class AppConfig { + +} diff --git a/spring-core/src/main/java/com/baeldung/resource/ClassPathResourceReader.java b/spring-core/src/main/java/com/baeldung/resource/ClassPathResourceReader.java new file mode 100644 index 0000000000..f1e88eef04 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/resource/ClassPathResourceReader.java @@ -0,0 +1,98 @@ +package com.baeldung.resource; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.stereotype.Component; +import org.springframework.util.ResourceUtils; + +@Component +public class ClassPathResourceReader { + + @Autowired + ResourceLoader resourceLoader; + + @Autowired + ApplicationContext applicationContext; + + @Value("classpath:data/resource-data.txt") + Resource resourceFile; + + /** + * Constructs Resource object by making use of its built-in implementations. + * + * @return Resource + */ + public Resource constructResourceManually() { + Resource resource = new ClassPathResource("data/resource-data.txt"); + return resource; + } + + /** + * Constructs resource object by making use of ResourceLoader. + * + * @return Resource + */ + public Resource retrieveResourceUsingResourceLoader() { + Resource resource = resourceLoader.getResource("classpath:data/resource-data.txt"); + return resource; + } + + /** + * Constructs Resource instance by making use of ApplicationContext. + * + * @return Resource + */ + public Resource retrieveResourceUsingApplicationContext() { + Resource resource = applicationContext.getResource("classpath:data/resource-data.txt"); + return resource; + } + + /** + * ResourceUtils example for getting file data. + * + * @return + * @throws FileNotFoundException + */ + public File retrieveFileUsingResourceUtils() throws FileNotFoundException { + return ResourceUtils.getFile("classpath:data/resource-data.txt"); + } + + /** + * Utility method to list contents ofa file. + * + * @param fileResource + * @return + * @throws IOException + */ + public String listResourceContentsUsingFile(File fileResource) throws IOException { + FileReader fileReader = new FileReader(fileResource); + BufferedReader bufReader = new BufferedReader(fileReader); + String dataLine = bufReader.readLine(); + StringBuilder fileData = new StringBuilder(); + while (null != dataLine) { + fileData.append(dataLine); + dataLine = bufReader.readLine(); + } + + fileReader.close(); + return fileData.toString(); + } + + public Resource getSampleFile() { + return resourceFile; + } + + public void setSampleFile(Resource sampleFile) { + this.resourceFile = sampleFile; + } +} diff --git a/spring-core/src/main/resources/data/resource-data.txt b/spring-core/src/main/resources/data/resource-data.txt new file mode 100644 index 0000000000..cf3720cd66 --- /dev/null +++ b/spring-core/src/main/resources/data/resource-data.txt @@ -0,0 +1 @@ +This is a sample text to demonstrate usage of Spring Resource. \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java new file mode 100644 index 0000000000..7703a016f4 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java @@ -0,0 +1,57 @@ +package com.baeldung.resource; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = AppConfig.class) +public class SpringResourceTest { + + @Autowired + private ClassPathResourceReader classPathResourceReader; + + static final String testData = "This is a sample text to demonstrate usage of Spring Resource."; + + @Test + public void whenManualInstance_thenReadSuccessful() throws IOException { + Resource resource = classPathResourceReader.constructResourceManually(); + String fileData = classPathResourceReader.listResourceContentsUsingFile(resource.getFile()); + assertEquals(testData, fileData); + } + + @Test + public void whenResourceLoader_thenReadSuccessful() throws IOException { + Resource resource = classPathResourceReader.retrieveResourceUsingResourceLoader(); + String fileData = classPathResourceReader.listResourceContentsUsingFile(resource.getFile()); + assertEquals(testData, fileData); + } + + @Test + public void whenApplicationContext_thenReadSuccessful() throws IOException { + Resource resource = classPathResourceReader.retrieveResourceUsingApplicationContext(); + String fileData = classPathResourceReader.listResourceContentsUsingFile(resource.getFile()); + assertEquals(testData, fileData); + } + + @Test + public void whenAutowired_thenReadSuccessful() throws IOException { + Resource resource = classPathResourceReader.getSampleFile(); + String fileData = classPathResourceReader.listResourceContentsUsingFile(resource.getFile()); + assertEquals(testData, fileData); + } + + @Test + public void whenResourceUtils_thenReadSuccessful() throws IOException { + String fileData = classPathResourceReader.listResourceContentsUsingFile(classPathResourceReader.retrieveFileUsingResourceUtils()); + assertEquals(testData, fileData); + } +} diff --git a/spring-core/src/test/resources/data/resource-data.txt b/spring-core/src/test/resources/data/resource-data.txt new file mode 100644 index 0000000000..cf3720cd66 --- /dev/null +++ b/spring-core/src/test/resources/data/resource-data.txt @@ -0,0 +1 @@ +This is a sample text to demonstrate usage of Spring Resource. \ No newline at end of file From d2301be9661987e0dc70ec47caa601767a7d58f4 Mon Sep 17 00:00:00 2001 From: tritty Date: Mon, 28 May 2018 00:59:22 +0530 Subject: [PATCH 03/69] inputstream retrieval added --- .../resource/ClassPathResourceReader.java | 26 +++++++++++++++++-- .../baeldung/resource/SpringResourceTest.java | 9 ++++++- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/spring-core/src/main/java/com/baeldung/resource/ClassPathResourceReader.java b/spring-core/src/main/java/com/baeldung/resource/ClassPathResourceReader.java index f1e88eef04..c4618247e9 100644 --- a/spring-core/src/main/java/com/baeldung/resource/ClassPathResourceReader.java +++ b/spring-core/src/main/java/com/baeldung/resource/ClassPathResourceReader.java @@ -5,6 +5,9 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -68,7 +71,7 @@ public class ClassPathResourceReader { } /** - * Utility method to list contents ofa file. + * Utility method to list contents of a file. * * @param fileResource * @return @@ -83,11 +86,30 @@ public class ClassPathResourceReader { fileData.append(dataLine); dataLine = bufReader.readLine(); } - + bufReader.close(); fileReader.close(); return fileData.toString(); } + /** + * Utility method to list contents of a stream + * + * @param ipStream + * @return + * @throws IOException + */ + public String listResourceContentsUsingInputStream(InputStream ipStream) throws IOException { + BufferedReader bufReader = new BufferedReader(new InputStreamReader(ipStream, "UTF-8")); + String dataLine = bufReader.readLine(); + StringBuilder fileData = new StringBuilder(); + while (null != dataLine) { + fileData.append(dataLine); + dataLine = bufReader.readLine(); + } + bufReader.close(); + return fileData.toString(); + } + public Resource getSampleFile() { return resourceFile; } diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java index 7703a016f4..ba1e2c6d37 100644 --- a/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java @@ -18,7 +18,7 @@ public class SpringResourceTest { @Autowired private ClassPathResourceReader classPathResourceReader; - + static final String testData = "This is a sample text to demonstrate usage of Spring Resource."; @Test @@ -54,4 +54,11 @@ public class SpringResourceTest { String fileData = classPathResourceReader.listResourceContentsUsingFile(classPathResourceReader.retrieveFileUsingResourceUtils()); assertEquals(testData, fileData); } + + @Test + public void whenResourceAsStream_thenReadSuccessful() throws IOException { + Resource resource = classPathResourceReader.retrieveResourceUsingResourceLoader(); + String fileData = classPathResourceReader.listResourceContentsUsingInputStream(resource.getInputStream()); + assertEquals(testData, fileData); + } } From afababb85d993ceea021cce07c9d80d1ef422542 Mon Sep 17 00:00:00 2001 From: tritty Date: Mon, 28 May 2018 01:15:13 +0530 Subject: [PATCH 04/69] Removed files related to evaluation article --- .../controller/StockBrokerController.java | 26 ------------ .../com/baeldung/reactive/model/Stock.java | 18 -------- .../reactive/webclient/StockClient.java | 42 ------------------- 3 files changed, 86 deletions(-) delete mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/controller/StockBrokerController.java delete mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/model/Stock.java delete mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/webclient/StockClient.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/StockBrokerController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/StockBrokerController.java deleted file mode 100644 index f904943a02..0000000000 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/StockBrokerController.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.reactive.controller; - -import java.time.Duration; -import java.util.Date; -import java.util.Random; -import java.util.stream.Stream; - -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.baeldung.reactive.model.Stock; - -import reactor.core.publisher.Flux; - -@RestController -public class StockBrokerController { - - @GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE, value = "/getStockPrice") - public Flux getStockUpdates() { - final Flux stockFlux = Flux.fromStream(Stream.generate(() -> new Stock(new Random().nextFloat(), "WebFluxStock", new Date()))); - final Flux intervalFlux = Flux.interval(Duration.ofSeconds(1)); - return Flux.zip(stockFlux, intervalFlux) - .map(t1 -> t1.getT1()); - } -} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/model/Stock.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/model/Stock.java deleted file mode 100644 index 959c8de685..0000000000 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/model/Stock.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.reactive.model; - -import java.util.Date; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@AllArgsConstructor -@Data -@NoArgsConstructor -public class Stock { - - private float price; - private String name; - private Date date; - -} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webclient/StockClient.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webclient/StockClient.java deleted file mode 100644 index d86660dd90..0000000000 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webclient/StockClient.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.reactive.webclient; - -import java.util.Collections; - -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.context.annotation.Bean; -import org.springframework.http.MediaType; -import org.springframework.web.reactive.function.client.WebClient; - -import com.baeldung.reactive.model.Stock; - -@SpringBootApplication -public class StockClient { - - @Bean - WebClient webClient() { - return WebClient.builder() - .baseUrl("http://localhost:8080/getStockPrice") - .build(); - } - - @Bean - CommandLineRunner runner(WebClient webClient) { - return args -> { - webClient.get() - .accept(MediaType.TEXT_EVENT_STREAM) - .retrieve() - .bodyToFlux(Stock.class) - .log() - .subscribe(System.out::println); - }; - } - - public static void main(String args[]) throws InterruptedException { - new SpringApplicationBuilder(StockClient.class).properties(Collections.singletonMap("server.port", "9090")) - .run(args); - - } - -} From 3f75993c4b45e302026c06f2af65eb6e4655dadb Mon Sep 17 00:00:00 2001 From: tritty Date: Fri, 8 Jun 2018 08:19:19 +0530 Subject: [PATCH 05/69] + Aligning code to the article. Removed Utility methods and classes --- .../java/com/baeldung/resource/AppConfig.java | 10 -- .../resource/ClassPathResourceReader.java | 120 ------------------ .../src/main/resources/data/resource-data.txt | 1 - .../baeldung/resource/SpringResourceTest.java | 83 ++++++++---- .../src/test/resources/data/resource-data.txt | 1 - 5 files changed, 60 insertions(+), 155 deletions(-) delete mode 100644 spring-core/src/main/java/com/baeldung/resource/AppConfig.java delete mode 100644 spring-core/src/main/java/com/baeldung/resource/ClassPathResourceReader.java delete mode 100644 spring-core/src/main/resources/data/resource-data.txt delete mode 100644 spring-core/src/test/resources/data/resource-data.txt diff --git a/spring-core/src/main/java/com/baeldung/resource/AppConfig.java b/spring-core/src/main/java/com/baeldung/resource/AppConfig.java deleted file mode 100644 index 5b266cb5cf..0000000000 --- a/spring-core/src/main/java/com/baeldung/resource/AppConfig.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.resource; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("com.baeldung.resource") -public class AppConfig { - -} diff --git a/spring-core/src/main/java/com/baeldung/resource/ClassPathResourceReader.java b/spring-core/src/main/java/com/baeldung/resource/ClassPathResourceReader.java deleted file mode 100644 index c4618247e9..0000000000 --- a/spring-core/src/main/java/com/baeldung/resource/ClassPathResourceReader.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.baeldung.resource; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.ApplicationContext; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.stereotype.Component; -import org.springframework.util.ResourceUtils; - -@Component -public class ClassPathResourceReader { - - @Autowired - ResourceLoader resourceLoader; - - @Autowired - ApplicationContext applicationContext; - - @Value("classpath:data/resource-data.txt") - Resource resourceFile; - - /** - * Constructs Resource object by making use of its built-in implementations. - * - * @return Resource - */ - public Resource constructResourceManually() { - Resource resource = new ClassPathResource("data/resource-data.txt"); - return resource; - } - - /** - * Constructs resource object by making use of ResourceLoader. - * - * @return Resource - */ - public Resource retrieveResourceUsingResourceLoader() { - Resource resource = resourceLoader.getResource("classpath:data/resource-data.txt"); - return resource; - } - - /** - * Constructs Resource instance by making use of ApplicationContext. - * - * @return Resource - */ - public Resource retrieveResourceUsingApplicationContext() { - Resource resource = applicationContext.getResource("classpath:data/resource-data.txt"); - return resource; - } - - /** - * ResourceUtils example for getting file data. - * - * @return - * @throws FileNotFoundException - */ - public File retrieveFileUsingResourceUtils() throws FileNotFoundException { - return ResourceUtils.getFile("classpath:data/resource-data.txt"); - } - - /** - * Utility method to list contents of a file. - * - * @param fileResource - * @return - * @throws IOException - */ - public String listResourceContentsUsingFile(File fileResource) throws IOException { - FileReader fileReader = new FileReader(fileResource); - BufferedReader bufReader = new BufferedReader(fileReader); - String dataLine = bufReader.readLine(); - StringBuilder fileData = new StringBuilder(); - while (null != dataLine) { - fileData.append(dataLine); - dataLine = bufReader.readLine(); - } - bufReader.close(); - fileReader.close(); - return fileData.toString(); - } - - /** - * Utility method to list contents of a stream - * - * @param ipStream - * @return - * @throws IOException - */ - public String listResourceContentsUsingInputStream(InputStream ipStream) throws IOException { - BufferedReader bufReader = new BufferedReader(new InputStreamReader(ipStream, "UTF-8")); - String dataLine = bufReader.readLine(); - StringBuilder fileData = new StringBuilder(); - while (null != dataLine) { - fileData.append(dataLine); - dataLine = bufReader.readLine(); - } - bufReader.close(); - return fileData.toString(); - } - - public Resource getSampleFile() { - return resourceFile; - } - - public void setSampleFile(Resource sampleFile) { - this.resourceFile = sampleFile; - } -} diff --git a/spring-core/src/main/resources/data/resource-data.txt b/spring-core/src/main/resources/data/resource-data.txt deleted file mode 100644 index cf3720cd66..0000000000 --- a/spring-core/src/main/resources/data/resource-data.txt +++ /dev/null @@ -1 +0,0 @@ -This is a sample text to demonstrate usage of Spring Resource. \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java index ba1e2c6d37..cd2b9ee7c1 100644 --- a/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java @@ -2,63 +2,100 @@ package com.baeldung.resource; import static org.junit.Assert.assertEquals; +import java.io.BufferedReader; +import java.io.File; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.util.stream.Collectors; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.util.ResourceUtils; + +/** + * Test class illustrating various methods of accessing a file from the classpath using Resource. + * @author tritty + * + */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = AppConfig.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class) public class SpringResourceTest { + /** + * Resource loader instance for lazily loading resources. + */ + @Autowired + private ResourceLoader resourceLoader; @Autowired - private ClassPathResourceReader classPathResourceReader; + private ApplicationContext appContext; - static final String testData = "This is a sample text to demonstrate usage of Spring Resource."; + /** + * Injecting resource + */ + @Value("classpath:data/employees.dat") + private Resource resourceFile; - @Test - public void whenManualInstance_thenReadSuccessful() throws IOException { - Resource resource = classPathResourceReader.constructResourceManually(); - String fileData = classPathResourceReader.listResourceContentsUsingFile(resource.getFile()); - assertEquals(testData, fileData); - } + /** + * Data in data/employee.dat + */ + private static final String EMPLOYEES_EXPECTED = "Joe Employee,Jan Employee,James T. Employee"; @Test public void whenResourceLoader_thenReadSuccessful() throws IOException { - Resource resource = classPathResourceReader.retrieveResourceUsingResourceLoader(); - String fileData = classPathResourceReader.listResourceContentsUsingFile(resource.getFile()); - assertEquals(testData, fileData); + final Resource resource = resourceLoader.getResource("classpath:data/employees.dat"); + final String employees = new String(Files.readAllBytes(resource.getFile() + .toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); } @Test public void whenApplicationContext_thenReadSuccessful() throws IOException { - Resource resource = classPathResourceReader.retrieveResourceUsingApplicationContext(); - String fileData = classPathResourceReader.listResourceContentsUsingFile(resource.getFile()); - assertEquals(testData, fileData); + final Resource resource = appContext.getResource("classpath:data/employees.dat"); + final String employees = new String(Files.readAllBytes(resource.getFile() + .toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); } @Test public void whenAutowired_thenReadSuccessful() throws IOException { - Resource resource = classPathResourceReader.getSampleFile(); - String fileData = classPathResourceReader.listResourceContentsUsingFile(resource.getFile()); - assertEquals(testData, fileData); + final String employees = new String(Files.readAllBytes(resourceFile.getFile() + .toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); } @Test public void whenResourceUtils_thenReadSuccessful() throws IOException { - String fileData = classPathResourceReader.listResourceContentsUsingFile(classPathResourceReader.retrieveFileUsingResourceUtils()); - assertEquals(testData, fileData); + final String employees = new String(Files.readAllBytes(ResourceUtils.getFile("classpath:data/employees.dat") + .toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); } @Test public void whenResourceAsStream_thenReadSuccessful() throws IOException { - Resource resource = classPathResourceReader.retrieveResourceUsingResourceLoader(); - String fileData = classPathResourceReader.listResourceContentsUsingInputStream(resource.getInputStream()); - assertEquals(testData, fileData); + final InputStream resource = new ClassPathResource("data/employees.dat").getInputStream(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource))) { + final String employees = reader.lines() + .collect(Collectors.joining("\n")); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + } + + @Test + public void whenResourceAsFile_thenReadSuccessful() throws IOException { + final File resource = new ClassPathResource("data/employees.dat").getFile(); + final String employees = new String(Files.readAllBytes(resource.toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); } } diff --git a/spring-core/src/test/resources/data/resource-data.txt b/spring-core/src/test/resources/data/resource-data.txt deleted file mode 100644 index cf3720cd66..0000000000 --- a/spring-core/src/test/resources/data/resource-data.txt +++ /dev/null @@ -1 +0,0 @@ -This is a sample text to demonstrate usage of Spring Resource. \ No newline at end of file From 00e495c2d5f64a7c768ecbff038c47a797a6c47a Mon Sep 17 00:00:00 2001 From: Tritty Date: Sat, 25 Aug 2018 20:10:17 +0530 Subject: [PATCH 06/69] Precommit fix --- .../SpringResourceIntegrationTest.java | 6 +- .../baeldung/resource/SpringResourceTest.java | 101 ------------------ 2 files changed, 3 insertions(+), 104 deletions(-) delete mode 100644 spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java index 38e8304f0f..cd2b9ee7c1 100644 --- a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java @@ -31,7 +31,7 @@ import org.springframework.util.ResourceUtils; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class) -public class SpringResourceIntegrationTest { +public class SpringResourceTest { /** * Resource loader instance for lazily loading resources. */ @@ -77,8 +77,8 @@ public class SpringResourceIntegrationTest { @Test public void whenResourceUtils_thenReadSuccessful() throws IOException { - final File employeeFile = ResourceUtils.getFile("classpath:data/employees.dat"); - final String employees = new String(Files.readAllBytes(employeeFile.toPath())); + final String employees = new String(Files.readAllBytes(ResourceUtils.getFile("classpath:data/employees.dat") + .toPath())); assertEquals(EMPLOYEES_EXPECTED, employees); } diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java deleted file mode 100644 index cd2b9ee7c1..0000000000 --- a/spring-core/src/test/java/com/baeldung/resource/SpringResourceTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.baeldung.resource; - -import static org.junit.Assert.assertEquals; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.file.Files; -import java.util.stream.Collectors; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.ApplicationContext; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; -import org.springframework.util.ResourceUtils; - -/** - * Test class illustrating various methods of accessing a file from the classpath using Resource. - * @author tritty - * - */ - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(loader = AnnotationConfigContextLoader.class) -public class SpringResourceTest { - /** - * Resource loader instance for lazily loading resources. - */ - @Autowired - private ResourceLoader resourceLoader; - - @Autowired - private ApplicationContext appContext; - - /** - * Injecting resource - */ - @Value("classpath:data/employees.dat") - private Resource resourceFile; - - /** - * Data in data/employee.dat - */ - private static final String EMPLOYEES_EXPECTED = "Joe Employee,Jan Employee,James T. Employee"; - - @Test - public void whenResourceLoader_thenReadSuccessful() throws IOException { - final Resource resource = resourceLoader.getResource("classpath:data/employees.dat"); - final String employees = new String(Files.readAllBytes(resource.getFile() - .toPath())); - assertEquals(EMPLOYEES_EXPECTED, employees); - } - - @Test - public void whenApplicationContext_thenReadSuccessful() throws IOException { - final Resource resource = appContext.getResource("classpath:data/employees.dat"); - final String employees = new String(Files.readAllBytes(resource.getFile() - .toPath())); - assertEquals(EMPLOYEES_EXPECTED, employees); - } - - @Test - public void whenAutowired_thenReadSuccessful() throws IOException { - final String employees = new String(Files.readAllBytes(resourceFile.getFile() - .toPath())); - assertEquals(EMPLOYEES_EXPECTED, employees); - } - - @Test - public void whenResourceUtils_thenReadSuccessful() throws IOException { - final String employees = new String(Files.readAllBytes(ResourceUtils.getFile("classpath:data/employees.dat") - .toPath())); - assertEquals(EMPLOYEES_EXPECTED, employees); - } - - @Test - public void whenResourceAsStream_thenReadSuccessful() throws IOException { - final InputStream resource = new ClassPathResource("data/employees.dat").getInputStream(); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource))) { - final String employees = reader.lines() - .collect(Collectors.joining("\n")); - assertEquals(EMPLOYEES_EXPECTED, employees); - } - } - - @Test - public void whenResourceAsFile_thenReadSuccessful() throws IOException { - final File resource = new ClassPathResource("data/employees.dat").getFile(); - final String employees = new String(Files.readAllBytes(resource.toPath())); - assertEquals(EMPLOYEES_EXPECTED, employees); - } -} From cca20da9e3814955d7a11968b411dd1a6d1181c7 Mon Sep 17 00:00:00 2001 From: Tritty Date: Fri, 8 Jun 2018 10:00:52 +0530 Subject: [PATCH 07/69] PMD fixes --- .../com/baeldung/resource/SpringResourceIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java index cd2b9ee7c1..85cabb55df 100644 --- a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java @@ -31,7 +31,7 @@ import org.springframework.util.ResourceUtils; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class) -public class SpringResourceTest { +public class SpringResourceIntegrationTest { /** * Resource loader instance for lazily loading resources. */ From 52092ffd70a02d5deaf07cb8ca6e705a8758a2f0 Mon Sep 17 00:00:00 2001 From: Tritty Date: Fri, 15 Jun 2018 19:06:40 +0530 Subject: [PATCH 08/69] Code Review changes Refactored : whenResourceUtils_thenReadSuccessful --- .../com/baeldung/resource/SpringResourceIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java index 85cabb55df..38e8304f0f 100644 --- a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java @@ -77,8 +77,8 @@ public class SpringResourceIntegrationTest { @Test public void whenResourceUtils_thenReadSuccessful() throws IOException { - final String employees = new String(Files.readAllBytes(ResourceUtils.getFile("classpath:data/employees.dat") - .toPath())); + final File employeeFile = ResourceUtils.getFile("classpath:data/employees.dat"); + final String employees = new String(Files.readAllBytes(employeeFile.toPath())); assertEquals(EMPLOYEES_EXPECTED, employees); } From 7f9a2ceace7dfccb3e62258d11f8233edd8ea793 Mon Sep 17 00:00:00 2001 From: Tritty Date: Fri, 20 Jul 2018 15:52:18 +0530 Subject: [PATCH 09/69] BAEL-1934 --- .../mimetype/MimeTypeIntegrationTest.java | 131 ++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/java/mimetype/MimeTypeIntegrationTest.java diff --git a/core-java/src/test/java/com/baeldung/java/mimetype/MimeTypeIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/mimetype/MimeTypeIntegrationTest.java new file mode 100644 index 0000000000..885579029a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/mimetype/MimeTypeIntegrationTest.java @@ -0,0 +1,131 @@ +package com.baeldung.java.mimetype; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.net.FileNameMap; +import java.net.MalformedURLException; +import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.Path; + +import javax.activation.MimetypesFileTypeMap; + +import org.apache.tika.Tika; +import org.junit.Test; + +import net.sf.jmimemagic.Magic; +import net.sf.jmimemagic.MagicException; +import net.sf.jmimemagic.MagicMatch; +import net.sf.jmimemagic.MagicMatchNotFoundException; +import net.sf.jmimemagic.MagicParseException; + +/** + * Test class demonstrating various strategies to resolve MIME type of a file. + * @author tritty + * + */ +public class MimeTypeIntegrationTest { + /** + * Expected Ouput. + */ + public static final String PNG_EXT = "image/png"; + + /** + * The location of the file. + */ + public static final String FILE_LOC = "src/test/resources/product.png"; + + /** + * Test method, demonstrating usage in Java 7. + * + * @throws IOException + */ + @Test + public void whenUsingJava7_thenSuccess() throws IOException { + final Path path = new File(FILE_LOC).toPath(); + final String mimeType = Files.probeContentType(path); + assertEquals(mimeType, PNG_EXT); + } + + /** + * Test method demonstrating the usage of URLConnection to resolve MIME type. + * + * @throws MalformedURLException + * @throws IOException + */ + @Test + public void whenUsingGetContentType_thenSuccess() throws MalformedURLException, IOException { + final File file = new File(FILE_LOC); + final URLConnection connection = file.toURL() + .openConnection(); + final String mimeType = connection.getContentType(); + assertEquals(mimeType, PNG_EXT); + } + + /** + * Test method demonstrating the usage of URLConnection to resolve MIME type. + * + */ + @Test + public void whenUsingGuessContentTypeFromName_thenSuccess() { + final File file = new File(FILE_LOC); + final String mimeType = URLConnection.guessContentTypeFromName(file.getName()); + assertEquals(mimeType, PNG_EXT); + } + + /** + * Test method demonstrating the usage of FileNameMap from URLConnection + * to resolve MIME type of a file. + * + */ + @Test + public void whenUsingGetFileNameMap_thenSuccess() { + final File file = new File(FILE_LOC); + final FileNameMap fileNameMap = URLConnection.getFileNameMap(); + final String mimeType = fileNameMap.getContentTypeFor(file.getName()); + assertEquals(mimeType, PNG_EXT); + } + + /** + * Test method demonstrating the usage of MimeTypesFileTypeMap for resolution of + * MIME type. + * + */ + @Test + public void whenUsingMimeTypesFileTypeMap_thenSuccess() { + final File file = new File(FILE_LOC); + final MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap(); + final String mimeType = fileTypeMap.getContentType(file.getName()); + assertEquals(mimeType, PNG_EXT); + } + + /** + * Test method demonstrating usage of jMimeMagic. + * + * @throws MagicParseException + * @throws MagicMatchNotFoundException + * @throws MagicException + */ + @Test + public void whenUsingJmimeMagic_thenSuccess() throws MagicParseException, MagicMatchNotFoundException, MagicException { + final File file = new File(FILE_LOC); + final Magic magic = new Magic(); + final MagicMatch match = magic.getMagicMatch(file, false); + assertEquals(match.getMimeType(), PNG_EXT); + } + + /** + * Test method demonstrating usage of Apache Tika. + * + * @throws IOException + */ + @Test + public void whenUsingTika_thenSuccess() throws IOException { + final File file = new File(FILE_LOC); + final Tika tika = new Tika(); + final String mimeType = tika.detect(file); + assertEquals(mimeType, PNG_EXT); + } +} From 37101781ae2847818c1efa4a79b9dca8b4735add Mon Sep 17 00:00:00 2001 From: Tritty Date: Sat, 21 Jul 2018 09:06:19 +0530 Subject: [PATCH 10/69] +indentation correction in pom.xml --- .../mimetype/MimeTypeIntegrationTest.java | 131 ------------------ 1 file changed, 131 deletions(-) delete mode 100644 core-java/src/test/java/com/baeldung/java/mimetype/MimeTypeIntegrationTest.java diff --git a/core-java/src/test/java/com/baeldung/java/mimetype/MimeTypeIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/mimetype/MimeTypeIntegrationTest.java deleted file mode 100644 index 885579029a..0000000000 --- a/core-java/src/test/java/com/baeldung/java/mimetype/MimeTypeIntegrationTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.baeldung.java.mimetype; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.net.FileNameMap; -import java.net.MalformedURLException; -import java.net.URLConnection; -import java.nio.file.Files; -import java.nio.file.Path; - -import javax.activation.MimetypesFileTypeMap; - -import org.apache.tika.Tika; -import org.junit.Test; - -import net.sf.jmimemagic.Magic; -import net.sf.jmimemagic.MagicException; -import net.sf.jmimemagic.MagicMatch; -import net.sf.jmimemagic.MagicMatchNotFoundException; -import net.sf.jmimemagic.MagicParseException; - -/** - * Test class demonstrating various strategies to resolve MIME type of a file. - * @author tritty - * - */ -public class MimeTypeIntegrationTest { - /** - * Expected Ouput. - */ - public static final String PNG_EXT = "image/png"; - - /** - * The location of the file. - */ - public static final String FILE_LOC = "src/test/resources/product.png"; - - /** - * Test method, demonstrating usage in Java 7. - * - * @throws IOException - */ - @Test - public void whenUsingJava7_thenSuccess() throws IOException { - final Path path = new File(FILE_LOC).toPath(); - final String mimeType = Files.probeContentType(path); - assertEquals(mimeType, PNG_EXT); - } - - /** - * Test method demonstrating the usage of URLConnection to resolve MIME type. - * - * @throws MalformedURLException - * @throws IOException - */ - @Test - public void whenUsingGetContentType_thenSuccess() throws MalformedURLException, IOException { - final File file = new File(FILE_LOC); - final URLConnection connection = file.toURL() - .openConnection(); - final String mimeType = connection.getContentType(); - assertEquals(mimeType, PNG_EXT); - } - - /** - * Test method demonstrating the usage of URLConnection to resolve MIME type. - * - */ - @Test - public void whenUsingGuessContentTypeFromName_thenSuccess() { - final File file = new File(FILE_LOC); - final String mimeType = URLConnection.guessContentTypeFromName(file.getName()); - assertEquals(mimeType, PNG_EXT); - } - - /** - * Test method demonstrating the usage of FileNameMap from URLConnection - * to resolve MIME type of a file. - * - */ - @Test - public void whenUsingGetFileNameMap_thenSuccess() { - final File file = new File(FILE_LOC); - final FileNameMap fileNameMap = URLConnection.getFileNameMap(); - final String mimeType = fileNameMap.getContentTypeFor(file.getName()); - assertEquals(mimeType, PNG_EXT); - } - - /** - * Test method demonstrating the usage of MimeTypesFileTypeMap for resolution of - * MIME type. - * - */ - @Test - public void whenUsingMimeTypesFileTypeMap_thenSuccess() { - final File file = new File(FILE_LOC); - final MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap(); - final String mimeType = fileTypeMap.getContentType(file.getName()); - assertEquals(mimeType, PNG_EXT); - } - - /** - * Test method demonstrating usage of jMimeMagic. - * - * @throws MagicParseException - * @throws MagicMatchNotFoundException - * @throws MagicException - */ - @Test - public void whenUsingJmimeMagic_thenSuccess() throws MagicParseException, MagicMatchNotFoundException, MagicException { - final File file = new File(FILE_LOC); - final Magic magic = new Magic(); - final MagicMatch match = magic.getMagicMatch(file, false); - assertEquals(match.getMimeType(), PNG_EXT); - } - - /** - * Test method demonstrating usage of Apache Tika. - * - * @throws IOException - */ - @Test - public void whenUsingTika_thenSuccess() throws IOException { - final File file = new File(FILE_LOC); - final Tika tika = new Tika(); - final String mimeType = tika.detect(file); - assertEquals(mimeType, PNG_EXT); - } -} From 4b4ac40345deea8a5b27d7b800f2f5d444bf4529 Mon Sep 17 00:00:00 2001 From: Tritty Date: Sat, 21 Jul 2018 10:00:45 +0530 Subject: [PATCH 11/69] synced with master --- .../connectionpools/BasicConnectionPool.java | 87 +++++++++++++ .../connectionpools/C3poDataSource.java | 28 +++++ .../connectionpools/ConnectionPool.java | 18 +++ .../connectionpools/DBCPDataSource.java | 25 ++++ .../connectionpools/HikariCPDataSource.java | 28 +++++ .../java/com/baeldung/manifest/MANIFEST.MF | 1 + .../BasicConnectionPoolUnitTest.java | 69 +++++++++++ .../C3poDataSourceUnitTest.java | 14 +++ .../DBCPDataSourceUnitTest.java | 14 +++ .../HikariCPDataSourceUnitTest.java | 14 +++ .../main/java/com/baeldung/jmapper/User.java | 56 +++++++++ .../java/com/baeldung/jmapper/UserDto.java | 69 +++++++++++ .../java/com/baeldung/jmapper/UserDto1.java | 47 ++++++++ .../com/baeldung/jmapper/relational/User.java | 49 ++++++++ .../baeldung/jmapper/relational/UserDto1.java | 44 +++++++ .../baeldung/jmapper/relational/UserDto2.java | 44 +++++++ libraries/src/main/resources/user_jmapper.xml | 10 ++ .../src/main/resources/user_jmapper1.xml | 5 + .../src/main/resources/user_jmapper2.xml | 21 ++++ .../jmapper/JMapperIntegrationTest.java | 114 ++++++++++++++++++ .../JMapperRelationalIntegrationTest.java | 76 ++++++++++++ .../baeldung/reactive/controller/.gitignore | 1 + .../java/com/baeldung/domain/Article.java | 23 ++++ .../repository/ArticleRepository.java | 22 ++++ .../ArticleRepositoryIntegrationTest.java | 66 ++++++++++ .../src/test/resources/application.properties | 2 +- .../src/test/resources/import_articles.sql | 3 + 27 files changed, 949 insertions(+), 1 deletion(-) create mode 100644 core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java create mode 100644 core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java create mode 100644 core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java create mode 100644 core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java create mode 100644 core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java create mode 100644 core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF create mode 100644 core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java create mode 100644 libraries/src/main/java/com/baeldung/jmapper/User.java create mode 100644 libraries/src/main/java/com/baeldung/jmapper/UserDto.java create mode 100644 libraries/src/main/java/com/baeldung/jmapper/UserDto1.java create mode 100644 libraries/src/main/java/com/baeldung/jmapper/relational/User.java create mode 100644 libraries/src/main/java/com/baeldung/jmapper/relational/UserDto1.java create mode 100644 libraries/src/main/java/com/baeldung/jmapper/relational/UserDto2.java create mode 100644 libraries/src/main/resources/user_jmapper.xml create mode 100644 libraries/src/main/resources/user_jmapper1.xml create mode 100644 libraries/src/main/resources/user_jmapper2.xml create mode 100644 libraries/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java create mode 100644 libraries/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/controller/.gitignore create mode 100644 spring-boot-persistence/src/main/java/com/baeldung/domain/Article.java create mode 100644 spring-boot-persistence/src/main/java/com/baeldung/repository/ArticleRepository.java create mode 100644 spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java create mode 100644 spring-boot-persistence/src/test/resources/import_articles.sql diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java new file mode 100644 index 0000000000..243ec88eb5 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java @@ -0,0 +1,87 @@ +package com.baeldung.connectionpool.connectionpools; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class BasicConnectionPool implements ConnectionPool { + + private final String url; + private final String user; + private final String password; + private final List connectionPool; + private final List usedConnections = new ArrayList<>(); + private static final int INITIAL_POOL_SIZE = 10; + private final int MAX_POOL_SIZE = 20; + + public static BasicConnectionPool create(String url, String user, String password) throws SQLException { + List pool = new ArrayList<>(INITIAL_POOL_SIZE); + for (int i = 0; i < INITIAL_POOL_SIZE; i++) { + pool.add(createConnection(url, user, password)); + } + return new BasicConnectionPool(url, user, password, pool); + } + + private BasicConnectionPool(String url, String user, String password, List connectionPool) { + this.url = url; + this.user = user; + this.password = password; + this.connectionPool = connectionPool; + } + + @Override + public Connection getConnection() throws SQLException { + if (connectionPool.size() == 0) { + if (usedConnections.size() < MAX_POOL_SIZE) { + connectionPool.add(createConnection(url, user, password)); + } else { + throw new RuntimeException("Maximum pool size reached, no available connections!"); + } + } + + Connection connection = connectionPool.remove(connectionPool.size() - 1); + usedConnections.add(connection); + return connection; + } + + @Override + public boolean releaseConnection(Connection connection) { + connectionPool.add(connection); + return usedConnections.remove(connection); + } + + private static Connection createConnection(String url, String user, String password) throws SQLException { + return DriverManager.getConnection(url, user, password); + } + + public int getSize() { + return connectionPool.size() + usedConnections.size(); + } + + @Override + public String getUrl() { + return url; + } + + @Override + public String getUser() { + return user; + } + + @Override + public String getPassword() { + return password; + } + + public void shutdown() throws SQLException { + for (Connection c : usedConnections) { + this.releaseConnection(c); + } + for (Connection c : connectionPool) { + c.close(); + } + connectionPool.clear(); + } +} diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java new file mode 100644 index 0000000000..5b91f707a9 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java @@ -0,0 +1,28 @@ +package com.baeldung.connectionpool.connectionpools; + +import com.mchange.v2.c3p0.ComboPooledDataSource; +import java.beans.PropertyVetoException; +import java.sql.Connection; +import java.sql.SQLException; + +public class C3poDataSource { + + private static final ComboPooledDataSource cpds = new ComboPooledDataSource(); + + static { + try { + cpds.setDriverClass("org.h2.Driver"); + cpds.setJdbcUrl("jdbc:h2:mem:test"); + cpds.setUser("user"); + cpds.setPassword("password"); + } catch (PropertyVetoException e) { + e.printStackTrace(); + } + } + + public static Connection getConnection() throws SQLException { + return cpds.getConnection(); + } + + private C3poDataSource(){} +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java new file mode 100644 index 0000000000..3d5ad06c3d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java @@ -0,0 +1,18 @@ +package com.baeldung.connectionpool.connectionpools; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; + +public interface ConnectionPool { + + Connection getConnection() throws SQLException; + + boolean releaseConnection(Connection connection); + + String getUrl(); + + String getUser(); + + String getPassword(); +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java new file mode 100644 index 0000000000..2f33cde883 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java @@ -0,0 +1,25 @@ +package com.baeldung.connectionpool.connectionpools; + +import java.sql.Connection; +import java.sql.SQLException; +import org.apache.commons.dbcp2.BasicDataSource; + +public class DBCPDataSource { + + private static final BasicDataSource ds = new BasicDataSource(); + + static { + ds.setUrl("jdbc:h2:mem:test"); + ds.setUsername("user"); + ds.setPassword("password"); + ds.setMinIdle(5); + ds.setMaxIdle(10); + ds.setMaxOpenPreparedStatements(100); + } + + public static Connection getConnection() throws SQLException { + return ds.getConnection(); + } + + private DBCPDataSource(){} +} diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java new file mode 100644 index 0000000000..5ed2de181d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java @@ -0,0 +1,28 @@ +package com.baeldung.connectionpool.connectionpools; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class HikariCPDataSource { + + private static final HikariConfig config = new HikariConfig(); + private static final HikariDataSource ds; + + static { + config.setJdbcUrl("jdbc:h2:mem:test"); + config.setUsername("user"); + config.setPassword("password"); + config.addDataSourceProperty("cachePrepStmts", "true"); + config.addDataSourceProperty("prepStmtCacheSize", "250"); + config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); + ds = new HikariDataSource(config); + } + + public static Connection getConnection() throws SQLException { + return ds.getConnection(); + } + + private HikariCPDataSource(){} +} diff --git a/core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF b/core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF new file mode 100644 index 0000000000..a363171952 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF @@ -0,0 +1 @@ +Main-Class: com.baeldung.manifest.AppExample diff --git a/core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java b/core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java new file mode 100644 index 0000000000..5edc6bba94 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.connectionpool; + +import com.baeldung.connectionpool.connectionpools.BasicConnectionPool; +import com.baeldung.connectionpool.connectionpools.ConnectionPool; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class BasicConnectionPoolUnitTest { + + private static ConnectionPool connectionPool; + + @BeforeClass + public static void setUpBasicConnectionPoolInstance() throws SQLException { + connectionPool = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password"); + } + + @Test + public void givenBasicConnectionPoolInstance_whenCalledgetConnection_thenCorrect() throws Exception { + assertTrue(connectionPool.getConnection().isValid(1)); + } + + @Test + public void givenBasicConnectionPoolInstance_whenCalledreleaseConnection_thenCorrect() throws Exception { + Connection connection = connectionPool.getConnection(); + assertThat(connectionPool.releaseConnection(connection)).isTrue(); + } + + @Test + public void givenBasicConnectionPoolInstance_whenCalledgetUrl_thenCorrect() { + assertThat(connectionPool.getUrl()).isEqualTo("jdbc:h2:mem:test"); + } + + @Test + public void givenBasicConnectionPoolInstance_whenCalledgetUser_thenCorrect() { + assertThat(connectionPool.getUser()).isEqualTo("user"); + } + + @Test + public void givenBasicConnectionPoolInstance_whenCalledgetPassword_thenCorrect() { + assertThat(connectionPool.getPassword()).isEqualTo("password"); + } + + @Test(expected = RuntimeException.class) + public void givenBasicConnectionPoolInstance_whenAskedForMoreThanMax_thenError() throws Exception { + // this test needs to be independent so it doesn't share the same connection pool as other tests + ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password"); + final int MAX_POOL_SIZE = 20; + for (int i = 0; i < MAX_POOL_SIZE + 1; i++) { + cp.getConnection(); + } + fail(); + } + + @Test + public void givenBasicConnectionPoolInstance_whenSutdown_thenEmpty() throws Exception { + ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password"); + assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(10); + + ((BasicConnectionPool) cp).shutdown(); + assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(0); + } +} diff --git a/core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java b/core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java new file mode 100644 index 0000000000..a02daa40f6 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java @@ -0,0 +1,14 @@ +package com.baeldung.connectionpool; + +import com.baeldung.connectionpool.connectionpools.C3poDataSource; +import java.sql.SQLException; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class C3poDataSourceUnitTest { + + @Test + public void givenC3poDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException { + assertTrue(C3poDataSource.getConnection().isValid(1)); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java b/core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java new file mode 100644 index 0000000000..9583eedf4b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java @@ -0,0 +1,14 @@ +package com.baeldung.connectionpool; + +import com.baeldung.connectionpool.connectionpools.DBCPDataSource; +import java.sql.SQLException; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class DBCPDataSourceUnitTest { + + @Test + public void givenDBCPDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException { + assertTrue(DBCPDataSource.getConnection().isValid(1)); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java b/core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java new file mode 100644 index 0000000000..6b78815797 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java @@ -0,0 +1,14 @@ +package com.baeldung.connectionpool; + +import com.baeldung.connectionpool.connectionpools.HikariCPDataSource; +import java.sql.SQLException; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class HikariCPDataSourceUnitTest { + + @Test + public void givenHikariDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException { + assertTrue(HikariCPDataSource.getConnection().isValid(1)); + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jmapper/User.java b/libraries/src/main/java/com/baeldung/jmapper/User.java new file mode 100644 index 0000000000..9f99157183 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jmapper/User.java @@ -0,0 +1,56 @@ +package com.baeldung.jmapper; + +import java.time.LocalDate; + + +public class User { + + private long id; + private String email; + private LocalDate birthDate; + + // constructors + + public User() { + super(); + } + + public User(long id, String email, LocalDate birthDate) { + super(); + this.id = id; + this.email = email; + this.birthDate = birthDate; + } + + // getters and setters + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public LocalDate getBirthDate() { + return birthDate; + } + + public void setBirthDate(LocalDate birthDate) { + this.birthDate = birthDate; + } + + @Override + public String toString() { + return "User [id=" + id + ", email=" + email + ", birthDate=" + birthDate + "]"; + } + +} diff --git a/libraries/src/main/java/com/baeldung/jmapper/UserDto.java b/libraries/src/main/java/com/baeldung/jmapper/UserDto.java new file mode 100644 index 0000000000..326e8f3cd5 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jmapper/UserDto.java @@ -0,0 +1,69 @@ +package com.baeldung.jmapper; + +import java.time.LocalDate; +import java.time.Period; + +import com.googlecode.jmapper.annotations.JMap; +import com.googlecode.jmapper.annotations.JMapConversion; + +public class UserDto { + + @JMap + private long id; + + @JMap("email") + private String username; + + @JMap("birthDate") + private int age; + + @JMapConversion(from={"birthDate"}, to={"age"}) + public int conversion(LocalDate birthDate){ + return Period.between(birthDate, LocalDate.now()).getYears(); + } + + // constructors + + public UserDto() { + super(); + } + + public UserDto(long id, String username, int age) { + super(); + this.id = id; + this.username = username; + this.age = age; + } + + // getters and setters + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return "UserDto [id=" + id + ", username=" + username + ", age=" + age + "]"; + } + +} diff --git a/libraries/src/main/java/com/baeldung/jmapper/UserDto1.java b/libraries/src/main/java/com/baeldung/jmapper/UserDto1.java new file mode 100644 index 0000000000..99247c56f6 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jmapper/UserDto1.java @@ -0,0 +1,47 @@ +package com.baeldung.jmapper; + +import com.googlecode.jmapper.annotations.JGlobalMap; + +@JGlobalMap +public class UserDto1 { + + private long id; + private String email; + + + // constructors + + public UserDto1() { + super(); + } + + public UserDto1(long id, String email) { + super(); + this.id = id; + this.email = email; + } + + // getters and setters + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "UserDto [id=" + id + ", email=" + email + "]"; + } + +} diff --git a/libraries/src/main/java/com/baeldung/jmapper/relational/User.java b/libraries/src/main/java/com/baeldung/jmapper/relational/User.java new file mode 100644 index 0000000000..1238a82684 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jmapper/relational/User.java @@ -0,0 +1,49 @@ +package com.baeldung.jmapper.relational; + +import com.googlecode.jmapper.annotations.JMap; + + +public class User { + + @JMap(classes = {UserDto1.class, UserDto2.class}) + private long id; + + @JMap(attributes = {"username", "email"}, classes = {UserDto1.class, UserDto2.class}) + private String email; + + // constructors + + public User() { + super(); + } + + public User(long id, String email) { + super(); + this.id = id; + this.email = email; + } + + // getters and setters + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "User [id=" + id + ", email=" + email + "]"; + } + +} diff --git a/libraries/src/main/java/com/baeldung/jmapper/relational/UserDto1.java b/libraries/src/main/java/com/baeldung/jmapper/relational/UserDto1.java new file mode 100644 index 0000000000..375fd267a0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jmapper/relational/UserDto1.java @@ -0,0 +1,44 @@ +package com.baeldung.jmapper.relational; + + +public class UserDto1 { + + private long id; + private String username; + + // constructors + + public UserDto1() { + super(); + } + + public UserDto1(long id, String username) { + super(); + this.id = id; + this.username = username; + } + + // getters and setters + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @Override + public String toString() { + return "UserDto [id=" + id + ", username=" + username + "]"; + } + +} diff --git a/libraries/src/main/java/com/baeldung/jmapper/relational/UserDto2.java b/libraries/src/main/java/com/baeldung/jmapper/relational/UserDto2.java new file mode 100644 index 0000000000..d0858c7d8e --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jmapper/relational/UserDto2.java @@ -0,0 +1,44 @@ +package com.baeldung.jmapper.relational; + + +public class UserDto2 { + + private long id; + private String email; + + // constructors + + public UserDto2() { + super(); + } + + public UserDto2(long id, String email) { + super(); + this.id = id; + this.email = email; + } + + // getters and setters + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "UserDto2 [id=" + id + ", email=" + email + "]"; + } + +} diff --git a/libraries/src/main/resources/user_jmapper.xml b/libraries/src/main/resources/user_jmapper.xml new file mode 100644 index 0000000000..f007de9f0a --- /dev/null +++ b/libraries/src/main/resources/user_jmapper.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/libraries/src/main/resources/user_jmapper1.xml b/libraries/src/main/resources/user_jmapper1.xml new file mode 100644 index 0000000000..abcfd77e1c --- /dev/null +++ b/libraries/src/main/resources/user_jmapper1.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/libraries/src/main/resources/user_jmapper2.xml b/libraries/src/main/resources/user_jmapper2.xml new file mode 100644 index 0000000000..1e708e14bf --- /dev/null +++ b/libraries/src/main/resources/user_jmapper2.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java b/libraries/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java new file mode 100644 index 0000000000..96ed090482 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java @@ -0,0 +1,114 @@ +package com.baeldung.jmapper; + +import static com.googlecode.jmapper.api.JMapperAPI.attribute; +import static com.googlecode.jmapper.api.JMapperAPI.global; +import static com.googlecode.jmapper.api.JMapperAPI.mappedClass; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.time.LocalDate; + +import org.junit.Test; + +import com.googlecode.jmapper.JMapper; +import com.googlecode.jmapper.api.JMapperAPI; + +public class JMapperIntegrationTest { + + + @Test + public void givenUser_whenUseAnnotation_thenConverted(){ + JMapper userMapper = new JMapper<>(UserDto.class, User.class); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto result = userMapper.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getUsername()); + } + + @Test + public void givenUser_whenUseGlobalMapAnnotation_thenConverted(){ + JMapper userMapper= new JMapper<>(UserDto1.class, User.class); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto1 result = userMapper.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getEmail()); + } + + @Test + public void givenUser_whenUseAnnotationExplicitConversion_thenConverted(){ + JMapper userMapper = new JMapper<>(UserDto.class, User.class); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto result = userMapper.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getUsername()); + assertTrue(result.getAge() > 0); + } + + //======================= XML + + @Test + public void givenUser_whenUseXml_thenConverted(){ + JMapper userMapper = new JMapper<>(UserDto.class, User.class,"user_jmapper.xml"); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto result = userMapper.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getUsername()); + } + + @Test + public void givenUser_whenUseXmlGlobal_thenConverted(){ + JMapper userMapper = new JMapper<>(UserDto1.class, User.class,"user_jmapper1.xml"); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto1 result = userMapper.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getEmail()); + } + + // ===== API + + @Test + public void givenUser_whenUseApi_thenConverted(){ + JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class) + .add(attribute("id").value("id")) + .add(attribute("username").value("email")) + ) ; + JMapper userMapper = new JMapper<>(UserDto.class, User.class, jmapperApi); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto result = userMapper.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getUsername()); + } + + @Test + public void givenUser_whenUseApiGlobal_thenConverted(){ + JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class) + .add(global()) + ) ; + JMapper userMapper1 = new JMapper<>(UserDto1.class, User.class,jmapperApi); + + User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + UserDto1 result = userMapper1.getDestination(user); + + System.out.println(result); + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getEmail()); + } +} diff --git a/libraries/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java b/libraries/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java new file mode 100644 index 0000000000..6af2865159 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java @@ -0,0 +1,76 @@ +package com.baeldung.jmapper; + +import static com.googlecode.jmapper.api.JMapperAPI.attribute; +import static com.googlecode.jmapper.api.JMapperAPI.mappedClass; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.jmapper.relational.User; +import com.baeldung.jmapper.relational.UserDto1; +import com.baeldung.jmapper.relational.UserDto2; +import com.googlecode.jmapper.RelationalJMapper; +import com.googlecode.jmapper.api.JMapperAPI; + +public class JMapperRelationalIntegrationTest { + + + @Test + public void givenUser_whenUseAnnotation_thenConverted(){ + RelationalJMapper relationalMapper = new RelationalJMapper<>(User.class); + + User user = new User(1L,"john@test.com"); + UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user); + UserDto2 result2= relationalMapper.oneToMany(UserDto2.class, user); + + System.out.println(result1); + System.out.println(result2); + assertEquals(user.getId(), result1.getId()); + assertEquals(user.getEmail(), result1.getUsername()); + assertEquals(user.getId(), result2.getId()); + assertEquals(user.getEmail(), result2.getEmail()); + } + + //======================= XML + + @Test + public void givenUser_whenUseXml_thenConverted(){ + RelationalJMapper relationalMapper = new RelationalJMapper<>(User.class,"user_jmapper2.xml"); + + User user = new User(1L,"john@test.com"); + UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user); + UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user); + + System.out.println(result1); + System.out.println(result2); + assertEquals(user.getId(), result1.getId()); + assertEquals(user.getEmail(), result1.getUsername()); + assertEquals(user.getId(), result2.getId()); + assertEquals(user.getEmail(), result2.getEmail()); + } + + + // ===== API + + @Test + public void givenUser_whenUseApi_thenConverted(){ + JMapperAPI jmapperApi = new JMapperAPI() + .add(mappedClass(User.class) + .add(attribute("id").value("id").targetClasses(UserDto1.class,UserDto2.class)) + .add(attribute("email").targetAttributes("username","email").targetClasses(UserDto1.class,UserDto2.class)) ) + ; + RelationalJMapper relationalMapper = new RelationalJMapper<>(User.class,jmapperApi); + + User user = new User(1L,"john@test.com"); + UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user); + UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user); + + System.out.println(result1); + System.out.println(result2); + assertEquals(user.getId(), result1.getId()); + assertEquals(user.getEmail(), result1.getUsername()); + assertEquals(user.getId(), result2.getId()); + assertEquals(user.getEmail(), result2.getEmail()); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/.gitignore b/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/.gitignore new file mode 100644 index 0000000000..90b27cf4da --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/.gitignore @@ -0,0 +1 @@ +/FooReactiveController.java diff --git a/spring-boot-persistence/src/main/java/com/baeldung/domain/Article.java b/spring-boot-persistence/src/main/java/com/baeldung/domain/Article.java new file mode 100644 index 0000000000..3b5a8be088 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/domain/Article.java @@ -0,0 +1,23 @@ +package com.baeldung.domain; + +import javax.persistence.*; +import java.util.Date; + +@Entity +public class Article { + + @Id + @GeneratedValue + private Integer id; + @Temporal(TemporalType.DATE) + private Date publicationDate; + @Temporal(TemporalType.TIME) + private Date publicationTime; + @Temporal(TemporalType.TIMESTAMP) + private Date creationDateTime; + + public Integer getId() { + return id; + } + +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/repository/ArticleRepository.java b/spring-boot-persistence/src/main/java/com/baeldung/repository/ArticleRepository.java new file mode 100644 index 0000000000..4e1b109430 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/repository/ArticleRepository.java @@ -0,0 +1,22 @@ +package com.baeldung.repository; + +import com.baeldung.domain.Article; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.Date; +import java.util.List; + +public interface ArticleRepository extends JpaRepository { + + List
findAllByPublicationDate(Date publicationDate); + + List
findAllByPublicationTimeBetween(Date publicationTimeStart, + Date publicationTimeEnd); + + @Query("select a from Article a where a.creationDateTime <= :creationDateTime") + List
findAllWithCreationDateTimeBefore( + @Param("creationDateTime") Date creationDateTime); + +} diff --git a/spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java new file mode 100644 index 0000000000..7d531d1461 --- /dev/null +++ b/spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java @@ -0,0 +1,66 @@ +package com.baeldung.repository; + +import com.baeldung.domain.Article; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@DataJpaTest +public class ArticleRepositoryIntegrationTest { + + @Autowired + private ArticleRepository repository; + + @Test + public void givenImportedArticlesWhenFindAllByPublicationDateThenArticles1And2Returned() + throws Exception { + List
result = repository.findAllByPublicationDate( + new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-01") + ); + + assertEquals(2, result.size()); + assertTrue(result.stream() + .map(Article::getId) + .allMatch(id -> Arrays.asList(1, 2).contains(id)) + ); + } + + @Test + public void givenImportedArticlesWhenFindAllByPublicationTimeBetweenThenArticles2And3Returned() + throws Exception { + List
result = repository.findAllByPublicationTimeBetween( + new SimpleDateFormat("HH:mm").parse("15:15"), + new SimpleDateFormat("HH:mm").parse("16:30") + ); + + assertEquals(2, result.size()); + assertTrue(result.stream() + .map(Article::getId) + .allMatch(id -> Arrays.asList(2, 3).contains(id)) + ); + } + + @Test + public void givenImportedArticlesWhenFindAllWithCreationDateTimeBeforeThenArticles2And3Returned() throws Exception { + List
result = repository.findAllWithCreationDateTimeBefore( + new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2017-12-15 10:00") + ); + + assertEquals(2, result.size()); + assertTrue(result.stream() + .map(Article::getId) + .allMatch(id -> Arrays.asList(2, 3).contains(id)) + ); + } + +} diff --git a/spring-boot-persistence/src/test/resources/application.properties b/spring-boot-persistence/src/test/resources/application.properties index a5c1d983cf..a5d09db840 100644 --- a/spring-boot-persistence/src/test/resources/application.properties +++ b/spring-boot-persistence/src/test/resources/application.properties @@ -13,4 +13,4 @@ hibernate.cache.use_query_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory spring.jpa.properties.hibernate.hbm2ddl.import_files=migrated_users.sql -spring.datasource.data=import_*_users.sql \ No newline at end of file +spring.datasource.data=import_*_users.sql,import_articles.sql \ No newline at end of file diff --git a/spring-boot-persistence/src/test/resources/import_articles.sql b/spring-boot-persistence/src/test/resources/import_articles.sql new file mode 100644 index 0000000000..4fe18bf4aa --- /dev/null +++ b/spring-boot-persistence/src/test/resources/import_articles.sql @@ -0,0 +1,3 @@ +insert into Article(id, publication_date, publication_time, creation_date_time) values(1, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:00', 'HH24:MI'), TO_DATE('31/12/2017 07:30', 'DD/MM/YYYY HH24:MI')); +insert into Article(id, publication_date, publication_time, creation_date_time) values(2, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:30', 'HH24:MI'), TO_DATE('15/12/2017 08:00', 'DD/MM/YYYY HH24:MI')); +insert into Article(id, publication_date, publication_time, creation_date_time) values(3, TO_DATE('15/12/2017', 'DD/MM/YYYY'), TO_DATE('16:00', 'HH24:MI'), TO_DATE('01/12/2017 13:45', 'DD/MM/YYYY HH24:MI')); \ No newline at end of file From fee82e22113cdfedb69a03f0f33734f2f039495e Mon Sep 17 00:00:00 2001 From: Tritty Date: Sat, 25 Aug 2018 20:38:13 +0530 Subject: [PATCH 12/69] Precommit : rebase --- .../connectionpools/BasicConnectionPool.java | 87 ------------- .../connectionpools/C3poDataSource.java | 28 ----- .../connectionpools/ConnectionPool.java | 18 --- .../connectionpools/DBCPDataSource.java | 25 ---- .../connectionpools/HikariCPDataSource.java | 28 ----- .../java/com/baeldung/manifest/MANIFEST.MF | 1 - .../BasicConnectionPoolUnitTest.java | 69 ----------- .../C3poDataSourceUnitTest.java | 14 --- .../DBCPDataSourceUnitTest.java | 14 --- .../HikariCPDataSourceUnitTest.java | 14 --- .../main/java/com/baeldung/jmapper/User.java | 56 --------- .../java/com/baeldung/jmapper/UserDto.java | 69 ----------- .../java/com/baeldung/jmapper/UserDto1.java | 47 -------- .../com/baeldung/jmapper/relational/User.java | 49 -------- .../baeldung/jmapper/relational/UserDto1.java | 44 ------- .../baeldung/jmapper/relational/UserDto2.java | 44 ------- libraries/src/main/resources/user_jmapper.xml | 10 -- .../src/main/resources/user_jmapper1.xml | 5 - .../src/main/resources/user_jmapper2.xml | 21 ---- .../jmapper/JMapperIntegrationTest.java | 114 ------------------ .../JMapperRelationalIntegrationTest.java | 76 ------------ .../baeldung/reactive/controller/.gitignore | 1 - .../java/com/baeldung/domain/Article.java | 23 ---- .../repository/ArticleRepository.java | 22 ---- .../ArticleRepositoryIntegrationTest.java | 66 ---------- .../src/test/resources/application.properties | 2 +- .../src/test/resources/import_articles.sql | 3 - 27 files changed, 1 insertion(+), 949 deletions(-) delete mode 100644 core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java delete mode 100644 core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java delete mode 100644 core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java delete mode 100644 core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java delete mode 100644 core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java delete mode 100644 core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF delete mode 100644 core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java delete mode 100644 core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java delete mode 100644 core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java delete mode 100644 core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java delete mode 100644 libraries/src/main/java/com/baeldung/jmapper/User.java delete mode 100644 libraries/src/main/java/com/baeldung/jmapper/UserDto.java delete mode 100644 libraries/src/main/java/com/baeldung/jmapper/UserDto1.java delete mode 100644 libraries/src/main/java/com/baeldung/jmapper/relational/User.java delete mode 100644 libraries/src/main/java/com/baeldung/jmapper/relational/UserDto1.java delete mode 100644 libraries/src/main/java/com/baeldung/jmapper/relational/UserDto2.java delete mode 100644 libraries/src/main/resources/user_jmapper.xml delete mode 100644 libraries/src/main/resources/user_jmapper1.xml delete mode 100644 libraries/src/main/resources/user_jmapper2.xml delete mode 100644 libraries/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java delete mode 100644 libraries/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java delete mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/controller/.gitignore delete mode 100644 spring-boot-persistence/src/main/java/com/baeldung/domain/Article.java delete mode 100644 spring-boot-persistence/src/main/java/com/baeldung/repository/ArticleRepository.java delete mode 100644 spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java delete mode 100644 spring-boot-persistence/src/test/resources/import_articles.sql diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java deleted file mode 100644 index 243ec88eb5..0000000000 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.connectionpool.connectionpools; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -public class BasicConnectionPool implements ConnectionPool { - - private final String url; - private final String user; - private final String password; - private final List connectionPool; - private final List usedConnections = new ArrayList<>(); - private static final int INITIAL_POOL_SIZE = 10; - private final int MAX_POOL_SIZE = 20; - - public static BasicConnectionPool create(String url, String user, String password) throws SQLException { - List pool = new ArrayList<>(INITIAL_POOL_SIZE); - for (int i = 0; i < INITIAL_POOL_SIZE; i++) { - pool.add(createConnection(url, user, password)); - } - return new BasicConnectionPool(url, user, password, pool); - } - - private BasicConnectionPool(String url, String user, String password, List connectionPool) { - this.url = url; - this.user = user; - this.password = password; - this.connectionPool = connectionPool; - } - - @Override - public Connection getConnection() throws SQLException { - if (connectionPool.size() == 0) { - if (usedConnections.size() < MAX_POOL_SIZE) { - connectionPool.add(createConnection(url, user, password)); - } else { - throw new RuntimeException("Maximum pool size reached, no available connections!"); - } - } - - Connection connection = connectionPool.remove(connectionPool.size() - 1); - usedConnections.add(connection); - return connection; - } - - @Override - public boolean releaseConnection(Connection connection) { - connectionPool.add(connection); - return usedConnections.remove(connection); - } - - private static Connection createConnection(String url, String user, String password) throws SQLException { - return DriverManager.getConnection(url, user, password); - } - - public int getSize() { - return connectionPool.size() + usedConnections.size(); - } - - @Override - public String getUrl() { - return url; - } - - @Override - public String getUser() { - return user; - } - - @Override - public String getPassword() { - return password; - } - - public void shutdown() throws SQLException { - for (Connection c : usedConnections) { - this.releaseConnection(c); - } - for (Connection c : connectionPool) { - c.close(); - } - connectionPool.clear(); - } -} diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java deleted file mode 100644 index 5b91f707a9..0000000000 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.connectionpool.connectionpools; - -import com.mchange.v2.c3p0.ComboPooledDataSource; -import java.beans.PropertyVetoException; -import java.sql.Connection; -import java.sql.SQLException; - -public class C3poDataSource { - - private static final ComboPooledDataSource cpds = new ComboPooledDataSource(); - - static { - try { - cpds.setDriverClass("org.h2.Driver"); - cpds.setJdbcUrl("jdbc:h2:mem:test"); - cpds.setUser("user"); - cpds.setPassword("password"); - } catch (PropertyVetoException e) { - e.printStackTrace(); - } - } - - public static Connection getConnection() throws SQLException { - return cpds.getConnection(); - } - - private C3poDataSource(){} -} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java deleted file mode 100644 index 3d5ad06c3d..0000000000 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.connectionpool.connectionpools; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.List; - -public interface ConnectionPool { - - Connection getConnection() throws SQLException; - - boolean releaseConnection(Connection connection); - - String getUrl(); - - String getUser(); - - String getPassword(); -} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java deleted file mode 100644 index 2f33cde883..0000000000 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.connectionpool.connectionpools; - -import java.sql.Connection; -import java.sql.SQLException; -import org.apache.commons.dbcp2.BasicDataSource; - -public class DBCPDataSource { - - private static final BasicDataSource ds = new BasicDataSource(); - - static { - ds.setUrl("jdbc:h2:mem:test"); - ds.setUsername("user"); - ds.setPassword("password"); - ds.setMinIdle(5); - ds.setMaxIdle(10); - ds.setMaxOpenPreparedStatements(100); - } - - public static Connection getConnection() throws SQLException { - return ds.getConnection(); - } - - private DBCPDataSource(){} -} diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java deleted file mode 100644 index 5ed2de181d..0000000000 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.connectionpool.connectionpools; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import java.sql.Connection; -import java.sql.SQLException; - -public class HikariCPDataSource { - - private static final HikariConfig config = new HikariConfig(); - private static final HikariDataSource ds; - - static { - config.setJdbcUrl("jdbc:h2:mem:test"); - config.setUsername("user"); - config.setPassword("password"); - config.addDataSourceProperty("cachePrepStmts", "true"); - config.addDataSourceProperty("prepStmtCacheSize", "250"); - config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); - ds = new HikariDataSource(config); - } - - public static Connection getConnection() throws SQLException { - return ds.getConnection(); - } - - private HikariCPDataSource(){} -} diff --git a/core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF b/core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF deleted file mode 100644 index a363171952..0000000000 --- a/core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF +++ /dev/null @@ -1 +0,0 @@ -Main-Class: com.baeldung.manifest.AppExample diff --git a/core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java b/core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java deleted file mode 100644 index 5edc6bba94..0000000000 --- a/core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.connectionpool; - -import com.baeldung.connectionpool.connectionpools.BasicConnectionPool; -import com.baeldung.connectionpool.connectionpools.ConnectionPool; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.BeforeClass; -import org.junit.Test; - -public class BasicConnectionPoolUnitTest { - - private static ConnectionPool connectionPool; - - @BeforeClass - public static void setUpBasicConnectionPoolInstance() throws SQLException { - connectionPool = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password"); - } - - @Test - public void givenBasicConnectionPoolInstance_whenCalledgetConnection_thenCorrect() throws Exception { - assertTrue(connectionPool.getConnection().isValid(1)); - } - - @Test - public void givenBasicConnectionPoolInstance_whenCalledreleaseConnection_thenCorrect() throws Exception { - Connection connection = connectionPool.getConnection(); - assertThat(connectionPool.releaseConnection(connection)).isTrue(); - } - - @Test - public void givenBasicConnectionPoolInstance_whenCalledgetUrl_thenCorrect() { - assertThat(connectionPool.getUrl()).isEqualTo("jdbc:h2:mem:test"); - } - - @Test - public void givenBasicConnectionPoolInstance_whenCalledgetUser_thenCorrect() { - assertThat(connectionPool.getUser()).isEqualTo("user"); - } - - @Test - public void givenBasicConnectionPoolInstance_whenCalledgetPassword_thenCorrect() { - assertThat(connectionPool.getPassword()).isEqualTo("password"); - } - - @Test(expected = RuntimeException.class) - public void givenBasicConnectionPoolInstance_whenAskedForMoreThanMax_thenError() throws Exception { - // this test needs to be independent so it doesn't share the same connection pool as other tests - ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password"); - final int MAX_POOL_SIZE = 20; - for (int i = 0; i < MAX_POOL_SIZE + 1; i++) { - cp.getConnection(); - } - fail(); - } - - @Test - public void givenBasicConnectionPoolInstance_whenSutdown_thenEmpty() throws Exception { - ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password"); - assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(10); - - ((BasicConnectionPool) cp).shutdown(); - assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(0); - } -} diff --git a/core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java b/core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java deleted file mode 100644 index a02daa40f6..0000000000 --- a/core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.connectionpool; - -import com.baeldung.connectionpool.connectionpools.C3poDataSource; -import java.sql.SQLException; -import static org.junit.Assert.assertTrue; -import org.junit.Test; - -public class C3poDataSourceUnitTest { - - @Test - public void givenC3poDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException { - assertTrue(C3poDataSource.getConnection().isValid(1)); - } -} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java b/core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java deleted file mode 100644 index 9583eedf4b..0000000000 --- a/core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.connectionpool; - -import com.baeldung.connectionpool.connectionpools.DBCPDataSource; -import java.sql.SQLException; -import static org.junit.Assert.assertTrue; -import org.junit.Test; - -public class DBCPDataSourceUnitTest { - - @Test - public void givenDBCPDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException { - assertTrue(DBCPDataSource.getConnection().isValid(1)); - } -} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java b/core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java deleted file mode 100644 index 6b78815797..0000000000 --- a/core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.connectionpool; - -import com.baeldung.connectionpool.connectionpools.HikariCPDataSource; -import java.sql.SQLException; -import static org.junit.Assert.assertTrue; -import org.junit.Test; - -public class HikariCPDataSourceUnitTest { - - @Test - public void givenHikariDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException { - assertTrue(HikariCPDataSource.getConnection().isValid(1)); - } -} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jmapper/User.java b/libraries/src/main/java/com/baeldung/jmapper/User.java deleted file mode 100644 index 9f99157183..0000000000 --- a/libraries/src/main/java/com/baeldung/jmapper/User.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.jmapper; - -import java.time.LocalDate; - - -public class User { - - private long id; - private String email; - private LocalDate birthDate; - - // constructors - - public User() { - super(); - } - - public User(long id, String email, LocalDate birthDate) { - super(); - this.id = id; - this.email = email; - this.birthDate = birthDate; - } - - // getters and setters - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public LocalDate getBirthDate() { - return birthDate; - } - - public void setBirthDate(LocalDate birthDate) { - this.birthDate = birthDate; - } - - @Override - public String toString() { - return "User [id=" + id + ", email=" + email + ", birthDate=" + birthDate + "]"; - } - -} diff --git a/libraries/src/main/java/com/baeldung/jmapper/UserDto.java b/libraries/src/main/java/com/baeldung/jmapper/UserDto.java deleted file mode 100644 index 326e8f3cd5..0000000000 --- a/libraries/src/main/java/com/baeldung/jmapper/UserDto.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.jmapper; - -import java.time.LocalDate; -import java.time.Period; - -import com.googlecode.jmapper.annotations.JMap; -import com.googlecode.jmapper.annotations.JMapConversion; - -public class UserDto { - - @JMap - private long id; - - @JMap("email") - private String username; - - @JMap("birthDate") - private int age; - - @JMapConversion(from={"birthDate"}, to={"age"}) - public int conversion(LocalDate birthDate){ - return Period.between(birthDate, LocalDate.now()).getYears(); - } - - // constructors - - public UserDto() { - super(); - } - - public UserDto(long id, String username, int age) { - super(); - this.id = id; - this.username = username; - this.age = age; - } - - // getters and setters - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - @Override - public String toString() { - return "UserDto [id=" + id + ", username=" + username + ", age=" + age + "]"; - } - -} diff --git a/libraries/src/main/java/com/baeldung/jmapper/UserDto1.java b/libraries/src/main/java/com/baeldung/jmapper/UserDto1.java deleted file mode 100644 index 99247c56f6..0000000000 --- a/libraries/src/main/java/com/baeldung/jmapper/UserDto1.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.jmapper; - -import com.googlecode.jmapper.annotations.JGlobalMap; - -@JGlobalMap -public class UserDto1 { - - private long id; - private String email; - - - // constructors - - public UserDto1() { - super(); - } - - public UserDto1(long id, String email) { - super(); - this.id = id; - this.email = email; - } - - // getters and setters - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - @Override - public String toString() { - return "UserDto [id=" + id + ", email=" + email + "]"; - } - -} diff --git a/libraries/src/main/java/com/baeldung/jmapper/relational/User.java b/libraries/src/main/java/com/baeldung/jmapper/relational/User.java deleted file mode 100644 index 1238a82684..0000000000 --- a/libraries/src/main/java/com/baeldung/jmapper/relational/User.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.jmapper.relational; - -import com.googlecode.jmapper.annotations.JMap; - - -public class User { - - @JMap(classes = {UserDto1.class, UserDto2.class}) - private long id; - - @JMap(attributes = {"username", "email"}, classes = {UserDto1.class, UserDto2.class}) - private String email; - - // constructors - - public User() { - super(); - } - - public User(long id, String email) { - super(); - this.id = id; - this.email = email; - } - - // getters and setters - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - @Override - public String toString() { - return "User [id=" + id + ", email=" + email + "]"; - } - -} diff --git a/libraries/src/main/java/com/baeldung/jmapper/relational/UserDto1.java b/libraries/src/main/java/com/baeldung/jmapper/relational/UserDto1.java deleted file mode 100644 index 375fd267a0..0000000000 --- a/libraries/src/main/java/com/baeldung/jmapper/relational/UserDto1.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.jmapper.relational; - - -public class UserDto1 { - - private long id; - private String username; - - // constructors - - public UserDto1() { - super(); - } - - public UserDto1(long id, String username) { - super(); - this.id = id; - this.username = username; - } - - // getters and setters - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - @Override - public String toString() { - return "UserDto [id=" + id + ", username=" + username + "]"; - } - -} diff --git a/libraries/src/main/java/com/baeldung/jmapper/relational/UserDto2.java b/libraries/src/main/java/com/baeldung/jmapper/relational/UserDto2.java deleted file mode 100644 index d0858c7d8e..0000000000 --- a/libraries/src/main/java/com/baeldung/jmapper/relational/UserDto2.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.jmapper.relational; - - -public class UserDto2 { - - private long id; - private String email; - - // constructors - - public UserDto2() { - super(); - } - - public UserDto2(long id, String email) { - super(); - this.id = id; - this.email = email; - } - - // getters and setters - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - @Override - public String toString() { - return "UserDto2 [id=" + id + ", email=" + email + "]"; - } - -} diff --git a/libraries/src/main/resources/user_jmapper.xml b/libraries/src/main/resources/user_jmapper.xml deleted file mode 100644 index f007de9f0a..0000000000 --- a/libraries/src/main/resources/user_jmapper.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/libraries/src/main/resources/user_jmapper1.xml b/libraries/src/main/resources/user_jmapper1.xml deleted file mode 100644 index abcfd77e1c..0000000000 --- a/libraries/src/main/resources/user_jmapper1.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/libraries/src/main/resources/user_jmapper2.xml b/libraries/src/main/resources/user_jmapper2.xml deleted file mode 100644 index 1e708e14bf..0000000000 --- a/libraries/src/main/resources/user_jmapper2.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java b/libraries/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java deleted file mode 100644 index 96ed090482..0000000000 --- a/libraries/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.baeldung.jmapper; - -import static com.googlecode.jmapper.api.JMapperAPI.attribute; -import static com.googlecode.jmapper.api.JMapperAPI.global; -import static com.googlecode.jmapper.api.JMapperAPI.mappedClass; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.time.LocalDate; - -import org.junit.Test; - -import com.googlecode.jmapper.JMapper; -import com.googlecode.jmapper.api.JMapperAPI; - -public class JMapperIntegrationTest { - - - @Test - public void givenUser_whenUseAnnotation_thenConverted(){ - JMapper userMapper = new JMapper<>(UserDto.class, User.class); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); - UserDto result = userMapper.getDestination(user); - - System.out.println(result); - assertEquals(user.getId(), result.getId()); - assertEquals(user.getEmail(), result.getUsername()); - } - - @Test - public void givenUser_whenUseGlobalMapAnnotation_thenConverted(){ - JMapper userMapper= new JMapper<>(UserDto1.class, User.class); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); - UserDto1 result = userMapper.getDestination(user); - - System.out.println(result); - assertEquals(user.getId(), result.getId()); - assertEquals(user.getEmail(), result.getEmail()); - } - - @Test - public void givenUser_whenUseAnnotationExplicitConversion_thenConverted(){ - JMapper userMapper = new JMapper<>(UserDto.class, User.class); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); - UserDto result = userMapper.getDestination(user); - - System.out.println(result); - assertEquals(user.getId(), result.getId()); - assertEquals(user.getEmail(), result.getUsername()); - assertTrue(result.getAge() > 0); - } - - //======================= XML - - @Test - public void givenUser_whenUseXml_thenConverted(){ - JMapper userMapper = new JMapper<>(UserDto.class, User.class,"user_jmapper.xml"); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); - UserDto result = userMapper.getDestination(user); - - System.out.println(result); - assertEquals(user.getId(), result.getId()); - assertEquals(user.getEmail(), result.getUsername()); - } - - @Test - public void givenUser_whenUseXmlGlobal_thenConverted(){ - JMapper userMapper = new JMapper<>(UserDto1.class, User.class,"user_jmapper1.xml"); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); - UserDto1 result = userMapper.getDestination(user); - - System.out.println(result); - assertEquals(user.getId(), result.getId()); - assertEquals(user.getEmail(), result.getEmail()); - } - - // ===== API - - @Test - public void givenUser_whenUseApi_thenConverted(){ - JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class) - .add(attribute("id").value("id")) - .add(attribute("username").value("email")) - ) ; - JMapper userMapper = new JMapper<>(UserDto.class, User.class, jmapperApi); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); - UserDto result = userMapper.getDestination(user); - - System.out.println(result); - assertEquals(user.getId(), result.getId()); - assertEquals(user.getEmail(), result.getUsername()); - } - - @Test - public void givenUser_whenUseApiGlobal_thenConverted(){ - JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class) - .add(global()) - ) ; - JMapper userMapper1 = new JMapper<>(UserDto1.class, User.class,jmapperApi); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); - UserDto1 result = userMapper1.getDestination(user); - - System.out.println(result); - assertEquals(user.getId(), result.getId()); - assertEquals(user.getEmail(), result.getEmail()); - } -} diff --git a/libraries/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java b/libraries/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java deleted file mode 100644 index 6af2865159..0000000000 --- a/libraries/src/test/java/com/baeldung/jmapper/JMapperRelationalIntegrationTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.baeldung.jmapper; - -import static com.googlecode.jmapper.api.JMapperAPI.attribute; -import static com.googlecode.jmapper.api.JMapperAPI.mappedClass; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import com.baeldung.jmapper.relational.User; -import com.baeldung.jmapper.relational.UserDto1; -import com.baeldung.jmapper.relational.UserDto2; -import com.googlecode.jmapper.RelationalJMapper; -import com.googlecode.jmapper.api.JMapperAPI; - -public class JMapperRelationalIntegrationTest { - - - @Test - public void givenUser_whenUseAnnotation_thenConverted(){ - RelationalJMapper relationalMapper = new RelationalJMapper<>(User.class); - - User user = new User(1L,"john@test.com"); - UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user); - UserDto2 result2= relationalMapper.oneToMany(UserDto2.class, user); - - System.out.println(result1); - System.out.println(result2); - assertEquals(user.getId(), result1.getId()); - assertEquals(user.getEmail(), result1.getUsername()); - assertEquals(user.getId(), result2.getId()); - assertEquals(user.getEmail(), result2.getEmail()); - } - - //======================= XML - - @Test - public void givenUser_whenUseXml_thenConverted(){ - RelationalJMapper relationalMapper = new RelationalJMapper<>(User.class,"user_jmapper2.xml"); - - User user = new User(1L,"john@test.com"); - UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user); - UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user); - - System.out.println(result1); - System.out.println(result2); - assertEquals(user.getId(), result1.getId()); - assertEquals(user.getEmail(), result1.getUsername()); - assertEquals(user.getId(), result2.getId()); - assertEquals(user.getEmail(), result2.getEmail()); - } - - - // ===== API - - @Test - public void givenUser_whenUseApi_thenConverted(){ - JMapperAPI jmapperApi = new JMapperAPI() - .add(mappedClass(User.class) - .add(attribute("id").value("id").targetClasses(UserDto1.class,UserDto2.class)) - .add(attribute("email").targetAttributes("username","email").targetClasses(UserDto1.class,UserDto2.class)) ) - ; - RelationalJMapper relationalMapper = new RelationalJMapper<>(User.class,jmapperApi); - - User user = new User(1L,"john@test.com"); - UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user); - UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user); - - System.out.println(result1); - System.out.println(result2); - assertEquals(user.getId(), result1.getId()); - assertEquals(user.getEmail(), result1.getUsername()); - assertEquals(user.getId(), result2.getId()); - assertEquals(user.getEmail(), result2.getEmail()); - } - -} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/.gitignore b/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/.gitignore deleted file mode 100644 index 90b27cf4da..0000000000 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/FooReactiveController.java diff --git a/spring-boot-persistence/src/main/java/com/baeldung/domain/Article.java b/spring-boot-persistence/src/main/java/com/baeldung/domain/Article.java deleted file mode 100644 index 3b5a8be088..0000000000 --- a/spring-boot-persistence/src/main/java/com/baeldung/domain/Article.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.domain; - -import javax.persistence.*; -import java.util.Date; - -@Entity -public class Article { - - @Id - @GeneratedValue - private Integer id; - @Temporal(TemporalType.DATE) - private Date publicationDate; - @Temporal(TemporalType.TIME) - private Date publicationTime; - @Temporal(TemporalType.TIMESTAMP) - private Date creationDateTime; - - public Integer getId() { - return id; - } - -} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/repository/ArticleRepository.java b/spring-boot-persistence/src/main/java/com/baeldung/repository/ArticleRepository.java deleted file mode 100644 index 4e1b109430..0000000000 --- a/spring-boot-persistence/src/main/java/com/baeldung/repository/ArticleRepository.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.domain.Article; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import java.util.Date; -import java.util.List; - -public interface ArticleRepository extends JpaRepository { - - List
findAllByPublicationDate(Date publicationDate); - - List
findAllByPublicationTimeBetween(Date publicationTimeStart, - Date publicationTimeEnd); - - @Query("select a from Article a where a.creationDateTime <= :creationDateTime") - List
findAllWithCreationDateTimeBefore( - @Param("creationDateTime") Date creationDateTime); - -} diff --git a/spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java deleted file mode 100644 index 7d531d1461..0000000000 --- a/spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.domain.Article; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.junit4.SpringRunner; - -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -@RunWith(SpringRunner.class) -@DataJpaTest -public class ArticleRepositoryIntegrationTest { - - @Autowired - private ArticleRepository repository; - - @Test - public void givenImportedArticlesWhenFindAllByPublicationDateThenArticles1And2Returned() - throws Exception { - List
result = repository.findAllByPublicationDate( - new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-01") - ); - - assertEquals(2, result.size()); - assertTrue(result.stream() - .map(Article::getId) - .allMatch(id -> Arrays.asList(1, 2).contains(id)) - ); - } - - @Test - public void givenImportedArticlesWhenFindAllByPublicationTimeBetweenThenArticles2And3Returned() - throws Exception { - List
result = repository.findAllByPublicationTimeBetween( - new SimpleDateFormat("HH:mm").parse("15:15"), - new SimpleDateFormat("HH:mm").parse("16:30") - ); - - assertEquals(2, result.size()); - assertTrue(result.stream() - .map(Article::getId) - .allMatch(id -> Arrays.asList(2, 3).contains(id)) - ); - } - - @Test - public void givenImportedArticlesWhenFindAllWithCreationDateTimeBeforeThenArticles2And3Returned() throws Exception { - List
result = repository.findAllWithCreationDateTimeBefore( - new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2017-12-15 10:00") - ); - - assertEquals(2, result.size()); - assertTrue(result.stream() - .map(Article::getId) - .allMatch(id -> Arrays.asList(2, 3).contains(id)) - ); - } - -} diff --git a/spring-boot-persistence/src/test/resources/application.properties b/spring-boot-persistence/src/test/resources/application.properties index a5d09db840..a5c1d983cf 100644 --- a/spring-boot-persistence/src/test/resources/application.properties +++ b/spring-boot-persistence/src/test/resources/application.properties @@ -13,4 +13,4 @@ hibernate.cache.use_query_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory spring.jpa.properties.hibernate.hbm2ddl.import_files=migrated_users.sql -spring.datasource.data=import_*_users.sql,import_articles.sql \ No newline at end of file +spring.datasource.data=import_*_users.sql \ No newline at end of file diff --git a/spring-boot-persistence/src/test/resources/import_articles.sql b/spring-boot-persistence/src/test/resources/import_articles.sql deleted file mode 100644 index 4fe18bf4aa..0000000000 --- a/spring-boot-persistence/src/test/resources/import_articles.sql +++ /dev/null @@ -1,3 +0,0 @@ -insert into Article(id, publication_date, publication_time, creation_date_time) values(1, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:00', 'HH24:MI'), TO_DATE('31/12/2017 07:30', 'DD/MM/YYYY HH24:MI')); -insert into Article(id, publication_date, publication_time, creation_date_time) values(2, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:30', 'HH24:MI'), TO_DATE('15/12/2017 08:00', 'DD/MM/YYYY HH24:MI')); -insert into Article(id, publication_date, publication_time, creation_date_time) values(3, TO_DATE('15/12/2017', 'DD/MM/YYYY'), TO_DATE('16:00', 'HH24:MI'), TO_DATE('01/12/2017 13:45', 'DD/MM/YYYY HH24:MI')); \ No newline at end of file From 1eca2b5c79768b611f37f2c8b8fc1c0bd7f77649 Mon Sep 17 00:00:00 2001 From: Tritty Date: Sat, 25 Aug 2018 20:44:53 +0530 Subject: [PATCH 13/69] BAEL-1782 --- .../event/listener/ContextEventListener.java | 24 +++++++++++++++++++ .../baeldung/event/listener/EventConfig.java | 10 ++++++++ .../baeldung/event/listener/SpringRunner.java | 12 ++++++++++ 3 files changed, 46 insertions(+) create mode 100644 spring-core/src/main/java/com/baeldung/event/listener/ContextEventListener.java create mode 100644 spring-core/src/main/java/com/baeldung/event/listener/EventConfig.java create mode 100644 spring-core/src/main/java/com/baeldung/event/listener/SpringRunner.java diff --git a/spring-core/src/main/java/com/baeldung/event/listener/ContextEventListener.java b/spring-core/src/main/java/com/baeldung/event/listener/ContextEventListener.java new file mode 100644 index 0000000000..a2603bb95c --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/event/listener/ContextEventListener.java @@ -0,0 +1,24 @@ +package com.baeldung.event.listener; + +import org.springframework.context.event.ContextStartedEvent; +import org.springframework.context.event.ContextStoppedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +@Component +public class ContextEventListener { + + @Order(2) + @EventListener + public void handleContextRefreshEvent(ContextStartedEvent ctxStartEvt) { + System.out.println("Context Start Event received."); + } + + @Order(1) + @EventListener(classes = { ContextStartedEvent.class, ContextStoppedEvent.class }) + public void handleMultipleEvents() { + System.out.println("Multi-event listener invoked"); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/event/listener/EventConfig.java b/spring-core/src/main/java/com/baeldung/event/listener/EventConfig.java new file mode 100644 index 0000000000..f2a3af7640 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/event/listener/EventConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.event.listener; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = "com.baeldung.event.listener") +public class EventConfig { + +} diff --git a/spring-core/src/main/java/com/baeldung/event/listener/SpringRunner.java b/spring-core/src/main/java/com/baeldung/event/listener/SpringRunner.java new file mode 100644 index 0000000000..bbe4693900 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/event/listener/SpringRunner.java @@ -0,0 +1,12 @@ +package com.baeldung.event.listener; + +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class SpringRunner { + + public static void main(String[] args) { + ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(EventConfig.class); + ctx.start(); + } +} From 978591ef59f5df83b8d812d56ca4f4f74abb335f Mon Sep 17 00:00:00 2001 From: "akash.pandey" Date: Wed, 19 Sep 2018 10:19:49 +0530 Subject: [PATCH 14/69] BAEL-2159: Mini Article on "Separate double into integer and decimal parts" --- .../doubles/SplitFloatingPointNumbers.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/doubles/SplitFloatingPointNumbers.java diff --git a/core-java/src/main/java/com/baeldung/doubles/SplitFloatingPointNumbers.java b/core-java/src/main/java/com/baeldung/doubles/SplitFloatingPointNumbers.java new file mode 100644 index 0000000000..a28ac3d5a1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/doubles/SplitFloatingPointNumbers.java @@ -0,0 +1,40 @@ +package com.baeldung.doubles; + +import java.math.BigDecimal; + +public class SplitFloatingPointNumbers { + + public static void main(String[] args) { + + double doubleNumber = 24.04; + splitUsingFloatingTypes(doubleNumber); + splitUsingString(doubleNumber); + splitUsingBigDecimal(doubleNumber); + } + + private static void splitUsingFloatingTypes(double doubleNumber) { + System.out.println("Using Floating Point Arithmetics:"); + int intPart = (int) doubleNumber; + System.out.println("Double Number: "+doubleNumber); + System.out.println("Integer Part: "+ intPart); + System.out.println("Decimal Part: "+ (doubleNumber - intPart)); + } + + private static void splitUsingString(double doubleNumber) { + System.out.println("Using String Operations:"); + String doubleAsString = String.valueOf(doubleNumber); + int indexOfDecimal = doubleAsString.indexOf("."); + System.out.println("Double Number: "+doubleNumber); + System.out.println("Integer Part: "+ doubleAsString.substring(0, indexOfDecimal)); + System.out.println("Decimal Part: "+ doubleAsString.substring(indexOfDecimal)); + } + + private static void splitUsingBigDecimal(double doubleNumber) { + System.out.println("Using BigDecimal Operations:"); + BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubleNumber)); + int intValue = bigDecimal.intValue(); + System.out.println("Double Number: "+bigDecimal.toPlainString()); + System.out.println("Integer Part: "+intValue); + System.out.println("Decimal Part: "+bigDecimal.subtract(new BigDecimal(intValue)).toPlainString()); + } +} From 5fa8e664453a7d1a79f78501f2bcfa12a4583614 Mon Sep 17 00:00:00 2001 From: Tritty Date: Tue, 2 Oct 2018 21:55:25 +0530 Subject: [PATCH 15/69] BAEL - 2166 : Password Generation --- java-strings/pom.xml | 12 +- .../password/StringPasswordUnitTest.java | 198 ++++++++++++++++++ 2 files changed, 209 insertions(+), 1 deletion(-) create mode 100644 java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java diff --git a/java-strings/pom.xml b/java-strings/pom.xml index b1ba49b33a..a43490ce5c 100644 --- a/java-strings/pom.xml +++ b/java-strings/pom.xml @@ -68,7 +68,17 @@ emoji-java 4.0.0 - + + + org.passay + passay + 1.3.1 + + + org.apache.commons + commons-text + 1.4 + diff --git a/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java b/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java new file mode 100644 index 0000000000..ac610aee6f --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java @@ -0,0 +1,198 @@ +package com.baeldung.string.password; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.security.SecureRandom; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.text.RandomStringGenerator; +import org.junit.Test; +import org.passay.CharacterData; +import org.passay.CharacterRule; +import org.passay.EnglishCharacterData; +import org.passay.PasswordGenerator; + +/** + * Examples of passwords conforming to various specifications, using different libraries. + * + * + * @author tritty + * + */ +public class StringPasswordUnitTest { + /** + * Special characters allowed in password. + */ + public static final String ALLOWED_SPL_CHARACTERS = "!@#$%^&*()_+"; + + public static final String ERROR_CODE = "ERRONEOUS_SPECIAL_CHARS"; + + Random random = new SecureRandom(); + + /** + * Password generated using Passay with minimum of 2 lowercase, 2 uppercase, 2 numbers and 2 special characters. + * + */ + @Test + public void whenPasswordGeneratedUsingPassay_thenSuccessful() { + PasswordGenerator gen = new PasswordGenerator(); + CharacterData lowerCaseChars = EnglishCharacterData.LowerCase; + CharacterRule lowerCaseRule = new CharacterRule(lowerCaseChars); + lowerCaseRule.setNumberOfCharacters(2); + CharacterData upperCaseChars = EnglishCharacterData.UpperCase; + CharacterRule upperCaseRule = new CharacterRule(upperCaseChars); + upperCaseRule.setNumberOfCharacters(2); + CharacterData digitChars = EnglishCharacterData.Digit; + CharacterRule digitRule = new CharacterRule(digitChars); + digitRule.setNumberOfCharacters(2); + CharacterData specialChars = new CharacterData() { + public String getErrorCode() { + return ERROR_CODE; + } + + public String getCharacters() { + return ALLOWED_SPL_CHARACTERS; + } + }; + CharacterRule splCharRule = new CharacterRule(specialChars); + splCharRule.setNumberOfCharacters(2); + String password = gen.generatePassword(10, splCharRule, lowerCaseRule, upperCaseRule, digitRule); + int specialCharCount = 0; + for (char c : password.toCharArray()) { + if (c >= 33 || c <= 47) { + specialCharCount++; + } + } + assertTrue(specialCharCount > 2); + } + + /** + * + * Password Generated using RandomStringGenerator conforming to the password requirements. + */ + @Test + public void whenPasswordGeneratedUsingCommonsText_thenSuccessful() { + String pwString = generateRandomSpecialCharacters(2).concat(generateRandomNumbers(2)) + .concat(generateRandomAlphabet(2, true)) + .concat(generateRandomAlphabet(2, false)) + .concat(generateRandomCharacters(2)); + List pwChars = pwString.chars() + .mapToObj(data -> (char) data) + .collect(Collectors.toList()); + Collections.shuffle(pwChars); + String password = pwChars.stream() + .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) + .toString(); + int specialCharCount = 0; + for (char c : password.toCharArray()) { + if (c >= 33 || c <= 47) { + specialCharCount++; + } + } + assertTrue(specialCharCount > 2); + } + + @Test + public void whenPasswordGeneratedUsingCommonsLang3_thenSuccessful() { + String upperCaseLetters = RandomStringUtils.random(2, 65, 90, true, true); + String lowerCaseLetters = RandomStringUtils.random(2, 97, 122, true, true); + String numbers = RandomStringUtils.randomNumeric(2); + String specialChar = RandomStringUtils.random(2, 33, 47, false, false); + String totalChars = RandomStringUtils.randomAlphanumeric(2); + String combinedChars = upperCaseLetters.concat(lowerCaseLetters) + .concat(numbers) + .concat(specialChar) + .concat(totalChars); + List pwdChars = combinedChars.chars() + .mapToObj(c -> (char) c) + .collect(Collectors.toList()); + Collections.shuffle(pwdChars); + String password = pwdChars.stream() + .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) + .toString(); + int specialCharCount = 0; + for (char c : password.toCharArray()) { + if (c >= 33 || c <= 47) { + specialCharCount++; + } + } + assertTrue(specialCharCount > 2); + } + + @Test + public void whenPasswordGeneratedUsingSecureRandom_thenSuccessful() { + Stream pwdStream = Stream.concat(getRandomNumbers(2), Stream.concat(getRandomSpecialChars(2), Stream.concat(getRandomAlphabets(2, true), getRandomAlphabets(4, false)))); + List charList = pwdStream.collect(Collectors.toList()); + Collections.shuffle(charList); + String password = charList.stream() + .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) + .toString(); + int specialCharCount = 0; + for (char c : password.toCharArray()) { + if (c >= 33 || c <= 47) { + specialCharCount++; + } + } + assertTrue(specialCharCount > 2); + } + + public String generateRandomSpecialCharacters(int length) { + RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(33, 45) + .build(); + return pwdGenerator.generate(length); + } + + public String generateRandomNumbers(int length) { + RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57) + .build(); + return pwdGenerator.generate(length); + } + + public String generateRandomCharacters(int length) { + RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57) + .build(); + return pwdGenerator.generate(length); + } + + public String generateRandomAlphabet(int length, boolean lowerCase) { + int low; + int hi; + if (lowerCase) { + low = 97; + hi = 122; + } else { + low = 65; + hi = 90; + } + RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(low, hi) + .build(); + return pwdGenerator.generate(length); + } + + public Stream getRandomAlphabets(int count, boolean upperCase) { + IntStream characters = null; + if (upperCase) { + characters = random.ints(count, 65, 90); + } else { + characters = random.ints(count, 97, 122); + } + return characters.mapToObj(data -> (char) data); + } + + public Stream getRandomNumbers(int count) { + IntStream numbers = random.ints(count, 48, 57); + return numbers.mapToObj(data -> (char) data); + } + + public Stream getRandomSpecialChars(int count) { + IntStream specialChars = random.ints(count, 33, 45); + return specialChars.mapToObj(data -> (char) data); + } + +} From 30f94c717669cebd05625de3c0e2bb89b27c231b Mon Sep 17 00:00:00 2001 From: Tritty Date: Sun, 7 Oct 2018 20:27:27 +0530 Subject: [PATCH 16/69] Removed unnecessary javaDoc --- .../string/password/StringPasswordUnitTest.java | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java b/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java index ac610aee6f..7a076b0e3f 100644 --- a/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java @@ -21,9 +21,6 @@ import org.passay.PasswordGenerator; /** * Examples of passwords conforming to various specifications, using different libraries. * - * - * @author tritty - * */ public class StringPasswordUnitTest { /** @@ -35,10 +32,6 @@ public class StringPasswordUnitTest { Random random = new SecureRandom(); - /** - * Password generated using Passay with minimum of 2 lowercase, 2 uppercase, 2 numbers and 2 special characters. - * - */ @Test public void whenPasswordGeneratedUsingPassay_thenSuccessful() { PasswordGenerator gen = new PasswordGenerator(); @@ -72,10 +65,6 @@ public class StringPasswordUnitTest { assertTrue(specialCharCount > 2); } - /** - * - * Password Generated using RandomStringGenerator conforming to the password requirements. - */ @Test public void whenPasswordGeneratedUsingCommonsText_thenSuccessful() { String pwString = generateRandomSpecialCharacters(2).concat(generateRandomNumbers(2)) From 955c23fc610563ed8fa1b18d73cee476d6fd5ac0 Mon Sep 17 00:00:00 2001 From: Tritty Date: Sun, 14 Oct 2018 23:52:10 +0530 Subject: [PATCH 17/69] Segregated utility method --- .../password/RandomPasswordGenerator.java | 152 +++++++++++++++++ .../password/StringPasswordUnitTest.java | 157 ++---------------- 2 files changed, 169 insertions(+), 140 deletions(-) create mode 100644 java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java diff --git a/java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java b/java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java new file mode 100644 index 0000000000..46af4d7c51 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java @@ -0,0 +1,152 @@ +package com.baeldung.string.password; + +import java.security.SecureRandom; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.text.RandomStringGenerator; +import org.passay.CharacterData; +import org.passay.CharacterRule; +import org.passay.EnglishCharacterData; +import org.passay.PasswordGenerator; + +public class RandomPasswordGenerator { + + /** + * Special characters allowed in password. + */ + public static final String ALLOWED_SPL_CHARACTERS = "!@#$%^&*()_+"; + + public static final String ERROR_CODE = "ERRONEOUS_SPECIAL_CHARS"; + + Random random = new SecureRandom(); + + public String generatePassayPassword() { + PasswordGenerator gen = new PasswordGenerator(); + CharacterData lowerCaseChars = EnglishCharacterData.LowerCase; + CharacterRule lowerCaseRule = new CharacterRule(lowerCaseChars); + lowerCaseRule.setNumberOfCharacters(2); + CharacterData upperCaseChars = EnglishCharacterData.UpperCase; + CharacterRule upperCaseRule = new CharacterRule(upperCaseChars); + upperCaseRule.setNumberOfCharacters(2); + CharacterData digitChars = EnglishCharacterData.Digit; + CharacterRule digitRule = new CharacterRule(digitChars); + digitRule.setNumberOfCharacters(2); + CharacterData specialChars = new CharacterData() { + public String getErrorCode() { + return ERROR_CODE; + } + + public String getCharacters() { + return ALLOWED_SPL_CHARACTERS; + } + }; + CharacterRule splCharRule = new CharacterRule(specialChars); + splCharRule.setNumberOfCharacters(2); + String password = gen.generatePassword(10, splCharRule, lowerCaseRule, upperCaseRule, digitRule); + return password; + } + + public String generateCommonTextPassword() { + String pwString = generateRandomSpecialCharacters(2).concat(generateRandomNumbers(2)) + .concat(generateRandomAlphabet(2, true)) + .concat(generateRandomAlphabet(2, false)) + .concat(generateRandomCharacters(2)); + List pwChars = pwString.chars() + .mapToObj(data -> (char) data) + .collect(Collectors.toList()); + Collections.shuffle(pwChars); + String password = pwChars.stream() + .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) + .toString(); + return password; + } + + public String generateCommonsLang3Password() { + String upperCaseLetters = RandomStringUtils.random(2, 65, 90, true, true); + String lowerCaseLetters = RandomStringUtils.random(2, 97, 122, true, true); + String numbers = RandomStringUtils.randomNumeric(2); + String specialChar = RandomStringUtils.random(2, 33, 47, false, false); + String totalChars = RandomStringUtils.randomAlphanumeric(2); + String combinedChars = upperCaseLetters.concat(lowerCaseLetters) + .concat(numbers) + .concat(specialChar) + .concat(totalChars); + List pwdChars = combinedChars.chars() + .mapToObj(c -> (char) c) + .collect(Collectors.toList()); + Collections.shuffle(pwdChars); + String password = pwdChars.stream() + .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) + .toString(); + return password; + } + + public String generateSecureRandomPassword() { + Stream pwdStream = Stream.concat(getRandomNumbers(2), Stream.concat(getRandomSpecialChars(2), Stream.concat(getRandomAlphabets(2, true), getRandomAlphabets(4, false)))); + List charList = pwdStream.collect(Collectors.toList()); + Collections.shuffle(charList); + String password = charList.stream() + .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) + .toString(); + return password; + } + + public String generateRandomSpecialCharacters(int length) { + RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(33, 45) + .build(); + return pwdGenerator.generate(length); + } + + public String generateRandomNumbers(int length) { + RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57) + .build(); + return pwdGenerator.generate(length); + } + + public String generateRandomCharacters(int length) { + RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57) + .build(); + return pwdGenerator.generate(length); + } + + public String generateRandomAlphabet(int length, boolean lowerCase) { + int low; + int hi; + if (lowerCase) { + low = 97; + hi = 122; + } else { + low = 65; + hi = 90; + } + RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(low, hi) + .build(); + return pwdGenerator.generate(length); + } + + public Stream getRandomAlphabets(int count, boolean upperCase) { + IntStream characters = null; + if (upperCase) { + characters = random.ints(count, 65, 90); + } else { + characters = random.ints(count, 97, 122); + } + return characters.mapToObj(data -> (char) data); + } + + public Stream getRandomNumbers(int count) { + IntStream numbers = random.ints(count, 48, 57); + return numbers.mapToObj(data -> (char) data); + } + + public Stream getRandomSpecialChars(int count) { + IntStream specialChars = random.ints(count, 33, 45); + return specialChars.mapToObj(data -> (char) data); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java b/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java index 7a076b0e3f..bfd4b0fe8e 100644 --- a/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java @@ -1,187 +1,64 @@ package com.baeldung.string.password; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.Assert.assertTrue; -import java.security.SecureRandom; -import java.util.Collections; -import java.util.List; -import java.util.Random; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.text.RandomStringGenerator; import org.junit.Test; -import org.passay.CharacterData; -import org.passay.CharacterRule; -import org.passay.EnglishCharacterData; -import org.passay.PasswordGenerator; /** * Examples of passwords conforming to various specifications, using different libraries. * */ public class StringPasswordUnitTest { - /** - * Special characters allowed in password. - */ - public static final String ALLOWED_SPL_CHARACTERS = "!@#$%^&*()_+"; - public static final String ERROR_CODE = "ERRONEOUS_SPECIAL_CHARS"; - - Random random = new SecureRandom(); + RandomPasswordGenerator passGen = new RandomPasswordGenerator(); @Test public void whenPasswordGeneratedUsingPassay_thenSuccessful() { - PasswordGenerator gen = new PasswordGenerator(); - CharacterData lowerCaseChars = EnglishCharacterData.LowerCase; - CharacterRule lowerCaseRule = new CharacterRule(lowerCaseChars); - lowerCaseRule.setNumberOfCharacters(2); - CharacterData upperCaseChars = EnglishCharacterData.UpperCase; - CharacterRule upperCaseRule = new CharacterRule(upperCaseChars); - upperCaseRule.setNumberOfCharacters(2); - CharacterData digitChars = EnglishCharacterData.Digit; - CharacterRule digitRule = new CharacterRule(digitChars); - digitRule.setNumberOfCharacters(2); - CharacterData specialChars = new CharacterData() { - public String getErrorCode() { - return ERROR_CODE; - } - - public String getCharacters() { - return ALLOWED_SPL_CHARACTERS; - } - }; - CharacterRule splCharRule = new CharacterRule(specialChars); - splCharRule.setNumberOfCharacters(2); - String password = gen.generatePassword(10, splCharRule, lowerCaseRule, upperCaseRule, digitRule); + String password = passGen.generatePassayPassword(); int specialCharCount = 0; for (char c : password.toCharArray()) { if (c >= 33 || c <= 47) { specialCharCount++; } } - assertTrue(specialCharCount > 2); + assertTrue("Password validation failed in Passay", specialCharCount >= 2); } @Test public void whenPasswordGeneratedUsingCommonsText_thenSuccessful() { - String pwString = generateRandomSpecialCharacters(2).concat(generateRandomNumbers(2)) - .concat(generateRandomAlphabet(2, true)) - .concat(generateRandomAlphabet(2, false)) - .concat(generateRandomCharacters(2)); - List pwChars = pwString.chars() - .mapToObj(data -> (char) data) - .collect(Collectors.toList()); - Collections.shuffle(pwChars); - String password = pwChars.stream() - .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) - .toString(); - int specialCharCount = 0; + RandomPasswordGenerator passGen = new RandomPasswordGenerator(); + String password = passGen.generateCommonTextPassword(); + int lowerCaseCount = 0; for (char c : password.toCharArray()) { - if (c >= 33 || c <= 47) { - specialCharCount++; + if (c >= 97 || c <= 122) { + lowerCaseCount++; } } - assertTrue(specialCharCount > 2); + assertTrue("Password validation failed in commons-text ", lowerCaseCount >= 2); } @Test public void whenPasswordGeneratedUsingCommonsLang3_thenSuccessful() { - String upperCaseLetters = RandomStringUtils.random(2, 65, 90, true, true); - String lowerCaseLetters = RandomStringUtils.random(2, 97, 122, true, true); - String numbers = RandomStringUtils.randomNumeric(2); - String specialChar = RandomStringUtils.random(2, 33, 47, false, false); - String totalChars = RandomStringUtils.randomAlphanumeric(2); - String combinedChars = upperCaseLetters.concat(lowerCaseLetters) - .concat(numbers) - .concat(specialChar) - .concat(totalChars); - List pwdChars = combinedChars.chars() - .mapToObj(c -> (char) c) - .collect(Collectors.toList()); - Collections.shuffle(pwdChars); - String password = pwdChars.stream() - .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) - .toString(); - int specialCharCount = 0; + String password = passGen.generateCommonsLang3Password(); + int numCount = 0; for (char c : password.toCharArray()) { - if (c >= 33 || c <= 47) { - specialCharCount++; + if (c >= 48 || c <= 57) { + numCount++; } } - assertTrue(specialCharCount > 2); + assertTrue("Password validation failed in commons-lang3", numCount >= 2); } @Test public void whenPasswordGeneratedUsingSecureRandom_thenSuccessful() { - Stream pwdStream = Stream.concat(getRandomNumbers(2), Stream.concat(getRandomSpecialChars(2), Stream.concat(getRandomAlphabets(2, true), getRandomAlphabets(4, false)))); - List charList = pwdStream.collect(Collectors.toList()); - Collections.shuffle(charList); - String password = charList.stream() - .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) - .toString(); + String password = passGen.generateSecureRandomPassword(); int specialCharCount = 0; for (char c : password.toCharArray()) { if (c >= 33 || c <= 47) { specialCharCount++; } } - assertTrue(specialCharCount > 2); - } - - public String generateRandomSpecialCharacters(int length) { - RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(33, 45) - .build(); - return pwdGenerator.generate(length); - } - - public String generateRandomNumbers(int length) { - RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57) - .build(); - return pwdGenerator.generate(length); - } - - public String generateRandomCharacters(int length) { - RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57) - .build(); - return pwdGenerator.generate(length); - } - - public String generateRandomAlphabet(int length, boolean lowerCase) { - int low; - int hi; - if (lowerCase) { - low = 97; - hi = 122; - } else { - low = 65; - hi = 90; - } - RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(low, hi) - .build(); - return pwdGenerator.generate(length); - } - - public Stream getRandomAlphabets(int count, boolean upperCase) { - IntStream characters = null; - if (upperCase) { - characters = random.ints(count, 65, 90); - } else { - characters = random.ints(count, 97, 122); - } - return characters.mapToObj(data -> (char) data); - } - - public Stream getRandomNumbers(int count) { - IntStream numbers = random.ints(count, 48, 57); - return numbers.mapToObj(data -> (char) data); - } - - public Stream getRandomSpecialChars(int count) { - IntStream specialChars = random.ints(count, 33, 45); - return specialChars.mapToObj(data -> (char) data); + assertTrue("Password validation failed in Secure Random", specialCharCount >= 2); } } From a32cb1a48968e1a33fa0fa161b2c9d12a2eaf132 Mon Sep 17 00:00:00 2001 From: TINO Date: Sun, 18 Nov 2018 21:53:48 +0300 Subject: [PATCH 18/69] BAEL - 1511 --- rxjava-2/pom.xml | 8 ++ ...yncAndSyncToObservableIntegrationTest.java | 103 ++++++++++++++++++ 2 files changed, 111 insertions(+) create mode 100644 rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java diff --git a/rxjava-2/pom.xml b/rxjava-2/pom.xml index a18b096b6d..f437a6005b 100644 --- a/rxjava-2/pom.xml +++ b/rxjava-2/pom.xml @@ -34,6 +34,13 @@ rxrelay ${rxrelay.version} + + + com.github.akarnokd + rxjava2-extensions + ${rxjava2.ext.version} + + @@ -41,5 +48,6 @@ 2.2.2 1.7.0 2.0.0 + 0.20.4 \ No newline at end of file diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java new file mode 100644 index 0000000000..a646b453ff --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java @@ -0,0 +1,103 @@ +package com.baeldung.rxjava; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import hu.akarnokd.rxjava2.async.AsyncObservable; +import io.reactivex.Observable; + +public class AsyncAndSyncToObservableIntegrationTest { + + AtomicInteger counter = new AtomicInteger(); + Callable callable = () -> counter.incrementAndGet(); + + @Test + public void givenSyncMethod_whenConvertedWithFromCallable_thenReturnObservable() {// method will execute every time it gets subscribed + + Observable source = Observable.fromCallable(callable); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(i); + + assertEquals(i, counter.get()); + } + } + + @Test + public void givenSyncMethod_whenConvertedWithStart_thenReturnObservable() {// method will execute only once and cache its result. + + Observable source = AsyncObservable.start(callable); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + assertEquals(1, counter.get()); + } + } + + @Test + public void givenAsyncMethod_whenConvertedWithFromFuture_thenRetrunObservble() { // method will execute only once and cache its result. + + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future future = executor.submit(callable); + Observable source = Observable.fromFuture(future); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + assertEquals(1, counter.get()); + } + + executor.shutdown(); + } + + @Test + public void givenAsyncMethod_whenConvertedWithStartFuture_thenRetrunObservble() {// method will execute every time it gets subscribed + + ExecutorService executor = Executors.newSingleThreadExecutor(); + Observable source = AsyncObservable.startFuture(() -> executor.submit(callable)); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(i); + + assertEquals(i, counter.get()); + } + + executor.shutdown(); + } + + @Test + public void givenAsyncMethod_whenConvertedWithDeferFuture_thenRetrunObservble() { // method will execute only once and cache its result. + + List list = Arrays.asList(new Integer[] { counter.incrementAndGet(), counter.incrementAndGet(), counter.incrementAndGet() }); + ExecutorService exec = Executors.newSingleThreadExecutor(); + Callable> callable = () -> Observable.fromIterable(list); + Observable source = AsyncObservable.deferFuture(() -> exec.submit(callable)); + for (int i = 1; i < 4; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1, 2, 3); + } + + exec.shutdown(); + } + +} From 09261fb3b94b3bc2b67d3f1efd356769df9edad6 Mon Sep 17 00:00:00 2001 From: "akash.pandey" Date: Mon, 26 Nov 2018 23:02:44 +0530 Subject: [PATCH 19/69] BAEL-2393: Longest Sub-string without repeating characters. --- ...ongestSubstringNonRepeatingCharacters.java | 51 +++++++++++++++++++ ...stSubstringNonRepeatingCharactersTest.java | 20 ++++++++ 2 files changed, 71 insertions(+) create mode 100644 algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java create mode 100644 algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java new file mode 100644 index 0000000000..840b57cd78 --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java @@ -0,0 +1,51 @@ +package com.baeldung.algorithms.string; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class LongestSubstringNonRepeatingCharacters { + + public static String getNonRepeatingCharactersBruteForce(String input) { + String output = ""; + for (int start = 0; start < input.length(); start++) { + Set visited = new HashSet<>(); + int end = start; + for (; end < input.length(); end++) { + char currChar = input.charAt(end); + if (visited.contains(currChar)) { + break; + } else { + visited.add(currChar); + } + } + if (output.length() < end - start + 1) { + output = input.substring(start, end); + } + } + return output; + } + + public static String getNonRepeatingCharacters(String input) { + Map visited = new HashMap<>(); + String output = ""; + for (int start = 0, end = 0; end < input.length(); end++) { + char currChar = input.charAt(end); + if(visited.containsKey(currChar)) { + start = Math.max(visited.get(currChar)+1, start); + } + if(output.length() < end - start + 1) { + output = input.substring(start, end+1); + } + visited.put(currChar, end); + } + return output; + } + + public static void main(String[] args) { + String input = "CODINGISAWESOME"; + System.out.println(getNonRepeatingCharacters(input)); + } + +} diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java new file mode 100644 index 0000000000..a3e67362ad --- /dev/null +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java @@ -0,0 +1,20 @@ +package com.baeldung.algorithms.string; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class LongestSubstringNonRepeatingCharactersTest { + + @Test + void givenString_whenGetNonRepeatingCharactersBruteForceCalled_thenResultFoundAsExpected() { + String input = "CODINGISAWESOME"; + Assertions.assertEquals("NGISAWE", LongestSubstringNonRepeatingCharacters.getNonRepeatingCharactersBruteForce(input)); + } + + @Test + void givenString_whenGetNonRepeatingCharactersCalled_thenResultFoundAsExpected() { + String input = "CODINGISAWESOME"; + Assertions.assertEquals("NGISAWE",LongestSubstringNonRepeatingCharacters.getNonRepeatingCharacters(input)); + } + +} From f06a9f4106cff01c7de0b05b6d980dfc98533e7d Mon Sep 17 00:00:00 2001 From: Juan Moreno Date: Fri, 30 Nov 2018 01:30:19 -0300 Subject: [PATCH 20/69] Sample code for BAEL-2333 --- java-streams/pom.xml | 10 +- .../com/baeldung/stream/filter/Customer.java | 55 +++++++++ .../stream/filter/StreamFilterUnitTest.java | 115 ++++++++++++++++++ 3 files changed, 178 insertions(+), 2 deletions(-) create mode 100644 java-streams/src/main/java/com/baeldung/stream/filter/Customer.java create mode 100644 java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java diff --git a/java-streams/pom.xml b/java-streams/pom.xml index e4670c268d..2b52ebb4b3 100644 --- a/java-streams/pom.xml +++ b/java-streams/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 java-streams 0.1.0-SNAPSHOT @@ -74,6 +74,11 @@ aspectjweaver ${asspectj.version} + + pl.touk + throwing-function + ${throwing-function.version} + @@ -108,8 +113,9 @@ 1.15 0.6.5 2.10 + 1.3 - 3.6.1 + 3.11.1 1.8.9 diff --git a/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java b/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java new file mode 100644 index 0000000000..49da6e7175 --- /dev/null +++ b/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java @@ -0,0 +1,55 @@ +package com.baeldung.stream.filter; + +import javax.net.ssl.HttpsURLConnection; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +public class Customer { + private String name; + private int points; + private String profilePhotoUrl; + + public Customer(String name, int points) { + this(name, points, ""); + } + + public Customer(String name, int points, String profilePhotoUrl) { + this.name = name; + this.points = points; + this.profilePhotoUrl = profilePhotoUrl; + } + + public String getName() { + return name; + } + + public int getPoints() { + return points; + } + + public boolean hasOver(int points) { + return this.points > points; + } + + public boolean hasOverThousandPoints() { + return this.points > 100; + } + + public boolean hasValidProfilePhoto() throws IOException { + URL url = new URL(this.profilePhotoUrl); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + return connection.getResponseCode() == HttpURLConnection.HTTP_OK; + } + + public boolean hasValidProfilePhotoWithoutCheckedException() { + try { + URL url = new URL(this.profilePhotoUrl); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + return connection.getResponseCode() == HttpURLConnection.HTTP_OK; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java new file mode 100644 index 0000000000..c89a27cdf1 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java @@ -0,0 +1,115 @@ +package com.baeldung.stream.filter; + +import org.junit.jupiter.api.Test; +import pl.touk.throwing.ThrowingPredicate; +import pl.touk.throwing.exception.WrappedException; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +public class StreamFilterUnitTest { + + @Test + public void givenListOfCustomers_whenFilterByLambda_thenGetTwo() { + List customers = Arrays.asList(new Customer("John P.", 15), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), new Customer("Mary T.", 1)); + + long customersWithMoreThan100Points = customers + .stream() + .filter(c -> c.getPoints() > 100) + .count(); + + assertThat(customersWithMoreThan100Points).isEqualTo(2); + } + + @Test + public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() { + List customers = Arrays.asList(new Customer("John P.", 15), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), new Customer("Mary T.", 1)); + + long customersWithMoreThan100Points = customers + .stream() + .filter(Customer::hasOverThousandPoints) + .count(); + + assertThat(customersWithMoreThan100Points).isEqualTo(2); + } + + @Test + public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() { + List> customers = Arrays.asList(Optional.of(new Customer("John P.", 15)), Optional.of(new Customer("Sarah M.", 200)), Optional.empty(), Optional.of(new Customer("Mary T.", 300)), Optional.empty()); + + long customersWithMoreThan100Points = customers + .stream() + .flatMap(c -> c + .map(Stream::of) + .orElseGet(Stream::empty)) + .filter(Customer::hasOverThousandPoints) + .count(); + + assertThat(customersWithMoreThan100Points).isEqualTo(2); + } + + @Test + public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() { + List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), + new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + + assertThatThrownBy(() -> customers + .stream() + .filter(Customer::hasValidProfilePhotoWithoutCheckedException) + .count()).isInstanceOf(RuntimeException.class); + } + + @Test + public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() { + List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), + new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + + assertThatThrownBy(() -> customers + .stream() + .filter((ThrowingPredicate.unchecked(Customer::hasValidProfilePhoto))) + .count()).isInstanceOf(WrappedException.class); + } + + @Test + public void givenListOfCustomers_whenFilterWithTryCatch_thenGetTwo() { + List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), + new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + + long customersWithValidProfilePhoto = customers + .stream() + .filter(c -> { + try { + return c.hasValidProfilePhoto(); + } catch (IOException e) { + //handle exception + } + return false; + }) + .count(); + + assertThat(customersWithValidProfilePhoto).isEqualTo(2); + } + + @Test + public void givenListOfCustomers_whenFilterWithTryCatchAndRuntime_thenThrowException() { + List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), + new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + + assertThatThrownBy(() -> customers + .stream() + .filter(c -> { + try { + return c.hasValidProfilePhoto(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }) + .count()).isInstanceOf(RuntimeException.class); + } +} From ed0713046ffb3dad79611b87a753dad780fce618 Mon Sep 17 00:00:00 2001 From: "akash.pandey" Date: Sat, 1 Dec 2018 09:08:53 +0530 Subject: [PATCH 21/69] Renamed method names to replace "non-repeating" with "Unique". --- ...ongestSubstringNonRepeatingCharacters.java | 102 +++++++++--------- ...stSubstringNonRepeatingCharactersTest.java | 40 +++---- 2 files changed, 71 insertions(+), 71 deletions(-) diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java index 840b57cd78..51ae013cd6 100644 --- a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java @@ -1,51 +1,51 @@ -package com.baeldung.algorithms.string; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -public class LongestSubstringNonRepeatingCharacters { - - public static String getNonRepeatingCharactersBruteForce(String input) { - String output = ""; - for (int start = 0; start < input.length(); start++) { - Set visited = new HashSet<>(); - int end = start; - for (; end < input.length(); end++) { - char currChar = input.charAt(end); - if (visited.contains(currChar)) { - break; - } else { - visited.add(currChar); - } - } - if (output.length() < end - start + 1) { - output = input.substring(start, end); - } - } - return output; - } - - public static String getNonRepeatingCharacters(String input) { - Map visited = new HashMap<>(); - String output = ""; - for (int start = 0, end = 0; end < input.length(); end++) { - char currChar = input.charAt(end); - if(visited.containsKey(currChar)) { - start = Math.max(visited.get(currChar)+1, start); - } - if(output.length() < end - start + 1) { - output = input.substring(start, end+1); - } - visited.put(currChar, end); - } - return output; - } - - public static void main(String[] args) { - String input = "CODINGISAWESOME"; - System.out.println(getNonRepeatingCharacters(input)); - } - -} +package com.baeldung.algorithms.string; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class LongestSubstringNonRepeatingCharacters { + + public static String getUniqueCharacterSubstringBruteForce(String input) { + String output = ""; + for (int start = 0; start < input.length(); start++) { + Set visited = new HashSet<>(); + int end = start; + for (; end < input.length(); end++) { + char currChar = input.charAt(end); + if (visited.contains(currChar)) { + break; + } else { + visited.add(currChar); + } + } + if (output.length() < end - start + 1) { + output = input.substring(start, end); + } + } + return output; + } + + public static String getUniqueCharacterSubstring(String input) { + Map visited = new HashMap<>(); + String output = ""; + for (int start = 0, end = 0; end < input.length(); end++) { + char currChar = input.charAt(end); + if (visited.containsKey(currChar)) { + start = Math.max(visited.get(currChar) + 1, start); + } + if (output.length() < end - start + 1) { + output = input.substring(start, end + 1); + } + visited.put(currChar, end); + } + return output; + } + + public static void main(String[] args) { + String input = "CODINGISAWESOME"; + System.out.println(getUniqueCharacterSubstring(input)); + } + +} diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java index a3e67362ad..2d8e762dd1 100644 --- a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java @@ -1,20 +1,20 @@ -package com.baeldung.algorithms.string; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class LongestSubstringNonRepeatingCharactersTest { - - @Test - void givenString_whenGetNonRepeatingCharactersBruteForceCalled_thenResultFoundAsExpected() { - String input = "CODINGISAWESOME"; - Assertions.assertEquals("NGISAWE", LongestSubstringNonRepeatingCharacters.getNonRepeatingCharactersBruteForce(input)); - } - - @Test - void givenString_whenGetNonRepeatingCharactersCalled_thenResultFoundAsExpected() { - String input = "CODINGISAWESOME"; - Assertions.assertEquals("NGISAWE",LongestSubstringNonRepeatingCharacters.getNonRepeatingCharacters(input)); - } - -} +package com.baeldung.algorithms.string; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class LongestSubstringNonRepeatingCharactersTest { + + @Test + void givenString_whenGetUniqueCharacterSubstringBruteForceCalled_thenResultFoundAsExpected() { + String input = "CODINGISAWESOME"; + Assertions.assertEquals("NGISAWE", LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstringBruteForce(input)); + } + + @Test + void givenString_whenGetUniqueCharacterSubstringCalled_thenResultFoundAsExpected() { + String input = "CODINGISAWESOME"; + Assertions.assertEquals("NGISAWE",LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstring(input)); + } + +} From 6ced1260225e5f57006b66edad77db9802c22288 Mon Sep 17 00:00:00 2001 From: geroza Date: Fri, 30 Nov 2018 20:50:40 -0200 Subject: [PATCH 22/69] created parent-boot-2 copy, and point all projects to that new temporary parent pom --- azure/pom.xml | 4 +- jib/pom.xml | 4 +- parent-boot-2.0-temp/README.md | 1 + parent-boot-2.0-temp/pom.xml | 85 +++++++++++++++++++ parent-boot-2/pom.xml | 2 +- .../spring-boot-persistence/pom.xml | 4 +- persistence-modules/spring-data-jpa/pom.xml | 4 +- .../spring-data-keyvalue/pom.xml | 4 +- persistence-modules/spring-data-redis/pom.xml | 4 +- pom.xml | 5 ++ spring-5-data-reactive/pom.xml | 4 +- spring-5-mvc/pom.xml | 4 +- spring-5-reactive-client/pom.xml | 4 +- spring-5-reactive-security/pom.xml | 4 +- spring-5-reactive/pom.xml | 4 +- spring-5-security-oauth/pom.xml | 4 +- spring-5-security/pom.xml | 4 +- spring-5/pom.xml | 4 +- spring-all/pom.xml | 4 +- spring-boot-autoconfiguration/pom.xml | 4 +- spring-boot-bootstrap/pom.xml | 4 +- spring-boot-client/pom.xml | 4 +- spring-boot-ctx-fluent/pom.xml | 4 +- spring-boot-disable-console-logging/pom.xml | 4 +- spring-boot-jasypt/pom.xml | 4 +- spring-boot-mvc/pom.xml | 4 +- spring-boot-ops/pom.xml | 4 +- spring-boot-vue/pom.xml | 4 +- spring-boot/pom.xml | 4 +- .../etl/customer-mongodb-sink/pom.xml | 4 +- .../etl/customer-transform/pom.xml | 4 +- spring-cloud/spring-cloud-vault/pom.xml | 4 +- spring-data-rest/pom.xml | 4 +- spring-mvc-forms-thymeleaf/pom.xml | 4 +- spring-rest-angular/pom.xml | 4 +- spring-rest-query-language/pom.xml | 4 +- spring-rest-shell/pom.xml | 4 +- spring-rest-simple/pom.xml | 4 +- spring-rest-template/pom.xml | 4 +- spring-rest/pom.xml | 4 +- spring-resttemplate/pom.xml | 4 +- spring-security-mvc-boot/pom.xml | 4 +- spring-security-openid/pom.xml | 4 +- spring-security-sso/pom.xml | 4 +- spring-security-thymeleaf/pom.xml | 4 +- spring-session/spring-session-jdbc/pom.xml | 4 +- spring-vault/pom.xml | 4 +- spring-webflux-amqp/pom.xml | 4 +- vaadin/pom.xml | 4 +- vavr/pom.xml | 4 +- 50 files changed, 184 insertions(+), 93 deletions(-) create mode 100644 parent-boot-2.0-temp/README.md create mode 100644 parent-boot-2.0-temp/pom.xml diff --git a/azure/pom.xml b/azure/pom.xml index 555efeef70..04438710a0 100644 --- a/azure/pom.xml +++ b/azure/pom.xml @@ -10,10 +10,10 @@ Demo project for Spring Boot on Azure - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/jib/pom.xml b/jib/pom.xml index e71250f157..d7bdcf0b34 100644 --- a/jib/pom.xml +++ b/jib/pom.xml @@ -6,10 +6,10 @@ jib - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/parent-boot-2.0-temp/README.md b/parent-boot-2.0-temp/README.md new file mode 100644 index 0000000000..740848a470 --- /dev/null +++ b/parent-boot-2.0-temp/README.md @@ -0,0 +1 @@ +This pom will be ued only temporary until we migrate parent-boot-2 to 2.1.0 for ticket BAEL-10354 diff --git a/parent-boot-2.0-temp/pom.xml b/parent-boot-2.0-temp/pom.xml new file mode 100644 index 0000000000..9284e4af13 --- /dev/null +++ b/parent-boot-2.0-temp/pom.xml @@ -0,0 +1,85 @@ + + 4.0.0 + parent-boot-2.0-temp + 0.0.1-SNAPSHOT + pom + Temporary Parent for all Spring Boot 2.0.x modules + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + io.rest-assured + rest-assured + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + ${start-class} + + + + + + + + + + thin-jar + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.springframework.boot.experimental + spring-boot-thin-layout + ${thin.version} + + + + + + + + + + 3.1.0 + + 1.0.11.RELEASE + 2.0.5.RELEASE + + + + diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index 89afd79bf4..280d226e95 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -78,7 +78,7 @@ 3.1.0 1.0.11.RELEASE - 2.0.5.RELEASE + 2.1.1.RELEASE diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index 0ea42b1cb7..b717bec31f 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -9,10 +9,10 @@ spring-boot-persistence - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-2.0-temp diff --git a/persistence-modules/spring-data-jpa/pom.xml b/persistence-modules/spring-data-jpa/pom.xml index 786e587734..6674bab70d 100644 --- a/persistence-modules/spring-data-jpa/pom.xml +++ b/persistence-modules/spring-data-jpa/pom.xml @@ -8,10 +8,10 @@ spring-data-jpa - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-2.0-temp diff --git a/persistence-modules/spring-data-keyvalue/pom.xml b/persistence-modules/spring-data-keyvalue/pom.xml index 1fee0a88d4..ece59d5586 100644 --- a/persistence-modules/spring-data-keyvalue/pom.xml +++ b/persistence-modules/spring-data-keyvalue/pom.xml @@ -5,10 +5,10 @@ spring-data-keyvalue - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-2.0-temp diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 683f874b6c..0520d253a1 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -8,10 +8,10 @@ jar - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-2.0-temp diff --git a/pom.xml b/pom.xml index ef7a7f6b1d..1db3b5d519 100644 --- a/pom.xml +++ b/pom.xml @@ -324,6 +324,7 @@ parent-boot-1 parent-boot-2 + parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java @@ -513,6 +514,7 @@ parent-boot-1 parent-boot-2 + parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java @@ -870,6 +872,7 @@ parent-boot-1 parent-boot-2 + parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java @@ -1055,6 +1058,7 @@ parent-boot-1 parent-boot-2 + parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java @@ -1263,6 +1267,7 @@ parent-boot-1 parent-boot-2 + parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml index aa73cf11ae..53e46b526d 100644 --- a/spring-5-data-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -7,10 +7,10 @@ jar - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index f5346a0fa0..24b46e7d2c 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-2.0-temp 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 6e39743ed0..1f2c961cf0 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-2.0-temp 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-5-reactive-security/pom.xml b/spring-5-reactive-security/pom.xml index 3b64b9b3ac..93700b4262 100644 --- a/spring-5-reactive-security/pom.xml +++ b/spring-5-reactive-security/pom.xml @@ -12,9 +12,9 @@ com.baeldung - parent-boot-2 + parent-boot-2.0-temp 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index e903b57c4e..969e8a7617 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -12,9 +12,9 @@ com.baeldung - parent-boot-2 + parent-boot-2.0-temp 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-5-security-oauth/pom.xml b/spring-5-security-oauth/pom.xml index 59150a153f..142326757b 100644 --- a/spring-5-security-oauth/pom.xml +++ b/spring-5-security-oauth/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-2.0-temp 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-5-security/pom.xml b/spring-5-security/pom.xml index 763e505e51..916af7f629 100644 --- a/spring-5-security/pom.xml +++ b/spring-5-security/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-2.0-temp 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 293edb5bda..6337f7d417 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -12,9 +12,9 @@ com.baeldung - parent-boot-2 + parent-boot-2.0-temp 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 2dc4915bab..faddab6ea6 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -7,10 +7,10 @@ war - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-boot-autoconfiguration/pom.xml b/spring-boot-autoconfiguration/pom.xml index 1c3d8796ed..87418bd2c7 100644 --- a/spring-boot-autoconfiguration/pom.xml +++ b/spring-boot-autoconfiguration/pom.xml @@ -9,10 +9,10 @@ This is simple boot application demonstrating a custom auto-configuration - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index b5bf4bc7b6..4b0abd5f2e 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -8,10 +8,10 @@ spring-boot-bootstrap Demo project for Spring Boot - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-boot-client/pom.xml b/spring-boot-client/pom.xml index fc89931f79..282488c4b1 100644 --- a/spring-boot-client/pom.xml +++ b/spring-boot-client/pom.xml @@ -9,10 +9,10 @@ This is simple boot client application for Spring boot actuator test - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-boot-ctx-fluent/pom.xml b/spring-boot-ctx-fluent/pom.xml index b238374612..52139fec3c 100644 --- a/spring-boot-ctx-fluent/pom.xml +++ b/spring-boot-ctx-fluent/pom.xml @@ -8,10 +8,10 @@ jar - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-boot-disable-console-logging/pom.xml b/spring-boot-disable-console-logging/pom.xml index 63ed129347..c8c43ada7a 100644 --- a/spring-boot-disable-console-logging/pom.xml +++ b/spring-boot-disable-console-logging/pom.xml @@ -7,10 +7,10 @@ Projects for Disabling Spring Boot Console Logging tutorials - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-boot-jasypt/pom.xml b/spring-boot-jasypt/pom.xml index de0df92678..a1707b45b0 100644 --- a/spring-boot-jasypt/pom.xml +++ b/spring-boot-jasypt/pom.xml @@ -10,10 +10,10 @@ Demo project for Spring Boot - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index b219e53431..8191645d76 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -8,10 +8,10 @@ Module For Spring Boot MVC - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index 57779c3f8e..760fc69462 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -9,10 +9,10 @@ Demo project for Spring Boot - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-boot-vue/pom.xml b/spring-boot-vue/pom.xml index d581b11d68..919f3e0ff9 100644 --- a/spring-boot-vue/pom.xml +++ b/spring-boot-vue/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot Vue project - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 87c782b044..40caf4fb97 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -8,10 +8,10 @@ This is simple boot application for Spring boot actuator test - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-2.0-temp diff --git a/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml b/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml index 468d8e17d0..8eba820dfa 100644 --- a/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml +++ b/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml @@ -12,10 +12,10 @@ Example ETL Load Project - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-2 + ../../../parent-boot-2.0-temp diff --git a/spring-cloud-data-flow/etl/customer-transform/pom.xml b/spring-cloud-data-flow/etl/customer-transform/pom.xml index bc4b648907..821f06541f 100644 --- a/spring-cloud-data-flow/etl/customer-transform/pom.xml +++ b/spring-cloud-data-flow/etl/customer-transform/pom.xml @@ -13,10 +13,10 @@ Example transform ETL step - parent-boot-2 + parent-boot-2.0-temp com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-2 + ../../../parent-boot-2.0-temp diff --git a/spring-cloud/spring-cloud-vault/pom.xml b/spring-cloud/spring-cloud-vault/pom.xml index 68b8e44875..a19d7f3459 100644 --- a/spring-cloud/spring-cloud-vault/pom.xml +++ b/spring-cloud/spring-cloud-vault/pom.xml @@ -12,9 +12,9 @@ com.baeldung - parent-boot-2 + parent-boot-2.0-temp 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-2.0-temp + org.apache.maven.plugins maven-surefire-plugin @@ -143,14 +144,6 @@ methods true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - diff --git a/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java b/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java index ed163f7fa7..82a5fe083b 100644 --- a/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java +++ b/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java @@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfi import org.springframework.context.annotation.ComponentScan; @SpringBootApplication(exclude = SecurityAutoConfiguration.class) -@ComponentScan(basePackages = { "com.baeldung.execption" }) +@ComponentScan(basePackages = { "com.baeldung.exception" }) public class SpringExceptionApplication { public static void main(String[] args) { SpringApplication.run(SpringExceptionApplication.class, args); diff --git a/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java b/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java index 00fce06834..540992b4bc 100644 --- a/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java +++ b/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java @@ -6,12 +6,13 @@ import java.util.Collection; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.JsonbHttpMessageConverter; -@SpringBootApplication +@SpringBootApplication(exclude = SecurityAutoConfiguration.class) @ComponentScan(basePackages = { "com.baeldung.jsonb" }) public class Spring5Application { diff --git a/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java b/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java index 02332ee7b6..f512b52af4 100644 --- a/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java @@ -2,8 +2,9 @@ package com.baeldung.restdocs; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -@SpringBootApplication +@SpringBootApplication(exclude = SecurityAutoConfiguration.class) public class SpringRestDocsApplication { public static void main(String[] args) { diff --git a/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java b/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java index ecc677465e..8b9e66213f 100644 --- a/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java @@ -3,12 +3,10 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -@EnableJpaRepositories("com.baeldung.persistence") public class Example1IntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java b/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java index e1d56c2fc3..6ed53ca4e9 100644 --- a/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java @@ -3,12 +3,10 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -@EnableJpaRepositories("com.baeldung.persistence") public class Example2IntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java index fba01726f4..9c462e0412 100644 --- a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java @@ -1,12 +1,11 @@ package com.baeldung.functional; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; 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.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.context.support.GenericWebApplicationContext; @@ -14,7 +13,6 @@ import com.baeldung.Spring5Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5Application.class) -@EnableJpaRepositories("com.baeldung.persistence") public class BeanRegistrationIntegrationTest { @Autowired From baa628837597a9a6a21d6c1d2659ff8ec056e9e4 Mon Sep 17 00:00:00 2001 From: geroza Date: Mon, 3 Dec 2018 14:53:39 -0200 Subject: [PATCH 25/69] Migration of the following modules: * spring-5-mvc * spring-5-reactive --- spring-5-mvc/pom.xml | 4 +-- .../java/com/baeldung/Spring5Application.java | 3 +- .../springbootkotlin/KotlinDemoApplication.kt | 3 +- .../com/baeldung/LiveTest.java | 0 spring-5-reactive/pom.xml | 16 +++++----- ...java => ConsumerDebuggingApplication.java} | 6 ++-- ...n.java => ServerDebuggingApplication.java} | 6 ++-- .../FunctionalSpringBootApplication.java | 14 ++++----- .../reactive/Spring5ReactiveApplication.java | 2 -- .../CorsOnAnnotatedElementsApplication.java | 8 +++++ .../global/CorsGlobalConfigApplication.java | 8 +++++ ....java => CorsGlobalFunctionalHandler.java} | 2 +- .../routers/CorsRouterFunctions.java | 4 +-- .../webfilter/CorsWebFilterApplication.java | 9 ++++++ .../CorsWithWebFilterRouterFunctions.java | 2 +- .../consumer/ConsumerSSEApplication.java | 14 ++++++++- .../server/ServerSSEApplication.java | 16 ++++++++-- .../FunctionalValidationsApplication.java | 12 ++++++++ .../routers/ValidationsRouters.java | 2 +- .../configuration/WebFluxSecurityConfig.java | 8 ++--- ...nctionalWebApplicationIntegrationTest.java | 1 + ...g5ReactiveServerClientIntegrationTest.java | 30 +++++++++++-------- .../cors/CorsOnAnnotatedElementsLiveTest.java | 3 -- .../cors/CorsOnGlobalConfigLiveTest.java | 3 -- .../cors/CorsOnWebFilterLiveTest.java | 3 -- .../ErrorHandlingIntegrationTest.java | 2 ++ .../filters/PlayerHandlerIntegrationTest.java | 2 ++ .../UserControllerIntegrationTest.java | 2 ++ .../ResponseHeaderLiveTest.java | 3 -- .../ServiceSentEventLiveTest.java | 5 ++-- ...ernsUsingHandlerMethodIntegrationTest.java | 2 ++ ...FunctionalEndpointValidationsLiveTest.java | 3 -- .../client/WebTestClientIntegrationTest.java | 6 +++- 33 files changed, 131 insertions(+), 73 deletions(-) rename spring-5-mvc/src/test/{kotlin => java}/com/baeldung/LiveTest.java (100%) rename spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/{ConsumerSSEApplication.java => ConsumerDebuggingApplication.java} (80%) rename spring-5-reactive/src/main/java/com/baeldung/debugging/server/{ServerSSEApplication.java => ServerDebuggingApplication.java} (77%) rename spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/{FunctionalHandler.java => CorsGlobalFunctionalHandler.java} (93%) diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 24b46e7d2c..f5346a0fa0 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2.0-temp + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java index 8251467122..74a348dea6 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java +++ b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java @@ -4,10 +4,11 @@ import javax.servlet.Filter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; -@SpringBootApplication +@SpringBootApplication( exclude = SecurityAutoConfiguration.class) public class Spring5Application { public static void main(String[] args) { diff --git a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt b/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt index f95586af80..8904d8d805 100644 --- a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt +++ b/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt @@ -2,8 +2,9 @@ package com.baeldung.springbootkotlin import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration -@SpringBootApplication(scanBasePackages = arrayOf("com.baeldung.springbootkotlin")) +@SpringBootApplication(scanBasePackages = arrayOf("com.baeldung.springbootkotlin"), exclude = arrayOf(SecurityAutoConfiguration::class)) class KotlinDemoApplication fun main(args: Array) { diff --git a/spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java b/spring-5-mvc/src/test/java/com/baeldung/LiveTest.java similarity index 100% rename from spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java rename to spring-5-mvc/src/test/java/com/baeldung/LiveTest.java diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index 969e8a7617..ab64d1e2fa 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -12,9 +12,9 @@ com.baeldung - parent-boot-2.0-temp + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 @@ -75,6 +75,11 @@ spring-boot-starter-test test + + org.springframework.security + spring-security-test + test + @@ -116,12 +121,6 @@ ${project-reactor-test} test - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - @@ -145,7 +144,6 @@ 1.0 4.1 3.1.6.RELEASE - 1.2.0 diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerDebuggingApplication.java similarity index 80% rename from spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerSSEApplication.java rename to spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerDebuggingApplication.java index 55db3d7392..486c5e77eb 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerSSEApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerDebuggingApplication.java @@ -14,17 +14,17 @@ import reactor.core.publisher.Hooks; @SpringBootApplication(exclude = MongoReactiveAutoConfiguration.class) @EnableScheduling -public class ConsumerSSEApplication { +public class ConsumerDebuggingApplication { public static void main(String[] args) { Hooks.onOperatorDebug(); - SpringApplication app = new SpringApplication(ConsumerSSEApplication.class); + SpringApplication app = new SpringApplication(ConsumerDebuggingApplication.class); app.setDefaultProperties(Collections.singletonMap("server.port", "8082")); app.run(args); } @Bean - public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + public SecurityWebFilterChain debuggingConsumerSpringSecurityFilterChain(ServerHttpSecurity http) { http.authorizeExchange() .anyExchange() .permitAll(); diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerDebuggingApplication.java similarity index 77% rename from spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerSSEApplication.java rename to spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerDebuggingApplication.java index 6b24ee39f0..4fdc1dd137 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerSSEApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerDebuggingApplication.java @@ -11,16 +11,16 @@ import org.springframework.web.reactive.config.EnableWebFlux; @EnableWebFlux @SpringBootApplication -public class ServerSSEApplication { +public class ServerDebuggingApplication { public static void main(String[] args) { - SpringApplication app = new SpringApplication(ServerSSEApplication.class); + SpringApplication app = new SpringApplication(ServerDebuggingApplication.class); app.setDefaultProperties(Collections.singletonMap("server.port", "8081")); app.run(args); } @Bean - public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + public SecurityWebFilterChain debuggingServerSpringSecurityFilterChain(ServerHttpSecurity http) { http.authorizeExchange() .anyExchange() .permitAll(); diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java index a1d5d87d5c..9cbc1b7669 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java @@ -17,8 +17,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; import org.springframework.core.io.ClassPathResource; import org.springframework.http.server.reactive.HttpHandler; import org.springframework.web.reactive.function.server.RouterFunction; @@ -40,11 +38,14 @@ public class FunctionalSpringBootApplication { private RouterFunction routingFunction() { FormHandler formHandler = new FormHandler(); - RouterFunction restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) - .doOnNext(actors::add) - .then(ok().build())); + RouterFunction restfulRouter = route(GET("/"), + serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), + serverRequest -> serverRequest.bodyToMono(Actor.class) + .doOnNext(actors::add) + .then(ok().build())); - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin) + return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) + .andRoute(POST("/login"), formHandler::handleLogin) .andRoute(POST("/upload"), formHandler::handleUpload) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .andNest(path("/actor"), restfulRouter) @@ -68,5 +69,4 @@ public class FunctionalSpringBootApplication { public static void main(String[] args) { SpringApplication.run(FunctionalSpringBootApplication.class, args); } - } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java index 1656f70221..a8cd18c470 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java @@ -1,9 +1,7 @@ package com.baeldung.reactive; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; @SpringBootApplication public class Spring5ReactiveApplication{ diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java index d990928abe..69ae24b849 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java @@ -4,6 +4,9 @@ import java.util.Collections; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; @SpringBootApplication public class CorsOnAnnotatedElementsApplication { @@ -14,4 +17,9 @@ public class CorsOnAnnotatedElementsApplication { app.run(args); } + @Bean + public SecurityWebFilterChain corsAnnotatedSpringSecurityFilterChain(ServerHttpSecurity http) { + http.csrf().disable(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java index 8228944569..a70f937980 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java @@ -8,6 +8,9 @@ import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfigurat import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; @SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, @@ -22,4 +25,9 @@ public class CorsGlobalConfigApplication { app.run(args); } + @Bean + public SecurityWebFilterChain corsGlobalSpringSecurityFilterChain(ServerHttpSecurity http) { + http.csrf().disable(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java similarity index 93% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java index e6e32d7cc8..d2b7af29a6 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java @@ -7,7 +7,7 @@ import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; @Component -public class FunctionalHandler { +public class CorsGlobalFunctionalHandler { public Mono useHandler(final ServerRequest request) { final String responseMessage = "CORS GLOBAL CONFIG IS NOT EFFECTIVE ON FUNCTIONAL ENDPOINTS!!!"; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java index 19621a9e97..0a520828b9 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java @@ -8,13 +8,13 @@ import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; -import com.baeldung.reactive.cors.global.functional.handlers.FunctionalHandler; +import com.baeldung.reactive.cors.global.functional.handlers.CorsGlobalFunctionalHandler; @Configuration public class CorsRouterFunctions { @Bean - public RouterFunction responseHeaderRoute(@Autowired FunctionalHandler handler) { + public RouterFunction corsGlobalRouter(@Autowired CorsGlobalFunctionalHandler handler) { return RouterFunctions.route(RequestPredicates.PUT("/global-config-on-functional/cors-disabled-functional-endpoint"), handler::useHandler); } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java index 38140c0d71..7792975768 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java @@ -8,6 +8,9 @@ import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfigurat import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; @SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, @@ -21,5 +24,11 @@ public class CorsWebFilterApplication { app.setDefaultProperties(Collections.singletonMap("server.port", "8083")); app.run(args); } + + @Bean + public SecurityWebFilterChain corsWebfilterSpringSecurityFilterChain(ServerHttpSecurity http) { + http.csrf().disable(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java index a3905bb79f..6056b9bf5a 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java @@ -14,7 +14,7 @@ import com.baeldung.reactive.cors.webfilter.functional.handlers.CorsWithWebFilte public class CorsWithWebFilterRouterFunctions { @Bean - public RouterFunction responseHeaderRoute(@Autowired CorsWithWebFilterHandler handler) { + public RouterFunction corsWebfilterRouter(@Autowired CorsWithWebFilterHandler handler) { return RouterFunctions.route(RequestPredicates.PUT("/web-filter-on-functional/functional-endpoint"), handler::useHandler); } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java index 3997607ef0..d8edaf7fd5 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java @@ -4,9 +4,13 @@ import java.util.Collections; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; -@SpringBootApplication +@SpringBootApplication(exclude = { RedisReactiveAutoConfiguration.class }) @EnableAsync public class ConsumerSSEApplication { @@ -15,5 +19,13 @@ public class ConsumerSSEApplication { app.setDefaultProperties(Collections.singletonMap("server.port", "8082")); app.run(args); } + + @Bean + public SecurityWebFilterChain sseConsumerSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .permitAll(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java index 2750e6616d..c040b83da0 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java @@ -4,14 +4,26 @@ import java.util.Collections; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; -@SpringBootApplication +@SpringBootApplication(exclude = { RedisReactiveAutoConfiguration.class }) public class ServerSSEApplication { - + public static void main(String[] args) { SpringApplication app = new SpringApplication(ServerSSEApplication.class); app.setDefaultProperties(Collections.singletonMap("server.port", "8081")); app.run(args); } + @Bean + public SecurityWebFilterChain sseServerSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .permitAll(); + return http.build(); + } + } diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java index e548e33c85..4cbb65dc60 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java @@ -2,6 +2,9 @@ package com.baeldung.validations.functional; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; @SpringBootApplication public class FunctionalValidationsApplication { @@ -9,4 +12,13 @@ public class FunctionalValidationsApplication { public static void main(String[] args) { SpringApplication.run(FunctionalValidationsApplication.class, args); } + + @Bean + public SecurityWebFilterChain functionalValidationsSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .permitAll(); + http.csrf().disable(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java index efbdbe3f99..29582a0b0f 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java @@ -17,7 +17,7 @@ import com.baeldung.validations.functional.handlers.impl.OtherEntityValidationHa public class ValidationsRouters { @Bean - public RouterFunction responseHeaderRoute(@Autowired CustomRequestEntityValidationHandler dryHandler, + public RouterFunction validationsRouter(@Autowired CustomRequestEntityValidationHandler dryHandler, @Autowired FunctionalHandler complexHandler, @Autowired OtherEntityValidationHandler otherHandler, @Autowired AnnotatedRequestEntityValidationHandler annotatedEntityHandler) { diff --git a/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java b/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java index 452bcac8ab..61927e47ab 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java @@ -34,9 +34,8 @@ public class WebFluxSecurityConfig { } @Bean - public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http - .authorizeExchange() + public SecurityWebFilterChain webSessionSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() .anyExchange().authenticated() .and() .httpBasic() @@ -44,8 +43,7 @@ public class WebFluxSecurityConfig { .and() .formLogin(); - http - .csrf().disable(); + http.csrf().disable(); return http.build(); diff --git a/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java index 4dea2a05cf..1256d5f129 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java @@ -10,6 +10,7 @@ import org.springframework.boot.web.server.WebServer; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java index 5ebfa39358..b8dd9c9509 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java @@ -1,6 +1,10 @@ package com.baeldung.reactive; -import com.baeldung.web.reactive.Task; +import static org.springframework.web.reactive.function.server.RequestPredicates.GET; +import static org.springframework.web.reactive.function.server.RequestPredicates.POST; + +import java.time.Duration; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.springframework.http.server.reactive.HttpHandler; @@ -8,22 +12,22 @@ import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.web.reactive.Task; + import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import reactor.ipc.netty.NettyContext; -import reactor.ipc.netty.http.server.HttpServer; - -import java.time.Duration; - -import static org.springframework.web.reactive.function.server.RequestPredicates.GET; -import static org.springframework.web.reactive.function.server.RequestPredicates.POST; +import reactor.netty.DisposableServer; +import reactor.netty.http.server.HttpServer; public class Spring5ReactiveServerClientIntegrationTest { - private static NettyContext nettyContext; + private static DisposableServer disposableServer; @BeforeAll public static void setUp() throws Exception { - HttpServer server = HttpServer.create("localhost", 8080); + HttpServer server = HttpServer.create() + .host("localhost") + .port(8080); RouterFunction route = RouterFunctions.route(POST("/task/process"), request -> ServerResponse.ok() .body(request.bodyToFlux(Task.class) .map(ll -> new Task("TaskName", 1)), Task.class)) @@ -31,13 +35,13 @@ public class Spring5ReactiveServerClientIntegrationTest { .body(Mono.just("server is alive"), String.class))); HttpHandler httpHandler = RouterFunctions.toHttpHandler(route); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); - nettyContext = server.newHandler(adapter) - .block(); + disposableServer = server.handle(adapter) + .bindNow(); } @AfterAll public static void shutDown() { - nettyContext.dispose(); + disposableServer.disposeNow(); } // @Test diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java index 0043d62e5a..e6847e63da 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java @@ -2,13 +2,10 @@ package com.baeldung.reactive.cors; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CorsOnAnnotatedElementsLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java index 39927af4c3..008f1a16f2 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java @@ -2,13 +2,10 @@ package com.baeldung.reactive.cors; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CorsOnGlobalConfigLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java index e5a3c8a99a..f8a4f34e29 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java @@ -2,13 +2,10 @@ package com.baeldung.reactive.cors; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CorsOnWebFilterLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java index bea2eaa75f..10cfaffce4 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java @@ -8,11 +8,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) +@WithMockUser public class ErrorHandlingIntegrationTest { @Autowired diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java index bb2408ea79..fbf46a93cc 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java @@ -4,6 +4,7 @@ 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.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; @@ -12,6 +13,7 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@WithMockUser public class PlayerHandlerIntegrationTest { @Autowired diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java index e7d289e5c4..22991b298f 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java @@ -4,6 +4,7 @@ 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.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; @@ -12,6 +13,7 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@WithMockUser public class UserControllerIntegrationTest { @Autowired diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java index db563e27d1..927c52e7e6 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java @@ -2,13 +2,10 @@ package com.baeldung.reactive.responseheaders; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class ResponseHeaderLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java index 53f4a3b1bb..547cd99034 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java @@ -3,14 +3,13 @@ package com.baeldung.reactive.serversentsevents; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.WebTestClient; -@RunWith(JUnitPlatform.class) @SpringBootTest +@WithMockUser public class ServiceSentEventLiveTest { private WebTestClient client = WebTestClient.bindToServer() diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java index 9f31608ff7..d4c1cfe4c8 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java @@ -4,6 +4,7 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; @@ -12,6 +13,7 @@ import com.baeldung.reactive.controller.PathPatternController; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5ReactiveApplication.class) +@WithMockUser public class PathPatternsUsingHandlerMethodIntegrationTest { private static WebTestClient client; diff --git a/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java index 5fe764bf8f..73968cdf05 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java @@ -2,9 +2,7 @@ package com.baeldung.validations.functional; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; @@ -13,7 +11,6 @@ import com.baeldung.validations.functional.model.CustomRequestEntity; import reactor.core.publisher.Mono; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class FunctionalEndpointValidationsLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java index 08bd883b0b..2e37f2ffbd 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java @@ -1,10 +1,10 @@ package com.baeldung.web.client; -import com.baeldung.reactive.Spring5ReactiveApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.server.RequestPredicates; @@ -12,10 +12,14 @@ import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.server.WebHandler; + +import com.baeldung.reactive.Spring5ReactiveApplication; + import reactor.core.publisher.Mono; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5ReactiveApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@WithMockUser public class WebTestClientIntegrationTest { @LocalServerPort From b91f7e321e52ad8e2879862dca126ee31dec8e57 Mon Sep 17 00:00:00 2001 From: geroza Date: Mon, 3 Dec 2018 19:13:43 -0200 Subject: [PATCH 26/69] Migrated the following modules to parent-boot with spring-boot 2.1: * spring-5-reactive-client * spring-5-reactive-security * spring-5-security * spring-5-security-oauth * spring-all --- spring-5-reactive-client/pom.xml | 4 ++-- spring-5-reactive-security/pom.xml | 4 ++-- .../actuator/Spring5ReactiveApplication.java | 2 -- .../security/SpringSecurity5Application.java | 15 +++++++++------ spring-5-security-oauth/pom.xml | 4 ++-- spring-5-security/pom.xml | 6 +++--- .../resources/templatesextrafields/index.html | 2 +- spring-all/pom.xml | 4 ++-- 8 files changed, 21 insertions(+), 20 deletions(-) diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 1f2c961cf0..6e39743ed0 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2.0-temp + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-5-reactive-security/pom.xml b/spring-5-reactive-security/pom.xml index 93700b4262..3b64b9b3ac 100644 --- a/spring-5-reactive-security/pom.xml +++ b/spring-5-reactive-security/pom.xml @@ -12,9 +12,9 @@ com.baeldung - parent-boot-2.0-temp + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java index f07ddfb0f7..03943d436d 100644 --- a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java @@ -1,9 +1,7 @@ package com.baeldung.reactive.actuator; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; @SpringBootApplication public class Spring5ReactiveApplication{ diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java index f2963c4fa5..325923f577 100644 --- a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java @@ -8,8 +8,9 @@ import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.config.EnableWebFlux; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; -import reactor.ipc.netty.NettyContext; -import reactor.ipc.netty.http.server.HttpServer; + +import reactor.netty.DisposableServer; +import reactor.netty.http.server.HttpServer; @ComponentScan(basePackages = {"com.baeldung.reactive.security"}) @EnableWebFlux @@ -18,17 +19,19 @@ public class SpringSecurity5Application { public static void main(String[] args) { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringSecurity5Application.class)) { - context.getBean(NettyContext.class).onClose().block(); + context.getBean(DisposableServer.class).onDispose().block(); } } @Bean - public NettyContext nettyContext(ApplicationContext context) { + public DisposableServer disposableServer(ApplicationContext context) { HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context) .build(); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler); - HttpServer httpServer = HttpServer.create("localhost", 8080); - return httpServer.newHandler(adapter).block(); + HttpServer httpServer = HttpServer.create(); + httpServer.host("localhost"); + httpServer.port(8080); + return httpServer.handle(adapter).bindNow(); } } diff --git a/spring-5-security-oauth/pom.xml b/spring-5-security-oauth/pom.xml index 142326757b..59150a153f 100644 --- a/spring-5-security-oauth/pom.xml +++ b/spring-5-security-oauth/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2.0-temp + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-5-security/pom.xml b/spring-5-security/pom.xml index 916af7f629..c26e370381 100644 --- a/spring-5-security/pom.xml +++ b/spring-5-security/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2.0-temp + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 @@ -31,7 +31,7 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity4 + thymeleaf-extras-springsecurity5 org.springframework diff --git a/spring-5-security/src/main/resources/templatesextrafields/index.html b/spring-5-security/src/main/resources/templatesextrafields/index.html index 37833ff0d2..1dd9c12d42 100644 --- a/spring-5-security/src/main/resources/templatesextrafields/index.html +++ b/spring-5-security/src/main/resources/templatesextrafields/index.html @@ -1,5 +1,5 @@ - + Spring Security with Extra Fields diff --git a/spring-all/pom.xml b/spring-all/pom.xml index faddab6ea6..2dc4915bab 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -7,10 +7,10 @@ war - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 From 64acbeec4e3caee2e35079a3c29adb00244fcbdb Mon Sep 17 00:00:00 2001 From: geroza Date: Mon, 3 Dec 2018 21:38:12 -0200 Subject: [PATCH 27/69] Migrated modules to parent-boot with spring-boot 2.1: * spring-boot-persistence * persistence-modules/spring-data-jpa * persistence-modules/spring-data-keyvalue * persistence-modules/spring-data-redis --- .../spring-boot-persistence/pom.xml | 4 +-- persistence-modules/spring-data-jpa/pom.xml | 4 +-- .../config/PersistenceConfiguration.java | 33 +++++++++---------- .../src/main/resources/application.properties | 4 ++- .../resources/import_entities.sql | 0 .../SpringContextIntegrationTest.java | 5 --- .../SpringJpaContextIntegrationTest.java | 25 ++++++++++++++ .../spring-data-keyvalue/pom.xml | 4 +-- persistence-modules/spring-data-redis/pom.xml | 18 ++-------- 9 files changed, 52 insertions(+), 45 deletions(-) rename persistence-modules/spring-data-jpa/src/{test => main}/resources/import_entities.sql (100%) create mode 100644 persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringJpaContextIntegrationTest.java diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index b717bec31f..0ea42b1cb7 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -9,10 +9,10 @@ spring-boot-persistence - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-2.0-temp + ../../parent-boot-2 diff --git a/persistence-modules/spring-data-jpa/pom.xml b/persistence-modules/spring-data-jpa/pom.xml index 6674bab70d..786e587734 100644 --- a/persistence-modules/spring-data-jpa/pom.xml +++ b/persistence-modules/spring-data-jpa/pom.xml @@ -8,10 +8,10 @@ spring-data-jpa - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-2.0-temp + ../../parent-boot-2 diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java index 16407e510a..2bdd4e5451 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java @@ -1,13 +1,14 @@ package com.baeldung.config; -import com.baeldung.services.IBarService; -import com.baeldung.services.impl.BarSpringDataJpaService; -import com.google.common.base.Preconditions; -import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; -import com.baeldung.services.IFooService; -import com.baeldung.services.impl.FooService; +import java.util.Properties; + +import javax.sql.DataSource; + import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.*; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; @@ -20,13 +21,15 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import javax.sql.DataSource; -import java.util.Properties; +import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; +import com.baeldung.services.IBarService; +import com.baeldung.services.impl.BarSpringDataJpaService; +import com.google.common.base.Preconditions; @Configuration -@ComponentScan({"com.baeldung.dao", "com.baeldung.services"}) +@ComponentScan({ "com.baeldung.dao", "com.baeldung.services" }) @EnableTransactionManagement -@EnableJpaRepositories(basePackages = {"com.baeldung.dao"}, repositoryBaseClass = ExtendedRepositoryImpl.class) +@EnableJpaRepositories(basePackages = { "com.baeldung.dao" }, repositoryBaseClass = ExtendedRepositoryImpl.class) @EnableJpaAuditing @PropertySource("classpath:persistence.properties") public class PersistenceConfiguration { @@ -79,11 +82,6 @@ public class PersistenceConfiguration { return new BarSpringDataJpaService(); } - @Bean - public IFooService fooService() { - return new FooService(); - } - private final Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); @@ -94,7 +92,8 @@ public class PersistenceConfiguration { // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); // Envers properties - hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); + hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", + env.getProperty("envers.audit_table_suffix")); return hibernateProperties; } diff --git a/persistence-modules/spring-data-jpa/src/main/resources/application.properties b/persistence-modules/spring-data-jpa/src/main/resources/application.properties index 73d72bc7d6..37fb9ca9c4 100644 --- a/persistence-modules/spring-data-jpa/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa/src/main/resources/application.properties @@ -12,4 +12,6 @@ hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory -spring.datasource.data=import_entities.sql \ No newline at end of file +spring.datasource.data=import_entities.sql + +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/test/resources/import_entities.sql b/persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql similarity index 100% rename from persistence-modules/spring-data-jpa/src/test/resources/import_entities.sql rename to persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql diff --git a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 0a60412813..7f906bdbcd 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -2,17 +2,12 @@ package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.Application; -import com.baeldung.config.PersistenceConfiguration; -import com.baeldung.config.PersistenceProductConfiguration; -import com.baeldung.config.PersistenceUserConfiguration; @RunWith(SpringRunner.class) -@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class}) @SpringBootTest(classes = Application.class) public class SpringContextIntegrationTest { diff --git a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringJpaContextIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringJpaContextIntegrationTest.java new file mode 100644 index 0000000000..66b5b20b97 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringJpaContextIntegrationTest.java @@ -0,0 +1,25 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; + +@RunWith(SpringRunner.class) +@DataJpaTest(excludeAutoConfiguration = { + PersistenceConfiguration.class, + PersistenceUserConfiguration.class, + PersistenceProductConfiguration.class }) +@ContextConfiguration(classes = Application.class) +public class SpringJpaContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-keyvalue/pom.xml b/persistence-modules/spring-data-keyvalue/pom.xml index ece59d5586..1fee0a88d4 100644 --- a/persistence-modules/spring-data-keyvalue/pom.xml +++ b/persistence-modules/spring-data-keyvalue/pom.xml @@ -5,10 +5,10 @@ spring-data-keyvalue - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-2.0-temp + ../../parent-boot-2 diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 0520d253a1..fb80b0413f 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -8,10 +8,10 @@ jar - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-2.0-temp + ../../parent-boot-2 @@ -47,21 +47,9 @@ org.junit.jupiter junit-jupiter-api - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - org.junit.platform junit-platform-runner - ${junit.platform.version} test @@ -97,8 +85,6 @@ 0.10.0 2.0.3.RELEASE 0.6 - 1.0.0 - 5.0.2 From 127c3eca04034f8098162bf37d1b8e1c03802c8d Mon Sep 17 00:00:00 2001 From: TINO Date: Tue, 4 Dec 2018 22:31:10 +0300 Subject: [PATCH 28/69] Code formatted --- rxjava-2/pom.xml | 94 +++++++++---------- ...yncAndSyncToObservableIntegrationTest.java | 16 ++-- 2 files changed, 57 insertions(+), 53 deletions(-) diff --git a/rxjava-2/pom.xml b/rxjava-2/pom.xml index f437a6005b..3038c20037 100644 --- a/rxjava-2/pom.xml +++ b/rxjava-2/pom.xml @@ -1,53 +1,53 @@ - - 4.0.0 + + 4.0.0 - rxjava-2 - 1.0-SNAPSHOT + rxjava-2 + 1.0-SNAPSHOT - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + - - - io.reactivex.rxjava2 - rxjava - ${rx.java2.version} - - - com.jayway.awaitility - awaitility - ${awaitility.version} - - - org.assertj - assertj-core - ${assertj.version} - - - com.jakewharton.rxrelay2 - rxrelay - ${rxrelay.version} - - - - com.github.akarnokd - rxjava2-extensions - ${rxjava2.ext.version} - - - + + + io.reactivex.rxjava2 + rxjava + ${rx.java2.version} + + + com.jayway.awaitility + awaitility + ${awaitility.version} + + + org.assertj + assertj-core + ${assertj.version} + + + com.jakewharton.rxrelay2 + rxrelay + ${rxrelay.version} + + + + com.github.akarnokd + rxjava2-extensions + ${rxjava2.ext.version} + + - - 3.8.0 - 2.2.2 - 1.7.0 - 2.0.0 - 0.20.4 - + + 3.8.0 + 2.2.2 + 1.7.0 + 2.0.0 + 0.20.4 + \ No newline at end of file diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java index a646b453ff..90f4fe94ae 100644 --- a/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java @@ -21,8 +21,9 @@ public class AsyncAndSyncToObservableIntegrationTest { AtomicInteger counter = new AtomicInteger(); Callable callable = () -> counter.incrementAndGet(); + /* Method will execute every time it gets subscribed*/ @Test - public void givenSyncMethod_whenConvertedWithFromCallable_thenReturnObservable() {// method will execute every time it gets subscribed + public void givenSyncMethod_whenConvertedWithFromCallable_thenReturnObservable() { Observable source = Observable.fromCallable(callable); @@ -35,8 +36,9 @@ public class AsyncAndSyncToObservableIntegrationTest { } } + /* Method will execute only once and cache its result.*/ @Test - public void givenSyncMethod_whenConvertedWithStart_thenReturnObservable() {// method will execute only once and cache its result. + public void givenSyncMethod_whenConvertedWithStart_thenReturnObservable() { Observable source = AsyncObservable.start(callable); @@ -49,8 +51,9 @@ public class AsyncAndSyncToObservableIntegrationTest { } } + /* Method will execute only once and cache its result.*/ @Test - public void givenAsyncMethod_whenConvertedWithFromFuture_thenRetrunObservble() { // method will execute only once and cache its result. + public void givenAsyncMethod_whenConvertedWithFromFuture_thenRetrunObservble() { ExecutorService executor = Executors.newSingleThreadExecutor(); Future future = executor.submit(callable); @@ -67,8 +70,9 @@ public class AsyncAndSyncToObservableIntegrationTest { executor.shutdown(); } + /* Method will execute every time it gets subscribed*/ @Test - public void givenAsyncMethod_whenConvertedWithStartFuture_thenRetrunObservble() {// method will execute every time it gets subscribed + public void givenAsyncMethod_whenConvertedWithStartFuture_thenRetrunObservble() { ExecutorService executor = Executors.newSingleThreadExecutor(); Observable source = AsyncObservable.startFuture(() -> executor.submit(callable)); @@ -84,9 +88,9 @@ public class AsyncAndSyncToObservableIntegrationTest { executor.shutdown(); } + /*Method will execute only once and cache its result.*/ @Test - public void givenAsyncMethod_whenConvertedWithDeferFuture_thenRetrunObservble() { // method will execute only once and cache its result. - + public void givenAsyncMethod_whenConvertedWithDeferFuture_thenRetrunObservble() { List list = Arrays.asList(new Integer[] { counter.incrementAndGet(), counter.incrementAndGet(), counter.incrementAndGet() }); ExecutorService exec = Executors.newSingleThreadExecutor(); Callable> callable = () -> Observable.fromIterable(list); From 744283db802a4019bd4e8aaeb545aa25cc314fb3 Mon Sep 17 00:00:00 2001 From: "akash.pandey" Date: Wed, 5 Dec 2018 10:07:06 +0530 Subject: [PATCH 29/69] Updated UnitTest name. --- .../string/LongestSubstringNonRepeatingCharactersTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java index 2150be2532..5c732ad134 100644 --- a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java @@ -9,7 +9,7 @@ import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharact public class LongestSubstringNonRepeatingCharactersTest { @Test - void givenString_whenGetUniqueCharacterSubstringBruteForceCalled_thenResultFoundAsExpected() { + void givenString_whenGetUniqueCharacterSubstringBruteForceCalled_thenResultFoundAsExpectedUnitTest() { assertEquals("", getUniqueCharacterSubstringBruteForce("")); assertEquals("A", getUniqueCharacterSubstringBruteForce("A")); assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("AABCDEF")); @@ -19,7 +19,7 @@ public class LongestSubstringNonRepeatingCharactersTest { } @Test - void givenString_whenGetUniqueCharacterSubstringCalled_thenResultFoundAsExpected() { + void givenString_whenGetUniqueCharacterSubstringCalled_thenResultFoundAsExpectedUnitTest() { assertEquals("", getUniqueCharacterSubstring("")); assertEquals("A", getUniqueCharacterSubstring("A")); assertEquals("ABCDEF", getUniqueCharacterSubstring("AABCDEF")); From 9fa39257e4ca61f3d0405e15c7e8ccead6da3d20 Mon Sep 17 00:00:00 2001 From: "akash.pandey" Date: Thu, 6 Dec 2018 08:38:51 +0530 Subject: [PATCH 30/69] PMD Fix: Update Test file name --- ...t.java => LongestSubstringNonRepeatingCharactersUnitTest.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/{LongestSubstringNonRepeatingCharactersTest.java => LongestSubstringNonRepeatingCharactersUnitTest.java} (100%) diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java similarity index 100% rename from algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java From 11f4a4aee053fa9139de9e28ddb92e092427d41d Mon Sep 17 00:00:00 2001 From: "akash.pandey" Date: Thu, 6 Dec 2018 08:43:21 +0530 Subject: [PATCH 31/69] PMD Fix : Renamed Unit Test --- .../string/LongestSubstringNonRepeatingCharactersUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java index 5c732ad134..9f1e6a2519 100644 --- a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java @@ -6,7 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstring; import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstringBruteForce; -public class LongestSubstringNonRepeatingCharactersTest { +public class LongestSubstringNonRepeatingCharactersUnitTest { @Test void givenString_whenGetUniqueCharacterSubstringBruteForceCalled_thenResultFoundAsExpectedUnitTest() { From 7f5789c274788a2ca15025fc3fc7f66adb1db0e9 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Thu, 6 Dec 2018 13:30:59 +0330 Subject: [PATCH 32/69] Added a simple function for bytecode inspection. --- .../kotlin/com/baeldung/functions/Inline.kt | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/functions/Inline.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/functions/Inline.kt b/core-kotlin/src/main/kotlin/com/baeldung/functions/Inline.kt new file mode 100644 index 0000000000..239c425c03 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/functions/Inline.kt @@ -0,0 +1,28 @@ +package com.baeldung.functions + +import kotlin.random.Random + +/** + * An extension function on all collections to apply a function to all collection + * elements. + */ +fun Collection.each(block: (T) -> Unit) { + for (e in this) block(e) +} + +/** + * In order to see the the JVM bytecode: + * 1. Compile the Kotlin file using `kotlinc Inline.kt` + * 2. Take a peek at the bytecode using the `javap -c InlineKt` + */ +fun main() { + val numbers = listOf(1, 2, 3, 4, 5) + val random = random() + + numbers.each { println(random * it) } // capturing the random variable +} + +/** + * Generates a random number. + */ +private fun random(): Int = Random.nextInt() \ No newline at end of file From dec5eabe81a7063ac5cdc5deeb64e46eb8673d0f Mon Sep 17 00:00:00 2001 From: clininger Date: Thu, 6 Dec 2018 23:09:43 +0700 Subject: [PATCH 33/69] BAELDUNG-2283 --- rsocket/pom.xml | 54 +++++++++ .../com/baeldung/rsocket/ChannelClient.java | 33 ++++++ .../baeldung/rsocket/FireNForgetClient.java | 86 ++++++++++++++ .../com/baeldung/rsocket/ReqResClient.java | 32 ++++++ .../com/baeldung/rsocket/ReqStreamClient.java | 33 ++++++ .../java/com/baeldung/rsocket/Server.java | 107 ++++++++++++++++++ .../baeldung/rsocket/support/Constants.java | 10 ++ .../rsocket/support/GameController.java | 84 ++++++++++++++ .../rsocket/support/WindDataPublisher.java | 31 +++++ rsocket/src/main/resources/logback.xml | 13 +++ .../rsocket/RSocketIntegrationTest.java | 71 ++++++++++++ 11 files changed, 554 insertions(+) create mode 100644 rsocket/pom.xml create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/Server.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java create mode 100644 rsocket/src/main/resources/logback.xml create mode 100644 rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java diff --git a/rsocket/pom.xml b/rsocket/pom.xml new file mode 100644 index 0000000000..8b04a31583 --- /dev/null +++ b/rsocket/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + rsocket + 0.0.1-SNAPSHOT + rsocket + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + jar + + + + io.rsocket + rsocket-core + 0.11.13 + + + io.rsocket + rsocket-transport-netty + 0.11.13 + + + junit + junit + 4.12 + test + + + org.hamcrest + hamcrest-core + 1.3 + test + + + ch.qos.logback + logback-classic + 1.2.3 + + + ch.qos.logback + logback-core + 1.2.3 + + + org.slf4j + slf4j-api + 1.7.25 + + + \ No newline at end of file diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java new file mode 100644 index 0000000000..9f26384c95 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java @@ -0,0 +1,33 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import com.baeldung.rsocket.support.GameController; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import reactor.core.publisher.Flux; + +public class ChannelClient { + + private final RSocket socket; + private final GameController gameController; + + public ChannelClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + + this.gameController = new GameController("Client Player"); + } + + public void playGame() { + socket.requestChannel(Flux.from(gameController)) + .doOnNext(gameController::processPayload) + .blockLast(); + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java new file mode 100644 index 0000000000..61d6173b23 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java @@ -0,0 +1,86 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import io.rsocket.util.DefaultPayload; +import java.nio.ByteBuffer; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Flux; + +public class FireNForgetClient { + + private static final Logger LOG = LoggerFactory.getLogger(FireNForgetClient.class); + + private final RSocket socket; + private final List data; + + public FireNForgetClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + this.data = Collections.unmodifiableList(generateData()); + } + + /** + * Send binary velocity (float) every 50ms + */ + public void sendData() { + Flux.interval(Duration.ofMillis(50)) + .take(data.size()) + .map(this::createFloatPayload) + .map(socket::fireAndForget) + .flatMap(Function.identity()) + .blockLast(); + } + + /** + * Create a binary payload containing a single float value + * + * @param index Index into the data list + * @return Payload ready to send to the server + */ + private Payload createFloatPayload(Long index) { + float velocity = data.get(index.intValue()); + ByteBuffer buffer = ByteBuffer.allocate(4).putFloat(velocity); + buffer.rewind(); + return DefaultPayload.create(buffer); + } + + /** + * Generate sample data + * + * @return List of random floats + */ + private List generateData() { + List dataList = new ArrayList<>(WIND_DATA_LENGTH); + float velocity = 0; + for (int i = 0; i < WIND_DATA_LENGTH; i++) { + velocity += Math.random(); + dataList.add(velocity); + } + return dataList; + } + + /** + * Get the data used for this client. + * + * @return list of data values + */ + public List getData() { + return data; + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java new file mode 100644 index 0000000000..8865acd995 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java @@ -0,0 +1,32 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import io.rsocket.util.DefaultPayload; + +public class ReqResClient { + + private final RSocket socket; + + public ReqResClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + } + + public String callBlocking(String string) { + return socket + .requestResponse(DefaultPayload.create(string)) + .map(Payload::getDataUtf8) + .onErrorReturn(ERROR_MSG) + .block(); + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java new file mode 100644 index 0000000000..eaab777c15 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java @@ -0,0 +1,33 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import io.rsocket.util.DefaultPayload; +import reactor.core.publisher.Flux; + +public class ReqStreamClient { + + private final RSocket socket; + + public ReqStreamClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + } + + public Flux getDataStream() { + return socket + .requestStream(DefaultPayload.create(WIND_DATA_STREAM_NAME)) + .map(Payload::getData) + .map(buf -> buf.getFloat()) + .onErrorReturn(null); + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/Server.java b/rsocket/src/main/java/com/baeldung/rsocket/Server.java new file mode 100644 index 0000000000..9cec3c69c8 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/Server.java @@ -0,0 +1,107 @@ +package com.baeldung.rsocket; + +import com.baeldung.rsocket.support.WindDataPublisher; +import static com.baeldung.rsocket.support.Constants.*; +import com.baeldung.rsocket.support.GameController; +import io.rsocket.AbstractRSocket; +import io.rsocket.Payload; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.server.TcpServerTransport; +import org.reactivestreams.Publisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.Disposable; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class Server { + + private static final Logger LOG = LoggerFactory.getLogger(Server.class); + + private final Disposable server; + private final WindDataPublisher windDataPublisher = new WindDataPublisher(); + private final GameController gameController; + + public Server() { + this.server = RSocketFactory.receive() + .acceptor((setupPayload, reactiveSocket) -> Mono.just(new RSocketImpl())) + .transport(TcpServerTransport.create("localhost", TCP_PORT)) + .start() + .doOnNext(x -> LOG.info("Server started")) + .subscribe(); + + this.gameController = new GameController("Server Player"); + } + + public void dispose() { + windDataPublisher.complete(); + this.server.dispose(); + } + + /** + * RSocket implementation + */ + private class RSocketImpl extends AbstractRSocket { + + /** + * Handle Request/Response messages + * + * @param payload Message payload + * @return payload response + */ + @Override + public Mono requestResponse(Payload payload) { + try { + return Mono.just(payload); // reflect the payload back to the sender + } catch (Exception x) { + return Mono.error(x); + } + } + + /** + * Handle Fire-and-Forget messages + * + * @param payload Message payload + * @return nothing + */ + @Override + public Mono fireAndForget(Payload payload) { + try { + windDataPublisher.publish(payload); // forward the payload + return Mono.empty(); + } catch (Exception x) { + return Mono.error(x); + } + } + + /** + * Handle Request/Stream messages. Each request returns a new stream. + * + * @param payload Payload that can be used to determine which stream to return + * @return Flux stream containing simulated wind speed data + */ + @Override + public Flux requestStream(Payload payload) { + String streamName = payload.getDataUtf8(); + if (WIND_DATA_STREAM_NAME.equals(streamName)) { + return Flux.from(windDataPublisher); + } + return Flux.error(new IllegalArgumentException(streamName)); + } + + /** + * Handle request for bidirectional channel + * + * @param payloads Stream of payloads delivered from the client + * @return + */ + @Override + public Flux requestChannel(Publisher payloads) { + Flux.from(payloads) + .subscribe(gameController::processPayload); + Flux channel = Flux.from(gameController); + return channel; + } + } + +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java b/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java new file mode 100644 index 0000000000..01bb374b4e --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java @@ -0,0 +1,10 @@ +package com.baeldung.rsocket.support; + +public interface Constants { + + int TCP_PORT = 7101; + String ERROR_MSG = "error"; + int WIND_DATA_LENGTH = 30; + String WIND_DATA_STREAM_NAME = "wind-data"; + int SHOT_COUNT = 10; +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java b/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java new file mode 100644 index 0000000000..35b6fe4b95 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java @@ -0,0 +1,84 @@ +package com.baeldung.rsocket.support; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.util.DefaultPayload; +import java.util.List; +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Flux; + +public class GameController implements Publisher { + + private static final Logger LOG = LoggerFactory.getLogger(GameController.class); + + private final String playerName; + private final List shots; + private Subscriber subscriber; + private boolean truce = false; + + public GameController(String playerName) { + this.playerName = playerName; + this.shots = generateShotList(); + } + + /** + * Create a random list of time intervals, 0-1000ms + * + * @return List of time intervals + */ + private List generateShotList() { + return Flux.range(1, SHOT_COUNT) + .map(x -> (long) Math.ceil(Math.random() * 1000)) + .collectList() + .block(); + } + + @Override + public void subscribe(Subscriber subscriber) { + this.subscriber = subscriber; + fireAtWill(); + } + + /** + * Publish game events asynchronously + */ + private void fireAtWill() { + new Thread(() -> { + for (Long shotDelay : shots) { + try { Thread.sleep(shotDelay); } catch (Exception x) {} + if (truce) { + break; + } + LOG.info("{}: bang!", playerName); + subscriber.onNext(DefaultPayload.create("bang!")); + } + if (!truce) { + LOG.info("{}: I give up!", playerName); + subscriber.onNext(DefaultPayload.create("I give up")); + } + subscriber.onComplete(); + }).start(); + } + + /** + * Process events from the opponent + * + * @param payload Payload received from the rSocket + */ + public void processPayload(Payload payload) { + String message = payload.getDataUtf8(); + switch (message) { + case "bang!": + String result = Math.random() < 0.5 ? "Haha missed!" : "Ow!"; + LOG.info("{}: {}", playerName, result); + break; + case "I give up": + truce = true; + LOG.info("{}: OK, truce", playerName); + break; + } + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java b/rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java new file mode 100644 index 0000000000..2ad5b5144b --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java @@ -0,0 +1,31 @@ +package com.baeldung.rsocket.support; + +import io.rsocket.Payload; +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; + +/** + * Simple PUblisher to provide async data to Flux stream + */ +public class WindDataPublisher implements Publisher { + + private Subscriber subscriber; + + @Override + public void subscribe(Subscriber subscriber) { + this.subscriber = subscriber; + } + + public void publish(Payload payload) { + if (subscriber != null) { + subscriber.onNext(payload); + } + } + + public void complete() { + if (subscriber != null) { + subscriber.onComplete(); + } + } + +} diff --git a/rsocket/src/main/resources/logback.xml b/rsocket/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/rsocket/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java b/rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java new file mode 100644 index 0000000000..8f2d4a9ffd --- /dev/null +++ b/rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java @@ -0,0 +1,71 @@ +package com.baeldung.rsocket; + +import java.util.List; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.Disposable; + +public class RSocketIntegrationTest { + + private static final Logger LOG = LoggerFactory.getLogger(RSocketIntegrationTest.class); + + private static Server server; + + public RSocketIntegrationTest() { + } + + @BeforeClass + public static void setUpClass() { + server = new Server(); + } + + @AfterClass + public static void tearDownClass() { + server.dispose(); + } + + @Test + public void testRequestResponse() { + ReqResClient client = new ReqResClient(); + String string = "Hello RSocket"; + assertEquals(string, client.callBlocking(string)); + client.dispose(); + } + + @Test + public void testFNFAndRequestStream() { + // create the client that pushes data to the server and start sending + FireNForgetClient fnfClient = new FireNForgetClient(); + // get the data that is used by the client + List data = fnfClient.getData(); + + // create a client to read a stream from the server and subscribe to events + ReqStreamClient streamClient = new ReqStreamClient(); + // assert that the data received is the same as the data sent + Disposable subscription = streamClient.getDataStream() + .index() + .doOnNext(element -> assertEquals(data.get(element.getT1().intValue()), element.getT2())) + .count() + .subscribe(count -> assertEquals(data.size(), count.intValue())); + + // start sending the data + fnfClient.sendData(); + + // wait a short time for the data to complete then dispose everything + try { Thread.sleep(500); } catch (Exception x) {} + subscription.dispose(); + fnfClient.dispose(); + } + + @Test + public void testChannel() { + ChannelClient client = new ChannelClient(); + client.playGame(); + client.dispose(); + } + +} From 291ba89004008aaf83cf198e9a582e8840ca9e97 Mon Sep 17 00:00:00 2001 From: pandachris Date: Thu, 6 Dec 2018 23:14:05 +0700 Subject: [PATCH 34/69] BAELDUNG-2283 (#6) --- rsocket/pom.xml | 54 +++++++++ .../com/baeldung/rsocket/ChannelClient.java | 33 ++++++ .../baeldung/rsocket/FireNForgetClient.java | 86 ++++++++++++++ .../com/baeldung/rsocket/ReqResClient.java | 32 ++++++ .../com/baeldung/rsocket/ReqStreamClient.java | 33 ++++++ .../java/com/baeldung/rsocket/Server.java | 107 ++++++++++++++++++ .../baeldung/rsocket/support/Constants.java | 10 ++ .../rsocket/support/GameController.java | 84 ++++++++++++++ .../rsocket/support/WindDataPublisher.java | 31 +++++ rsocket/src/main/resources/logback.xml | 13 +++ .../rsocket/RSocketIntegrationTest.java | 71 ++++++++++++ 11 files changed, 554 insertions(+) create mode 100644 rsocket/pom.xml create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/Server.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java create mode 100644 rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java create mode 100644 rsocket/src/main/resources/logback.xml create mode 100644 rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java diff --git a/rsocket/pom.xml b/rsocket/pom.xml new file mode 100644 index 0000000000..8b04a31583 --- /dev/null +++ b/rsocket/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + rsocket + 0.0.1-SNAPSHOT + rsocket + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + jar + + + + io.rsocket + rsocket-core + 0.11.13 + + + io.rsocket + rsocket-transport-netty + 0.11.13 + + + junit + junit + 4.12 + test + + + org.hamcrest + hamcrest-core + 1.3 + test + + + ch.qos.logback + logback-classic + 1.2.3 + + + ch.qos.logback + logback-core + 1.2.3 + + + org.slf4j + slf4j-api + 1.7.25 + + + \ No newline at end of file diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java new file mode 100644 index 0000000000..9f26384c95 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java @@ -0,0 +1,33 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import com.baeldung.rsocket.support.GameController; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import reactor.core.publisher.Flux; + +public class ChannelClient { + + private final RSocket socket; + private final GameController gameController; + + public ChannelClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + + this.gameController = new GameController("Client Player"); + } + + public void playGame() { + socket.requestChannel(Flux.from(gameController)) + .doOnNext(gameController::processPayload) + .blockLast(); + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java new file mode 100644 index 0000000000..61d6173b23 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java @@ -0,0 +1,86 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import io.rsocket.util.DefaultPayload; +import java.nio.ByteBuffer; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Flux; + +public class FireNForgetClient { + + private static final Logger LOG = LoggerFactory.getLogger(FireNForgetClient.class); + + private final RSocket socket; + private final List data; + + public FireNForgetClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + this.data = Collections.unmodifiableList(generateData()); + } + + /** + * Send binary velocity (float) every 50ms + */ + public void sendData() { + Flux.interval(Duration.ofMillis(50)) + .take(data.size()) + .map(this::createFloatPayload) + .map(socket::fireAndForget) + .flatMap(Function.identity()) + .blockLast(); + } + + /** + * Create a binary payload containing a single float value + * + * @param index Index into the data list + * @return Payload ready to send to the server + */ + private Payload createFloatPayload(Long index) { + float velocity = data.get(index.intValue()); + ByteBuffer buffer = ByteBuffer.allocate(4).putFloat(velocity); + buffer.rewind(); + return DefaultPayload.create(buffer); + } + + /** + * Generate sample data + * + * @return List of random floats + */ + private List generateData() { + List dataList = new ArrayList<>(WIND_DATA_LENGTH); + float velocity = 0; + for (int i = 0; i < WIND_DATA_LENGTH; i++) { + velocity += Math.random(); + dataList.add(velocity); + } + return dataList; + } + + /** + * Get the data used for this client. + * + * @return list of data values + */ + public List getData() { + return data; + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java new file mode 100644 index 0000000000..8865acd995 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java @@ -0,0 +1,32 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import io.rsocket.util.DefaultPayload; + +public class ReqResClient { + + private final RSocket socket; + + public ReqResClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + } + + public String callBlocking(String string) { + return socket + .requestResponse(DefaultPayload.create(string)) + .map(Payload::getDataUtf8) + .onErrorReturn(ERROR_MSG) + .block(); + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java new file mode 100644 index 0000000000..eaab777c15 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java @@ -0,0 +1,33 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import io.rsocket.util.DefaultPayload; +import reactor.core.publisher.Flux; + +public class ReqStreamClient { + + private final RSocket socket; + + public ReqStreamClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + } + + public Flux getDataStream() { + return socket + .requestStream(DefaultPayload.create(WIND_DATA_STREAM_NAME)) + .map(Payload::getData) + .map(buf -> buf.getFloat()) + .onErrorReturn(null); + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/Server.java b/rsocket/src/main/java/com/baeldung/rsocket/Server.java new file mode 100644 index 0000000000..9cec3c69c8 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/Server.java @@ -0,0 +1,107 @@ +package com.baeldung.rsocket; + +import com.baeldung.rsocket.support.WindDataPublisher; +import static com.baeldung.rsocket.support.Constants.*; +import com.baeldung.rsocket.support.GameController; +import io.rsocket.AbstractRSocket; +import io.rsocket.Payload; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.server.TcpServerTransport; +import org.reactivestreams.Publisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.Disposable; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class Server { + + private static final Logger LOG = LoggerFactory.getLogger(Server.class); + + private final Disposable server; + private final WindDataPublisher windDataPublisher = new WindDataPublisher(); + private final GameController gameController; + + public Server() { + this.server = RSocketFactory.receive() + .acceptor((setupPayload, reactiveSocket) -> Mono.just(new RSocketImpl())) + .transport(TcpServerTransport.create("localhost", TCP_PORT)) + .start() + .doOnNext(x -> LOG.info("Server started")) + .subscribe(); + + this.gameController = new GameController("Server Player"); + } + + public void dispose() { + windDataPublisher.complete(); + this.server.dispose(); + } + + /** + * RSocket implementation + */ + private class RSocketImpl extends AbstractRSocket { + + /** + * Handle Request/Response messages + * + * @param payload Message payload + * @return payload response + */ + @Override + public Mono requestResponse(Payload payload) { + try { + return Mono.just(payload); // reflect the payload back to the sender + } catch (Exception x) { + return Mono.error(x); + } + } + + /** + * Handle Fire-and-Forget messages + * + * @param payload Message payload + * @return nothing + */ + @Override + public Mono fireAndForget(Payload payload) { + try { + windDataPublisher.publish(payload); // forward the payload + return Mono.empty(); + } catch (Exception x) { + return Mono.error(x); + } + } + + /** + * Handle Request/Stream messages. Each request returns a new stream. + * + * @param payload Payload that can be used to determine which stream to return + * @return Flux stream containing simulated wind speed data + */ + @Override + public Flux requestStream(Payload payload) { + String streamName = payload.getDataUtf8(); + if (WIND_DATA_STREAM_NAME.equals(streamName)) { + return Flux.from(windDataPublisher); + } + return Flux.error(new IllegalArgumentException(streamName)); + } + + /** + * Handle request for bidirectional channel + * + * @param payloads Stream of payloads delivered from the client + * @return + */ + @Override + public Flux requestChannel(Publisher payloads) { + Flux.from(payloads) + .subscribe(gameController::processPayload); + Flux channel = Flux.from(gameController); + return channel; + } + } + +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java b/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java new file mode 100644 index 0000000000..01bb374b4e --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java @@ -0,0 +1,10 @@ +package com.baeldung.rsocket.support; + +public interface Constants { + + int TCP_PORT = 7101; + String ERROR_MSG = "error"; + int WIND_DATA_LENGTH = 30; + String WIND_DATA_STREAM_NAME = "wind-data"; + int SHOT_COUNT = 10; +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java b/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java new file mode 100644 index 0000000000..35b6fe4b95 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java @@ -0,0 +1,84 @@ +package com.baeldung.rsocket.support; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.util.DefaultPayload; +import java.util.List; +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Flux; + +public class GameController implements Publisher { + + private static final Logger LOG = LoggerFactory.getLogger(GameController.class); + + private final String playerName; + private final List shots; + private Subscriber subscriber; + private boolean truce = false; + + public GameController(String playerName) { + this.playerName = playerName; + this.shots = generateShotList(); + } + + /** + * Create a random list of time intervals, 0-1000ms + * + * @return List of time intervals + */ + private List generateShotList() { + return Flux.range(1, SHOT_COUNT) + .map(x -> (long) Math.ceil(Math.random() * 1000)) + .collectList() + .block(); + } + + @Override + public void subscribe(Subscriber subscriber) { + this.subscriber = subscriber; + fireAtWill(); + } + + /** + * Publish game events asynchronously + */ + private void fireAtWill() { + new Thread(() -> { + for (Long shotDelay : shots) { + try { Thread.sleep(shotDelay); } catch (Exception x) {} + if (truce) { + break; + } + LOG.info("{}: bang!", playerName); + subscriber.onNext(DefaultPayload.create("bang!")); + } + if (!truce) { + LOG.info("{}: I give up!", playerName); + subscriber.onNext(DefaultPayload.create("I give up")); + } + subscriber.onComplete(); + }).start(); + } + + /** + * Process events from the opponent + * + * @param payload Payload received from the rSocket + */ + public void processPayload(Payload payload) { + String message = payload.getDataUtf8(); + switch (message) { + case "bang!": + String result = Math.random() < 0.5 ? "Haha missed!" : "Ow!"; + LOG.info("{}: {}", playerName, result); + break; + case "I give up": + truce = true; + LOG.info("{}: OK, truce", playerName); + break; + } + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java b/rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java new file mode 100644 index 0000000000..2ad5b5144b --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java @@ -0,0 +1,31 @@ +package com.baeldung.rsocket.support; + +import io.rsocket.Payload; +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; + +/** + * Simple PUblisher to provide async data to Flux stream + */ +public class WindDataPublisher implements Publisher { + + private Subscriber subscriber; + + @Override + public void subscribe(Subscriber subscriber) { + this.subscriber = subscriber; + } + + public void publish(Payload payload) { + if (subscriber != null) { + subscriber.onNext(payload); + } + } + + public void complete() { + if (subscriber != null) { + subscriber.onComplete(); + } + } + +} diff --git a/rsocket/src/main/resources/logback.xml b/rsocket/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/rsocket/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java b/rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java new file mode 100644 index 0000000000..8f2d4a9ffd --- /dev/null +++ b/rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java @@ -0,0 +1,71 @@ +package com.baeldung.rsocket; + +import java.util.List; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.Disposable; + +public class RSocketIntegrationTest { + + private static final Logger LOG = LoggerFactory.getLogger(RSocketIntegrationTest.class); + + private static Server server; + + public RSocketIntegrationTest() { + } + + @BeforeClass + public static void setUpClass() { + server = new Server(); + } + + @AfterClass + public static void tearDownClass() { + server.dispose(); + } + + @Test + public void testRequestResponse() { + ReqResClient client = new ReqResClient(); + String string = "Hello RSocket"; + assertEquals(string, client.callBlocking(string)); + client.dispose(); + } + + @Test + public void testFNFAndRequestStream() { + // create the client that pushes data to the server and start sending + FireNForgetClient fnfClient = new FireNForgetClient(); + // get the data that is used by the client + List data = fnfClient.getData(); + + // create a client to read a stream from the server and subscribe to events + ReqStreamClient streamClient = new ReqStreamClient(); + // assert that the data received is the same as the data sent + Disposable subscription = streamClient.getDataStream() + .index() + .doOnNext(element -> assertEquals(data.get(element.getT1().intValue()), element.getT2())) + .count() + .subscribe(count -> assertEquals(data.size(), count.intValue())); + + // start sending the data + fnfClient.sendData(); + + // wait a short time for the data to complete then dispose everything + try { Thread.sleep(500); } catch (Exception x) {} + subscription.dispose(); + fnfClient.dispose(); + } + + @Test + public void testChannel() { + ChannelClient client = new ChannelClient(); + client.playGame(); + client.dispose(); + } + +} From 31741530ddc52b3df9754ae6a0552c19c10af84c Mon Sep 17 00:00:00 2001 From: clininger Date: Thu, 6 Dec 2018 23:48:18 +0700 Subject: [PATCH 35/69] Indentation changes --- .../java/com/baeldung/rsocket/ChannelClient.java | 10 +++++----- .../com/baeldung/rsocket/FireNForgetClient.java | 16 ++++++++-------- .../java/com/baeldung/rsocket/ReqResClient.java | 14 +++++++------- .../com/baeldung/rsocket/ReqStreamClient.java | 14 +++++++------- .../main/java/com/baeldung/rsocket/Server.java | 12 ++++++------ .../baeldung/rsocket/support/GameController.java | 6 +++--- 6 files changed, 36 insertions(+), 36 deletions(-) diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java index 9f26384c95..f35d337427 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java @@ -14,17 +14,17 @@ public class ChannelClient { public ChannelClient() { this.socket = RSocketFactory.connect() - .transport(TcpClientTransport.create("localhost", TCP_PORT)) - .start() - .block(); + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); this.gameController = new GameController("Client Player"); } public void playGame() { socket.requestChannel(Flux.from(gameController)) - .doOnNext(gameController::processPayload) - .blockLast(); + .doOnNext(gameController::processPayload) + .blockLast(); } public void dispose() { diff --git a/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java index 61d6173b23..6c7362a008 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java @@ -25,9 +25,9 @@ public class FireNForgetClient { public FireNForgetClient() { this.socket = RSocketFactory.connect() - .transport(TcpClientTransport.create("localhost", TCP_PORT)) - .start() - .block(); + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); this.data = Collections.unmodifiableList(generateData()); } @@ -36,11 +36,11 @@ public class FireNForgetClient { */ public void sendData() { Flux.interval(Duration.ofMillis(50)) - .take(data.size()) - .map(this::createFloatPayload) - .map(socket::fireAndForget) - .flatMap(Function.identity()) - .blockLast(); + .take(data.size()) + .map(this::createFloatPayload) + .map(socket::fireAndForget) + .flatMap(Function.identity()) + .blockLast(); } /** diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java index 8865acd995..fff196a580 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java @@ -13,17 +13,17 @@ public class ReqResClient { public ReqResClient() { this.socket = RSocketFactory.connect() - .transport(TcpClientTransport.create("localhost", TCP_PORT)) - .start() - .block(); + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); } public String callBlocking(String string) { return socket - .requestResponse(DefaultPayload.create(string)) - .map(Payload::getDataUtf8) - .onErrorReturn(ERROR_MSG) - .block(); + .requestResponse(DefaultPayload.create(string)) + .map(Payload::getDataUtf8) + .onErrorReturn(ERROR_MSG) + .block(); } public void dispose() { diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java index eaab777c15..e97192bdf0 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java @@ -14,17 +14,17 @@ public class ReqStreamClient { public ReqStreamClient() { this.socket = RSocketFactory.connect() - .transport(TcpClientTransport.create("localhost", TCP_PORT)) - .start() - .block(); + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); } public Flux getDataStream() { return socket - .requestStream(DefaultPayload.create(WIND_DATA_STREAM_NAME)) - .map(Payload::getData) - .map(buf -> buf.getFloat()) - .onErrorReturn(null); + .requestStream(DefaultPayload.create(WIND_DATA_STREAM_NAME)) + .map(Payload::getData) + .map(buf -> buf.getFloat()) + .onErrorReturn(null); } public void dispose() { diff --git a/rsocket/src/main/java/com/baeldung/rsocket/Server.java b/rsocket/src/main/java/com/baeldung/rsocket/Server.java index 9cec3c69c8..b5718ab36d 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/Server.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/Server.java @@ -24,11 +24,11 @@ public class Server { public Server() { this.server = RSocketFactory.receive() - .acceptor((setupPayload, reactiveSocket) -> Mono.just(new RSocketImpl())) - .transport(TcpServerTransport.create("localhost", TCP_PORT)) - .start() - .doOnNext(x -> LOG.info("Server started")) - .subscribe(); + .acceptor((setupPayload, reactiveSocket) -> Mono.just(new RSocketImpl())) + .transport(TcpServerTransport.create("localhost", TCP_PORT)) + .start() + .doOnNext(x -> LOG.info("Server started")) + .subscribe(); this.gameController = new GameController("Server Player"); } @@ -98,7 +98,7 @@ public class Server { @Override public Flux requestChannel(Publisher payloads) { Flux.from(payloads) - .subscribe(gameController::processPayload); + .subscribe(gameController::processPayload); Flux channel = Flux.from(gameController); return channel; } diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java b/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java index 35b6fe4b95..bc1bc0f861 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java @@ -31,9 +31,9 @@ public class GameController implements Publisher { */ private List generateShotList() { return Flux.range(1, SHOT_COUNT) - .map(x -> (long) Math.ceil(Math.random() * 1000)) - .collectList() - .block(); + .map(x -> (long) Math.ceil(Math.random() * 1000)) + .collectList() + .block(); } @Override From 7a7561fb7647306f02a260dcfc1bd416174066fa Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Thu, 6 Dec 2018 22:32:30 +0530 Subject: [PATCH 36/69] Remove corrupted/invalid/stray projects - Removed ethereumj, events, spring-boot-h2, spring-hibernate3 corrupted projects - Moved files from spring-hibernate3 folder to spring-hibernate-3 --- ethereumj/src/main/resources/logback.xml | 13 ------------- ...0638124c-9a1b-4d25-8fce-cc223d472e77.events | Bin 663 -> 0 bytes ...d2ba9cbe-1a44-428e-a710-13b1bdc67c4b.events | Bin 675 -> 0 bytes events/README.md | 1 - ...bf420ffc-0c3b-403e-bb8c-66cf499c773e.events | Bin 714 -> 0 bytes ...e72a057b-adea-4c69-83a0-0431318823e7.events | Bin 714 -> 0 bytes .../baeldung/SpringContextIntegrationTest.java | 17 ----------------- .../spring-hibernate-3/README.md | 1 + .../spring/PersistenceConfigHibernate3.java | 0 ...rnateExceptionScen1MainIntegrationTest.java | 2 -- ...rnateExceptionScen2MainIntegrationTest.java | 2 -- .../spring-hibernate3/README.md | 2 -- .../src/main/resources/logback.xml | 13 ------------- .../src/main/resources/logback.xml | 13 ------------- 14 files changed, 1 insertion(+), 63 deletions(-) delete mode 100644 ethereumj/src/main/resources/logback.xml delete mode 100644 events/MessagesAggregate/0638124c-9a1b-4d25-8fce-cc223d472e77.events delete mode 100644 events/MessagesAggregate/d2ba9cbe-1a44-428e-a710-13b1bdc67c4b.events delete mode 100644 events/README.md delete mode 100644 events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events delete mode 100644 events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events delete mode 100644 persistence-modules/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename persistence-modules/{spring-hibernate3 => spring-hibernate-3}/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java (100%) rename persistence-modules/{spring-hibernate3 => spring-hibernate-3}/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java (98%) rename persistence-modules/{spring-hibernate3 => spring-hibernate-3}/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java (98%) delete mode 100644 persistence-modules/spring-hibernate3/README.md delete mode 100644 persistence-modules/spring-hibernate3/src/main/resources/logback.xml delete mode 100644 spring-5-reactive-functional/src/main/resources/logback.xml diff --git a/ethereumj/src/main/resources/logback.xml b/ethereumj/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/ethereumj/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/events/MessagesAggregate/0638124c-9a1b-4d25-8fce-cc223d472e77.events b/events/MessagesAggregate/0638124c-9a1b-4d25-8fce-cc223d472e77.events deleted file mode 100644 index d3ce8b9cea0dd432ac369a37c2281c78d9b98a7e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 663 zcmbV|O-jT-5QW>lR}iwuMzoUZpQL+2la094g?NEVcV!%K5-_dI0X&Q6bPV`|2s5#k zkM~|ZJ|S`wRy{gK;D8;Ns1!I899XF=>B?F{Db5s13#b9>d#M{$Hxi55sSA`1qR6q< zPAU^%MRG2w!1aM41f_H|R^De`pnD?D4^6&f`hoWKAlfhgLaqndeHZ@*_YUaJ B!ZiQ@ diff --git a/events/MessagesAggregate/d2ba9cbe-1a44-428e-a710-13b1bdc67c4b.events b/events/MessagesAggregate/d2ba9cbe-1a44-428e-a710-13b1bdc67c4b.events deleted file mode 100644 index 2ab0ec469f90efe0f09ac43380e620738125a0ce..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 675 zcmbV|%}T>S6otpVuOMX6O|dtbJ2TECVTcP6+_;gxz@3@fT4)<+Qf>D>kxytW_=5Zfq;`tB*0x5>wYHZMYbnJj zsX$c>3`oX+Q6&R8lz=*5NYT1zg7~;eY*%?8UZ(AOp3|;f=lsO$zRT~q>uAn58>XJq z?R$6_z4}uojbEhZFGRi=ioWMv-`w$X*-o;@_BmU0*}mOwvPApqtcI~K4h>(N#4vE5 z`xW;DiFzs;Ax2t87g9)2&YT7lm4b>Z1IcKL<)Ar*@VjYa^gm3WiSaSy2c~bDUyf@2 P?4RiPsJpMnKgGQPZ1>2E diff --git a/events/README.md b/events/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/events/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events b/events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events deleted file mode 100644 index d805fc253e397456a33c8b6b1d5de5b42af14043..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 714 zcmbV|zfQw25QojqD0Xq?%h7JV7VWa4wZIZDKbZ8x1G`)uw4yLanf^6zW@SR)}or zljN9E01U!|L_y$v7eJ|yq%lEjLF~66b z`0zFTPJP(3GQBN1=5_2(;j;D5v5j;H`(amxJoS%6aZ&Oj=0$lP4z~WgwDoy7^AFc{ zq~ajD;_9BUWowLYNlS==&&Fbh(3#YL);uXqE^5>LuU(_KK>HOtfjN)6Eggw}KSBIa O>O%GB!p#bgm3{(Qui1M5 diff --git a/events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events b/events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events deleted file mode 100644 index 3d67b74ced4494b9f3af4f38b6bef9622c565329..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 714 zcmbWzJx&8L5CveCo(s|90)j+6E}nP~`%%_5>nj*HK~+N8vP_jRk>3B#IU(=vG1IB*R{7Y%t8QQRn$EuaQ$R#GmsTG+NS5^qs15XGEZ zMQGa|C^3PFjR&U*0gaYgI;S+Z;&&kCq3VgZ>1BMX=q-;Gzw%fP)hgfTW#Qp&&r~=) ze7%0BKEhd - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-5-reactive-functional/src/main/resources/logback.xml b/spring-5-reactive-functional/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-5-reactive-functional/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file From ddeb2dd5abd0862b299b4bfc7984b5002e844e74 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Thu, 6 Dec 2018 23:54:56 +0530 Subject: [PATCH 37/69] BAEL-10877 Fix build of micronaut project - Version upgraded, now using the standard maven central - API changes per the new library in ConcreteGreetingClient and GreetingClient --- micronaut/pom.xml | 11 +++-------- .../helloworld/client/ConcreteGreetingClient.java | 2 +- .../micronaut/helloworld/client/GreetingClient.java | 5 +---- 3 files changed, 5 insertions(+), 13 deletions(-) diff --git a/micronaut/pom.xml b/micronaut/pom.xml index 7b722306b6..aa69c77f73 100644 --- a/micronaut/pom.xml +++ b/micronaut/pom.xml @@ -7,15 +7,10 @@ com.baeldung.micronaut.helloworld.server.ServerApplication - 1.0.0.M2 - 9 + 1.0.0.RC2 + 1.8 - - - jcenter.bintray.com - http://jcenter.bintray.com - - + diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java index d4051cef52..96bc51f235 100644 --- a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java @@ -1,7 +1,7 @@ package com.baeldung.micronaut.helloworld.client; import io.micronaut.http.HttpRequest; -import io.micronaut.http.client.Client; +import io.micronaut.http.client.annotation.Client; import io.micronaut.http.client.RxHttpClient; import io.reactivex.Single; diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java index 8a691d5b06..d29a97fd50 100644 --- a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java @@ -1,10 +1,7 @@ package com.baeldung.micronaut.helloworld.client; import io.micronaut.http.annotation.Get; -import io.micronaut.http.client.Client; -import io.micronaut.http.client.RxHttpClient; - -import javax.inject.Inject; +import io.micronaut.http.client.annotation.Client; @Client("/greet") public interface GreetingClient { From 80ea4f2e763d1d6e4e6011087142fac251f405b0 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 6 Dec 2018 23:04:24 +0200 Subject: [PATCH 38/69] Update README.md --- parent-boot-2.0-temp/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/parent-boot-2.0-temp/README.md b/parent-boot-2.0-temp/README.md index 740848a470..8134c8eafe 100644 --- a/parent-boot-2.0-temp/README.md +++ b/parent-boot-2.0-temp/README.md @@ -1 +1,2 @@ This pom will be ued only temporary until we migrate parent-boot-2 to 2.1.0 for ticket BAEL-10354 + From 5a87e036faafdedb6315980eaa1d76f077d0c2ae Mon Sep 17 00:00:00 2001 From: Priyesh Mashelkar Date: Fri, 7 Dec 2018 15:04:39 +0000 Subject: [PATCH 39/69] BAEL-2344 Removed unused code (#5860) * Added implementation and test class * Added more details * Updated tests * Added implementation and test class * Added more details * Updated tests * Updated code as per review comments * BAEL-2344 Moved files to new hibernate5 module --- .../hibernate/entities/DeptEmployee.java | 75 ------------- .../src/main/resources/init_database.sql | 10 -- .../hibernate/NamedQueryIntegrationTest.java | 103 ------------------ .../resources/hibernate-namedquery.properties | 9 -- 4 files changed, 197 deletions(-) delete mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java delete mode 100644 hibernate5/src/main/resources/init_database.sql delete mode 100644 hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java delete mode 100644 hibernate5/src/test/resources/hibernate-namedquery.properties diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java deleted file mode 100644 index 7813e89a48..0000000000 --- a/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.hibernate.entities; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; - -@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), - @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), - @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), - @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) -@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), - @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) -@Entity -public class DeptEmployee { - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE) - private long id; - - private String employeeNumber; - - private String designation; - - private String name; - - @ManyToOne - private Department department; - - public DeptEmployee(String name, String employeeNumber, Department department) { - this.name = name; - this.employeeNumber = employeeNumber; - this.department = department; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getEmployeeNumber() { - return employeeNumber; - } - - public void setEmployeeNumber(String employeeNumber) { - this.employeeNumber = employeeNumber; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Department getDepartment() { - return department; - } - - public void setDepartment(Department department) { - this.department = department; - } - - public String getDesignation() { - return designation; - } - - public void setDesignation(String designation) { - this.designation = designation; - } -} diff --git a/hibernate5/src/main/resources/init_database.sql b/hibernate5/src/main/resources/init_database.sql deleted file mode 100644 index 154a5a0bc0..0000000000 --- a/hibernate5/src/main/resources/init_database.sql +++ /dev/null @@ -1,10 +0,0 @@ -CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.SQLException; -@CODE -void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String designation) throws SQLException { - CallableStatement updateStatement = conn.prepareCall("update deptemployee set designation = '" + designation + "' where employeeNumber = '" + employeeNumber + "'"); - updateStatement.execute(); -} -$$; \ No newline at end of file diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java deleted file mode 100644 index ef6ec89bc4..0000000000 --- a/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.baeldung.hibernate; - -import java.io.IOException; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.query.NativeQuery; -import org.hibernate.query.Query; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.baeldung.hibernate.entities.Department; -import com.baeldung.hibernate.entities.DeptEmployee; - -public class NamedQueryIntegrationTest { - private static Session session; - - private Transaction transaction; - - private Long purchaseDeptId; - - @BeforeClass - public static void setUpClass() throws IOException { - session = HibernateUtil.getSessionFactory("hibernate-namedquery.properties").openSession(); - } - - @Before - public void setUp() throws IOException { - transaction = session.beginTransaction(); - session.createNativeQuery("delete from deptemployee").executeUpdate(); - session.createNativeQuery("delete from department").executeUpdate(); - Department salesDepartment = new Department("Sales"); - Department purchaseDepartment = new Department("Purchase"); - DeptEmployee employee1 = new DeptEmployee("John Wayne", "001", salesDepartment); - DeptEmployee employee2 = new DeptEmployee("Sarah Vinton", "002", salesDepartment); - DeptEmployee employee3 = new DeptEmployee("Lisa Carter", "003", salesDepartment); - session.persist(salesDepartment); - session.persist(purchaseDepartment); - purchaseDeptId = purchaseDepartment.getId(); - session.persist(employee1); - session.persist(employee2); - session.persist(employee3); - transaction.commit(); - transaction = session.beginTransaction(); - } - - @After - public void tearDown() { - if(transaction.isActive()) { - transaction.rollback(); - } - } - - @Test - public void whenNamedQueryIsCalledUsingCreateNamedQuery_ThenOk() { - Query query = session.createNamedQuery("DeptEmployee_FindByEmployeeNumber", DeptEmployee.class); - query.setParameter("employeeNo", "001"); - DeptEmployee result = query.getSingleResult(); - Assert.assertNotNull(result); - Assert.assertEquals("John Wayne", result.getName()); - } - - @Test - public void whenNamedNativeQueryIsCalledUsingCreateNamedQuery_ThenOk() { - Query query = session.createNamedQuery("DeptEmployee_FindByEmployeeName", DeptEmployee.class); - query.setParameter("name", "John Wayne"); - DeptEmployee result = query.getSingleResult(); - Assert.assertNotNull(result); - Assert.assertEquals("001", result.getEmployeeNumber()); - } - - @Test - public void whenNamedNativeQueryIsCalledUsingGetNamedNativeQuery_ThenOk() { - @SuppressWarnings("rawtypes") - NativeQuery query = session.getNamedNativeQuery("DeptEmployee_FindByEmployeeName"); - query.setParameter("name", "John Wayne"); - DeptEmployee result = (DeptEmployee) query.getSingleResult(); - Assert.assertNotNull(result); - Assert.assertEquals("001", result.getEmployeeNumber()); - } - - @Test - public void whenUpdateQueryIsCalledWithCreateNamedQuery_ThenOk() { - Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDepartment"); - spQuery.setParameter("employeeNo", "001"); - Department newDepartment = session.find(Department.class, purchaseDeptId); - spQuery.setParameter("newDepartment", newDepartment); - spQuery.executeUpdate(); - transaction.commit(); - } - - @Test - public void whenNamedStoredProcedureIsCalledWithCreateNamedQuery_ThenOk() { - Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDesignation"); - spQuery.setParameter("employeeNumber", "002"); - spQuery.setParameter("newDesignation", "Supervisor"); - spQuery.executeUpdate(); - transaction.commit(); - } -} diff --git a/hibernate5/src/test/resources/hibernate-namedquery.properties b/hibernate5/src/test/resources/hibernate-namedquery.properties deleted file mode 100644 index 457f965347..0000000000 --- a/hibernate5/src/test/resources/hibernate-namedquery.properties +++ /dev/null @@ -1,9 +0,0 @@ -hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/main/resources/init_database.sql' -hibernate.connection.username=sa -hibernate.connection.autocommit=true -jdbc.password= - -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop \ No newline at end of file From 5072291b3283bf4c867abee046dc2bbe02d285f8 Mon Sep 17 00:00:00 2001 From: PranayVJain Date: Sat, 8 Dec 2018 08:46:28 +0530 Subject: [PATCH 40/69] BAEL-2337: Find Substring which are palindromes (#5766) * BAEL-2337: Added test cases to find substring which are palindromes * BAEL-2337: Changed the names of the variables * BAEL-2237: Formatted code using formatter.xml * BAEL-2237: Renamed method and added variety of test cases * BAEL-2337: Renamed unit test cases name according to BBD style naming convention --- .../baeldung/string/SubstringPalindrome.java | 90 +++++++++++++++++++ .../string/SubstringPalindromeUnitTest.java | 83 +++++++++++++++++ 2 files changed, 173 insertions(+) create mode 100644 java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java create mode 100644 java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java diff --git a/java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java b/java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java new file mode 100644 index 0000000000..688bf43b3c --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java @@ -0,0 +1,90 @@ +package com.baeldung.string; + +import java.util.HashSet; +import java.util.Set; + +public class SubstringPalindrome { + + public Set findAllPalindromesUsingCenter(String input) { + final Set palindromes = new HashSet<>(); + if (input == null || input.isEmpty()) { + return palindromes; + } + if (input.length() == 1) { + palindromes.add(input); + return palindromes; + } + for (int i = 0; i < input.length(); i++) { + palindromes.addAll(findPalindromes(input, i, i + 1)); + palindromes.addAll(findPalindromes(input, i, i)); + } + return palindromes; + } + + private Set findPalindromes(String input, int low, int high) { + Set result = new HashSet<>(); + while (low >= 0 && high < input.length() && input.charAt(low) == input.charAt(high)) { + result.add(input.substring(low, high + 1)); + low--; + high++; + } + return result; + } + + public Set findAllPalindromesUsingBruteForceApproach(String input) { + Set palindromes = new HashSet<>(); + if (input == null || input.isEmpty()) { + return palindromes; + } + if (input.length() == 1) { + palindromes.add(input); + return palindromes; + } + for (int i = 0; i < input.length(); i++) { + for (int j = i + 1; j <= input.length(); j++) + if (isPalindrome(input.substring(i, j))) { + palindromes.add(input.substring(i, j)); + } + } + return palindromes; + } + + private boolean isPalindrome(String input) { + StringBuilder plain = new StringBuilder(input); + StringBuilder reverse = plain.reverse(); + return (reverse.toString()).equals(input); + } + + public Set findAllPalindromesUsingManachersAlgorithm(String input) { + Set palindromes = new HashSet<>(); + String formattedInput = "@" + input + "#"; + char inputCharArr[] = formattedInput.toCharArray(); + int max; + int radius[][] = new int[2][input.length() + 1]; + for (int j = 0; j <= 1; j++) { + radius[j][0] = max = 0; + int i = 1; + while (i <= input.length()) { + palindromes.add(Character.toString(inputCharArr[i])); + while (inputCharArr[i - max - 1] == inputCharArr[i + j + max]) + max++; + radius[j][i] = max; + int k = 1; + while ((radius[j][i - k] != max - k) && (k < max)) { + radius[j][i + k] = Math.min(radius[j][i - k], max - k); + k++; + } + max = Math.max(max - k, 0); + i += k; + } + } + for (int i = 1; i <= input.length(); i++) { + for (int j = 0; j <= 1; j++) { + for (max = radius[j][i]; max > 0; max--) { + palindromes.add(input.substring(i - max - 1, max + j + i - 1)); + } + } + } + return palindromes; + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java b/java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java new file mode 100644 index 0000000000..b18a8d4a5f --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.string; + +import static org.junit.Assert.assertEquals; +import java.util.HashSet; +import java.util.Set; +import org.junit.Test; + +public class SubstringPalindromeUnitTest { + + private static final String INPUT_BUBBLE = "bubble"; + private static final String INPUT_CIVIC = "civic"; + private static final String INPUT_INDEED = "indeed"; + private static final String INPUT_ABABAC = "ababac"; + + Set EXPECTED_PALINDROME_BUBBLE = new HashSet() { + { + add("b"); + add("u"); + add("l"); + add("e"); + add("bb"); + add("bub"); + } + }; + + Set EXPECTED_PALINDROME_CIVIC = new HashSet() { + { + add("civic"); + add("ivi"); + add("i"); + add("c"); + add("v"); + } + }; + + Set EXPECTED_PALINDROME_INDEED = new HashSet() { + { + add("i"); + add("n"); + add("d"); + add("e"); + add("ee"); + add("deed"); + } + }; + + Set EXPECTED_PALINDROME_ABABAC = new HashSet() { + { + add("a"); + add("b"); + add("c"); + add("aba"); + add("bab"); + add("ababa"); + } + }; + + private SubstringPalindrome palindrome = new SubstringPalindrome(); + + @Test + public void whenUsingManachersAlgorithm_thenFindsAllPalindromes() { + assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_BUBBLE)); + assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_INDEED)); + assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_CIVIC)); + assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_ABABAC)); + } + + @Test + public void whenUsingCenterApproach_thenFindsAllPalindromes() { + assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingCenter(INPUT_BUBBLE)); + assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingCenter(INPUT_INDEED)); + assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingCenter(INPUT_CIVIC)); + assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingCenter(INPUT_ABABAC)); + } + + @Test + public void whenUsingBruteForceApproach_thenFindsAllPalindromes() { + assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_BUBBLE)); + assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_INDEED)); + assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_CIVIC)); + assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_ABABAC)); + } +} From 183c7a0fe330d1210ea10a101ef96f0ed49a19c7 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 8 Dec 2018 11:22:54 +0530 Subject: [PATCH 41/69] BAEL-10876 Removed corrupted RMI module --- rmi/README.md | 1 - rmi/client.policy | 3 --- rmi/server.policy | 3 --- rmi/src/org/baeldung/Client.java | 20 ----------------- .../org/baeldung/RandomNumberGenerator.java | 8 ------- .../baeldung/RandomNumberGeneratorEngine.java | 10 --------- rmi/src/org/baeldung/Server.java | 22 ------------------- 7 files changed, 67 deletions(-) delete mode 100644 rmi/README.md delete mode 100644 rmi/client.policy delete mode 100644 rmi/server.policy delete mode 100644 rmi/src/org/baeldung/Client.java delete mode 100644 rmi/src/org/baeldung/RandomNumberGenerator.java delete mode 100644 rmi/src/org/baeldung/RandomNumberGeneratorEngine.java delete mode 100644 rmi/src/org/baeldung/Server.java diff --git a/rmi/README.md b/rmi/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/rmi/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/rmi/client.policy b/rmi/client.policy deleted file mode 100644 index 5d74bde76d..0000000000 --- a/rmi/client.policy +++ /dev/null @@ -1,3 +0,0 @@ -grant { - permission java.security.AllPermission; -}; \ No newline at end of file diff --git a/rmi/server.policy b/rmi/server.policy deleted file mode 100644 index 5d74bde76d..0000000000 --- a/rmi/server.policy +++ /dev/null @@ -1,3 +0,0 @@ -grant { - permission java.security.AllPermission; -}; \ No newline at end of file diff --git a/rmi/src/org/baeldung/Client.java b/rmi/src/org/baeldung/Client.java deleted file mode 100644 index 0376952bab..0000000000 --- a/rmi/src/org/baeldung/Client.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung; - -import java.rmi.NotBoundException; -import java.rmi.RemoteException; -import java.rmi.registry.LocateRegistry; -import java.rmi.registry.Registry; - -public class Client { - public static void main(String[] args) throws RemoteException, NotBoundException { - System.setProperty("java.security.policy", "file:./client.policy"); - if (System.getSecurityManager() == null) { - System.setSecurityManager(new SecurityManager()); - } - String name = "RandomNumberGenerator"; - Registry registry = LocateRegistry.getRegistry(); - RandomNumberGenerator randomNumberGenerator = (RandomNumberGenerator) registry.lookup(name); - int number = randomNumberGenerator.get(); - System.out.println("Received random number:" + number); - } -} diff --git a/rmi/src/org/baeldung/RandomNumberGenerator.java b/rmi/src/org/baeldung/RandomNumberGenerator.java deleted file mode 100644 index 50e49d2652..0000000000 --- a/rmi/src/org/baeldung/RandomNumberGenerator.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung; - -import java.rmi.Remote; -import java.rmi.RemoteException; - -public interface RandomNumberGenerator extends Remote{ - int get() throws RemoteException; -} diff --git a/rmi/src/org/baeldung/RandomNumberGeneratorEngine.java b/rmi/src/org/baeldung/RandomNumberGeneratorEngine.java deleted file mode 100644 index 04d90b2ff9..0000000000 --- a/rmi/src/org/baeldung/RandomNumberGeneratorEngine.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung; - -import java.rmi.RemoteException; - -public class RandomNumberGeneratorEngine implements RandomNumberGenerator { - @Override - public int get() throws RemoteException { - return (int) (100 * Math.random()); - } -} diff --git a/rmi/src/org/baeldung/Server.java b/rmi/src/org/baeldung/Server.java deleted file mode 100644 index 8e613cb6bb..0000000000 --- a/rmi/src/org/baeldung/Server.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung; - -import java.rmi.RemoteException; -import java.rmi.registry.LocateRegistry; -import java.rmi.registry.Registry; -import java.rmi.server.UnicastRemoteObject; - -public class Server { - public static void main(String[] args) throws RemoteException { - System.setProperty("java.security.policy", "file:./server.policy"); - if (System.getSecurityManager() == null) { - System.setSecurityManager(new SecurityManager()); - } - String name = "RandomNumberGenerator"; - RandomNumberGenerator randomNumberGenerator = new RandomNumberGeneratorEngine(); - RandomNumberGenerator stub = - (RandomNumberGenerator) UnicastRemoteObject.exportObject(randomNumberGenerator, 0); - Registry registry = LocateRegistry.getRegistry(); - registry.rebind(name, stub); - System.out.println("RandomNumberGenerator bound"); - } -} From 03e852e74753f9eccb3f53dba106a8dfcddb21b1 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 8 Dec 2018 13:27:17 +0200 Subject: [PATCH 42/69] compare hashmap --- .../compare/HashMapComparisonUnitTest.java | 227 ++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java diff --git a/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java new file mode 100644 index 0000000000..c9a6b953ef --- /dev/null +++ b/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java @@ -0,0 +1,227 @@ +package com.baeldung.java.map.compare; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsMapContaining.hasEntry; +import static org.hamcrest.collection.IsMapContaining.hasKey; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; + +import com.google.common.base.Equivalence; +import com.google.common.collect.MapDifference; +import com.google.common.collect.MapDifference.ValueDifference; +import com.google.common.collect.Maps; + +public class HashMapComparisonUnitTest { + + Map asiaCapital1; + Map asiaCapital2; + Map asiaCapital3; + + Map asiaCity1; + Map asiaCity2; + Map asiaCity3; + + @Before + public void setup(){ + asiaCapital1 = new HashMap(); + asiaCapital1.put("Japan", "Tokyo"); + asiaCapital1.put("South Korea", "Seoul"); + + asiaCapital2 = new HashMap(); + asiaCapital2.put("South Korea", "Seoul"); + asiaCapital2.put("Japan", "Tokyo"); + + asiaCapital3 = new HashMap(); + asiaCapital3.put("Japan", "Tokyo"); + asiaCapital3.put("China", "Beijing"); + + asiaCity1 = new HashMap(); + asiaCity1.put("Japan", new String[] { "Tokyo", "Osaka" }); + asiaCity1.put("South Korea", new String[] { "Seoul", "Busan" }); + + asiaCity2 = new HashMap(); + asiaCity2.put("South Korea", new String[] { "Seoul", "Busan" }); + asiaCity2.put("Japan", new String[] { "Tokyo", "Osaka" }); + + asiaCity3 = new HashMap(); + asiaCity3.put("Japan", new String[] { "Tokyo", "Osaka" }); + asiaCity3.put("China", new String[] { "Beijing", "Hong Kong" }); + } + + @Test + public void whenCompareTwoHashMapsUsingEquals_thenSuccess() { + assertTrue(asiaCapital1.equals(asiaCapital2)); + assertFalse(asiaCapital1.equals(asiaCapital3)); + } + + @Test + public void whenCompareTwoHashMapsWithArrayValuesUsingEquals_thenFail() { + assertFalse(asiaCity1.equals(asiaCity2)); + } + + @Test + public void whenCompareTwoHashMapsUsingStreamAPI_thenSuccess() { + assertTrue(areEqual(asiaCapital1, asiaCapital2)); + assertFalse(areEqual(asiaCapital1, asiaCapital3)); + } + + @Test + public void whenCompareTwoHashMapsWithArrayValuesUsingStreamAPI_thenSuccess() { + assertTrue(areEqualWithArrayValue(asiaCity1, asiaCity2)); + assertFalse(areEqualWithArrayValue(asiaCity1, asiaCity3)); + } + + @Test + public void whenCompareTwoHashMapKeys_thenSuccess() { + assertTrue(asiaCapital1.keySet().equals(asiaCapital2.keySet())); + assertFalse(asiaCapital1.keySet().equals(asiaCapital3.keySet())); + } + + @Test + public void whenCompareTwoHashMapKeyValuesUsingStreamAPI_thenSuccess() { + Map asiaCapital3 = new HashMap(); + asiaCapital3.put("Japan", "Tokyo"); + asiaCapital3.put("South Korea", "Seoul"); + asiaCapital3.put("China", "Beijing"); + + Map asiaCapital4 = new HashMap(); + asiaCapital4.put("South Korea", "Seoul"); + asiaCapital4.put("Japan", "Osaka"); + asiaCapital4.put("China", "Beijing"); + + Map result = areEqualKeys(asiaCapital3, asiaCapital4); + assertEquals(3, result.size()); + assertThat(result, hasEntry("Japan", false)); + assertThat(result, hasEntry("South Korea", true)); + assertThat(result, hasEntry("China", true)); + } + + @Test + public void givenDifferentMaps_whenGetDiffUsingGuava_thenSuccess() { + Map asia1 = new HashMap(); + asia1.put("Japan", "Tokyo"); + asia1.put("South Korea", "Seoul"); + asia1.put("India", "New Delhi"); + + Map asia2 = new HashMap(); + asia2.put("Japan", "Tokyo"); + asia2.put("China", "Beijing"); + asia2.put("India", "Delhi"); + + MapDifference diff = Maps.difference(asia1, asia2); + Map> entriesDiffering = diff.entriesDiffering(); + + assertFalse(diff.areEqual()); + assertEquals(1, entriesDiffering.size()); + assertThat(entriesDiffering, hasKey("India")); + assertEquals("New Delhi", entriesDiffering.get("India").leftValue()); + assertEquals("Delhi", entriesDiffering.get("India").rightValue()); + } + + @Test + public void givenDifferentMaps_whenGetEntriesOnOneSideUsingGuava_thenSuccess() { + Map asia1 = new HashMap(); + asia1.put("Japan", "Tokyo"); + asia1.put("South Korea", "Seoul"); + asia1.put("India", "New Delhi"); + + Map asia2 = new HashMap(); + asia2.put("Japan", "Tokyo"); + asia2.put("China", "Beijing"); + asia2.put("India", "Delhi"); + + MapDifference diff = Maps.difference(asia1, asia2); + Map entriesOnlyOnRight = diff.entriesOnlyOnRight(); + assertEquals(1, entriesOnlyOnRight.size()); + assertThat(entriesOnlyOnRight, hasEntry("China", "Beijing")); + + Map entriesOnlyOnLeft = diff.entriesOnlyOnLeft(); + assertEquals(1, entriesOnlyOnLeft.size()); + assertThat(entriesOnlyOnLeft, hasEntry("South Korea", "Seoul")); + } + + @Test + public void givenDifferentMaps_whenGetCommonEntriesUsingGuava_thenSuccess() { + Map asia1 = new HashMap(); + asia1.put("Japan", "Tokyo"); + asia1.put("South Korea", "Seoul"); + asia1.put("India", "New Delhi"); + + Map asia2 = new HashMap(); + asia2.put("Japan", "Tokyo"); + asia2.put("China", "Beijing"); + asia2.put("India", "Delhi"); + + MapDifference diff = Maps.difference(asia1, asia2); + Map entriesInCommon = diff.entriesInCommon(); + + assertEquals(1, entriesInCommon.size()); + assertThat(entriesInCommon, hasEntry("Japan", "Tokyo")); + } + + @Test + public void givenSimilarMapsWithArrayValue_whenCompareUsingGuava_thenFail() { + MapDifference diff = Maps.difference(asiaCity1, asiaCity2); + assertFalse(diff.areEqual()); + } + + @Test + public void givenSimilarMapsWithArrayValue_whenCompareUsingGuavaEquivalence_thenSuccess() { + Equivalence eq = new Equivalence() { + @Override + protected boolean doEquivalent(String[] a, String[] b) { + return Arrays.equals(a, b); + } + + @Override + protected int doHash(String[] value) { + return value.hashCode(); + } + }; + + MapDifference diff = Maps.difference(asiaCity1, asiaCity2, eq); + assertTrue(diff.areEqual()); + + diff = Maps.difference(asiaCity1, asiaCity3, eq); + assertFalse(diff.areEqual()); + } + + // =========================================================================== + + private boolean areEqual(Map first, Map second) { + if (first.size() != second.size()) { + return false; + } + + return first.entrySet() + .stream() + .allMatch(e -> e.getValue() + .equals(second.get(e.getKey()))); + } + + private boolean areEqualWithArrayValue(Map first, Map second) { + if (first.size() != second.size()) { + return false; + } + + return first.entrySet() + .stream() + .allMatch(e -> Arrays.equals(e.getValue(), second.get(e.getKey()))); + } + + private Map areEqualKeys(Map first, Map second) { + return first.entrySet() + .stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().equals(second.get(e.getKey())))); + } + +} From 670e4f348d7178242f900fef958c38b25c8c4df9 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 8 Dec 2018 14:02:10 +0200 Subject: [PATCH 43/69] minor cleanup --- .../java/map/compare/HashMapComparisonUnitTest.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java index c9a6b953ef..e8aa12d4bd 100644 --- a/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java +++ b/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java @@ -98,7 +98,8 @@ public class HashMapComparisonUnitTest { asiaCapital4.put("Japan", "Osaka"); asiaCapital4.put("China", "Beijing"); - Map result = areEqualKeys(asiaCapital3, asiaCapital4); + Map result = areEqualKeyValues(asiaCapital3, asiaCapital4); + assertEquals(3, result.size()); assertThat(result, hasEntry("Japan", false)); assertThat(result, hasEntry("South Korea", true)); @@ -141,10 +142,10 @@ public class HashMapComparisonUnitTest { MapDifference diff = Maps.difference(asia1, asia2); Map entriesOnlyOnRight = diff.entriesOnlyOnRight(); + Map entriesOnlyOnLeft = diff.entriesOnlyOnLeft(); + assertEquals(1, entriesOnlyOnRight.size()); assertThat(entriesOnlyOnRight, hasEntry("China", "Beijing")); - - Map entriesOnlyOnLeft = diff.entriesOnlyOnLeft(); assertEquals(1, entriesOnlyOnLeft.size()); assertThat(entriesOnlyOnLeft, hasEntry("South Korea", "Seoul")); } @@ -218,7 +219,7 @@ public class HashMapComparisonUnitTest { .allMatch(e -> Arrays.equals(e.getValue(), second.get(e.getKey()))); } - private Map areEqualKeys(Map first, Map second) { + private Map areEqualKeyValues(Map first, Map second) { return first.entrySet() .stream() .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().equals(second.get(e.getKey())))); From 9eff0c662b61595d1c7386acdfa609c821a119c2 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 8 Dec 2018 18:37:08 +0530 Subject: [PATCH 44/69] [BAEL-9710] - Standardized packages for spring-rest module --- .../baeldung/resttemplate/lists/EmployeeApplication.java | 2 +- .../resttemplate/lists/client/EmployeeClient.java | 7 ++++--- .../resttemplate/lists/controller/EmployeeResource.java | 9 +++++---- .../baeldung/resttemplate/lists/dto/Employee.java | 2 +- .../baeldung/resttemplate/lists/dto/EmployeeList.java | 2 +- .../resttemplate/lists/service/EmployeeService.java | 5 +++-- .../baeldung/sampleapp}/config/MainApplication.java | 4 ++-- .../baeldung/sampleapp}/config/RestClientConfig.java | 5 +++-- .../baeldung/sampleapp}/config/WebConfig.java | 4 ++-- .../RestTemplateHeaderModifierInterceptor.java | 2 +- .../sampleapp}/repository/HeavyResourceRepository.java | 8 ++++---- .../web/controller/BarMappingExamplesController.java | 2 +- .../sampleapp}/web/controller/CompanyController.java | 5 +++-- .../web/controller/DeferredResultController.java | 2 +- .../web/controller/HeavyResourceController.java | 9 +++++---- .../sampleapp}/web/controller/ItemController.java | 8 ++++---- .../sampleapp}/web/controller/MyFooController.java | 7 ++++--- .../sampleapp}/web/controller/PactController.java | 5 +++-- .../sampleapp}/web/controller/SimplePostController.java | 5 +++-- .../web/controller/advice/JsonpControllerAdvice.java | 2 +- .../controller/mediatypes/CustomMediaTypeController.java | 7 ++++--- .../web/controller/redirect/RedirectController.java | 2 +- .../baeldung/sampleapp}/web/dto/BaeldungItem.java | 2 +- .../baeldung/sampleapp}/web/dto/BaeldungItemV2.java | 2 +- .../baeldung/sampleapp}/web/dto/Company.java | 2 +- .../baeldung => com/baeldung/sampleapp}/web/dto/Foo.java | 2 +- .../baeldung/sampleapp}/web/dto/HeavyResource.java | 2 +- .../sampleapp}/web/dto/HeavyResourceAddressOnly.java | 2 +- .../web/dto/HeavyResourceAddressPartialUpdate.java | 2 +- .../baeldung/sampleapp}/web/dto/Item.java | 2 +- .../baeldung/sampleapp}/web/dto/ItemManager.java | 2 +- .../baeldung/sampleapp}/web/dto/PactDto.java | 2 +- .../baeldung/sampleapp}/web/dto/Views.java | 2 +- .../web/exception/ResourceNotFoundException.java | 2 +- .../baeldung/SpringContextIntegrationTest.java | 4 ++-- .../test/java/{org => com}/baeldung/client/Consts.java | 2 +- .../ExamplePostControllerRequestIntegrationTest.java | 2 +- .../ExamplePostControllerResponseIntegrationTest.java | 2 +- .../baeldung/okhttp/DefaultContentTypeInterceptor.java | 2 +- .../baeldung/okhttp/OkHttpFileUploadingLiveTest.java | 4 ++-- .../{org => com}/baeldung/okhttp/OkHttpGetLiveTest.java | 4 ++-- .../baeldung/okhttp/OkHttpHeaderLiveTest.java | 2 +- .../{org => com}/baeldung/okhttp/OkHttpMiscLiveTest.java | 4 ++-- .../baeldung/okhttp/OkHttpPostingLiveTest.java | 4 ++-- .../baeldung/okhttp/OkHttpRedirectLiveTest.java | 2 +- .../baeldung/okhttp/ProgressRequestWrapper.java | 2 +- .../{org => com}/baeldung/pact/PactProviderLiveTest.java | 5 +++-- .../baeldung/resttemplate/RestTemplateLiveTest.java | 4 ++-- .../uribuilder/SpringUriBuilderIntegrationTest.java | 2 +- .../HeavyResourceControllerIntegrationTest.java | 8 ++++---- .../CustomMediaTypeControllerIntegrationTest.java | 5 +++-- .../mediatypes/CustomMediaTypeControllerLiveTest.java | 2 +- .../baeldung/web/controller/mediatypes/TestConfig.java | 2 +- .../redirect/RedirectControllerIntegrationTest.java | 2 +- .../resources/cache/2d9345a30d2cc31bb3091d70a8ef6c18.0 | 2 +- .../resources/cache/4b217e04ba52215f3a6b64d28f6729c6.0 | 6 +++--- spring-rest/src/test/resources/cache/journal | 6 ++++++ 57 files changed, 112 insertions(+), 94 deletions(-) rename spring-rest/src/main/java/{org => com}/baeldung/resttemplate/lists/EmployeeApplication.java (90%) rename spring-rest/src/main/java/{org => com}/baeldung/resttemplate/lists/client/EmployeeClient.java (94%) rename spring-rest/src/main/java/{org => com}/baeldung/resttemplate/lists/controller/EmployeeResource.java (85%) rename spring-rest/src/main/java/{org => com}/baeldung/resttemplate/lists/dto/Employee.java (92%) rename spring-rest/src/main/java/{org => com}/baeldung/resttemplate/lists/dto/EmployeeList.java (91%) rename spring-rest/src/main/java/{org => com}/baeldung/resttemplate/lists/service/EmployeeService.java (83%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/config/MainApplication.java (85%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/config/RestClientConfig.java (85%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/config/WebConfig.java (95%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/interceptors/RestTemplateHeaderModifierInterceptor.java (91%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/repository/HeavyResourceRepository.java (72%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/controller/BarMappingExamplesController.java (96%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/controller/CompanyController.java (82%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/controller/DeferredResultController.java (98%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/controller/HeavyResourceController.java (88%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/controller/ItemController.java (83%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/controller/MyFooController.java (94%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/controller/PactController.java (90%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/controller/SimplePostController.java (97%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/controller/advice/JsonpControllerAdvice.java (85%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/controller/mediatypes/CustomMediaTypeController.java (85%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/controller/redirect/RedirectController.java (98%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/dto/BaeldungItem.java (83%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/dto/BaeldungItemV2.java (84%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/dto/Company.java (93%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/dto/Foo.java (94%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/dto/HeavyResource.java (96%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/dto/HeavyResourceAddressOnly.java (93%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/dto/HeavyResourceAddressPartialUpdate.java (93%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/dto/Item.java (94%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/dto/ItemManager.java (80%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/dto/PactDto.java (93%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/dto/Views.java (75%) rename spring-rest/src/main/java/{org/baeldung => com/baeldung/sampleapp}/web/exception/ResourceNotFoundException.java (82%) rename spring-rest/src/test/java/{org => com}/baeldung/SpringContextIntegrationTest.java (91%) rename spring-rest/src/test/java/{org => com}/baeldung/client/Consts.java (68%) rename spring-rest/src/test/java/{org => com}/baeldung/okhttp/DefaultContentTypeInterceptor.java (92%) rename spring-rest/src/test/java/{org => com}/baeldung/okhttp/OkHttpFileUploadingLiveTest.java (93%) rename spring-rest/src/test/java/{org => com}/baeldung/okhttp/OkHttpGetLiveTest.java (92%) rename spring-rest/src/test/java/{org => com}/baeldung/okhttp/OkHttpHeaderLiveTest.java (93%) rename spring-rest/src/test/java/{org => com}/baeldung/okhttp/OkHttpMiscLiveTest.java (94%) rename spring-rest/src/test/java/{org => com}/baeldung/okhttp/OkHttpPostingLiveTest.java (94%) rename spring-rest/src/test/java/{org => com}/baeldung/okhttp/OkHttpRedirectLiveTest.java (92%) rename spring-rest/src/test/java/{org => com}/baeldung/okhttp/ProgressRequestWrapper.java (94%) rename spring-rest/src/test/java/{org => com}/baeldung/pact/PactProviderLiveTest.java (93%) rename spring-rest/src/test/java/{org => com}/baeldung/resttemplate/RestTemplateLiveTest.java (94%) rename spring-rest/src/test/java/{org => com}/baeldung/uribuilder/SpringUriBuilderIntegrationTest.java (98%) rename spring-rest/src/test/java/{org => com}/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java (92%) rename spring-rest/src/test/java/{org => com}/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java (94%) rename spring-rest/src/test/java/{org => com}/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java (96%) rename spring-rest/src/test/java/{org => com}/baeldung/web/controller/mediatypes/TestConfig.java (81%) rename spring-rest/src/test/java/{org => com}/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java (98%) diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/EmployeeApplication.java similarity index 90% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/EmployeeApplication.java index baaa4c4d80..1967d4f2aa 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/EmployeeApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.lists; +package com.baeldung.resttemplate.lists; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java similarity index 94% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java index 729fa3ca3e..d811045733 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java @@ -1,11 +1,12 @@ -package org.baeldung.resttemplate.lists.client; +package com.baeldung.resttemplate.lists.client; -import org.baeldung.resttemplate.lists.dto.Employee; -import org.baeldung.resttemplate.lists.dto.EmployeeList; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; +import com.baeldung.resttemplate.lists.dto.Employee; +import com.baeldung.resttemplate.lists.dto.EmployeeList; + import java.util.ArrayList; import java.util.List; diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/controller/EmployeeResource.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/controller/EmployeeResource.java index f051c6a78b..8a4d510f63 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/controller/EmployeeResource.java @@ -1,14 +1,15 @@ -package org.baeldung.resttemplate.lists.controller; +package com.baeldung.resttemplate.lists.controller; -import org.baeldung.resttemplate.lists.dto.Employee; -import org.baeldung.resttemplate.lists.dto.EmployeeList; -import org.baeldung.resttemplate.lists.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; 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.RestController; +import com.baeldung.resttemplate.lists.dto.Employee; +import com.baeldung.resttemplate.lists.dto.EmployeeList; +import com.baeldung.resttemplate.lists.service.EmployeeService; + import java.util.List; @RestController diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/Employee.java similarity index 92% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/Employee.java index bd8ebbf969..0754c13c5b 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/Employee.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.lists.dto; +package com.baeldung.resttemplate.lists.dto; public class Employee { diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/EmployeeList.java similarity index 91% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/EmployeeList.java index 2bb86ac5b4..eeabbfe450 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/EmployeeList.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.lists.dto; +package com.baeldung.resttemplate.lists.dto; import java.util.ArrayList; import java.util.List; diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java similarity index 83% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java index 08196dda77..226134787f 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java @@ -1,8 +1,9 @@ -package org.baeldung.resttemplate.lists.service; +package com.baeldung.resttemplate.lists.service; -import org.baeldung.resttemplate.lists.dto.Employee; import org.springframework.stereotype.Service; +import com.baeldung.resttemplate.lists.dto.Employee; + import java.util.ArrayList; import java.util.List; diff --git a/spring-rest/src/main/java/org/baeldung/config/MainApplication.java b/spring-rest/src/main/java/com/baeldung/sampleapp/config/MainApplication.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/config/MainApplication.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/config/MainApplication.java index 6a7fdc041a..507f340e9d 100644 --- a/spring-rest/src/main/java/org/baeldung/config/MainApplication.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/config/MainApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.sampleapp.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @EnableAutoConfiguration -@ComponentScan("org.baeldung") +@ComponentScan("com.baeldung.sampleapp") public class MainApplication implements WebMvcConfigurer { public static void main(final String[] args) { diff --git a/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java b/spring-rest/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java index 8743af20fe..8abc368bdb 100644 --- a/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java @@ -1,15 +1,16 @@ -package org.baeldung.config; +package com.baeldung.sampleapp.config; import java.util.ArrayList; import java.util.List; -import org.baeldung.interceptors.RestTemplateHeaderModifierInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.util.CollectionUtils; import org.springframework.web.client.RestTemplate; +import com.baeldung.sampleapp.interceptors.RestTemplateHeaderModifierInterceptor; + @Configuration public class RestClientConfig { diff --git a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest/src/main/java/com/baeldung/sampleapp/config/WebConfig.java similarity index 95% rename from spring-rest/src/main/java/org/baeldung/config/WebConfig.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/config/WebConfig.java index b3e3cd179a..d5209a520b 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/config/WebConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.sampleapp.config; import java.text.SimpleDateFormat; import java.util.List; @@ -18,7 +18,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; */ @Configuration @EnableWebMvc -@ComponentScan({ "org.baeldung.web" }) +@ComponentScan({ "com.baeldung.sampleapp.web" }) public class WebConfig implements WebMvcConfigurer { public WebConfig() { diff --git a/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java b/spring-rest/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java similarity index 91% rename from spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java index fabb904634..519e5ebf0d 100644 --- a/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.interceptors; +package com.baeldung.sampleapp.interceptors; import java.io.IOException; diff --git a/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java b/spring-rest/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java similarity index 72% rename from spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java index e4eb6d8875..ea9541c31a 100644 --- a/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java @@ -1,10 +1,10 @@ -package org.baeldung.repository; - -import org.baeldung.web.dto.HeavyResource; -import org.baeldung.web.dto.HeavyResourceAddressOnly; +package com.baeldung.sampleapp.repository; import java.util.Map; +import com.baeldung.sampleapp.web.dto.HeavyResource; +import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly; + public class HeavyResourceRepository { public void save(HeavyResource heavyResource) { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java similarity index 96% rename from spring-rest/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java index 1c3a1086ca..c6b8d23944 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java similarity index 82% rename from spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java index aa694c08ed..bfda2fe0d6 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java @@ -1,10 +1,11 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; -import org.baeldung.web.dto.Company; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.web.dto.Company; + @RestController public class CompanyController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/DeferredResultController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java similarity index 98% rename from spring-rest/src/main/java/org/baeldung/web/controller/DeferredResultController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java index 5d039d2d02..8f4eb3218a 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/DeferredResultController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/HeavyResourceController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java similarity index 88% rename from spring-rest/src/main/java/org/baeldung/web/controller/HeavyResourceController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java index fed45066bd..8156fc14a9 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/HeavyResourceController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java @@ -1,11 +1,8 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.Map; -import org.baeldung.repository.HeavyResourceRepository; -import org.baeldung.web.dto.HeavyResource; -import org.baeldung.web.dto.HeavyResourceAddressOnly; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; @@ -14,6 +11,10 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.repository.HeavyResourceRepository; +import com.baeldung.sampleapp.web.dto.HeavyResource; +import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly; + @RestController public class HeavyResourceController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java similarity index 83% rename from spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java index 1cc3eae432..69bd458968 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java @@ -1,14 +1,14 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.Date; -import org.baeldung.web.dto.Item; -import org.baeldung.web.dto.ItemManager; -import org.baeldung.web.dto.Views; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.web.dto.Item; +import com.baeldung.sampleapp.web.dto.ItemManager; +import com.baeldung.sampleapp.web.dto.Views; import com.fasterxml.jackson.annotation.JsonView; @RestController diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java similarity index 94% rename from spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java index 251e0b23e7..11ea5b70c9 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.Collection; import java.util.HashMap; @@ -6,8 +6,6 @@ import java.util.Map; import javax.servlet.http.HttpServletResponse; -import org.baeldung.web.dto.Foo; -import org.baeldung.web.exception.ResourceNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -18,6 +16,9 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import com.baeldung.sampleapp.web.dto.Foo; +import com.baeldung.sampleapp.web.exception.ResourceNotFoundException; + @Controller @RequestMapping(value = "/foos") public class MyFooController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/PactController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java similarity index 90% rename from spring-rest/src/main/java/org/baeldung/web/controller/PactController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java index 4f586479ef..0f5d7f1acb 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/PactController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java @@ -1,9 +1,8 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.ArrayList; import java.util.List; -import org.baeldung.web.dto.PactDto; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; @@ -12,6 +11,8 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.web.dto.PactDto; + @RestController public class PactController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/SimplePostController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java similarity index 97% rename from spring-rest/src/main/java/org/baeldung/web/controller/SimplePostController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java index f8407acb47..7b57d35088 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/SimplePostController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.io.BufferedOutputStream; import java.io.File; @@ -7,7 +7,6 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; -import org.baeldung.web.dto.Foo; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -15,6 +14,8 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; +import com.baeldung.sampleapp.web.dto.Foo; + // used to test HttpClientPostingTest @RestController public class SimplePostController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/advice/JsonpControllerAdvice.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/advice/JsonpControllerAdvice.java index 996f229128..853e417d46 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/advice/JsonpControllerAdvice.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.advice; +package com.baeldung.sampleapp.web.controller.advice; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice; diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java index a0a6c6341e..fc73bade87 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java @@ -1,13 +1,14 @@ -package org.baeldung.web.controller.mediatypes; +package com.baeldung.sampleapp.web.controller.mediatypes; -import org.baeldung.web.dto.BaeldungItem; -import org.baeldung.web.dto.BaeldungItemV2; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.web.dto.BaeldungItem; +import com.baeldung.sampleapp.web.dto.BaeldungItemV2; + @RestController @RequestMapping(value = "/", produces = "application/vnd.baeldung.api.v1+json") public class CustomMediaTypeController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java similarity index 98% rename from spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java index 59868593a3..321f3be3ef 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.redirect; +package com.baeldung.sampleapp.web.controller.redirect; import javax.servlet.http.HttpServletRequest; diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItem.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java similarity index 83% rename from spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItem.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java index 9b3ecd33b9..807a254cfc 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItem.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class BaeldungItem { private final String itemId; diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItemV2.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java similarity index 84% rename from spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItemV2.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java index 64df20a14e..f84591ea43 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItemV2.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class BaeldungItemV2 { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Company.java similarity index 93% rename from spring-rest/src/main/java/org/baeldung/web/dto/Company.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Company.java index 3164d604ad..6cfcc079d9 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Company.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class Company { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java similarity index 94% rename from spring-rest/src/main/java/org/baeldung/web/dto/Foo.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java index 240b368b50..186df8e678 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; import com.thoughtworks.xstream.annotations.XStreamAlias; diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResource.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java similarity index 96% rename from spring-rest/src/main/java/org/baeldung/web/dto/HeavyResource.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java index 934e76606f..2821341888 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResource.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class HeavyResource { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressOnly.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java similarity index 93% rename from spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressOnly.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java index f96347d60c..01ee6e7dd4 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressOnly.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class HeavyResourceAddressOnly { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressPartialUpdate.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java similarity index 93% rename from spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressPartialUpdate.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java index f90f02ea08..1832a1a58b 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressPartialUpdate.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class HeavyResourceAddressPartialUpdate { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Item.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Item.java similarity index 94% rename from spring-rest/src/main/java/org/baeldung/web/dto/Item.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Item.java index 536c72020f..a4fcef5dce 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Item.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Item.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; import com.fasterxml.jackson.annotation.JsonView; diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/ItemManager.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java similarity index 80% rename from spring-rest/src/main/java/org/baeldung/web/dto/ItemManager.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java index 74ffada300..0009c0180b 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/ItemManager.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class ItemManager { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/PactDto.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java similarity index 93% rename from spring-rest/src/main/java/org/baeldung/web/dto/PactDto.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java index e34e2bdf3b..e184119611 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/PactDto.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class PactDto { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Views.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Views.java similarity index 75% rename from spring-rest/src/main/java/org/baeldung/web/dto/Views.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Views.java index 6231e12bcc..e2d83fda22 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Views.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Views.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class Views { public static class Public { diff --git a/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java similarity index 82% rename from spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java index aab737b6ec..69532f196d 100644 --- a/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java @@ -1,4 +1,4 @@ -package org.baeldung.web.exception; +package com.baeldung.sampleapp.web.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; diff --git a/spring-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest/src/test/java/com/baeldung/SpringContextIntegrationTest.java similarity index 91% rename from spring-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-rest/src/test/java/com/baeldung/SpringContextIntegrationTest.java index d99dacd331..e659897303 100644 --- a/spring-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-rest/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -1,6 +1,5 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.config.MainApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; @@ -10,6 +9,7 @@ import com.baeldung.custom.CustomApplication; import com.baeldung.produceimage.ImageApplication; import com.baeldung.propertyeditor.PropertyEditorApplication; import com.baeldung.responseheaders.ResponseHeadersApplication; +import com.baeldung.sampleapp.config.MainApplication; import com.baeldung.web.log.app.Application; @RunWith(SpringRunner.class) diff --git a/spring-rest/src/test/java/org/baeldung/client/Consts.java b/spring-rest/src/test/java/com/baeldung/client/Consts.java similarity index 68% rename from spring-rest/src/test/java/org/baeldung/client/Consts.java rename to spring-rest/src/test/java/com/baeldung/client/Consts.java index b40561d9c3..b392c4d199 100644 --- a/spring-rest/src/test/java/org/baeldung/client/Consts.java +++ b/spring-rest/src/test/java/com/baeldung/client/Consts.java @@ -1,4 +1,4 @@ -package org.baeldung.client; +package com.baeldung.client; public interface Consts { int APPLICATION_PORT = 8082; diff --git a/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestIntegrationTest.java b/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestIntegrationTest.java index 33926d6200..94b8bf40e7 100644 --- a/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestIntegrationTest.java +++ b/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.controllers; +import com.baeldung.sampleapp.config.MainApplication; import com.baeldung.services.ExampleService; import com.baeldung.transfer.LoginForm; import org.junit.Before; @@ -12,7 +13,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.baeldung.config.MainApplication; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; diff --git a/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseIntegrationTest.java b/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseIntegrationTest.java index 5c5e5c0a64..5743ad450b 100644 --- a/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseIntegrationTest.java +++ b/spring-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.controllers; +import com.baeldung.sampleapp.config.MainApplication; import com.baeldung.services.ExampleService; import com.baeldung.transfer.LoginForm; import org.junit.Before; @@ -19,7 +20,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder 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.status; -import org.baeldung.config.MainApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = MainApplication.class) diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java b/spring-rest/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java similarity index 92% rename from spring-rest/src/test/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java rename to spring-rest/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java index f49d7668e8..0450c1d6ba 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java +++ b/spring-rest/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.okhttp; +package com.baeldung.okhttp; import java.io.IOException; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java b/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java similarity index 93% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java rename to spring-rest/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java index 71fc755321..75980a5360 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java +++ b/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java @@ -1,6 +1,6 @@ -package org.baeldung.okhttp; +package com.baeldung.okhttp; -import static org.baeldung.client.Consts.APPLICATION_PORT; +import static com.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java b/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java similarity index 92% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java rename to spring-rest/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java index fc78899da1..3edd2eab06 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java @@ -1,6 +1,6 @@ -package org.baeldung.okhttp; +package com.baeldung.okhttp; -import static org.baeldung.client.Consts.APPLICATION_PORT; +import static com.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java b/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java similarity index 93% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java rename to spring-rest/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java index c3dddc69e1..305c86d8c5 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java +++ b/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.okhttp; +package com.baeldung.okhttp; import java.io.IOException; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java b/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java similarity index 94% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java rename to spring-rest/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java index 6ab485ee14..207ad14e71 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java +++ b/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -1,6 +1,6 @@ -package org.baeldung.okhttp; +package com.baeldung.okhttp; -import static org.baeldung.client.Consts.APPLICATION_PORT; +import static com.baeldung.client.Consts.APPLICATION_PORT; import java.io.File; import java.io.IOException; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java b/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java similarity index 94% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java rename to spring-rest/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java index d681a56822..66fee0b626 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java +++ b/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java @@ -1,6 +1,6 @@ -package org.baeldung.okhttp; +package com.baeldung.okhttp; -import static org.baeldung.client.Consts.APPLICATION_PORT; +import static com.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectLiveTest.java b/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java similarity index 92% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectLiveTest.java rename to spring-rest/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java index e3f567a693..5dd159c372 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectLiveTest.java +++ b/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.okhttp; +package com.baeldung.okhttp; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java b/spring-rest/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java similarity index 94% rename from spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java rename to spring-rest/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java index 04a2fcc6e7..6f0ebce1e1 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java +++ b/spring-rest/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java @@ -1,4 +1,4 @@ -package org.baeldung.okhttp; +package com.baeldung.okhttp; import okhttp3.RequestBody; import okhttp3.MediaType; diff --git a/spring-rest/src/test/java/org/baeldung/pact/PactProviderLiveTest.java b/spring-rest/src/test/java/com/baeldung/pact/PactProviderLiveTest.java similarity index 93% rename from spring-rest/src/test/java/org/baeldung/pact/PactProviderLiveTest.java rename to spring-rest/src/test/java/com/baeldung/pact/PactProviderLiveTest.java index f020fb88db..7ac9c1d9ce 100644 --- a/spring-rest/src/test/java/org/baeldung/pact/PactProviderLiveTest.java +++ b/spring-rest/src/test/java/com/baeldung/pact/PactProviderLiveTest.java @@ -1,11 +1,12 @@ -package org.baeldung.pact; +package com.baeldung.pact; -import org.baeldung.config.MainApplication; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.springframework.boot.SpringApplication; import org.springframework.web.context.ConfigurableWebApplicationContext; +import com.baeldung.sampleapp.config.MainApplication; + import au.com.dius.pact.provider.junit.PactRunner; import au.com.dius.pact.provider.junit.Provider; import au.com.dius.pact.provider.junit.State; diff --git a/spring-rest/src/test/java/org/baeldung/resttemplate/RestTemplateLiveTest.java b/spring-rest/src/test/java/com/baeldung/resttemplate/RestTemplateLiveTest.java similarity index 94% rename from spring-rest/src/test/java/org/baeldung/resttemplate/RestTemplateLiveTest.java rename to spring-rest/src/test/java/com/baeldung/resttemplate/RestTemplateLiveTest.java index 4f00bebdf4..8db31fd0a7 100644 --- a/spring-rest/src/test/java/org/baeldung/resttemplate/RestTemplateLiveTest.java +++ b/spring-rest/src/test/java/com/baeldung/resttemplate/RestTemplateLiveTest.java @@ -1,10 +1,9 @@ -package org.baeldung.resttemplate; +package com.baeldung.resttemplate; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; -import org.baeldung.config.RestClientConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -17,6 +16,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; +import com.baeldung.sampleapp.config.RestClientConfig; import com.baeldung.transfer.LoginForm; @RunWith(SpringJUnit4ClassRunner.class) diff --git a/spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderIntegrationTest.java b/spring-rest/src/test/java/com/baeldung/uribuilder/SpringUriBuilderIntegrationTest.java similarity index 98% rename from spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderIntegrationTest.java rename to spring-rest/src/test/java/com/baeldung/uribuilder/SpringUriBuilderIntegrationTest.java index bdc24f7f34..0af5cb1e1a 100644 --- a/spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderIntegrationTest.java +++ b/spring-rest/src/test/java/com/baeldung/uribuilder/SpringUriBuilderIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.uribuilder; +package com.baeldung.uribuilder; import static org.junit.Assert.assertEquals; diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java b/spring-rest/src/test/java/com/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java similarity index 92% rename from spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java rename to spring-rest/src/test/java/com/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java index 478e4948dc..5a0b08958e 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java +++ b/spring-rest/src/test/java/com/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; @@ -6,9 +6,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.util.HashMap; -import org.baeldung.config.WebConfig; -import org.baeldung.web.dto.HeavyResource; -import org.baeldung.web.dto.HeavyResourceAddressOnly; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -21,6 +18,9 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import com.baeldung.sampleapp.config.WebConfig; +import com.baeldung.sampleapp.web.dto.HeavyResource; +import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java b/spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java similarity index 94% rename from spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java rename to spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java index 9ef2dfa215..7b695cd23b 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java +++ b/spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java @@ -1,6 +1,5 @@ -package org.baeldung.web.controller.mediatypes; +package com.baeldung.web.controller.mediatypes; -import org.baeldung.config.WebConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -12,6 +11,8 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import com.baeldung.sampleapp.config.WebConfig; + import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java b/spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java similarity index 96% rename from spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java rename to spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java index 2b57e7049c..e48edc723c 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java +++ b/spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.mediatypes; +package com.baeldung.web.controller.mediatypes; import io.restassured.http.ContentType; import org.junit.Test; diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java b/spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java similarity index 81% rename from spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java rename to spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java index 66ffe4947d..7fc7f17e50 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java +++ b/spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.mediatypes; +package com.baeldung.web.controller.mediatypes; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java b/spring-rest/src/test/java/com/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java similarity index 98% rename from spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java rename to spring-rest/src/test/java/com/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java index c604db596a..745f7d5a31 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java +++ b/spring-rest/src/test/java/com/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.redirect; +package com.baeldung.web.controller.redirect; import static org.hamcrest.CoreMatchers.equalTo; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; diff --git a/spring-rest/src/test/resources/cache/2d9345a30d2cc31bb3091d70a8ef6c18.0 b/spring-rest/src/test/resources/cache/2d9345a30d2cc31bb3091d70a8ef6c18.0 index bc64f40e5d..e6cfcabe71 100644 --- a/spring-rest/src/test/resources/cache/2d9345a30d2cc31bb3091d70a8ef6c18.0 +++ b/spring-rest/src/test/resources/cache/2d9345a30d2cc31bb3091d70a8ef6c18.0 @@ -8,7 +8,7 @@ Content-Length: 1759 Connection: keep-alive Accept-Ranges: bytes Server: nginx/1.10.0 (Ubuntu) -Date: Sat, 28 Apr 2018 20:53:35 GMT +Date: Sat, 08 Dec 2018 13:02:07 GMT Last-Modified: Tue, 27 May 2014 02:35:47 GMT ETag: "5383fa03-6df" OkHttp-Sent-Millis: 1489054646765 diff --git a/spring-rest/src/test/resources/cache/4b217e04ba52215f3a6b64d28f6729c6.0 b/spring-rest/src/test/resources/cache/4b217e04ba52215f3a6b64d28f6729c6.0 index bbd34c75f6..85fc22d658 100644 --- a/spring-rest/src/test/resources/cache/4b217e04ba52215f3a6b64d28f6729c6.0 +++ b/spring-rest/src/test/resources/cache/4b217e04ba52215f3a6b64d28f6729c6.0 @@ -4,10 +4,10 @@ GET HTTP/1.1 301 Moved Permanently 8 Server: nginx/1.10.0 (Ubuntu) -Date: Sat, 28 Apr 2018 20:53:33 GMT +Date: Sat, 08 Dec 2018 13:02:04 GMT Content-Type: text/html Content-Length: 194 Connection: keep-alive Location: https://publicobject.com/helloworld.txt -OkHttp-Sent-Millis: 1524948815122 -OkHttp-Received-Millis: 1524948815342 +OkHttp-Sent-Millis: 1544274128028 +OkHttp-Received-Millis: 1544274128386 diff --git a/spring-rest/src/test/resources/cache/journal b/spring-rest/src/test/resources/cache/journal index eed030a85d..a139399103 100644 --- a/spring-rest/src/test/resources/cache/journal +++ b/spring-rest/src/test/resources/cache/journal @@ -67,3 +67,9 @@ CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194 READ 2d9345a30d2cc31bb3091d70a8ef6c18 DIRTY 2d9345a30d2cc31bb3091d70a8ef6c18 CLEAN 2d9345a30d2cc31bb3091d70a8ef6c18 7618 1759 +READ 4b217e04ba52215f3a6b64d28f6729c6 +DIRTY 4b217e04ba52215f3a6b64d28f6729c6 +CLEAN 4b217e04ba52215f3a6b64d28f6729c6 333 194 +READ 2d9345a30d2cc31bb3091d70a8ef6c18 +DIRTY 2d9345a30d2cc31bb3091d70a8ef6c18 +CLEAN 2d9345a30d2cc31bb3091d70a8ef6c18 7618 1759 From 0b0aedc2873f7de8d71e6fe04d0fdd8c8ec762d8 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sat, 8 Dec 2018 08:58:16 -0600 Subject: [PATCH 45/69] BAEL-2174: rename core-java-net module to core-java-networking (#5837) * BAEL-2246: add link back to article * BAEL-2174: rename core-java-net module to core-java-networking --- {core-java-net => core-java-networking}/.gitignore | 0 {core-java-net => core-java-networking}/README.md | 0 {core-java-net => core-java-networking}/pom.xml | 6 +++--- .../baeldung/networking/proxies/CommandLineProxyDemo.java | 0 .../com/baeldung/networking/proxies/DirectProxyDemo.java | 0 .../com/baeldung/networking/proxies/SocksProxyDemo.java | 0 .../networking/proxies/SystemPropertyProxyDemo.java | 0 .../com/baeldung/networking/proxies/UrlConnectionUtils.java | 0 .../java/com/baeldung/networking/proxies/WebProxyDemo.java | 0 .../src/test/resources/.gitignore | 0 pom.xml | 4 ++-- 11 files changed, 5 insertions(+), 5 deletions(-) rename {core-java-net => core-java-networking}/.gitignore (100%) rename {core-java-net => core-java-networking}/README.md (100%) rename {core-java-net => core-java-networking}/pom.xml (80%) rename {core-java-net => core-java-networking}/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java (100%) rename {core-java-net => core-java-networking}/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java (100%) rename {core-java-net => core-java-networking}/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java (100%) rename {core-java-net => core-java-networking}/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java (100%) rename {core-java-net => core-java-networking}/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java (100%) rename {core-java-net => core-java-networking}/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java (100%) rename {core-java-net => core-java-networking}/src/test/resources/.gitignore (100%) diff --git a/core-java-net/.gitignore b/core-java-networking/.gitignore similarity index 100% rename from core-java-net/.gitignore rename to core-java-networking/.gitignore diff --git a/core-java-net/README.md b/core-java-networking/README.md similarity index 100% rename from core-java-net/README.md rename to core-java-networking/README.md diff --git a/core-java-net/pom.xml b/core-java-networking/pom.xml similarity index 80% rename from core-java-net/pom.xml rename to core-java-networking/pom.xml index 28d5766a9a..178295e1ec 100644 --- a/core-java-net/pom.xml +++ b/core-java-networking/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - core-java-net + core-java-networking 0.1.0-SNAPSHOT jar - core-java-net + core-java-networking com.baeldung @@ -14,6 +14,6 @@ - core-java-net + core-java-networking diff --git a/core-java-net/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java similarity index 100% rename from core-java-net/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java diff --git a/core-java-net/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java similarity index 100% rename from core-java-net/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java diff --git a/core-java-net/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java similarity index 100% rename from core-java-net/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java diff --git a/core-java-net/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java similarity index 100% rename from core-java-net/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java diff --git a/core-java-net/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java similarity index 100% rename from core-java-net/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java diff --git a/core-java-net/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java similarity index 100% rename from core-java-net/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java diff --git a/core-java-net/src/test/resources/.gitignore b/core-java-networking/src/test/resources/.gitignore similarity index 100% rename from core-java-net/src/test/resources/.gitignore rename to core-java-networking/src/test/resources/.gitignore diff --git a/pom.xml b/pom.xml index 4a1db4a937..78ce1821fa 100644 --- a/pom.xml +++ b/pom.xml @@ -367,7 +367,7 @@ core-java - core-java-net + core-java-networking dozer disruptor @@ -923,7 +923,7 @@ core-java - core-java-net + core-java-networking dozer disruptor From 0abf2d243aebf58ebaaced42eaea45b0ee723605 Mon Sep 17 00:00:00 2001 From: Mikhail Chugunov Date: Sat, 8 Dec 2018 17:59:10 +0300 Subject: [PATCH 46/69] BAEL-2327: Implement simple escaping and tests (#5745) * BAEL-2327: Implement simple escaping and tests * BAEL-2327: Rename test to comply with CI rules --- json/pom.xml | 10 +++++ .../java/com/baeldung/escape/JsonEscape.java | 41 +++++++++++++++++++ .../baeldung/escape/JsonEscapeUnitTest.java | 36 ++++++++++++++++ 3 files changed, 87 insertions(+) create mode 100644 json/src/main/java/com/baeldung/escape/JsonEscape.java create mode 100644 json/src/test/java/com/baeldung/escape/JsonEscapeUnitTest.java diff --git a/json/pom.xml b/json/pom.xml index db98ec437e..fce2d26db5 100644 --- a/json/pom.xml +++ b/json/pom.xml @@ -33,6 +33,16 @@ org.json json 20171018 + + + com.google.code.gson + gson + 2.8.5 + + + com.fasterxml.jackson.core + jackson-databind + 2.9.7 javax.json.bind diff --git a/json/src/main/java/com/baeldung/escape/JsonEscape.java b/json/src/main/java/com/baeldung/escape/JsonEscape.java new file mode 100644 index 0000000000..1e5f0d87cb --- /dev/null +++ b/json/src/main/java/com/baeldung/escape/JsonEscape.java @@ -0,0 +1,41 @@ +package com.baeldung.escape; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonObject; +import org.json.JSONObject; + +class JsonEscape { + + String escapeJson(String input) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("message", input); + return jsonObject.toString(); + } + + String escapeGson(String input) { + JsonObject gsonObject = new JsonObject(); + gsonObject.addProperty("message", input); + return gsonObject.toString(); + } + + String escapeJackson(String input) throws JsonProcessingException { + return new ObjectMapper().writeValueAsString(new Payload(input)); + } + + static class Payload { + String message; + + Payload(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + } +} diff --git a/json/src/test/java/com/baeldung/escape/JsonEscapeUnitTest.java b/json/src/test/java/com/baeldung/escape/JsonEscapeUnitTest.java new file mode 100644 index 0000000000..e959fa227b --- /dev/null +++ b/json/src/test/java/com/baeldung/escape/JsonEscapeUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.escape; + +import com.fasterxml.jackson.core.JsonProcessingException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class JsonEscapeUnitTest { + + private JsonEscape testedInstance; + private static final String EXPECTED = "{\"message\":\"Hello \\\"World\\\"\"}"; + + @BeforeEach + void setUp() { + testedInstance = new JsonEscape(); + } + + @Test + void escapeJson() { + String actual = testedInstance.escapeJson("Hello \"World\""); + assertEquals(EXPECTED, actual); + } + + @Test + void escapeGson() { + String actual = testedInstance.escapeGson("Hello \"World\""); + assertEquals(EXPECTED, actual); + } + + @Test + void escapeJackson() throws JsonProcessingException { + String actual = testedInstance.escapeJackson("Hello \"World\""); + assertEquals(EXPECTED, actual); + } +} \ No newline at end of file From ea70595615dbecc4a2b169563d4aea431e863981 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 9 Dec 2018 00:36:34 +0530 Subject: [PATCH 47/69] [BAEL-9643] - Create code for Properties article --- .../java/properties/PropertiesUnitTest.java | 146 ++++++++++++++++++ core-java/src/test/resources/app.properties | 3 + core-java/src/test/resources/catalog | 3 + .../src/test/resources/default.properties | 4 + core-java/src/test/resources/icons.xml | 8 + 5 files changed, 164 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java create mode 100644 core-java/src/test/resources/app.properties create mode 100644 core-java/src/test/resources/catalog create mode 100644 core-java/src/test/resources/default.properties create mode 100644 core-java/src/test/resources/icons.xml diff --git a/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java b/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java new file mode 100644 index 0000000000..a5c3890edb --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java @@ -0,0 +1,146 @@ +package com.baeldung.java.properties; + +import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Properties; + +import org.junit.Test; + +public class PropertiesUnitTest { + + @Test + public void givenPropertyValue_whenPropertiesFileLoaded_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + String catalogConfigPath = rootPath + "catalog"; + + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + Properties catalogProps = new Properties(); + catalogProps.load(new FileInputStream(catalogConfigPath)); + + String appVersion = appProps.getProperty("version"); + assertEquals("1.0", appVersion); + + assertEquals("files", catalogProps.getProperty("c1")); + } + + @Test + public void givenPropertyValue_whenXMLPropertiesFileLoaded_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String iconConfigPath = rootPath + "icons.xml"; + Properties iconProps = new Properties(); + iconProps.loadFromXML(new FileInputStream(iconConfigPath)); + + assertEquals("icon1.jpg", iconProps.getProperty("fileIcon")); + } + + @Test + public void givenAbsentProperty_whenPropertiesFileLoaded_thenReturnsDefault() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + String appVersion = appProps.getProperty("version"); + String appName = appProps.getProperty("name", "defaultName"); + String appGroup = appProps.getProperty("group", "baeldung"); + String appDownloadAddr = appProps.getProperty("downloadAddr"); + + assertEquals("1.0", appVersion); + assertEquals("TestApp", appName); + assertEquals("baeldung", appGroup); + assertNull(appDownloadAddr); + } + + @Test(expected = Exception.class) + public void givenImproperObjectCasting_whenPropertiesFileLoaded_thenThrowsException() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + float appVerFloat = (float) appProps.get("version"); + } + + @Test + public void givenPropertyValue_whenPropertiesSet_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + appProps.setProperty("name", "NewAppName"); + appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); + + String newAppName = appProps.getProperty("name"); + assertEquals("NewAppName", newAppName); + + String newAppDownloadAddr = appProps.getProperty("downloadAddr"); + assertEquals("www.baeldung.com/downloads", newAppDownloadAddr); + } + + @Test + public void givenPropertyValueNull_whenPropertiesRemoved_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + String versionBeforeRemoval = appProps.getProperty("version"); + assertEquals("1.0", versionBeforeRemoval); + + appProps.remove("version"); + String versionAfterRemoval = appProps.getProperty("version"); + assertNull(versionAfterRemoval); + } + + @Test + public void whenPropertiesStoredInFile_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + String newAppConfigPropertiesFile = rootPath + "newApp.properties"; + appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file"); + + String newAppConfigXmlFile = rootPath + "newApp.xml"; + appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file"); + } + + @Test + public void givenPropertyValueAbsent_LoadsValuesFromDefaultProperties() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + + String defaultConfigPath = rootPath + "default.properties"; + Properties defaultProps = new Properties(); + defaultProps.load(new FileInputStream(defaultConfigPath)); + + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(defaultProps); + appProps.load(new FileInputStream(appConfigPath)); + + String appName = appProps.getProperty("name"); + String appVersion = appProps.getProperty("version"); + String defaultSite = appProps.getProperty("site"); + + assertEquals("1.0", appVersion); + assertEquals("TestApp", appName); + assertEquals("www.google.com", defaultSite); + } +} diff --git a/core-java/src/test/resources/app.properties b/core-java/src/test/resources/app.properties new file mode 100644 index 0000000000..ff6174ec2a --- /dev/null +++ b/core-java/src/test/resources/app.properties @@ -0,0 +1,3 @@ +version=1.0 +name=TestApp +date=2016-11-12 \ No newline at end of file diff --git a/core-java/src/test/resources/catalog b/core-java/src/test/resources/catalog new file mode 100644 index 0000000000..488513d0ce --- /dev/null +++ b/core-java/src/test/resources/catalog @@ -0,0 +1,3 @@ +c1=files +c2=images +c3=videos \ No newline at end of file diff --git a/core-java/src/test/resources/default.properties b/core-java/src/test/resources/default.properties new file mode 100644 index 0000000000..df1bab371c --- /dev/null +++ b/core-java/src/test/resources/default.properties @@ -0,0 +1,4 @@ +site=www.google.com +name=DefaultAppName +topic=Properties +category=core-java \ No newline at end of file diff --git a/core-java/src/test/resources/icons.xml b/core-java/src/test/resources/icons.xml new file mode 100644 index 0000000000..0db7b2699a --- /dev/null +++ b/core-java/src/test/resources/icons.xml @@ -0,0 +1,8 @@ + + + + xml example + icon1.jpg + icon2.jpg + icon3.jpg + \ No newline at end of file From be16616bb82749212e259b4d0e44d3f28601a9f4 Mon Sep 17 00:00:00 2001 From: Juan Moreno Date: Sat, 8 Dec 2018 16:21:30 -0300 Subject: [PATCH 48/69] Added new samples --- java-streams/.attach_pid12113 | 0 .../stream/filter/StreamFilterUnitTest.java | 94 ++++++++++++++----- 2 files changed, 69 insertions(+), 25 deletions(-) create mode 100644 java-streams/.attach_pid12113 diff --git a/java-streams/.attach_pid12113 b/java-streams/.attach_pid12113 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java index c89a27cdf1..cf82802940 100644 --- a/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java @@ -8,56 +8,93 @@ import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; public class StreamFilterUnitTest { @Test - public void givenListOfCustomers_whenFilterByLambda_thenGetTwo() { - List customers = Arrays.asList(new Customer("John P.", 15), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), new Customer("Mary T.", 1)); + public void givenListOfCustomers_whenFilterByPoints_thenGetTwo() { + Customer john = new Customer("John P.", 15); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1); + List customers = Arrays.asList(john, sarah, charles, mary); - long customersWithMoreThan100Points = customers + List customersWithMoreThan100Points = customers .stream() .filter(c -> c.getPoints() > 100) - .count(); + .collect(Collectors.toList()); - assertThat(customersWithMoreThan100Points).isEqualTo(2); + assertThat(customersWithMoreThan100Points).hasSize(2); + assertThat(customersWithMoreThan100Points).contains(sarah, charles); + } + + @Test + public void givenListOfCustomers_whenFilterByPointsAndName_thenGetOne() { + Customer john = new Customer("John P.", 15); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1); + List customers = Arrays.asList(john, sarah, charles, mary); + + List charlesWithMoreThan100Points = customers + .stream() + .filter(c -> c.getPoints() > 100 && c + .getName() + .startsWith("Charles")) + .collect(Collectors.toList()); + + assertThat(charlesWithMoreThan100Points).hasSize(1); + assertThat(charlesWithMoreThan100Points).contains(charles); } @Test public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() { - List customers = Arrays.asList(new Customer("John P.", 15), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), new Customer("Mary T.", 1)); + Customer john = new Customer("John P.", 15); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1); + List customers = Arrays.asList(john, sarah, charles, mary); - long customersWithMoreThan100Points = customers + List customersWithMoreThan100Points = customers .stream() .filter(Customer::hasOverThousandPoints) - .count(); + .collect(Collectors.toList()); - assertThat(customersWithMoreThan100Points).isEqualTo(2); + assertThat(customersWithMoreThan100Points).hasSize(2); + assertThat(customersWithMoreThan100Points).contains(sarah, charles); } @Test public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() { - List> customers = Arrays.asList(Optional.of(new Customer("John P.", 15)), Optional.of(new Customer("Sarah M.", 200)), Optional.empty(), Optional.of(new Customer("Mary T.", 300)), Optional.empty()); + Optional john = Optional.of(new Customer("John P.", 15)); + Optional sarah = Optional.of(new Customer("Sarah M.", 200)); + Optional mary = Optional.of(new Customer("Mary T.", 300)); + List> customers = Arrays.asList(john, sarah, Optional.empty(), mary, Optional.empty()); - long customersWithMoreThan100Points = customers + List customersWithMoreThan100Points = customers .stream() .flatMap(c -> c .map(Stream::of) .orElseGet(Stream::empty)) .filter(Customer::hasOverThousandPoints) - .count(); + .collect(Collectors.toList()); - assertThat(customersWithMoreThan100Points).isEqualTo(2); + assertThat(customersWithMoreThan100Points).hasSize(2); + assertThat(customersWithMoreThan100Points).contains(sarah.get(), mary.get()); } @Test public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() { - List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), - new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"); + List customers = Arrays.asList(john, sarah, charles, mary); assertThatThrownBy(() -> customers .stream() @@ -67,21 +104,27 @@ public class StreamFilterUnitTest { @Test public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() { - List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), - new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"); + List customers = Arrays.asList(john, sarah, charles, mary); assertThatThrownBy(() -> customers .stream() .filter((ThrowingPredicate.unchecked(Customer::hasValidProfilePhoto))) - .count()).isInstanceOf(WrappedException.class); + .collect(Collectors.toList())).isInstanceOf(WrappedException.class); } @Test public void givenListOfCustomers_whenFilterWithTryCatch_thenGetTwo() { - List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), - new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"); + List customers = Arrays.asList(john, sarah, charles, mary); - long customersWithValidProfilePhoto = customers + List customersWithValidProfilePhoto = customers .stream() .filter(c -> { try { @@ -91,9 +134,10 @@ public class StreamFilterUnitTest { } return false; }) - .count(); + .collect(Collectors.toList()); - assertThat(customersWithValidProfilePhoto).isEqualTo(2); + assertThat(customersWithValidProfilePhoto).hasSize(2); + assertThat(customersWithValidProfilePhoto).contains(john, mary); } @Test @@ -110,6 +154,6 @@ public class StreamFilterUnitTest { throw new RuntimeException(e); } }) - .count()).isInstanceOf(RuntimeException.class); + .collect(Collectors.toList())).isInstanceOf(RuntimeException.class); } } From dfca36b9addbd24a123ca250d40a3c8dfda75258 Mon Sep 17 00:00:00 2001 From: Juan Moreno Date: Sat, 8 Dec 2018 16:31:20 -0300 Subject: [PATCH 49/69] Removed .attach_pid12113 file --- java-streams/.attach_pid12113 | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 java-streams/.attach_pid12113 diff --git a/java-streams/.attach_pid12113 b/java-streams/.attach_pid12113 deleted file mode 100644 index e69de29bb2..0000000000 From b51ae5b065521814e8d84fcc05f9e7c340968e4e Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 8 Dec 2018 22:16:52 +0200 Subject: [PATCH 50/69] fix package name, start class --- spring-rest/pom.xml | 4 +--- spring-rest/src/main/webapp/WEB-INF/api-servlet.xml | 2 +- spring-rest/src/main/webapp/WEB-INF/web.xml | 2 +- .../com/baeldung/web/controller/mediatypes/TestConfig.java | 2 +- 4 files changed, 4 insertions(+), 6 deletions(-) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 1a4ad2fbb6..ea4cfc26d7 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -183,9 +183,6 @@ org.springframework.boot spring-boot-maven-plugin - - true - org.apache.maven.plugins @@ -300,6 +297,7 @@ 2.2.0 3.5.11 3.1.0 + com.baeldung.sampleapp.config.MainApplication diff --git a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml index 7e7d820836..ddb9c91792 100644 --- a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml +++ b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml @@ -6,7 +6,7 @@ http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd" > - + diff --git a/spring-rest/src/main/webapp/WEB-INF/web.xml b/spring-rest/src/main/webapp/WEB-INF/web.xml index 1b8b767ae3..20a11f3422 100644 --- a/spring-rest/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest/src/main/webapp/WEB-INF/web.xml @@ -16,7 +16,7 @@ contextConfigLocation - org.baeldung.config + com.baeldung.sampleapp.config + + diff --git a/spring-boot/src/main/resources/templates/displayallbeans.html b/spring-boot/src/main/resources/templates/displayallbeans.html new file mode 100644 index 0000000000..5fc78a7fca --- /dev/null +++ b/spring-boot/src/main/resources/templates/displayallbeans.html @@ -0,0 +1,10 @@ + + + + Baeldung + + +

+

+ + diff --git a/spring-boot/src/main/resources/templates/error-404.html b/spring-boot/src/main/resources/templates/error-404.html new file mode 100644 index 0000000000..cf68032596 --- /dev/null +++ b/spring-boot/src/main/resources/templates/error-404.html @@ -0,0 +1,14 @@ + + + + + + + +
+
+

Sorry, we couldn't find the page you were looking for.

+

Go Home

+
+ + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/error-500.html b/spring-boot/src/main/resources/templates/error-500.html new file mode 100644 index 0000000000..5ddf458229 --- /dev/null +++ b/spring-boot/src/main/resources/templates/error-500.html @@ -0,0 +1,16 @@ + + + + + + + +
+
+

Sorry, something went wrong!

+ +

We're fixing it.

+

Go Home

+
+ + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/error.html b/spring-boot/src/main/resources/templates/error.html new file mode 100644 index 0000000000..bc517913b2 --- /dev/null +++ b/spring-boot/src/main/resources/templates/error.html @@ -0,0 +1,16 @@ + + + + + + + +
+
+

Something went wrong!

+ +

Our Engineers are on it.

+

Go Home

+
+ + diff --git a/spring-boot/src/main/resources/templates/error/404.html b/spring-boot/src/main/resources/templates/error/404.html new file mode 100644 index 0000000000..df83ce219b --- /dev/null +++ b/spring-boot/src/main/resources/templates/error/404.html @@ -0,0 +1,8 @@ + + + RESOURCE NOT FOUND + + +

404 RESOURCE NOT FOUND

+ + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/external.html b/spring-boot/src/main/resources/templates/external.html new file mode 100644 index 0000000000..2f9cc76961 --- /dev/null +++ b/spring-boot/src/main/resources/templates/external.html @@ -0,0 +1,31 @@ + + + + + +
+
+

Customer Portal

+
+
+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam + erat lectus, vehicula feugiat ultricies at, tempus sed ante. Cras + arcu erat, lobortis vitae quam et, mollis pharetra odio. Nullam sit + amet congue ipsum. Nunc dapibus odio ut ligula venenatis porta non + id dui. Duis nec tempor tellus. Suspendisse id blandit ligula, sit + amet varius mauris. Nulla eu eros pharetra, tristique dui quis, + vehicula libero. Aenean a neque sit amet tellus porttitor rutrum nec + at leo.

+ +

Existing Customers

+
+ Enter the intranet: customers +
+
+ +
+ + + + diff --git a/spring-boot/src/main/resources/templates/index.html b/spring-boot/src/main/resources/templates/index.html new file mode 100644 index 0000000000..c1314558f6 --- /dev/null +++ b/spring-boot/src/main/resources/templates/index.html @@ -0,0 +1,19 @@ + + + WebJars Demo + + + +

Welcome Home

+

+
+ × + Success! It is working as we expected. +
+
+ + + + + + diff --git a/spring-boot/src/main/resources/templates/international.html b/spring-boot/src/main/resources/templates/international.html new file mode 100644 index 0000000000..e0cfb5143b --- /dev/null +++ b/spring-boot/src/main/resources/templates/international.html @@ -0,0 +1,20 @@ + + + + +Home + + + + +

+ +

+: + + + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/layout.html b/spring-boot/src/main/resources/templates/layout.html new file mode 100644 index 0000000000..bab0c2982b --- /dev/null +++ b/spring-boot/src/main/resources/templates/layout.html @@ -0,0 +1,18 @@ + + + +Customer Portal + + + + + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/other.html b/spring-boot/src/main/resources/templates/other.html new file mode 100644 index 0000000000..d13373f9fe --- /dev/null +++ b/spring-boot/src/main/resources/templates/other.html @@ -0,0 +1,16 @@ + + + + +Spring Utils Demo + + + + Parameter set by you:

+ + \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/utils.html b/spring-boot/src/main/resources/templates/utils.html new file mode 100644 index 0000000000..93030f424f --- /dev/null +++ b/spring-boot/src/main/resources/templates/utils.html @@ -0,0 +1,23 @@ + + + + +Spring Utils Demo + + + +

+

Set Parameter:

+

+ + +

+
+Another Page + + \ No newline at end of file From 22d22c7c4e832acf2956f402ddfdc3adbff071e3 Mon Sep 17 00:00:00 2001 From: Wosin Date: Sun, 9 Dec 2018 22:26:28 +0100 Subject: [PATCH 61/69] BAEL-1039: Introduction to Derive4J (#5845) --- libraries/pom.xml | 7 ++++ .../com/baeldung/derive4j/adt/Either.java | 10 ++++++ .../baeldung/derive4j/lazy/LazyRequest.java | 21 ++++++++++++ .../derive4j/pattern/HTTPRequest.java | 15 +++++++++ .../derive4j/pattern/HTTPResponse.java | 19 +++++++++++ .../baeldung/derive4j/pattern/HTTPServer.java | 17 ++++++++++ .../baeldung/derive4j/adt/EitherUnitTest.java | 33 +++++++++++++++++++ .../derive4j/lazy/LazyRequestUnitTest.java | 28 ++++++++++++++++ .../derive4j/pattern/HTTPRequestUnitTest.java | 22 +++++++++++++ 9 files changed, 172 insertions(+) create mode 100644 libraries/src/main/java/com/baeldung/derive4j/adt/Either.java create mode 100644 libraries/src/main/java/com/baeldung/derive4j/lazy/LazyRequest.java create mode 100644 libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPRequest.java create mode 100644 libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPResponse.java create mode 100644 libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPServer.java create mode 100644 libraries/src/test/java/com/baeldung/derive4j/adt/EitherUnitTest.java create mode 100644 libraries/src/test/java/com/baeldung/derive4j/lazy/LazyRequestUnitTest.java create mode 100644 libraries/src/test/java/com/baeldung/derive4j/pattern/HTTPRequestUnitTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index fb1f1cd1b6..cb85a57304 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -717,6 +717,12 @@ ${suanshu.version} + + org.derive4j + derive4j + ${derive4j.version} + true +
@@ -952,6 +958,7 @@ 4.5.1 3.3.0 3.0.2 + 1.1.0 diff --git a/libraries/src/main/java/com/baeldung/derive4j/adt/Either.java b/libraries/src/main/java/com/baeldung/derive4j/adt/Either.java new file mode 100644 index 0000000000..d22bb89fe2 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/adt/Either.java @@ -0,0 +1,10 @@ +package com.baeldung.derive4j.adt; + +import org.derive4j.Data; + +import java.util.function.Function; + +@Data +interface Either{ + X match(Function left, Function right); +} diff --git a/libraries/src/main/java/com/baeldung/derive4j/lazy/LazyRequest.java b/libraries/src/main/java/com/baeldung/derive4j/lazy/LazyRequest.java new file mode 100644 index 0000000000..9f53f3d25b --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/lazy/LazyRequest.java @@ -0,0 +1,21 @@ +package com.baeldung.derive4j.lazy; + +import org.derive4j.Data; +import org.derive4j.Derive; +import org.derive4j.Make; + +@Data(value = @Derive( + inClass = "{ClassName}Impl", + make = {Make.lazyConstructor, Make.constructors} +)) +public interface LazyRequest { + interface Cases{ + R GET(String path); + R POST(String path, String body); + R PUT(String path, String body); + R DELETE(String path); + } + + R match(LazyRequest.Cases method); +} + diff --git a/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPRequest.java b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPRequest.java new file mode 100644 index 0000000000..04d630f1ef --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPRequest.java @@ -0,0 +1,15 @@ +package com.baeldung.derive4j.pattern; + +import org.derive4j.Data; + +@Data +interface HTTPRequest { + interface Cases{ + R GET(String path); + R POST(String path, String body); + R PUT(String path, String body); + R DELETE(String path); + } + + R match(Cases method); +} diff --git a/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPResponse.java b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPResponse.java new file mode 100644 index 0000000000..593f94a8b7 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPResponse.java @@ -0,0 +1,19 @@ +package com.baeldung.derive4j.pattern; + +public class HTTPResponse { + private int statusCode; + private String responseBody; + + public int getStatusCode() { + return statusCode; + } + + public String getResponseBody() { + return responseBody; + } + + public HTTPResponse(int statusCode, String responseBody) { + this.statusCode = statusCode; + this.responseBody = responseBody; + } +} diff --git a/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPServer.java b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPServer.java new file mode 100644 index 0000000000..53f4af628c --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPServer.java @@ -0,0 +1,17 @@ +package com.baeldung.derive4j.pattern; + + +public class HTTPServer { + public static String GET_RESPONSE_BODY = "Success!"; + public static String PUT_RESPONSE_BODY = "Resource Created!"; + public static String POST_RESPONSE_BODY = "Resource Updated!"; + public static String DELETE_RESPONSE_BODY = "Resource Deleted!"; + + public HTTPResponse acceptRequest(HTTPRequest request) { + return HTTPRequests.caseOf(request) + .GET((path) -> new HTTPResponse(200, GET_RESPONSE_BODY)) + .POST((path,body) -> new HTTPResponse(201, POST_RESPONSE_BODY)) + .PUT((path,body) -> new HTTPResponse(200, PUT_RESPONSE_BODY)) + .DELETE(path -> new HTTPResponse(200, DELETE_RESPONSE_BODY)); + } +} diff --git a/libraries/src/test/java/com/baeldung/derive4j/adt/EitherUnitTest.java b/libraries/src/test/java/com/baeldung/derive4j/adt/EitherUnitTest.java new file mode 100644 index 0000000000..511e24961f --- /dev/null +++ b/libraries/src/test/java/com/baeldung/derive4j/adt/EitherUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.derive4j.adt; + +import org.assertj.core.api.Assertions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Optional; +import java.util.function.Function; +@RunWith(MockitoJUnitRunner.class) +public class EitherUnitTest { + @Test + public void testEitherIsCreatedFromRight() { + Either either = Eithers.right("Okay"); + Optional leftOptional = Eithers.getLeft(either); + Optional rightOptional = Eithers.getRight(either); + Assertions.assertThat(leftOptional).isEmpty(); + Assertions.assertThat(rightOptional).hasValue("Okay"); + + } + + @Test + public void testEitherIsMatchedWithRight() { + Either either = Eithers.right("Okay"); + Function leftFunction = Mockito.mock(Function.class); + Function rightFunction = Mockito.mock(Function.class); + either.match(leftFunction, rightFunction); + Mockito.verify(rightFunction, Mockito.times(1)).apply("Okay"); + Mockito.verify(leftFunction, Mockito.times(0)).apply(Mockito.any(Exception.class)); + } + +} diff --git a/libraries/src/test/java/com/baeldung/derive4j/lazy/LazyRequestUnitTest.java b/libraries/src/test/java/com/baeldung/derive4j/lazy/LazyRequestUnitTest.java new file mode 100644 index 0000000000..3830bc52d0 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/derive4j/lazy/LazyRequestUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.derive4j.lazy; + +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +import java.util.function.Supplier; + +public class LazyRequestUnitTest { + + @Test + public void givenLazyContstructedRequest_whenRequestIsReferenced_thenRequestIsLazilyContructed() { + LazyRequestSupplier mockSupplier = Mockito.spy(new LazyRequestSupplier()); + + LazyRequest request = LazyRequestImpl.lazy(() -> mockSupplier.get()); + Mockito.verify(mockSupplier, Mockito.times(0)).get(); + Assert.assertEquals(LazyRequestImpl.getPath(request), "http://test.com/get"); + Mockito.verify(mockSupplier, Mockito.times(1)).get(); + + } + + class LazyRequestSupplier implements Supplier { + @Override + public LazyRequest get() { + return LazyRequestImpl.GET("http://test.com/get"); + } + } +} diff --git a/libraries/src/test/java/com/baeldung/derive4j/pattern/HTTPRequestUnitTest.java b/libraries/src/test/java/com/baeldung/derive4j/pattern/HTTPRequestUnitTest.java new file mode 100644 index 0000000000..0fc257742a --- /dev/null +++ b/libraries/src/test/java/com/baeldung/derive4j/pattern/HTTPRequestUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.derive4j.pattern; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class HTTPRequestUnitTest { + public static HTTPServer server; + + @BeforeClass + public static void setUp() { + server = new HTTPServer(); + } + + @Test + public void givenHttpGETRequest_whenRequestReachesServer_thenProperResponseIsReturned() { + HTTPRequest postRequest = HTTPRequests.POST("http://test.com/post", "Resource"); + HTTPResponse response = server.acceptRequest(postRequest); + Assert.assertEquals(201, response.getStatusCode()); + Assert.assertEquals(HTTPServer.POST_RESPONSE_BODY, response.getResponseBody()); + } +} From 36decb42b9fd72460e62e76739bcfa285e87af09 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Mon, 10 Dec 2018 23:07:46 +0530 Subject: [PATCH 62/69] Task/bael 10829 (#5844) * BAEL-10829 Clean up the parent pom of the tutorials project - Cleaned up projects list for default-first and integration-lite-first profiles * BAEL-10829 Fixing unit test in JGit * BAEL-10829 Clean up the parent pom of the tutorials project -Updated modules list for default-second and integration-lite-second profiles * BAEL-10829 Fixed repository for structurizr libraries and api changes done in StructurizrSimple to incorporate new version --- .../java/com/baeldung/jgit/porcelain/Log.java | 4 +- .../baeldung/jgit/JGitBugIntegrationTest.java | 2 + pom.xml | 920 ++++++++++++------ spring-cloud/pom.xml | 2 +- structurizr/pom.xml | 29 +- .../structurizr/StructurizrSimple.java | 15 +- 6 files changed, 617 insertions(+), 355 deletions(-) diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java b/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java index cb476b9d9e..a50028a9ae 100644 --- a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java +++ b/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java @@ -28,14 +28,14 @@ public class Log { System.out.println("Had " + count + " commits overall on current branch"); logs = git.log() - .add(repository.resolve("remotes/origin/testbranch")) + .add(repository.resolve(git.getRepository().getFullBranch())) .call(); count = 0; for (RevCommit rev : logs) { System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); count++; } - System.out.println("Had " + count + " commits overall on test-branch"); + System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch()); logs = git.log() .all() diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java index ed7168b2c2..ad34890996 100644 --- a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java +++ b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java @@ -1,3 +1,5 @@ +package com.baeldung.jgit; + import com.baeldung.jgit.helper.Helper; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.ObjectReader; diff --git a/pom.xml b/pom.xml index eb60cb2e45..4e1e61961e 100644 --- a/pom.xml +++ b/pom.xml @@ -330,165 +330,235 @@ parent-java parent-kotlin - asm - atomix - aws - aws-lambda akka-streams algorithms-genetic algorithms-miscellaneous-1 algorithms-miscellaneous-2 algorithms-sorting + animal-sniffer-mvn-plugin annotations + antlr + apache-avro + apache-bval + apache-curator apache-cxf apache-fop - apache-poi - apache-tika - apache-thrift - apache-curator - apache-zookeeper + apache-geode + apache-meecrowave apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix autovalue + aws + aws-lambda axon azure - apache-velocity - apache-solrj - apache-meecrowave - antlr - - bootique - - cdi - core-java-collections - core-java-io - core-java-8 - core-groovy - couchbase - - - core-java - core-java-networking - dozer - disruptor - drools + bootique + + cas/cas-secured-app + cas/cas-server + cdi + checker-plugin + core-groovy + + + core-java-8 + + core-java-arrays + core-java-collections + core-java-concurrency-collections + core-java-io + core-java-lang + core-java-networking + core-java-sun + core-scala + couchbase + custom-pmd + + dagger + data-structures + ddd deeplearning4j + disruptor + dozer + drools + dubbo ethereum feign flips + flyway-cdi-extension + geotools google-cloud + google-web-toolkit + + + graphql/graphql-java + grpc gson guava guava-collections guava-modules/guava-18 guava-modules/guava-19 guava-modules/guava-21 + guice hazelcast - hystrix + helidon httpclient + hystrix image-processing immutables - + jackson - java-strings - java-collections-conversions java-collections-maps - java-streams + + java-ee-8-security-api java-lite java-numbers java-rmi + java-spi + java-streams + java-strings java-vavr-stream + java-websocket + javafx javax-servlets javaxval jaxb - javafx - jgroups jee-7-security + jersey + JGit + jgroups + jhipster + jib jjwt + jmeter + jmh + jni + jooby jsf - json-path json + json-path jsoup jta - jws - jersey - java-spi - java-ee-8-security-api + + + kotlin-libraries - + libraries-data + libraries-security + libraries-server linkrest - logging-modules/log-mdc logging-modules/log4j + logging-modules/log4j2 logging-modules/logback + logging-modules/log-mdc lombok lucene - + mapstruct maven + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + mesos-marathon + metrics + + microprofile msf4j + mustache mvn-wrapper mybatis - metrics - maven-archetype noexception - osgi + optaplanner orika - + osgi + patterns pdf - protobuffer performance-tests + + protobuffer + persistence-modules/activejdbc + persistence-modules/apache-cayenne + persistence-modules/core-java-persistence + persistence-modules/deltaspike + persistence-modules/flyway + persistence-modules/hbase + persistence-modules/hibernate5 + persistence-modules/influxdb + persistence-modules/java-cassandra + persistence-modules/java-cockroachdb persistence-modules/java-jdbi - persistence-modules/redis + persistence-modules/java-jpa + persistence-modules/java-mongodb + persistence-modules/jnosql + persistence-modules/liquibase persistence-modules/orientdb persistence-modules/querydsl - persistence-modules/apache-cayenne + persistence-modules/redis persistence-modules/solr - persistence-modules/spring-data-dynamodb - persistence-modules/spring-data-keyvalue - persistence-modules/spring-data-neo4j - persistence-modules/spring-data-solr - persistence-modules/spring-hibernate-5 - persistence-modules/spring-data-eclipselink - persistence-modules/spring-jpa - persistence-modules/spring-hibernate-3 - persistence-modules/spring-data-gemfire + persistence-modules/spring-boot-h2/spring-boot-h2-database persistence-modules/spring-boot-persistence - persistence-modules/liquibase - persistence-modules/java-cockroachdb - persistence-modules/deltaspike - persistence-modules/hbase - persistence-modules/influxdb - persistence-modules/spring-hibernate4 - persistence-modules/spring-data-mongodb - persistence-modules/java-cassandra + persistence-modules/spring-boot-persistence-mongodb persistence-modules/spring-data-cassandra + persistence-modules/spring-data-cassandra-reactive persistence-modules/spring-data-couchbase-2 + persistence-modules/spring-data-dynamodb + persistence-modules/spring-data-eclipselink + persistence-modules/spring-data-elasticsearch + persistence-modules/spring-data-gemfire + persistence-modules/spring-data-jpa + persistence-modules/spring-data-keyvalue + persistence-modules/spring-data-mongodb + persistence-modules/spring-data-neo4j persistence-modules/spring-data-redis - persistence-modules/spring-boot-persistence-mongodb - - reactor-core - resteasy - rsocket - rxjava - rxjava-2 + persistence-modules/spring-data-solr + persistence-modules/spring-hibernate-3 + persistence-modules/spring-hibernate-5 + persistence-modules/spring-hibernate4 + persistence-modules/spring-jpa + rabbitmq - + + ratpack + reactor-core + rest-with-spark-java + resteasy + restx + + rule-engines/easy-rules + rule-engines/openl-tablets + rule-engines/rulebook + rsocket + rxjava + rxjava-2 +
@@ -528,98 +598,120 @@ parent-java parent-kotlin - spring-4 - spring-5 - spring-5-reactive - spring-5-reactive-security - spring-5-reactive-client - spring-5-mvc - spring-5-security - spring-5-security-oauth + saas + spark-java + + spring-4 + + spring-5 + spring-5-mvc + spring-5-reactive + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security + spring-5-security + spring-5-security-oauth - spring-aop spring-activiti spring-akka - spring-amqp spring-all + spring-amqp + spring-aop spring-apache-camel spring-batch spring-bom - spring-boot-keycloak - spring-boot-bootstrap - spring-boot-admin - spring-boot-camel - spring-boot-security - spring-boot-mvc - spring-boot-logging-log4j2 - spring-boot-disable-console-logging - spring-boot-property-exp - spring-boot-ctx-fluent - spring-boot - spring-boot-ops - spring-cloud-data-flow + spring-boot + spring-boot-admin + spring-boot-angular-ecommerce + spring-boot-autoconfiguration + spring-boot-bootstrap + spring-boot-camel + + spring-boot-client + spring-boot-crud + spring-boot-ctx-fluent + spring-boot-custom-starter + spring-boot-disable-console-logging + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-ops + spring-boot-property-exp + spring-boot-security + spring-boot-vue + spring-cloud spring-cloud-bus + + spring-cloud-data-flow + spring-core spring-cucumber + spring-data-rest - spring-drools + spring-data-rest-querydsl spring-dispatcher-servlet + spring-drools + spring-ejb spring-exceptions spring-freemarker + + spring-groovy + spring-integration - spring-jinq spring-jenkins-pipeline spring-jersey + spring-jinq spring-jms spring-jooq + spring-kafka spring-katharsis + spring-ldap + spring-mobile spring-mockito + spring-mustache spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java + spring-mvc-kotlin + spring-mvc-simple spring-mvc-velocity spring-mvc-webflow spring-mvc-xml - spring-mvc-kotlin + spring-mybatis spring-protobuf + spring-quartz - spring-rest-angular - spring-rest-full - spring-rest-query-language - spring-rest - spring-resttemplate - spring-rest-simple - spring-remoting - spring-session - spring-sleuth - spring-social-login - spring-spel - spring-state-machine - spring-thymeleaf - spring-userservice - - spring-zuul + spring-reactive-kotlin spring-reactor - spring-vertx - spring-vault + spring-remoting + spring-rest + spring-rest-angular spring-rest-embedded-tomcat - spring-swagger-codegen - spring-webflux-amqp + spring-rest-full + spring-rest-hal-browser + spring-rest-query-language + spring-rest-shell + spring-rest-simple + spring-rest-template + spring-resttemplate + spring-roo - spring-static-resources - spring-security-thymeleaf spring-security-acl + spring-security-angular/server spring-security-cache-control + spring-security-client/spring-security-jsp-authentication spring-security-client/spring-security-jsp-authorize spring-security-client/spring-security-jsp-config @@ -627,8 +719,10 @@ spring-security-client/spring-security-thymeleaf-authentication spring-security-client/spring-security-thymeleaf-authorize spring-security-client/spring-security-thymeleaf-config + spring-security-core spring-security-mvc-boot + spring-security-mvc-custom spring-security-mvc-digest-auth spring-security-mvc-ldap spring-security-mvc-login @@ -637,65 +731,73 @@ spring-security-mvc-socket spring-security-openid + spring-security-rest spring-security-rest-basic-auth spring-security-rest-custom - spring-security-rest spring-security-sso + spring-security-stormpath + spring-security-thymeleaf spring-security-x509 - spring-security-mvc-custom + spring-session + spring-sleuth + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen - spark-java - saas + spring-thymeleaf + + spring-userservice + + spring-vault + spring-vertx + + spring-webflux-amqp + + spring-zuul + + sse-jaxrs + static-analysis + stripe + structurizr struts-2 - testing-modules/selenium-junit-testng + testing-modules/gatling testing-modules/groovy-spock + testing-modules/junit-5 + testing-modules/junit5-migration + testing-modules/load-testing-comparison testing-modules/mockito testing-modules/mockito-2 testing-modules/mocks + testing-modules/mockserver + testing-modules/parallel-tests-junit testing-modules/rest-assured testing-modules/rest-testing - testing-modules/junit-5 - testing-modules/junit5-migration + + testing-modules/selenium-junit-testng + testing-modules/spring-testing + testing-modules/test-containers testing-modules/testing testing-modules/testng - testing-modules/mockserver - testing-modules/test-containers + twilio + Twitter4J undertow - video-tutorials - vaadin - vertx-and-rxjava - vraptor - vertx vavr + vertx + vertx-and-rxjava + video-tutorials + vraptor + + wicket - xmlunit-2 xml - - - - - - - - - + xmlunit-2 + xstream
@@ -845,7 +947,7 @@ spring-swagger-codegen/spring-swagger-codegen-app spring-thymeleaf spring-userservice - spring-vault + spring-vault spring-vertx spring-zuul/spring-zuul-foos-resource persistence-modules/spring-data-dynamodb @@ -856,6 +958,61 @@ + + default-heavy + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*JdbcTest.java + **/*LiveTest.java + + + + + + + + + parent-boot-1 + parent-boot-2 + parent-boot-2.0-temp + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + core-java + core-java-concurrency + core-kotlin + + jenkins/hello-world + jws + + libraries + + persistence-modules/hibernate5 + persistence-modules/java-jpa + persistence-modules/jnosql + + spring-5-data-reactive + spring-amqp-simple + + vaadin + + + integration-lite-first @@ -887,165 +1044,236 @@ parent-java parent-kotlin - asm - atomix - aws - aws-lambda akka-streams algorithms-genetic algorithms-miscellaneous-1 algorithms-miscellaneous-2 algorithms-sorting + animal-sniffer-mvn-plugin annotations + antlr + apache-avro + apache-bval + apache-curator apache-cxf apache-fop - apache-poi - apache-tika - apache-thrift - apache-curator - apache-zookeeper + apache-geode + apache-meecrowave apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix autovalue + aws + aws-lambda axon azure - apache-velocity - apache-solrj - apache-meecrowave - antlr - + bootique - + + cas/cas-secured-app + cas/cas-server cdi - core-java-collections - core-java-io - core-java-8 + checker-plugin core-groovy - couchbase - - - core-java + + + core-java-8 + + core-java-arrays + core-java-collections + core-java-concurrency-collections + core-java-io + core-java-lang core-java-networking - - dozer - disruptor - drools + core-java-sun + core-scala + couchbase + custom-pmd + + dagger + data-structures + ddd deeplearning4j + disruptor + dozer + drools + dubbo ethereum feign flips + flyway-cdi-extension + geotools google-cloud + google-web-toolkit + + + graphql/graphql-java + grpc gson guava guava-collections guava-modules/guava-18 guava-modules/guava-19 guava-modules/guava-21 + guice hazelcast - hystrix + helidon httpclient + hystrix image-processing immutables - + jackson - java-strings - java-collections-conversions java-collections-maps - java-streams + + java-ee-8-security-api java-lite java-numbers java-rmi + java-spi + java-streams + java-strings java-vavr-stream + java-websocket + javafx javax-servlets javaxval jaxb - javafx - jgroups jee-7-security + jersey + JGit + jgroups + jhipster + jib jjwt + jmeter + jmh + jni + jooby jsf - json-path json + json-path jsoup jta - jws - jersey - java-spi - java-ee-8-security-api + + + kotlin-libraries - + libraries-data + libraries-security + libraries-server linkrest - logging-modules/log-mdc logging-modules/log4j + logging-modules/log4j2 logging-modules/logback + logging-modules/log-mdc lombok lucene - + mapstruct maven + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + mesos-marathon + metrics + + microprofile msf4j + mustache mvn-wrapper mybatis - metrics - maven-archetype noexception - osgi + optaplanner orika - + osgi + patterns pdf - protobuffer performance-tests + + protobuffer + persistence-modules/activejdbc + persistence-modules/apache-cayenne + persistence-modules/core-java-persistence + persistence-modules/deltaspike + persistence-modules/flyway + persistence-modules/hbase + persistence-modules/hibernate5 + persistence-modules/influxdb + persistence-modules/java-cassandra + persistence-modules/java-cockroachdb persistence-modules/java-jdbi - persistence-modules/redis + persistence-modules/java-jpa + persistence-modules/java-mongodb + persistence-modules/jnosql + persistence-modules/liquibase persistence-modules/orientdb persistence-modules/querydsl - persistence-modules/apache-cayenne + persistence-modules/redis persistence-modules/solr - persistence-modules/spring-data-dynamodb - persistence-modules/spring-data-keyvalue - persistence-modules/spring-data-neo4j - persistence-modules/spring-data-solr - persistence-modules/spring-hibernate-5 - persistence-modules/spring-data-eclipselink - persistence-modules/spring-jpa - persistence-modules/spring-hibernate-3 - persistence-modules/spring-data-gemfire + persistence-modules/spring-boot-h2/spring-boot-h2-database persistence-modules/spring-boot-persistence - persistence-modules/liquibase - persistence-modules/java-cockroachdb - persistence-modules/deltaspike - persistence-modules/hbase - persistence-modules/influxdb - persistence-modules/spring-hibernate4 - persistence-modules/spring-data-mongodb - persistence-modules/java-cassandra + persistence-modules/spring-boot-persistence-mongodb persistence-modules/spring-data-cassandra + persistence-modules/spring-data-cassandra-reactive persistence-modules/spring-data-couchbase-2 + persistence-modules/spring-data-dynamodb + persistence-modules/spring-data-eclipselink + persistence-modules/spring-data-elasticsearch + persistence-modules/spring-data-gemfire + persistence-modules/spring-data-jpa + persistence-modules/spring-data-keyvalue + persistence-modules/spring-data-mongodb + persistence-modules/spring-data-neo4j persistence-modules/spring-data-redis - - reactor-core - resteasy - rsocket - rxjava - rxjava-2 + persistence-modules/spring-data-solr + persistence-modules/spring-hibernate-3 + persistence-modules/spring-hibernate-5 + persistence-modules/spring-hibernate4 + persistence-modules/spring-jpa + rabbitmq - -
+ + ratpack + reactor-core + rest-with-spark-java + resteasy + restx + + rule-engines/easy-rules + rule-engines/openl-tablets + rule-engines/rulebook + rsocket + rxjava + rxjava-2 + +
@@ -1080,98 +1308,120 @@ parent-java parent-kotlin - spring-4 - spring-5 - spring-5-reactive - spring-5-reactive-security - spring-5-reactive-client - spring-5-mvc - spring-5-security - spring-5-security-oauth + saas + spark-java + + spring-4 + + spring-5 + spring-5-mvc + spring-5-reactive + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security + spring-5-security + spring-5-security-oauth - spring-aop spring-activiti spring-akka - spring-amqp spring-all + spring-amqp + spring-aop spring-apache-camel spring-batch spring-bom - spring-boot-keycloak - spring-boot-bootstrap - spring-boot-admin - spring-boot-camel - spring-boot-security - spring-boot-mvc - spring-boot-logging-log4j2 - spring-boot-disable-console-logging - spring-boot-property-exp - spring-boot-ctx-fluent - spring-boot - spring-boot-ops - spring-cloud-data-flow + spring-boot + spring-boot-admin + spring-boot-angular-ecommerce + spring-boot-autoconfiguration + spring-boot-bootstrap + spring-boot-camel + + spring-boot-client + spring-boot-crud + spring-boot-ctx-fluent + spring-boot-custom-starter + spring-boot-disable-console-logging + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-ops + spring-boot-property-exp + spring-boot-security + spring-boot-vue + spring-cloud spring-cloud-bus + + spring-cloud-data-flow + spring-core spring-cucumber + spring-data-rest - spring-drools + spring-data-rest-querydsl spring-dispatcher-servlet + spring-drools + spring-ejb spring-exceptions spring-freemarker + + spring-groovy + spring-integration - spring-jinq spring-jenkins-pipeline spring-jersey + spring-jinq spring-jms spring-jooq + spring-kafka spring-katharsis + spring-ldap + spring-mobile spring-mockito + spring-mustache spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java + spring-mvc-kotlin + spring-mvc-simple spring-mvc-velocity spring-mvc-webflow spring-mvc-xml - spring-mvc-kotlin + spring-mybatis spring-protobuf + spring-quartz - spring-rest-angular - spring-rest-full - spring-rest-query-language - spring-rest - spring-resttemplate - spring-rest-simple - spring-remoting - spring-session - spring-sleuth - spring-social-login - spring-spel - spring-state-machine - spring-thymeleaf - spring-userservice - - spring-zuul + spring-reactive-kotlin spring-reactor - spring-vertx - spring-vault + spring-remoting + spring-rest + spring-rest-angular spring-rest-embedded-tomcat - spring-swagger-codegen - spring-webflux-amqp + spring-rest-full + spring-rest-hal-browser + spring-rest-query-language + spring-rest-shell + spring-rest-simple + spring-rest-template + spring-resttemplate + spring-roo - spring-static-resources - spring-security-thymeleaf spring-security-acl + spring-security-angular/server spring-security-cache-control + spring-security-client/spring-security-jsp-authentication spring-security-client/spring-security-jsp-authorize spring-security-client/spring-security-jsp-config @@ -1179,8 +1429,10 @@ spring-security-client/spring-security-thymeleaf-authentication spring-security-client/spring-security-thymeleaf-authorize spring-security-client/spring-security-thymeleaf-config + spring-security-core spring-security-mvc-boot + spring-security-mvc-custom spring-security-mvc-digest-auth spring-security-mvc-ldap spring-security-mvc-login @@ -1189,65 +1441,73 @@ spring-security-mvc-socket spring-security-openid + spring-security-rest spring-security-rest-basic-auth spring-security-rest-custom - spring-security-rest spring-security-sso + spring-security-stormpath + spring-security-thymeleaf spring-security-x509 - spring-security-mvc-custom + spring-session + spring-sleuth + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen - spark-java - saas + spring-thymeleaf + + spring-userservice + + spring-vault + spring-vertx + + spring-webflux-amqp + + spring-zuul + + sse-jaxrs + static-analysis + stripe + structurizr struts-2 - testing-modules/selenium-junit-testng + testing-modules/gatling testing-modules/groovy-spock + testing-modules/junit-5 + testing-modules/junit5-migration + testing-modules/load-testing-comparison testing-modules/mockito testing-modules/mockito-2 testing-modules/mocks + testing-modules/mockserver + testing-modules/parallel-tests-junit testing-modules/rest-assured testing-modules/rest-testing - testing-modules/junit-5 - testing-modules/junit5-migration + + testing-modules/selenium-junit-testng + testing-modules/spring-testing + testing-modules/test-containers testing-modules/testing testing-modules/testng - testing-modules/mockserver - testing-modules/test-containers + twilio + Twitter4J undertow - video-tutorials - vaadin - vertx-and-rxjava - vraptor - vertx vavr + vertx + vertx-and-rxjava + video-tutorials + vraptor + + wicket - xmlunit-2 xml - - - - - - - - - + xmlunit-2 + xstream
@@ -1282,9 +1542,25 @@ parent-spring-4 parent-spring-5 parent-java - parent-kotlin + parent-kotlin - + core-java + core-java-concurrency + core-kotlin + + jenkins/hello-world + jws + + libraries + + persistence-modules/hibernate5 + persistence-modules/java-jpa + persistence-modules/jnosql + + spring-5-data-reactive + spring-amqp-simple + + vaadin diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 28db4a7a3d..39cda888c5 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -35,7 +35,7 @@ spring-cloud-archaius spring-cloud-functions spring-cloud-vault - spring-cloud-security + spring-cloud-task spring-cloud-zuul diff --git a/structurizr/pom.xml b/structurizr/pom.xml index 76b1e355f1..b9f9b68717 100644 --- a/structurizr/pom.xml +++ b/structurizr/pom.xml @@ -2,7 +2,6 @@ 4.0.0 - com.baeldung structurizr structurizr @@ -26,32 +25,24 @@ com.structurizr structurizr-client - ${structurizr-client.version} + ${structurizr.version} - org.springframework - spring-context - ${spring.version} + com.structurizr + structurizr-analysis + ${structurizr.version} + + + com.structurizr + structurizr-plantuml + ${structurizr.version}
- - - - false - - central - bintray - http://jcenter.bintray.com - - - 1.8 1.8 - 1.0.0-RC3 - 0.6.0 - 4.3.8.RELEASE + 1.0.0-RC5 \ No newline at end of file diff --git a/structurizr/src/main/java/com/baeldung/structurizr/StructurizrSimple.java b/structurizr/src/main/java/com/baeldung/structurizr/StructurizrSimple.java index 6eb0c7de73..b33a1d9a77 100644 --- a/structurizr/src/main/java/com/baeldung/structurizr/StructurizrSimple.java +++ b/structurizr/src/main/java/com/baeldung/structurizr/StructurizrSimple.java @@ -4,12 +4,10 @@ import java.io.File; import java.io.StringWriter; import com.structurizr.Workspace; -import com.structurizr.api.StructurizrClient; -import com.structurizr.api.StructurizrClientException; -import com.structurizr.componentfinder.ComponentFinder; -import com.structurizr.componentfinder.ReferencedTypesSupportingTypesStrategy; -import com.structurizr.componentfinder.SourceCodeComponentFinderStrategy; -import com.structurizr.componentfinder.SpringComponentFinderStrategy; +import com.structurizr.analysis.ComponentFinder; +import com.structurizr.analysis.ReferencedTypesSupportingTypesStrategy; +import com.structurizr.analysis.SourceCodeComponentFinderStrategy; +import com.structurizr.analysis.SpringComponentFinderStrategy; import com.structurizr.io.WorkspaceWriterException; import com.structurizr.io.plantuml.PlantUMLWriter; import com.structurizr.model.Component; @@ -112,11 +110,6 @@ public class StructurizrSimple { view.addAllContainers(); } - private static void uploadToExternal(Workspace workspace) throws StructurizrClientException { - StructurizrClient client = new StructurizrClient("e94bc0c9-76ef-41b0-8de7-82afc1010d04", "78d555dd-2a31-487c-952c-50508f1da495"); - client.putWorkspace(32961L, workspace); - } - private static void exportToPlantUml(View view) throws WorkspaceWriterException { StringWriter stringWriter = new StringWriter(); PlantUMLWriter plantUMLWriter = new PlantUMLWriter(); From 5dec6f7006df5049355998bb111384968e50e227 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Mon, 10 Dec 2018 19:07:29 +0100 Subject: [PATCH 63/69] added example code for BAEL-2418 (#5882) * added example code for BAEL-2366 * moved example code for BAEL-2366 * example code for BAEL-1961 * moved example code into integration test * updated the test assertions * refactor the spring boot persistence mongodb module * remove redundant example code * declared the spring boot persistence module in the root pom * fixed issue with non-imported file * added example code for BAEL-2418 --- .../java/com/baeldung/basicsyntax/SimpleAddition.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java diff --git a/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java b/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java new file mode 100644 index 0000000000..20a13178cc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java @@ -0,0 +1,11 @@ +package com.baeldung.basicsyntax; + +public class SimpleAddition { + + public static void main(String[] args) { + int a = 10; + int b = 5; + double c = a + b; + System.out.println( a + " + " + b + " = " + c); + } +} From e51a0d042807edc5af3cc8a42d9e2e6dab95a71a Mon Sep 17 00:00:00 2001 From: Daniel Barrigas Date: Mon, 10 Dec 2018 21:42:28 +0000 Subject: [PATCH 64/69] Spring Boot Actuator + Kubernetes Issue: BAEL-2356 --- .../liveness-example/Dockerfile | 11 ++++ .../liveness-example/pom.xml | 51 ++++++++++++++++++ .../com/baeldung/liveness/Application.java | 12 +++++ .../health/CustomHealthIndicator.java | 27 ++++++++++ .../resources/application.properties | 1 + .../src/main/resources/resources/logback.xml | 13 +++++ .../SpringContextIntegrationTest.java | 17 ++++++ .../liveness-example-k8s-template.yaml | 54 +++++++++++++++++++ .../readiness-example-k8s-template.yaml | 54 +++++++++++++++++++ spring-cloud/spring-cloud-kubernetes/pom.xml | 2 + .../readiness-example/Dockerfile | 11 ++++ .../readiness-example/pom.xml | 49 +++++++++++++++++ .../com/baeldung/readiness/Application.java | 12 +++++ .../health/CustomHealthIndicator.java | 27 ++++++++++ .../resources/application.properties | 1 + .../src/main/resources/resources/logback.xml | 13 +++++ .../SpringContextIntegrationTest.java | 17 ++++++ 17 files changed, 372 insertions(+) create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java create mode 100644 spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml create mode 100644 spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile b/spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile new file mode 100644 index 0000000000..0fc0a9bd64 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile @@ -0,0 +1,11 @@ +FROM openjdk:8-jdk-alpine + +# Create app directory +RUN mkdir -p /usr/opt/service + +# Copy app +COPY target/*.jar /usr/opt/service/service.jar + +EXPOSE 8080 + +ENTRYPOINT exec java -jar /usr/opt/service/service.jar \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml new file mode 100644 index 0000000000..e963dafe67 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml @@ -0,0 +1,51 @@ + + + + + org.springframework.boot + spring-boot-starter-parent + 1.5.17.RELEASE + + + + 4.0.0 + + liveness-example + 1.0-SNAPSHOT + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java new file mode 100644 index 0000000000..2cfa242965 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.liveness; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java new file mode 100644 index 0000000000..715c4cb178 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java @@ -0,0 +1,27 @@ +package com.baeldung.liveness.health; + +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +@Component +public class CustomHealthIndicator implements HealthIndicator { + + private boolean isHealthy = true; + + public CustomHealthIndicator() { + ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor(); + scheduled.schedule(() -> { + isHealthy = false; + }, 30, TimeUnit.SECONDS); + } + + @Override + public Health health() { + return isHealthy ? Health.up().build() : Health.down().build(); + } +} diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties new file mode 100644 index 0000000000..a3ac65cee5 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties @@ -0,0 +1 @@ +server.port=8080 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..60b4a28aa6 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.liveness.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml b/spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml new file mode 100644 index 0000000000..9fd3fd5674 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml @@ -0,0 +1,54 @@ +apiVersion: v1 +kind: Service +metadata: + name: liveness-example +spec: + selector: + app: liveness-example + ports: + - port: 8080 + +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: liveness-example +spec: + selector: + matchLabels: + app: liveness-example + replicas: 1 + strategy: + rollingUpdate: + maxUnavailable: 0 + template: + metadata: + labels: + app: liveness-example + spec: + containers: + - name: liveness-example + image: dbdock/liveness-example:1.0.0 + imagePullPolicy: IfNotPresent + resources: + requests: + memory: 400Mi + cpu: 400m + ports: + - containerPort: 8080 + readinessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 10 + timeoutSeconds: 2 + periodSeconds: 3 + failureThreshold: 1 + livenessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 20 + timeoutSeconds: 2 + periodSeconds: 8 + failureThreshold: 1 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml b/spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml new file mode 100644 index 0000000000..010c468107 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml @@ -0,0 +1,54 @@ +apiVersion: v1 +kind: Service +metadata: + name: readiness-example +spec: + selector: + app: readiness-example + ports: + - port: 8080 + +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: readiness-example +spec: + selector: + matchLabels: + app: readiness-example + replicas: 1 + strategy: + rollingUpdate: + maxUnavailable: 0 + template: + metadata: + labels: + app: readiness-example + spec: + containers: + - name: readiness-example + image: dbdock/readiness-example:1.0.0 + imagePullPolicy: IfNotPresent + resources: + requests: + memory: 400Mi + cpu: 400m + ports: + - containerPort: 8080 + readinessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 40 + timeoutSeconds: 2 + periodSeconds: 3 + failureThreshold: 5 + livenessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 100 + timeoutSeconds: 2 + periodSeconds: 8 + failureThreshold: 1 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/pom.xml b/spring-cloud/spring-cloud-kubernetes/pom.xml index 984b3811dd..de0718633e 100644 --- a/spring-cloud/spring-cloud-kubernetes/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/pom.xml @@ -11,6 +11,8 @@ demo-frontend demo-backend + liveness-example + readiness-example diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile b/spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile new file mode 100644 index 0000000000..0fc0a9bd64 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile @@ -0,0 +1,11 @@ +FROM openjdk:8-jdk-alpine + +# Create app directory +RUN mkdir -p /usr/opt/service + +# Copy app +COPY target/*.jar /usr/opt/service/service.jar + +EXPOSE 8080 + +ENTRYPOINT exec java -jar /usr/opt/service/service.jar \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml new file mode 100644 index 0000000000..fa85120d21 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml @@ -0,0 +1,49 @@ + + + + org.springframework.boot + spring-boot-starter-parent + 1.5.17.RELEASE + + + 4.0.0 + + readiness-example + 1.0-SNAPSHOT + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java new file mode 100644 index 0000000000..11ffe577c3 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.readiness; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java new file mode 100644 index 0000000000..d37a1905f6 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java @@ -0,0 +1,27 @@ +package com.baeldung.readiness.health; + +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +@Component +public class CustomHealthIndicator implements HealthIndicator { + + private boolean isHealthy = false; + + public CustomHealthIndicator() { + ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor(); + scheduled.schedule(() -> { + isHealthy = true; + }, 40, TimeUnit.SECONDS); + } + + @Override + public Health health() { + return isHealthy ? Health.up().build() : Health.down().build(); + } +} diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties new file mode 100644 index 0000000000..a3ac65cee5 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties @@ -0,0 +1 @@ +server.port=8080 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..18458182c7 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.readiness.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} From 7ddcb76c093d93394af403bd6ccf29a5906300a9 Mon Sep 17 00:00:00 2001 From: j-bennett Date: Mon, 10 Dec 2018 18:27:48 -0500 Subject: [PATCH 65/69] Persist a JSON object using Hibernate Issue: BAEL-2353 --- persistence-modules/hibernate5/pom.xml | 6 + .../hibernate/persistjson/Customer.java | 80 +++++++++++++ .../persistjson/HashMapConverter.java | 47 ++++++++ .../persistjson/PersistJSONUnitTest.java | 111 ++++++++++++++++++ .../hibernate-persistjson.properties | 7 ++ 5 files changed, 251 insertions(+) create mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java create mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java create mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java create mode 100644 persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 363e2153b6..7e9a0ddb29 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -51,6 +51,11 @@ hibernate-testing 5.2.2.Final + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} +
@@ -69,6 +74,7 @@ 2.2.3 1.4.196 3.8.0 + 2.8.11.3 diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java new file mode 100644 index 0000000000..6bd1c24869 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java @@ -0,0 +1,80 @@ +package com.baeldung.hibernate.persistjson; + +import java.io.IOException; +import java.util.Map; + +import javax.persistence.Convert; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Entity +@Table(name = "Customers") +public class Customer { + + @Id + private int id; + + private String firstName; + + private String lastName; + + private String customerAttributeJSON; + + @Convert(converter = HashMapConverter.class) + private Map customerAttributes; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCustomerAttributeJSON() { + return customerAttributeJSON; + } + + public void setCustomerAttributeJSON(String customerAttributeJSON) { + this.customerAttributeJSON = customerAttributeJSON; + } + + public Map getCustomerAttributes() { + return customerAttributes; + } + + public void setCustomerAttributes(Map customerAttributes) { + this.customerAttributes = customerAttributes; + } + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public void serializeCustomerAttributes() throws JsonProcessingException { + this.customerAttributeJSON = objectMapper.writeValueAsString(customerAttributes); + } + + public void deserializeCustomerAttributes() throws IOException { + this.customerAttributes = objectMapper.readValue(customerAttributeJSON, Map.class); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java new file mode 100644 index 0000000000..b1c2d50480 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.persistjson; + +import java.io.IOException; +import java.util.Map; + +import javax.persistence.AttributeConverter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.hibernate.interceptors.CustomInterceptor; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HashMapConverter implements AttributeConverter, String> { + + private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class); + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public String convertToDatabaseColumn(Map customerInfo) { + + String customerInfoJson = null; + try { + customerInfoJson = objectMapper.writeValueAsString(customerInfo); + } catch (final JsonProcessingException e) { + logger.error("JSON writing error", e); + } + + return customerInfoJson; + } + + @Override + public Map convertToEntityAttribute(String customerInfoJSON) { + + Map customerInfo = null; + try { + customerInfo = objectMapper.readValue(customerInfoJSON, Map.class); + } catch (final IOException e) { + logger.error("JSON reading error", e); + } + + return customerInfo; + } + +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java new file mode 100644 index 0000000000..ecbb073e89 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java @@ -0,0 +1,111 @@ +package com.baeldung.hibernate.persistjson; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class PersistJSONUnitTest { + + private Session session; + + @Before + public void init() { + try { + Configuration configuration = new Configuration(); + + Properties properties = new Properties(); + properties.load(Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream("hibernate-persistjson.properties")); + + configuration.setProperties(properties); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Customer.class); + + SessionFactory factory = metadataSources.buildMetadata() + .buildSessionFactory(); + + session = factory.openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + } + + @After + public void close() { + if (session != null) + session.close(); + } + + @Test + public void givenCustomer_whenCallingSerializeCustomerAttributes_thenAttributesAreConverted() throws IOException { + + Customer customer = new Customer(); + customer.setFirstName("first name"); + customer.setLastName("last name"); + + Map attributes = new HashMap<>(); + attributes.put("address", "123 Main Street"); + attributes.put("zipcode", 12345); + + customer.setCustomerAttributes(attributes); + + customer.serializeCustomerAttributes(); + + String serialized = customer.getCustomerAttributeJSON(); + + customer.setCustomerAttributeJSON(serialized); + customer.deserializeCustomerAttributes(); + + Map deserialized = customer.getCustomerAttributes(); + + assertEquals("123 Main Street", deserialized.get("address")); + } + + @Test + public void givenCustomer_whenSaving_thenAttributesAreConverted() { + + Customer customer = new Customer(); + customer.setFirstName("first name"); + customer.setLastName("last name"); + + Map attributes = new HashMap<>(); + attributes.put("address", "123 Main Street"); + attributes.put("zipcode", 12345); + + customer.setCustomerAttributes(attributes); + + session.beginTransaction(); + + int id = (int) session.save(customer); + + session.flush(); + session.clear(); + + Customer result = session.createNativeQuery("select * from Customers where Customers.id = :id", Customer.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(2, result.getCustomerAttributes() + .size()); + } + +} diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties new file mode 100644 index 0000000000..2cf8ac5b63 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties @@ -0,0 +1,7 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.dialect=org.hibernate.dialect.H2Dialect + +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file From 5afdce78ead6d1854ef6d787cb70b10f9527a6b5 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Tue, 11 Dec 2018 09:52:10 +0200 Subject: [PATCH 66/69] quick compilation fix --- .../com/baeldung/jpa/stringcast/QueryExecutor.java | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java index 6f1e2ee5ca..2cb5679d4d 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java @@ -1,13 +1,12 @@ package com.baeldung.jpa.stringcast; -import com.sun.istack.internal.Nullable; - -import javax.persistence.EntityManager; -import javax.persistence.Query; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; +import javax.persistence.EntityManager; +import javax.persistence.Query; + public class QueryExecutor { public static List executeNativeQueryNoCastCheck(String statement, EntityManager em) { @@ -24,10 +23,7 @@ public class QueryExecutor { } if (results.get(0) instanceof String) { - return ((List) results) - .stream() - .map(s -> new String[] { s }) - .collect(Collectors.toList()); + return ((List) results).stream().map(s -> new String[] { s }).collect(Collectors.toList()); } else { return (List) results; } From cfab18ae96ef8342001466d541e4c04da5c952e2 Mon Sep 17 00:00:00 2001 From: Loredana Date: Tue, 11 Dec 2018 22:46:08 +0200 Subject: [PATCH 67/69] add code for jgrapht image gen --- algorithms-miscellaneous-2/pom.xml | 6 +++ .../jgrapht/GraphImageGenerationUnitTest.java | 47 ++++++++++++++++++ .../src/test/resources/graph.png | Bin 0 -> 9365 bytes 3 files changed, 53 insertions(+) create mode 100644 algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java create mode 100644 algorithms-miscellaneous-2/src/test/resources/graph.png diff --git a/algorithms-miscellaneous-2/pom.xml b/algorithms-miscellaneous-2/pom.xml index 25472d4888..5461f4ebe1 100644 --- a/algorithms-miscellaneous-2/pom.xml +++ b/algorithms-miscellaneous-2/pom.xml @@ -33,6 +33,11 @@ jgrapht-core ${org.jgrapht.core.version} + + org.jgrapht + jgrapht-ext + ${org.jgrapht.ext.version} + pl.allegro.finance tradukisto @@ -83,6 +88,7 @@ 3.6.1 1.0.1 1.0.1 + 1.0.1 3.9.0 1.11 diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java new file mode 100644 index 0000000000..3b841d574a --- /dev/null +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.jgrapht; + +import static org.junit.Assert.assertTrue; +import java.awt.Color; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import javax.imageio.ImageIO; +import org.jgrapht.ext.JGraphXAdapter; +import org.jgrapht.graph.DefaultDirectedGraph; +import org.jgrapht.graph.DefaultEdge; +import org.junit.Before; +import org.junit.Test; +import com.mxgraph.layout.mxCircleLayout; +import com.mxgraph.layout.mxIGraphLayout; +import com.mxgraph.util.mxCellRenderer; + +public class GraphImageGenerationUnitTest { + static DefaultDirectedGraph g; + + @Before + public void createGraph() throws IOException { + File imgFile = new File("src/test/resources/graph.png"); + imgFile.createNewFile(); + g = new DefaultDirectedGraph(DefaultEdge.class); + String x1 = "x1"; + String x2 = "x2"; + String x3 = "x3"; + g.addVertex(x1); + g.addVertex(x2); + g.addVertex(x3); + g.addEdge(x1, x2); + g.addEdge(x2, x3); + g.addEdge(x3, x1); + } + + @Test + public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException { + JGraphXAdapter graphAdapter = new JGraphXAdapter(g); + mxIGraphLayout layout = new mxCircleLayout(graphAdapter); + layout.execute(graphAdapter.getDefaultParent()); + File imgFile = new File("src/test/resources/graph.png"); + BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null); + ImageIO.write(image, "PNG", imgFile); + assertTrue(imgFile.exists()); + } +} \ No newline at end of file diff --git a/algorithms-miscellaneous-2/src/test/resources/graph.png b/algorithms-miscellaneous-2/src/test/resources/graph.png new file mode 100644 index 0000000000000000000000000000000000000000..56995b8dd9be23e173c365a616ac64123004d81c GIT binary patch literal 9365 zcmZ{Kc{r5O`}bHIJITI`EfTVhEyivrvP8BRNky_#WQGwU${*zVDHJ--XCJ z_F;y3AAP^?@A|!eyspc|bLN~g_jd04bAQhB#`q4Lj+&Di1On0N>uH;UKqO(nuLYPC z7-^|&zX<{f-PhOFF!P(*`fO!u8WO$X*=#t3urV8&W& zI`GI4a;SSix61zk~}r(F&{8?Ysj;OQA6dm4#!|q9XLV zLAam6bo0~1o*-J(S#9T!215I%ez6*EY^)4-v_fOeZtp->IRi1_+`MDu%fQ`scQ?ZT z*SmYKV@6a5!@?d_nyaKV0U4tdvt#1O9v`l+>jiI6F|asMEk|tUX1b zf3Rn_SBg@NQN?bSgUihi=$|AIiVwN;om@7i^ONs6CNM=$dDF!RTeciiN<+bm`qwYN z8Ct2`35?e{RIdn*8CbxXY$u*LhJ-YpJ()+vd-!po+B)5d149P`C%&hL13Q7=W{#BV zTxS!weEAl$(p!Ejey}TDKb+V%KT!66`e(3if8$^S@;oiK(&-WdSlkHwtKNTYMy z-KqValsYudspH3hZ0O)EHXv-MZNpJPY4`DCUtLo<1^dXv#3k3K25eH*vE)5ZBaXl|I<%bRkiluCB+z1$o5uY0d1h zpbGyE)Ln7Xn%DjlVe$-HG;h94x4J*m&)Isu6T7EP`bosh!eS@aMKNv}A5S^>9neQDCa<&zQY<iQ641&vFF*%_Au!y05 zaMzT7QLqBJ{DE$5N`!eZwHm=fz8R?JlKieFLQDbbin0of+u0kvzFpOQJZQ~4m~d|( zT79>uQMXq@ya8{*iXeeTrjKrbj%^;vHWB$=fGl3xc2IySjTFo;>;@OyPBI{b%w@Ls4n= zgKVs>DvjihLu^W;MiG=Z@c2GyqHyL`kWoU0XZa1@y)$jkcAkcC53i27QDRK8nu5(v z(Nxj5P5Bv5XpH030`eAVkJGHP%iPIY!QoNCHe@oI#<7?y z?)lA{6}AKAtzHG;fuN|Ot<~R|^v`g-TPd906IxW~tTu~oySLo9M=LOSRp}*1mG3z! ze0bc{OskHH$`Y*+(gThbrZGG7eM$eDb!b|FF zq)#dg^9vCSjYowH3E>HWwX)MEhw}vAlRInUl_|6A4SSKb-GyRSM;=z~mXnj-CS)er z^UwNyP8Q9`%or|YAXf5CqUD_xN>Eo`cq~N?uB8>7f`KU7@y+JJeaIXdi)Vf?a?1fV z6yzLUMGPRCnzYyGs(iGpH>GhobvdA(f_we2g-5Mv8g@C~pSHu5%zipa;9VVWy#Dum zwwQKR_`?%O(dp`WIcAwn6x#TRn9ntG>vzYMv&82UyjE4~>^TzBm7XW`J6Ss5*L)S2 z`E70f>M&ECKtFMa zJ+zDYx+K`0117^=YuXsCDZiYgx3Op6a`b0R?qRXTZFoJu5X;7B3%uD{4R3R=^c7{(Hyz`*~i)l47|>=gzC z!ZIPrK}d24$$vh^fnlTI#ITi$C7Xdnq=Rvw%m;1PMwRwsd<`fMn9@7_&|iP9t6(+vOv$-TPG zg-jUjZBR_GgP2(iAQVJBVon~Z`baT#SI~FLrg(u4T1GYr&7n{8&%AOnB`1PRs2~zI zl#V*$hj%}2PU70iS$?$&;3D$es*O6!@Y%kL-FH)-fy#Ra*0NM{ zzxD}Fd47#QpPqpVM_}|SAMBbFknj|DP&pNpt&ipTS03j%ruxmS;%0pfWZTdz;WyKS zWeNmD=T(Sbj9$vQA&Y?URtyBeJ0Vd^f&%=NVbSY8eG(}Fpz_wYuKaSvLt4Txp&+v^d`qRcjT!ynC^jD7cuy8>3{rPdNh$Aq47Dv9QYQkky z003mobLCp}bioti_BU=KX5xJoUnX|JGAS2-mB&dNOOJ!8ee{>irzBcni@ zG*Se12;sF%ZQ0c9%b(gjUYWisv*eLFp>CA@6-iO!0a&-EQyK zudZ<<>25e4ly5Xm*kL62fC z-=Y@RE);>N5|xi3oEC5ViJ)u#gVjB|TvPC)ldE>2IW;RVQVO)a;0kU!ptIuc_4m&s zTWqbKsyo{2pI}`4wRPD{?hjPsFn@N;d706il{1vFnVC(ZlaM%ob7MD#$6Gsvq*` zr{splHUw=CxZ#fuwA|m*c@RGGHoGIcC&v;vpR&@boeI3ibp1|cp~9}LQHcf9fxX|K z<|~8H{n&-C36QR*L(jSuk4t*5e*%FSR&mhtrk7i%c`hDth3-xVOs}XwK^}^!Jh#5u zRoqiUF7qI1oPA!B{RW2foOqvCUyM=6{s`OZ6gR^Zy?_X0gRpeYUQXWQA3LI+4*8w< zQSUWOPy;^4(lrF@vYpWu;q`u=xj3FFgAOQsWyWj^A+Wtyr_m;_A<)^)K!t=2uR!O!LYb(87upCeVOPP3@ch?8H}I+lZdZ1k!ZT zukW<#?lndWE3I|F0g*m;-mXwNqy%lL)Bg^5bWi~**M~n^p>PFE%{K+Y8lZW{#Dw}7Fl^(zoLgY=)2WOBtzRu(&a+`+MfzR?J72;DnaOA@hZVNJDDG8zMZ z%02igLa(^JNnT30-TbWXOBskkY@{BOy`so<6T&AKJjlq`DH)F;#|MI%#K^mLqy7kr z9%G=y;0#8=PRS%pYNOvriO($SRVK%D52$Hh`EC464poYq*nF(4KvgXPzH3kJxAhrt zya4J_)Kb>qZs)5CTN00OJ*7Zt)WMANGlpI2Hr)~KXk*xA@nb6V?Yxi<&pWpA&Gf&7 zCU*7axhw}*BW?kOjl$pOWr$z6a1us)%Yv*4TV~?Syf>LAyi2d2WTPmp8jhuS#eY<` zWT?r@qK42I@usAWict#OMG2_}6+Cg`)Szv%_v~h3Md+B=-XE1*mrl}Fm0CUzw!dN- zAeybUbe+QPr=}%@|CmAB!Qo}}QZ*1v3$1cg$Y+F2HeenIoU)`4iOI7HxK_$p9hCl} zt#6mB9p2xVdMxPyBV`Zn8c_~ejxub40I5@bT<*oY-4_K+sab*zm>B$}Qyps;to1K6 zQ}noFXh?6_47A0Pj}arrf=YRBb>FKA{>nZLF@+kszKnF@laj{^tm15TU~*mj$+TW6 zqY}rlz!n1a-$Gu=%hygShCjP8E^(v~A8_V*9`x3I>o$fb$B#$Os13k? zbH=$}J8TKl+=i?w$JnF8QJ!NTYuKT(nOCL&h+*COQ7I4yB&u|sJC1UumXELaa{iz+ zc&+LM80pK}X4=AzUNf%}4Wt_|qnnM{8>X=;(y7ixKi1g$F1_4p$Z}H2nCKZbV;&$Y zQ@7VkuTb`vvQNRIZbt*P2hhVegPwC0m*4XkTOh?jz$qO|9?3eQJE}eEX|{ZDP85A- zG=#UR>5pFPLc+9@6yP)I5MwUv;LldBA37fl4Ei(V(JgI{6^6$j6jyVZlR%1^Xb>DH z4GihOUt~0U6R?9%A3viRfwj~HrAra`vH%z4QRCKZu2>x2b<`Fb&%BP7!K$2p!(Auq zTMEaF1v@yn8&p47H75%zon%w$oS(ZHJ%z^HH=dSvnDBjqZUH7UbG)k>B!_v?tey|1 zUD9~ubTIfQf~)*pw3@DK6Wk4`MLE}~-pFw+PPVB_+*zH`gt5WmDEje6U9KADX!`+K zIm3DXo0vp_P6kL3L&aOg<9Vp!n<-FmJ7BiJFRwFuOoJFINFd#>m`ec+!|p;Jykh+e z6viq_rNoTWyD?Npoch5uLJ7X|pCs$_vK4L@0wroR>5Dma#${t;F&^6xW*!Z7cHT12 z_2u9$rn{P4wcLl`jDTd#>r4hYp;$dP0>m>1^7an<%C?#p0UNtxKc|LGYrhJ& zM6&3Z`1YViD3Qx-{t2~L^Z}Rwn9CjeP*C9Rh6f&uT$a3|mErl}iqTjH{|F^E>gavP-d=%#h>m9OMf(>sK80ONHU*s=lEm_RXBppqCS*GL956GmEyx?bSX8TwD ziRGdm`(3z^rMRioE}@>FZNl#l$M2oID@Ayq^>~1~K`tAy`kK*znWor6)U?)o*{Y|BHUr& z3A>-os-5rti?s67fnP7!KGkAa`y|AvxhYSN1}}ITPUV+KWXWrPd?{J$d!MI& zXG%~}-oz_UBCoow+~@i)J@deTgF=Ot^mms1GOjS`Ql7p0&QC@~TAxipm}>5j*u8q* zfQCrBT+nC#1E8n;JFd0~GjboK-_RBEof>awz%J*z@1LV?#HF}|*jzH>>NqfIYHbRF z7#j3f_wM33K8*wdR%i(YBx(~$uWN3%9tT|Wx5(BcF(=mf^ucN@X`o4;JvsEFDg*Vz zW|Uo6iMvkRKG0g-kkr%i9V2C@Y&hvULHKv=;+a3qBoc-jo&~q6cfwBBa4gCssGt|p zNwO}X3> zwf&~)LHa{Tea-IM)hhlXkDz3E2E$ZySSBV%_i)S3$SCXpNNtUJcD7u+uUSGx&<_@f zxY%Cq#!8*1HL8S;1hXlX@Ep(szVDcbVXIMYyL|t{jX=J`ab4cNKX&dYAOH>)54YSz zzM9-k@g@S<{-w>cl1OrhD1;J*kKoo8j{CHfh!Bd@l407i@^&%CNiqKT$7YyTrt~XA z{g;De=6`AMC@|nXG>?rPDlDjM-J^t7rz`<7Ln7wELK$Xx6}Q6nhP%!6n)feT!O-B3 zOOpnUabeFV{Ik(;##uV@(<5_16vs>G&iu4MceQ*TrBo_UlN9zBeA|m~ekC6uG-$lr zYtG*bwu8x}_y0pl6nXxKl4x{v`|^!X|k%v9C z&KMb03*tyjR$)UYt&AYvb2I>KM{9)!6piOUqaq`sv|R)^_3Q=3n%`jZlm1pZ%&c6)luVDaE+L*6p2t-%iAg?4#swBX*qe zY6D7wLP*Bh#_LdAU%Ev-^rRdJMwiBG@;tq^zEgi#Sx@ZXe{17wW}ZmO8;iYZ{Jz#$ z-nuKdQNR!{JHz;XvV8kRVv2x&fU7;Mi1=V37gIHTqw%U(uHM`!c;6XH(!T{(Lus|k z098#?c4z*orMvd56!v;2Mv8F;ZfavOE4yg3t!6x)(OaA|k;g(=w;ZyUYd0dr_@I7D zq4G<9t#Q74br3NlYmPB4^6=>>bx5f`9;i$OC8Lt2?Dnd}CNz{tr)Th(d2Br#BS&3w zVnpX>7RHn=&-B^tQG!`G20f0|WCj}xHYo)n&zj&#lnm1{U?90G4+7;XGk_lA%;xJ& zROjf@a1>DPNjMG2qr>S9=Y7CmifmRoAE>&O;(*iJ5Wk`1_bbTPJ%&uf!H3|fmpxgT zQvyO}lOFP9!PLNvPAM07vD%qp3n;~U3Rr=kdJPfdioYvPb04poaA9NJ)VC3O0NfZF zHwd(1C?JImade&0=mKzM8Mi1{FZ0kQrV%YVpa_5n08soiG6}_~Hvwzdi$`e}%v#_z zL{pt@1nA4-Ra9Ud3mPLw?nNYR(h4489wI?zKa9bTLt7vI_{F4jyC5*I>Slqa zBzB8a@ewu_t;pS-+6Vw>evdT4b%Px~JBGIV$W8bFElBG_ zd7y?n^5L9&YK^R2k90;}>o%zb;<~ClE{kO4F`H*lD0ViUeGIeK2i)1^@itoR%N&U< z*&2`2>PALY0R%u*9PwWZU#xLPbU)KH&$|tv0%az=gIElJnBLOpsI8t$huohnYf?Jz z=(}{W#{gDyH{jvV(w1oJWvlHW(Fo-LW&lQZt?BKb@5XDG$BeCaZslW{EMM19spQjr z;#txE>7tXs3?rStAVrEJ?|Um0XzJr`d;?ku_Kw$>CIvm0^M`Ydao9b{F2H8?P`2V1 zgB2QdSIxp?0H7gPe7SW3*zcX3KQ)7fIcPn73+9|N<+j5E2OwD!MGAhN&8D2VK zrEm9c5FMZs$#~3bJze%eu>8aK&v}bl4R~;1zgNmG%Yy4w{KpU##m+Q<6fQtxnv~ld zsI1&6xPr+NAZCDeaZvCz2F->|A`bqg)6==c>axTLU@0an zeKIO`^=#?E4-)c1Q9us3;&CH@yuZkhQ(r{#g5XF7SnaOXID@TD9vx8wa6M^Yb2TwW zPj-xO4C%AJK!_ysi#ngBcjk>QtgQ}O2)7%MS3YO2SoH2^yMX58uj2{wH3=6u(;P>6 z@wH%f(``uMFFfeqgVe}iQ(e$}*R^%+i~WPOt@j~nt@RAR$b75Bx1&t?1wqCuc^ewz6F|#q7WO2Y7WA0d4Ck{n z9uFxS|7H6ykM0HEg}geACk$8bEp5a8^B5MRtJ~`vlJ~9x`yQGfSVJiS9C0SFatc1T z(Cq@6T2egWj|Fr?4_WXCS5(VEFT_?a(H2v+x{xbfPUR`rC+qNFSIP@@^Ipe~7Q1q3 zxc;|`*$zcx&_5+!0g1o|%2{_EI0t#x0mf?3IuwIewr>mNNG=c8PRi${)P2mvf@LzM zONG`*6gWP8KKJcIOw6?AhnTqe*M1k9U<)|^hVi_H?g2T|(edARznP<6J*S(niGBIi z;`%8g6_#m$JOz(Y4j6XIss@gq&%)x9r{Cfvk>usC;_(V2NyO#!3rR*UXb;K-!E}CH zJ`6aa9nJzdY|pVzjW2>%-G<$DuCe@{T53EMghZm{!r^61H%x#IQ@#)kA>nDNCIT6< zl%cFF=#{nZe>(+|qGN}))MLzr-+Z)ESBfWOs}(zqZnb<>#eto8M2``JD&lj4u_20` zn6Nb9s~Lb`!)Kew3DA)Tu zwh;iEllp}GUN&yeTIb~uB^Rs9As}|5-U}&)cd*M}E?r;dQ$=HFNr3*r zQEvTAJ)2wYOF=VSy<}oF@p)SLI%-ahhoWTkqIvSB1{Bib;jZt;uU4G?^YeDBuAPta zP7sj)`q51GS7@8y_Wnnrw*AVVQ9qT=X~t_kcozlvz{c7-L4#+t3Cn7~eE<%ivRrI)I_X7(+%(zEgpXBy@=wiB z8xmZy;sg|09j}B-mZ)p<)bO3zigp^QEr^3~;IC3rGPT!_(_ZF(wxe37iv&`kb?PJy z5Qv-vAq>EeolZ_Ew#iVZVyt&y%l-swyA$#zxH?bXqxiUad1+Mzxl^ZMk@2e#ozL|g z*v6|XI9vKm;57ht9TX+SX29;FJPRyQaG%u0MK`dI$zxpO)-ATM&*Y%!UC z*3|}9uR)|+DF5ED$kDfpF`P0X0*eZrH<3*=8AY>IBrHw%5Wk|p-la=eCXb$$_qjll z5aaaX)H}t7VMr_NAG%J1`T^_4C0=e2SJm&ES$~S9iE2pC?q-zMztu4= z?+D*he=+s6>L$agn_Y9zGgp0bG8y)9BuMhQ$9}!6pR7eH;s`;hTW?(f2FGQe|2DAc z)OtRPWq^gNw3XpzR@UnJc*Dl%(QZ^l4MUrGHL^0mgE|+uTd}7I6iBw7UfHutAq7E# z-A}HGXYg-3>`ZNqB--9U90%Quu>`U+4qSz0qRRY^ua28u^{>Y=p)tTc&4S>+mn~qV z7td%Dq+^3p3hEpQTx!yvcdBg#v}7T67)@eO4NaLB-?P0Ce@xS9*jd+rJotsT?Kqu-7OtdTNQ?Hj#kL2|l zZUXh0$3aLUPN)20ZTx<0j{mDExKJVv%NQ6I=r`ze%2ZErA^f#f!Kuiit&EbOL_*yE zz8QBQfPrXoh72A(y2E?&h$u;nl|Ky*Z1`W z!VzXd26$P7_G0I}KUouJJK`cEFuymQKknY)4!sb?3~K`1!N%R5C}~6tNtya(rH04s z-CzY?Oo5R`o&uMr&(}8Q`Ky-$&A(;ljtGstuXY2jx_~m%1z+LWPpiW-%iMNoi>{ch z>^cs#n>%T1MNavyj4=qHvaF>f4uh3i~lnpjrs3~|KG{93t41u4u!y16;7l6`HlvXU-3_` o`2kf$9aCeMtj6fOpa|k6k6vV*^qxsH2>8+0xuadIY5(f~0EG)fM*si- literal 0 HcmV?d00001 From 652a7a3f46d4cb0e2a197ff5bdb6ffb9c0e7d79e Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Tue, 11 Dec 2018 20:43:13 -0600 Subject: [PATCH 68/69] BAEL-2174 update README.md (#5901) * BAEL-2246: add link back to article * BAEL-2174: rename core-java-net module to core-java-networking * BAEL-2174: add link back to article --- core-java-networking/README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/core-java-networking/README.md b/core-java-networking/README.md index b7a142ea27..626ea794e6 100644 --- a/core-java-networking/README.md +++ b/core-java-networking/README.md @@ -1,3 +1,7 @@ ========= -## Core Java Net +## Core Java Networking + +### Relevant Articles + +- [Connecting Through Proxy Servers in Core Java](https://www.baeldung.com/java-connect-via-proxy-server) From 9c9e32aa7c55afcc69ba6ebcacce59eb8a54d050 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Wed, 12 Dec 2018 04:44:11 +0000 Subject: [PATCH 69/69] Guide to ShedLock with Spring Issue: BAEL-2360 --- spring-all/pom.xml | 12 ++++++++++++ .../shedlock/SchedulerConfiguration.java | 12 ++++++++++++ .../scheduling/shedlock/TaskScheduler.java | 15 +++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 spring-all/src/main/java/org/baeldung/scheduling/shedlock/SchedulerConfiguration.java create mode 100644 spring-all/src/main/java/org/baeldung/scheduling/shedlock/TaskScheduler.java diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 2dc4915bab..77c7e74e08 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -155,6 +155,18 @@ org.apache.logging.log4j log4j-core + + + + net.javacrumbs.shedlock + shedlock-spring + 2.1.0 + + + net.javacrumbs.shedlock + shedlock-provider-jdbc-template + 2.1.0 +
diff --git a/spring-all/src/main/java/org/baeldung/scheduling/shedlock/SchedulerConfiguration.java b/spring-all/src/main/java/org/baeldung/scheduling/shedlock/SchedulerConfiguration.java new file mode 100644 index 0000000000..74ea39683d --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/scheduling/shedlock/SchedulerConfiguration.java @@ -0,0 +1,12 @@ +package com.baeldung.scheduling.shedlock; + +import org.springframework.context.annotation.Configuration; +import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; +import org.springframework.scheduling.annotation.EnableScheduling; + +@Configuration +@EnableScheduling +@EnableSchedulerLock(defaultLockAtMostFor = "PT30S") +public class SchedulerConfiguration { + +} \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/scheduling/shedlock/TaskScheduler.java b/spring-all/src/main/java/org/baeldung/scheduling/shedlock/TaskScheduler.java new file mode 100644 index 0000000000..b1b1ad921f --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/scheduling/shedlock/TaskScheduler.java @@ -0,0 +1,15 @@ +package com.baeldung.scheduling.shedlock; + +import net.javacrumbs.shedlock.core.SchedulerLock; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +class TaskScheduler { + + @Scheduled(cron = "*/15 * * * * *") + @SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastForString = "PT5M", lockAtMostForString = "PT14M") + public void scheduledTask() { + System.out.println("Running ShedLock task"); + } +} \ No newline at end of file