From d1b8f9b9b35ee84409571844317474295e7a6b4f Mon Sep 17 00:00:00 2001 From: tritty Date: Wed, 9 May 2018 03:58:04 +0530 Subject: [PATCH 01/17] 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/17] 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/17] 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/17] 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/17] + 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/17] 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/17] 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/17] 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/17] 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/17] +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/17] 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/17] 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/17] 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 5fa8e664453a7d1a79f78501f2bcfa12a4583614 Mon Sep 17 00:00:00 2001 From: Tritty Date: Tue, 2 Oct 2018 21:55:25 +0530 Subject: [PATCH 14/17] 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 15/17] 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 16/17] 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 138b22a7dd1aa5543f26a985c810219d898a54d3 Mon Sep 17 00:00:00 2001 From: Tritty Date: Sun, 9 Dec 2018 20:55:51 +0530 Subject: [PATCH 17/17] Files associates with BAEL-2343 --- .../operations/HibernateOperations.java | 114 ++++++++++++++++++ .../com/baeldung/hibernate/pojo/Movie.java | 52 ++++++++ .../main/resources/META-INF/persistence.xml | 19 +++ 3 files changed, 185 insertions(+) create mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/operations/HibernateOperations.java create mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Movie.java create mode 100644 persistence-modules/hibernate5/src/main/resources/META-INF/persistence.xml diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/operations/HibernateOperations.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/operations/HibernateOperations.java new file mode 100644 index 0000000000..d45daabe71 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/operations/HibernateOperations.java @@ -0,0 +1,114 @@ +package com.baeldung.hibernate.operations; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import com.baeldung.hibernate.pojo.Movie; + +/** + * + *Class to illustrate the usage of EntityManager API. + */ +public class HibernateOperations { + + private static final EntityManagerFactory emf; + + /** + * Static block for creating EntityManagerFactory. The Persistence class looks for META-INF/persistence.xml in the classpath. + */ + static { + emf = Persistence.createEntityManagerFactory("com.baeldung.movie_catalog"); + } + + /** + * Static method returning EntityManager. + * @return EntityManager + */ + public static EntityManager getEntityManager() { + return emf.createEntityManager(); + } + + /** + * Saves the movie entity into the database. Here we are using Application Managed EntityManager, hence should handle transactions by ourselves. + */ + public void saveMovie() { + EntityManager em = HibernateOperations.getEntityManager(); + em.getTransaction() + .begin(); + Movie movie = new Movie(); + movie.setId(1L); + movie.setMovieName("The Godfather"); + movie.setReleaseYear(1972); + movie.setLanguage("English"); + em.persist(movie); + em.getTransaction() + .commit(); + } + + /** + * Method to illustrate the querying support in EntityManager when the result is a single object. + * @return Movie + */ + public Movie queryForMovieById() { + EntityManager em = HibernateOperations.getEntityManager(); + Movie movie = (Movie) em.createQuery("SELECT movie from Movie movie where movie.id = ?1") + .setParameter(1, new Long(1L)) + .getSingleResult(); + return movie; + } + + /** + * Method to illustrate the querying support in EntityManager when the result is a list. + * @return + */ + public List queryForMovies() { + EntityManager em = HibernateOperations.getEntityManager(); + List movies = em.createQuery("SELECT movie from Movie movie where movie.language = ?1") + .setParameter(1, "English") + .getResultList(); + return movies; + } + + /** + * Method to illustrate the usage of find() method. + * @param movieId + * @return Movie + */ + public Movie getMovie(Long movieId) { + EntityManager em = HibernateOperations.getEntityManager(); + Movie movie = em.find(Movie.class, new Long(movieId)); + return movie; + } + + /** + * Method to illustrate the usage of merge() function. + */ + public void mergeMovie() { + EntityManager em = HibernateOperations.getEntityManager(); + Movie movie = getMovie(1L); + em.detach(movie); + movie.setLanguage("Italian"); + em.getTransaction() + .begin(); + em.merge(movie); + em.getTransaction() + .commit(); + } + + /** + * Method to illustrate the usage of remove() function. + */ + public void removeMovie() { + EntityManager em = HibernateOperations.getEntityManager(); + em.getTransaction() + .begin(); + Movie movie = em.find(Movie.class, new Long(1L)); + em.remove(movie); + em.getTransaction() + .commit(); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Movie.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Movie.java new file mode 100644 index 0000000000..5fae7f6a97 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Movie.java @@ -0,0 +1,52 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "MOVIE") +public class Movie { + + @Id + private Long id; + + private String movieName; + + private Integer releaseYear; + + private String language; + + public String getMovieName() { + return movieName; + } + + public void setMovieName(String movieName) { + this.movieName = movieName; + } + + public Integer getReleaseYear() { + return releaseYear; + } + + public void setReleaseYear(Integer releaseYear) { + this.releaseYear = releaseYear; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + +} diff --git a/persistence-modules/hibernate5/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate5/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..4dfade1af3 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,19 @@ + + + + Hibernate EntityManager Demo + com.baeldung.hibernate.pojo.Movie + true + + + + + + + + + + \ No newline at end of file