From d76d39fb87892a38da04105836facefbc7face5c Mon Sep 17 00:00:00 2001 From: Chris Franklin Date: Fri, 22 Dec 2017 10:59:53 -0500 Subject: [PATCH 01/91] Christopher Franklin Different Types of Bean Injection in Spring My first article about the three different types of bean injection supported by the Spring Framework. This code walks through all three methods and has supporting tests. --- .../baeldung/beaninjectiontypes/Config.java | 16 ++++++++ .../beaninjectiontypes/ExampleService.java | 11 +++++ .../ExampleWithConstructorInjection.java | 19 +++++++++ .../ExampleWithPropertyInjection.java | 16 ++++++++ .../ExampleWithSetterInjection.java | 20 +++++++++ .../beaninjectiontypes/BeanInjectionTest.java | 41 +++++++++++++++++++ 6 files changed, 123 insertions(+) create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/Config.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleService.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithConstructorInjection.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithPropertyInjection.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithSetterInjection.java create mode 100644 spring-core/src/test/java/com/baeldung/beaninjectiontypes/BeanInjectionTest.java diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/Config.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/Config.java new file mode 100644 index 0000000000..d523dc3f1f --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/Config.java @@ -0,0 +1,16 @@ +package com.baeldung.beaninjectiontypes; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.beaninjectiontypes") +public class Config { + + @Bean + public ExampleService exampleService() { + return new ExampleService(); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleService.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleService.java new file mode 100644 index 0000000000..9112fee577 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleService.java @@ -0,0 +1,11 @@ +package com.baeldung.beaninjectiontypes; + +import org.springframework.stereotype.Component; + +@Component +public class ExampleService { + + public String getExampleText() { + return "Example"; + } +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithConstructorInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithConstructorInjection.java new file mode 100644 index 0000000000..340d283dbd --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithConstructorInjection.java @@ -0,0 +1,19 @@ +package com.baeldung.beaninjectiontypes; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class ExampleWithConstructorInjection { + + private ExampleService exampleService; + + @Autowired + public ExampleWithConstructorInjection(ExampleService exampleService) { + this.exampleService = exampleService; + } + + public String verifyInjection() { + return this.exampleService.getExampleText(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithPropertyInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithPropertyInjection.java new file mode 100644 index 0000000000..d9495e5c05 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithPropertyInjection.java @@ -0,0 +1,16 @@ +package com.baeldung.beaninjectiontypes; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class ExampleWithPropertyInjection { + + @Autowired + private ExampleService exampleService; + + public String verifyInjection() { + return this.exampleService.getExampleText(); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithSetterInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithSetterInjection.java new file mode 100644 index 0000000000..97f1355ec5 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithSetterInjection.java @@ -0,0 +1,20 @@ +package com.baeldung.beaninjectiontypes; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class ExampleWithSetterInjection { + + private ExampleService exampleService; + + @Autowired + public void setExampleService(ExampleService exampleService) { + this.exampleService = exampleService; + } + + public String verifyInjection() { + return this.exampleService.getExampleText(); + } + +} diff --git a/spring-core/src/test/java/com/baeldung/beaninjectiontypes/BeanInjectionTest.java b/spring-core/src/test/java/com/baeldung/beaninjectiontypes/BeanInjectionTest.java new file mode 100644 index 0000000000..ae609d5df5 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/beaninjectiontypes/BeanInjectionTest.java @@ -0,0 +1,41 @@ +package com.baeldung.beaninjectiontypes; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +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 = Config.class) +public class BeanInjectionTest { + + @Test + public void whenConstructorInjection_ThenBeanValid() { + ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); + ExampleWithConstructorInjection exampleBean = context.getBean(ExampleWithConstructorInjection.class); + + assertEquals("Example", exampleBean.verifyInjection()); + } + + @Test + public void whenSetterInjection_ThenBeanValid() { + ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); + ExampleWithSetterInjection exampleBean = context.getBean(ExampleWithSetterInjection.class); + + assertEquals("Example", exampleBean.verifyInjection()); + } + + @Test + public void whenProperyInjection_ThenBeanValid() { + ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); + ExampleWithPropertyInjection exampleBean = context.getBean(ExampleWithPropertyInjection.class); + + assertEquals("Example", exampleBean.verifyInjection()); + } + +} From 4f7d19e86a42172c0c49eee1c9d6e9d7b75aa666 Mon Sep 17 00:00:00 2001 From: Chris Franklin Date: Tue, 26 Dec 2017 12:19:13 -0500 Subject: [PATCH 02/91] Revert "Christopher Franklin Different Types of Bean Injection in Spring" This reverts commit d76d39fb87892a38da04105836facefbc7face5c. --- .../baeldung/beaninjectiontypes/Config.java | 16 -------- .../beaninjectiontypes/ExampleService.java | 11 ----- .../ExampleWithConstructorInjection.java | 19 --------- .../ExampleWithPropertyInjection.java | 16 -------- .../ExampleWithSetterInjection.java | 20 --------- .../beaninjectiontypes/BeanInjectionTest.java | 41 ------------------- 6 files changed, 123 deletions(-) delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/Config.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleService.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithConstructorInjection.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithPropertyInjection.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithSetterInjection.java delete mode 100644 spring-core/src/test/java/com/baeldung/beaninjectiontypes/BeanInjectionTest.java diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/Config.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/Config.java deleted file mode 100644 index d523dc3f1f..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/Config.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.beaninjectiontypes; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan("com.baeldung.beaninjectiontypes") -public class Config { - - @Bean - public ExampleService exampleService() { - return new ExampleService(); - } - -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleService.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleService.java deleted file mode 100644 index 9112fee577..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.beaninjectiontypes; - -import org.springframework.stereotype.Component; - -@Component -public class ExampleService { - - public String getExampleText() { - return "Example"; - } -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithConstructorInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithConstructorInjection.java deleted file mode 100644 index 340d283dbd..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithConstructorInjection.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.beaninjectiontypes; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class ExampleWithConstructorInjection { - - private ExampleService exampleService; - - @Autowired - public ExampleWithConstructorInjection(ExampleService exampleService) { - this.exampleService = exampleService; - } - - public String verifyInjection() { - return this.exampleService.getExampleText(); - } -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithPropertyInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithPropertyInjection.java deleted file mode 100644 index d9495e5c05..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithPropertyInjection.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.beaninjectiontypes; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class ExampleWithPropertyInjection { - - @Autowired - private ExampleService exampleService; - - public String verifyInjection() { - return this.exampleService.getExampleText(); - } - -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithSetterInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithSetterInjection.java deleted file mode 100644 index 97f1355ec5..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/ExampleWithSetterInjection.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.beaninjectiontypes; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class ExampleWithSetterInjection { - - private ExampleService exampleService; - - @Autowired - public void setExampleService(ExampleService exampleService) { - this.exampleService = exampleService; - } - - public String verifyInjection() { - return this.exampleService.getExampleText(); - } - -} diff --git a/spring-core/src/test/java/com/baeldung/beaninjectiontypes/BeanInjectionTest.java b/spring-core/src/test/java/com/baeldung/beaninjectiontypes/BeanInjectionTest.java deleted file mode 100644 index ae609d5df5..0000000000 --- a/spring-core/src/test/java/com/baeldung/beaninjectiontypes/BeanInjectionTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.beaninjectiontypes; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -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 = Config.class) -public class BeanInjectionTest { - - @Test - public void whenConstructorInjection_ThenBeanValid() { - ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); - ExampleWithConstructorInjection exampleBean = context.getBean(ExampleWithConstructorInjection.class); - - assertEquals("Example", exampleBean.verifyInjection()); - } - - @Test - public void whenSetterInjection_ThenBeanValid() { - ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); - ExampleWithSetterInjection exampleBean = context.getBean(ExampleWithSetterInjection.class); - - assertEquals("Example", exampleBean.verifyInjection()); - } - - @Test - public void whenProperyInjection_ThenBeanValid() { - ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); - ExampleWithPropertyInjection exampleBean = context.getBean(ExampleWithPropertyInjection.class); - - assertEquals("Example", exampleBean.verifyInjection()); - } - -} From 33b93d18f64f83f1c46ecf07f1f351fa49f27b13 Mon Sep 17 00:00:00 2001 From: Chris Franklin Date: Sat, 20 Jan 2018 02:36:26 -0500 Subject: [PATCH 03/91] Christopher Franklin A Simple Tagging Implementation with Elasticsearch Modifying the existing Spring Data Elasticsearch example to use the tags already on the model. Also added a number of tests as examples of how to use the tags. --- .../data/es/repository/ArticleRepository.java | 9 +++++++- .../data/es/service/ArticleService.java | 7 +++++- .../data/es/service/ArticleServiceImpl.java | 15 +++++++++++-- .../data/es/ElasticSearchIntegrationTest.java | 22 ++++++++++++++++++- .../es/ElasticSearchQueryIntegrationTest.java | 12 ++++++++++ 5 files changed, 60 insertions(+), 5 deletions(-) diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java index 8aef865401..93812a3cea 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java @@ -1,12 +1,13 @@ package com.baeldung.spring.data.es.repository; -import com.baeldung.spring.data.es.model.Article; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; +import com.baeldung.spring.data.es.model.Article; + @Repository public interface ArticleRepository extends ElasticsearchRepository { @@ -14,4 +15,10 @@ public interface ArticleRepository extends ElasticsearchRepository findByAuthorsNameUsingCustomQuery(String name, Pageable pageable); + + @Query("{\"bool\": {\"must\": {\"match_all\": {}}, \"filter\": {\"term\": {\"tags\": \"?0\" }}}}") + Page
findByFilteredTagQuery(String tag, Pageable pageable); + + @Query("{\"bool\": {\"must\": {\"match\": {\"authors.name\": \"?0\"}}, \"filter\": {\"term\": {\"tags\": \"?1\" }}}}") + Page
findByAuthorsNameAndFilteredTagQuery(String name, String tag, Pageable pageable); } diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java index b5a8fde633..63e2d91fa7 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java @@ -1,9 +1,10 @@ package com.baeldung.spring.data.es.service; -import com.baeldung.spring.data.es.model.Article; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; +import com.baeldung.spring.data.es.model.Article; + public interface ArticleService { Article save(Article article); @@ -15,6 +16,10 @@ public interface ArticleService { Page
findByAuthorNameUsingCustomQuery(String name, Pageable pageable); + Page
findByFilteredTagQuery(String tag, Pageable pageable); + + Page
findByAuthorsNameAndFilteredTagQuery(String name, String tag, Pageable pageable); + long count(); void delete(Article article); diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java index 2a31b52602..0908ffa70e 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java @@ -1,12 +1,13 @@ package com.baeldung.spring.data.es.service; -import com.baeldung.spring.data.es.repository.ArticleRepository; -import com.baeldung.spring.data.es.model.Article; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; +import com.baeldung.spring.data.es.model.Article; +import com.baeldung.spring.data.es.repository.ArticleRepository; + @Service public class ArticleServiceImpl implements ArticleService { @@ -42,6 +43,16 @@ public class ArticleServiceImpl implements ArticleService { return articleRepository.findByAuthorsNameUsingCustomQuery(name, pageable); } + @Override + public Page
findByFilteredTagQuery(String tag, Pageable pageable) { + return articleRepository.findByFilteredTagQuery(tag, pageable); + } + + @Override + public Page
findByAuthorsNameAndFilteredTagQuery(String name, String tag, Pageable pageable) { + return articleRepository.findByAuthorsNameAndFilteredTagQuery(name, tag, pageable); + } + @Override public long count() { return articleRepository.count(); diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java index 1280c8e1de..4a4cadb550 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java @@ -47,14 +47,22 @@ public class ElasticSearchIntegrationTest { Article article = new Article("Spring Data Elasticsearch"); article.setAuthors(asList(johnSmith, johnDoe)); + article.setTags("elasticsearch", "spring data"); articleService.save(article); article = new Article("Search engines"); article.setAuthors(asList(johnDoe)); + article.setTags("search engines", "tutorial"); articleService.save(article); article = new Article("Second Article About Elasticsearch"); article.setAuthors(asList(johnSmith)); + article.setTags("elasticsearch", "spring data"); + articleService.save(article); + + article = new Article("Elasticsearch Tutorial"); + article.setAuthors(asList(johnDoe)); + article.setTags("elasticsearch"); articleService.save(article); } @@ -79,10 +87,22 @@ public class ElasticSearchIntegrationTest { @Test public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() { - final Page
articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("John Smith", new PageRequest(0, 10)); + final Page
articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("Smith", new PageRequest(0, 10)); + assertEquals(2L, articleByAuthorName.getTotalElements()); + } + + @Test + public void givenTagFilterQuery_whenSearchByTag_thenArticleIsFound() { + final Page
articleByAuthorName = articleService.findByFilteredTagQuery("elasticsearch", new PageRequest(0, 10)); assertEquals(3L, articleByAuthorName.getTotalElements()); } + @Test + public void givenTagFilterQuery_whenSearchByAuthorsName_thenArticleIsFound() { + final Page
articleByAuthorName = articleService.findByAuthorsNameAndFilteredTagQuery("Doe", "elasticsearch", new PageRequest(0, 10)); + assertEquals(2L, articleByAuthorName.getTotalElements()); + } + @Test public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() { diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java index cc4bce0c75..af69f74c1b 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java @@ -174,4 +174,16 @@ public class ElasticSearchQueryIntegrationTest { final List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(2, articles.size()); } + + @Test + public void givenBoolQuery_whenQueryByAuthorsName_thenFoundArticlesByThatAuthorAndFilteredTag() { + final QueryBuilder builder = boolQuery().must(nestedQuery("authors", boolQuery().must(termQuery("authors.name", "doe")))) + .filter(termQuery("tags", "elasticsearch")); + + final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder) + .build(); + final List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); + + assertEquals(2, articles.size()); + } } From 8f4df6b903866dac1725832d06ee7382fc89d0ce Mon Sep 17 00:00:00 2001 From: orrym Date: Sat, 27 Jan 2018 18:11:07 +0200 Subject: [PATCH 04/91] Add XML, JavaConfig and Autowired examples. --- .../BeanInjectorAutowiredExample.java | 18 ++++++++++++ .../autowiredexample/SimpleAutowiredBean.java | 16 ++++++++++ .../SimpleAutowiredDependency.java | 12 ++++++++ .../javaconfigexample/BeanInjectorConfig.java | 29 +++++++++++++++++++ .../BeanInjectorJavaConfigExample.java | 19 ++++++++++++ .../SimpleBeanConstructorInjection.java | 16 ++++++++++ .../SimpleBeanSetterInjection.java | 16 ++++++++++ .../javaconfigexample/SimpleDependency.java | 9 ++++++ .../BeanInjectorXMLExample.java | 17 +++++++++++ .../SimpleBeanConstructorInjection.java | 16 ++++++++++ .../SimpleBeanSetterInjection.java | 16 ++++++++++ .../xmlconfigexample/SimpleDependency.java | 9 ++++++ .../src/main/resources/bean-injector.xml | 19 ++++++++++++ 13 files changed, 212 insertions(+) create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/BeanInjectorAutowiredExample.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredBean.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredDependency.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorConfig.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorJavaConfigExample.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanConstructorInjection.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanSetterInjection.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleDependency.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/BeanInjectorXMLExample.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanConstructorInjection.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanSetterInjection.java create mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleDependency.java create mode 100644 spring-core/src/main/resources/bean-injector.xml diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/BeanInjectorAutowiredExample.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/BeanInjectorAutowiredExample.java new file mode 100644 index 0000000000..43c0314619 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/BeanInjectorAutowiredExample.java @@ -0,0 +1,18 @@ +package com.baeldung.beaninjectiontypes.autowiredexample; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan +public class BeanInjectorAutowiredExample { + + public static void main(String[] args) { + ApplicationContext ctx = new AnnotationConfigApplicationContext(BeanInjectorAutowiredExample.class); + SimpleAutowiredBean simpleBean = (SimpleAutowiredBean) ctx.getBean("simpleAutowiredBean"); + simpleBean.doSomething(); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredBean.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredBean.java new file mode 100644 index 0000000000..1dcd35196b --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredBean.java @@ -0,0 +1,16 @@ +package com.baeldung.beaninjectiontypes.autowiredexample; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class SimpleAutowiredBean { + + @Autowired + private SimpleAutowiredDependency simpleAutowiredDependency; + + public void doSomething() { + System.out.println("I'm a Simple Bean. I'm doing something!"); + simpleAutowiredDependency.doSomethingElse(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredDependency.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredDependency.java new file mode 100644 index 0000000000..f456bafe4a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredDependency.java @@ -0,0 +1,12 @@ +package com.baeldung.beaninjectiontypes.autowiredexample; + +import org.springframework.stereotype.Component; + +@Component +public class SimpleAutowiredDependency { + + public void doSomethingElse() { + System.out.println("I'm a simple autowired dependency! I'm doing something!"); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorConfig.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorConfig.java new file mode 100644 index 0000000000..14e73187a8 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorConfig.java @@ -0,0 +1,29 @@ +package com.baeldung.beaninjectiontypes.javaconfigexample; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class BeanInjectorConfig { + + @Bean + public SimpleDependency simpleDependency() { + return new SimpleDependency(); + } + + // The following illustrates constructor injection: + + @Bean + public SimpleBeanConstructorInjection simpleBeanConstructorInjection() { + return new SimpleBeanConstructorInjection(simpleDependency()); + } + + // The following illustrates setter injection: + + @Bean + public SimpleBeanSetterInjection simpleBeanSetterInjection() { + SimpleBeanSetterInjection simpleBeanSetterInjection = new SimpleBeanSetterInjection(); + simpleBeanSetterInjection.setSimpleDependency(new SimpleDependency()); + return simpleBeanSetterInjection; + } +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorJavaConfigExample.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorJavaConfigExample.java new file mode 100644 index 0000000000..fd6e00105e --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorJavaConfigExample.java @@ -0,0 +1,19 @@ +package com.baeldung.beaninjectiontypes.javaconfigexample; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class BeanInjectorJavaConfigExample { + + public static void main(String[] args) { + ApplicationContext ctx = new AnnotationConfigApplicationContext(BeanInjectorConfig.class); + SimpleBeanConstructorInjection simpleBeanConstructorInjection = (SimpleBeanConstructorInjection) ctx.getBean("simpleBeanConstructorInjection"); + simpleBeanConstructorInjection.doSomething(); + + System.out.println("******************"); + + SimpleBeanSetterInjection simpleBeanSetterInjection = (SimpleBeanSetterInjection) ctx.getBean("simpleBeanSetterInjection"); + simpleBeanSetterInjection.doSomething(); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanConstructorInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanConstructorInjection.java new file mode 100644 index 0000000000..03918602c0 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanConstructorInjection.java @@ -0,0 +1,16 @@ +package com.baeldung.beaninjectiontypes.javaconfigexample; + +public class SimpleBeanConstructorInjection { + + private SimpleDependency simpleDependency; + + SimpleBeanConstructorInjection(SimpleDependency simpleDependency) { + this.simpleDependency = simpleDependency; + } + + public void doSomething() { + System.out.println("I'm a Simple Bean. My dependency is wired using constructor injection - I'm doing something!"); + simpleDependency.doSomethingElse(); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanSetterInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanSetterInjection.java new file mode 100644 index 0000000000..60c3d17997 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanSetterInjection.java @@ -0,0 +1,16 @@ +package com.baeldung.beaninjectiontypes.javaconfigexample; + +public class SimpleBeanSetterInjection { + + private SimpleDependency simpleDependency; + + public void doSomething() { + System.out.println("I'm a Simple Bean. My dependency is wired using setter injection - I'm doing something!"); + simpleDependency.doSomethingElse(); + } + + public void setSimpleDependency(SimpleDependency simpleDependency) { + this.simpleDependency = simpleDependency; + } + +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleDependency.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleDependency.java new file mode 100644 index 0000000000..1867518b12 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleDependency.java @@ -0,0 +1,9 @@ +package com.baeldung.beaninjectiontypes.javaconfigexample; + +public class SimpleDependency { + + public void doSomethingElse() { + System.out.println("I'm a simple dependency! I'm doing something (else)!"); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/BeanInjectorXMLExample.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/BeanInjectorXMLExample.java new file mode 100644 index 0000000000..a637d0f4a4 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/BeanInjectorXMLExample.java @@ -0,0 +1,17 @@ +package com.baeldung.beaninjectiontypes.xmlconfigexample; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class BeanInjectorXMLExample { + + public static void main(String[] args) { + ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-injector.xml"); + SimpleBeanConstructorInjection simpleBeanConstructorInjection = (SimpleBeanConstructorInjection) ctx.getBean("simpleBeanConstructorInjection"); + simpleBeanConstructorInjection.doSomething(); + + System.out.println("********************"); + SimpleBeanSetterInjection simpleBeanSetterInjection = (SimpleBeanSetterInjection) ctx.getBean("simpleBeanSetterInjection"); + simpleBeanSetterInjection.doSomething(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanConstructorInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanConstructorInjection.java new file mode 100644 index 0000000000..db6f58d10d --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanConstructorInjection.java @@ -0,0 +1,16 @@ +package com.baeldung.beaninjectiontypes.xmlconfigexample; + +public class SimpleBeanConstructorInjection { + + private SimpleDependency simpleDependency; + + SimpleBeanConstructorInjection(SimpleDependency simpleDependency) { + this.simpleDependency = simpleDependency; + } + + public void doSomething() { + System.out.println("I'm a Simple Bean. My dependency is wired using constructor injection - I'm doing something!"); + simpleDependency.doSomethingElse(); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanSetterInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanSetterInjection.java new file mode 100644 index 0000000000..7e845c3cd1 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanSetterInjection.java @@ -0,0 +1,16 @@ +package com.baeldung.beaninjectiontypes.xmlconfigexample; + +public class SimpleBeanSetterInjection { + + private SimpleDependency simpleDependency; + + public void setSimpleDependency(SimpleDependency simpleDependency) { + this.simpleDependency = simpleDependency; + } + + public void doSomething() { + System.out.println("I'm a Simple Bean. My dependency is wired using setter injection - I'm doing something!"); + simpleDependency.doSomethingElse(); + } + +} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleDependency.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleDependency.java new file mode 100644 index 0000000000..7b1f2ad35a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleDependency.java @@ -0,0 +1,9 @@ +package com.baeldung.beaninjectiontypes.xmlconfigexample; + +public class SimpleDependency { + + public void doSomethingElse() { + System.out.println("I'm a simple dependency! I'm doing something (else)!"); + } + +} diff --git a/spring-core/src/main/resources/bean-injector.xml b/spring-core/src/main/resources/bean-injector.xml new file mode 100644 index 0000000000..cb084a405f --- /dev/null +++ b/spring-core/src/main/resources/bean-injector.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + \ No newline at end of file From 4344479d7a724932efb897b279d040d3f157abb3 Mon Sep 17 00:00:00 2001 From: orrym Date: Sat, 3 Feb 2018 13:06:31 +0200 Subject: [PATCH 05/91] BAEL-1517: Added Java7 style assertions --- .../exceptions/Java7StyleAssertions.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java7StyleAssertions.java diff --git a/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java7StyleAssertions.java b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java7StyleAssertions.java new file mode 100644 index 0000000000..0dff8d2964 --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java7StyleAssertions.java @@ -0,0 +1,23 @@ +package com.baeldung.testing.assertj.exceptions; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; + +import org.junit.Test; + +public class Java7StyleAssertions { + + @Test + public void whenDividingByZero_thenArithmeticException() { + try { + int numerator = 10; + int denominator = 0; + int quotient = numerator / denominator; + fail("ArithmeticException expected because dividing by zero yields an ArithmeticException."); + failBecauseExceptionWasNotThrown(IndexOutOfBoundsException.class); + } catch (ArithmeticException e) { + assertThat(e).hasMessage("/ by zero"); + } + } +} From 145db059499a055bb1eba4677d6e3215701bb270 Mon Sep 17 00:00:00 2001 From: orrym Date: Sat, 3 Feb 2018 15:45:17 +0200 Subject: [PATCH 06/91] BAEL-1517: Upgrade AssertJ to 3.9.0; add Java 8 style assertion tests --- testing-modules/testing/pom.xml | 2 +- .../exceptions/Java7StyleAssertions.java | 5 ++- .../exceptions/Java8StyleAssertions.java | 42 +++++++++++++++++++ 3 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java8StyleAssertions.java diff --git a/testing-modules/testing/pom.xml b/testing-modules/testing/pom.xml index c76045380b..91792a4681 100644 --- a/testing-modules/testing/pom.xml +++ b/testing-modules/testing/pom.xml @@ -173,7 +173,7 @@ 0.7.7.201606060606 21.0 3.1.0 - 3.6.1 + 3.9.0 2.1.0 0.32 1.1.0 diff --git a/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java7StyleAssertions.java b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java7StyleAssertions.java index 0dff8d2964..07a5be1118 100644 --- a/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java7StyleAssertions.java +++ b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java7StyleAssertions.java @@ -15,9 +15,10 @@ public class Java7StyleAssertions { int denominator = 0; int quotient = numerator / denominator; fail("ArithmeticException expected because dividing by zero yields an ArithmeticException."); - failBecauseExceptionWasNotThrown(IndexOutOfBoundsException.class); - } catch (ArithmeticException e) { + failBecauseExceptionWasNotThrown(ArithmeticException.class); + } catch (Exception e) { assertThat(e).hasMessage("/ by zero"); + assertThat(e).isInstanceOf(ArithmeticException.class); } } } diff --git a/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java8StyleAssertions.java b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java8StyleAssertions.java new file mode 100644 index 0000000000..53f192bb2f --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java8StyleAssertions.java @@ -0,0 +1,42 @@ +package com.baeldung.testing.assertj.exceptions; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.catchThrowable; + +import org.junit.Test; + +public class Java8StyleAssertions { + + @Test + public void whenDividingByZero_thenArithmeticException() { + assertThatThrownBy(() -> { + int numerator = 10; + int denominator = 0; + int quotient = numerator / denominator; + }).isInstanceOf(ArithmeticException.class) + .hasMessageContaining("/ by zero"); + + assertThatExceptionOfType(ArithmeticException.class).isThrownBy(() -> { + int numerator = 10; + int denominator = 0; + int quotient = numerator / denominator; + }) + .withMessageContaining("/ by zero"); + + // BDD style: + + // when + Throwable thrown = catchThrowable(() -> { + int numerator = 10; + int denominator = 0; + int quotient = numerator / denominator; + }); + + // then + assertThat(thrown).isInstanceOf(ArithmeticException.class) + .hasMessageContaining("/ by zero"); + + } +} From c9006942c2716f542e275b0bbd1c4c60bc37d6bd Mon Sep 17 00:00:00 2001 From: orrym Date: Tue, 6 Feb 2018 19:54:52 +0200 Subject: [PATCH 07/91] Revert "Add XML, JavaConfig and Autowired examples." This reverts commit 8f4df6b903866dac1725832d06ee7382fc89d0ce. --- .../BeanInjectorAutowiredExample.java | 18 ------------ .../autowiredexample/SimpleAutowiredBean.java | 16 ---------- .../SimpleAutowiredDependency.java | 12 -------- .../javaconfigexample/BeanInjectorConfig.java | 29 ------------------- .../BeanInjectorJavaConfigExample.java | 19 ------------ .../SimpleBeanConstructorInjection.java | 16 ---------- .../SimpleBeanSetterInjection.java | 16 ---------- .../javaconfigexample/SimpleDependency.java | 9 ------ .../BeanInjectorXMLExample.java | 17 ----------- .../SimpleBeanConstructorInjection.java | 16 ---------- .../SimpleBeanSetterInjection.java | 16 ---------- .../xmlconfigexample/SimpleDependency.java | 9 ------ .../src/main/resources/bean-injector.xml | 19 ------------ 13 files changed, 212 deletions(-) delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/BeanInjectorAutowiredExample.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredBean.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredDependency.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorConfig.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorJavaConfigExample.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanConstructorInjection.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanSetterInjection.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleDependency.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/BeanInjectorXMLExample.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanConstructorInjection.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanSetterInjection.java delete mode 100644 spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleDependency.java delete mode 100644 spring-core/src/main/resources/bean-injector.xml diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/BeanInjectorAutowiredExample.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/BeanInjectorAutowiredExample.java deleted file mode 100644 index 43c0314619..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/BeanInjectorAutowiredExample.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.beaninjectiontypes.autowiredexample; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan -public class BeanInjectorAutowiredExample { - - public static void main(String[] args) { - ApplicationContext ctx = new AnnotationConfigApplicationContext(BeanInjectorAutowiredExample.class); - SimpleAutowiredBean simpleBean = (SimpleAutowiredBean) ctx.getBean("simpleAutowiredBean"); - simpleBean.doSomething(); - } - -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredBean.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredBean.java deleted file mode 100644 index 1dcd35196b..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredBean.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.beaninjectiontypes.autowiredexample; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class SimpleAutowiredBean { - - @Autowired - private SimpleAutowiredDependency simpleAutowiredDependency; - - public void doSomething() { - System.out.println("I'm a Simple Bean. I'm doing something!"); - simpleAutowiredDependency.doSomethingElse(); - } -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredDependency.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredDependency.java deleted file mode 100644 index f456bafe4a..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/autowiredexample/SimpleAutowiredDependency.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.beaninjectiontypes.autowiredexample; - -import org.springframework.stereotype.Component; - -@Component -public class SimpleAutowiredDependency { - - public void doSomethingElse() { - System.out.println("I'm a simple autowired dependency! I'm doing something!"); - } - -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorConfig.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorConfig.java deleted file mode 100644 index 14e73187a8..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorConfig.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.beaninjectiontypes.javaconfigexample; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class BeanInjectorConfig { - - @Bean - public SimpleDependency simpleDependency() { - return new SimpleDependency(); - } - - // The following illustrates constructor injection: - - @Bean - public SimpleBeanConstructorInjection simpleBeanConstructorInjection() { - return new SimpleBeanConstructorInjection(simpleDependency()); - } - - // The following illustrates setter injection: - - @Bean - public SimpleBeanSetterInjection simpleBeanSetterInjection() { - SimpleBeanSetterInjection simpleBeanSetterInjection = new SimpleBeanSetterInjection(); - simpleBeanSetterInjection.setSimpleDependency(new SimpleDependency()); - return simpleBeanSetterInjection; - } -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorJavaConfigExample.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorJavaConfigExample.java deleted file mode 100644 index fd6e00105e..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/BeanInjectorJavaConfigExample.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.beaninjectiontypes.javaconfigexample; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; - -public class BeanInjectorJavaConfigExample { - - public static void main(String[] args) { - ApplicationContext ctx = new AnnotationConfigApplicationContext(BeanInjectorConfig.class); - SimpleBeanConstructorInjection simpleBeanConstructorInjection = (SimpleBeanConstructorInjection) ctx.getBean("simpleBeanConstructorInjection"); - simpleBeanConstructorInjection.doSomething(); - - System.out.println("******************"); - - SimpleBeanSetterInjection simpleBeanSetterInjection = (SimpleBeanSetterInjection) ctx.getBean("simpleBeanSetterInjection"); - simpleBeanSetterInjection.doSomething(); - } - -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanConstructorInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanConstructorInjection.java deleted file mode 100644 index 03918602c0..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanConstructorInjection.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.beaninjectiontypes.javaconfigexample; - -public class SimpleBeanConstructorInjection { - - private SimpleDependency simpleDependency; - - SimpleBeanConstructorInjection(SimpleDependency simpleDependency) { - this.simpleDependency = simpleDependency; - } - - public void doSomething() { - System.out.println("I'm a Simple Bean. My dependency is wired using constructor injection - I'm doing something!"); - simpleDependency.doSomethingElse(); - } - -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanSetterInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanSetterInjection.java deleted file mode 100644 index 60c3d17997..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleBeanSetterInjection.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.beaninjectiontypes.javaconfigexample; - -public class SimpleBeanSetterInjection { - - private SimpleDependency simpleDependency; - - public void doSomething() { - System.out.println("I'm a Simple Bean. My dependency is wired using setter injection - I'm doing something!"); - simpleDependency.doSomethingElse(); - } - - public void setSimpleDependency(SimpleDependency simpleDependency) { - this.simpleDependency = simpleDependency; - } - -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleDependency.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleDependency.java deleted file mode 100644 index 1867518b12..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/javaconfigexample/SimpleDependency.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.beaninjectiontypes.javaconfigexample; - -public class SimpleDependency { - - public void doSomethingElse() { - System.out.println("I'm a simple dependency! I'm doing something (else)!"); - } - -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/BeanInjectorXMLExample.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/BeanInjectorXMLExample.java deleted file mode 100644 index a637d0f4a4..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/BeanInjectorXMLExample.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.beaninjectiontypes.xmlconfigexample; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class BeanInjectorXMLExample { - - public static void main(String[] args) { - ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-injector.xml"); - SimpleBeanConstructorInjection simpleBeanConstructorInjection = (SimpleBeanConstructorInjection) ctx.getBean("simpleBeanConstructorInjection"); - simpleBeanConstructorInjection.doSomething(); - - System.out.println("********************"); - SimpleBeanSetterInjection simpleBeanSetterInjection = (SimpleBeanSetterInjection) ctx.getBean("simpleBeanSetterInjection"); - simpleBeanSetterInjection.doSomething(); - } -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanConstructorInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanConstructorInjection.java deleted file mode 100644 index db6f58d10d..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanConstructorInjection.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.beaninjectiontypes.xmlconfigexample; - -public class SimpleBeanConstructorInjection { - - private SimpleDependency simpleDependency; - - SimpleBeanConstructorInjection(SimpleDependency simpleDependency) { - this.simpleDependency = simpleDependency; - } - - public void doSomething() { - System.out.println("I'm a Simple Bean. My dependency is wired using constructor injection - I'm doing something!"); - simpleDependency.doSomethingElse(); - } - -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanSetterInjection.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanSetterInjection.java deleted file mode 100644 index 7e845c3cd1..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleBeanSetterInjection.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.beaninjectiontypes.xmlconfigexample; - -public class SimpleBeanSetterInjection { - - private SimpleDependency simpleDependency; - - public void setSimpleDependency(SimpleDependency simpleDependency) { - this.simpleDependency = simpleDependency; - } - - public void doSomething() { - System.out.println("I'm a Simple Bean. My dependency is wired using setter injection - I'm doing something!"); - simpleDependency.doSomethingElse(); - } - -} diff --git a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleDependency.java b/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleDependency.java deleted file mode 100644 index 7b1f2ad35a..0000000000 --- a/spring-core/src/main/java/com/baeldung/beaninjectiontypes/xmlconfigexample/SimpleDependency.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.beaninjectiontypes.xmlconfigexample; - -public class SimpleDependency { - - public void doSomethingElse() { - System.out.println("I'm a simple dependency! I'm doing something (else)!"); - } - -} diff --git a/spring-core/src/main/resources/bean-injector.xml b/spring-core/src/main/resources/bean-injector.xml deleted file mode 100644 index cb084a405f..0000000000 --- a/spring-core/src/main/resources/bean-injector.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file From d0ff2aa57d12e8fac11c64a8e0974ff3c46e2453 Mon Sep 17 00:00:00 2001 From: Chris Franklin Date: Fri, 9 Feb 2018 14:37:58 -0500 Subject: [PATCH 08/91] Code samples for Simple Tagging with JPA --- .../persistence/dao/StudentRepository.java | 11 +++++ .../inmemory/persistence/model/Student.java | 13 ++++++ .../repository/InMemoryDBIntegrationTest.java | 45 +++++++++++++++++++ 3 files changed, 69 insertions(+) diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java index bfcf6f5cdc..f856b78c52 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java @@ -2,6 +2,17 @@ package org.baeldung.inmemory.persistence.dao; import org.baeldung.inmemory.persistence.model.Student; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; public interface StudentRepository extends JpaRepository { + + @Query("SELECT s FROM Student s JOIN s.tags t WHERE t = LOWER(:tag)") + List retrieveByTag(@Param("tag") String tag); + + @Query("SELECT s FROM Student s JOIN s.tags t WHERE s.name = LOWER(:name) AND t = LOWER(:tag)") + List retrieveByNameFilterByTag(@Param("name") String name, @Param("tag") String tag); + } diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java index b50fe9122e..2e4e3ea2cb 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java @@ -1,7 +1,10 @@ package org.baeldung.inmemory.persistence.model; +import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.Id; +import java.util.ArrayList; +import java.util.List; @Entity public class Student { @@ -10,6 +13,9 @@ public class Student { private long id; private String name; + @ElementCollection + private List tags = new ArrayList<>(); + public Student() { } @@ -35,4 +41,11 @@ public class Student { this.name = name; } + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags.addAll(tags); + } } diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java index 8380ab5434..28d7e3772c 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java @@ -12,6 +12,9 @@ import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; +import java.util.Arrays; +import java.util.List; + import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @@ -34,4 +37,46 @@ public class InMemoryDBIntegrationTest { assertEquals("name incorrect", NAME, student2.getName()); } + @Test + public void givenStudentWithTags_whenSave_thenGetByTagOk(){ + Student student = new Student(ID, NAME); + student.setTags(Arrays.asList("full time", "computer science")); + studentRepository.save(student); + + Student student2 = studentRepository.retrieveByTag("full time").get(0); + assertEquals("name incorrect", NAME, student2.getName()); + } + + @Test + public void givenMultipleStudentsWithTags_whenSave_thenGetByTagReturnsCorrectCount(){ + Student student = new Student(0, "Larry"); + student.setTags(Arrays.asList("full time", "computer science")); + studentRepository.save(student); + + Student student2 = new Student(1, "Curly"); + student2.setTags(Arrays.asList("part time", "rocket science")); + studentRepository.save(student2); + + Student student3 = new Student(2, "Moe"); + student3.setTags(Arrays.asList("full time", "philosophy")); + studentRepository.save(student3); + + Student student4 = new Student(3, "Shemp"); + student4.setTags(Arrays.asList("part time", "mathematics")); + studentRepository.save(student4); + + List students = studentRepository.retrieveByTag("full time"); + assertEquals("size incorrect", 2, students.size()); + } + + @Test + public void givenStudentWithTags_whenSave_thenGetByNameAndTagOk(){ + Student student = new Student(ID, NAME); + student.setTags(Arrays.asList("full time", "computer science")); + studentRepository.save(student); + + Student student2 = studentRepository.retrieveByNameFilterByTag("John", "full time").get(0); + assertEquals("name incorrect", NAME, student2.getName()); + } + } From 0b71d385f0507cd28b8cedb6bae789de94d47f0b Mon Sep 17 00:00:00 2001 From: orrym Date: Sun, 11 Feb 2018 10:33:00 +0200 Subject: [PATCH 09/91] BAEL-1517: Editor Review changes --- .../exceptions/Java8StyleAssertions.java | 43 ++++++++++++++++--- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java8StyleAssertions.java b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java8StyleAssertions.java index 53f192bb2f..15b41dc896 100644 --- a/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java8StyleAssertions.java +++ b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java8StyleAssertions.java @@ -3,21 +3,50 @@ package com.baeldung.testing.assertj.exceptions; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +import static org.assertj.core.api.Assertions.assertThatIOException; +import static org.assertj.core.api.Assertions.assertThatNullPointerException; import static org.assertj.core.api.Assertions.catchThrowable; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; + import org.junit.Test; public class Java8StyleAssertions { @Test - public void whenDividingByZero_thenArithmeticException() { + public void whenGettingOutOfBoundsItem_thenIndexOutOfBoundsException() { assertThatThrownBy(() -> { - int numerator = 10; - int denominator = 0; - int quotient = numerator / denominator; - }).isInstanceOf(ArithmeticException.class) - .hasMessageContaining("/ by zero"); + ArrayList myStringList = new ArrayList(Arrays.asList("Strine one", "String two")); + myStringList.get(2); + }).isInstanceOf(IndexOutOfBoundsException.class) + .hasMessageStartingWith("Index: 2") + .hasMessageContaining("2") + .hasMessageEndingWith("Size: 2") + .hasMessageContaining("Index: 2, Size: 2") + .hasMessage("Index: %s, Size: %s", 2, 2) + .hasMessageMatching("Index: \\d+, Size: \\d+") + .hasNoCause(); + } + @Test + public void whenWrappingException_thenCauseInstanceOfWrappedExceptionType() { + assertThatThrownBy(() -> { + try { + throw new IOException(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }).isInstanceOf(RuntimeException.class) + .hasCauseInstanceOf(IOException.class) + .hasStackTraceContaining("java.io.IOException"); + } + + @Test + public void whenDividingByZero_thenArithmeticException() { assertThatExceptionOfType(ArithmeticException.class).isThrownBy(() -> { int numerator = 10; int denominator = 0; @@ -25,7 +54,7 @@ public class Java8StyleAssertions { }) .withMessageContaining("/ by zero"); - // BDD style: + // Alternatively: // when Throwable thrown = catchThrowable(() -> { From febfb466a60d97e98cc718c5ea9e2f160bb95d12 Mon Sep 17 00:00:00 2001 From: orrym Date: Sun, 11 Feb 2018 10:33:28 +0200 Subject: [PATCH 10/91] BAEL-1517: Formatting... --- .../testing/assertj/exceptions/Java8StyleAssertions.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java8StyleAssertions.java b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java8StyleAssertions.java index 15b41dc896..2fbbf6d8d3 100644 --- a/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java8StyleAssertions.java +++ b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/exceptions/Java8StyleAssertions.java @@ -42,7 +42,7 @@ public class Java8StyleAssertions { } }).isInstanceOf(RuntimeException.class) .hasCauseInstanceOf(IOException.class) - .hasStackTraceContaining("java.io.IOException"); + .hasStackTraceContaining("IOException"); } @Test From dc6c89efbeb5f956c3a1921b8a02a4886651e823 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Mon, 12 Feb 2018 20:12:51 +0100 Subject: [PATCH 11/91] added article link --- testing-modules/testing/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/testing/README.md b/testing-modules/testing/README.md index 2894da3496..c9c656dde9 100644 --- a/testing-modules/testing/README.md +++ b/testing-modules/testing/README.md @@ -18,3 +18,4 @@ - [Custom JUnit 4 Test Runners](http://www.baeldung.com/junit-4-custom-runners) - [Guide to JSpec](http://www.baeldung.com/jspec) - [Custom Assertions with AssertJ](http://www.baeldung.com/assertj-custom-assertion) +- [Using Conditions with AssertJ](http://www.baeldung.com/assertj-conditions) From 42ffe6cb7c3da4c13dec442477c26615c23f4b31 Mon Sep 17 00:00:00 2001 From: Chris Franklin Date: Mon, 12 Feb 2018 15:16:59 -0500 Subject: [PATCH 12/91] Fix pom relative path for spring-jpa --- persistence-modules/spring-jpa/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 04c64fafc3..bc0b2381f3 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -13,7 +13,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - ../ + ../../ From 64dd15eaf44bd859f2e2b1ae5834ec09696f4dab Mon Sep 17 00:00:00 2001 From: Chris Franklin Date: Fri, 23 Feb 2018 17:01:23 -0500 Subject: [PATCH 13/91] [BAEL-1575] Advanced tagging implementation with JPA --- .../dao/ManyStudentRepository.java | 10 ++++ .../persistence/dao/ManyTagRepository.java | 7 +++ .../persistence/dao/StudentRepository.java | 6 +++ .../inmemory/persistence/model/KVTag.java | 33 ++++++++++++ .../persistence/model/LocationTag.java | 39 ++++++++++++++ .../persistence/model/ManyStudent.java | 34 ++++++++++++ .../inmemory/persistence/model/ManyTag.java | 39 ++++++++++++++ .../inmemory/persistence/model/SkillTag.java | 29 ++++++++++ .../inmemory/persistence/model/Student.java | 29 ++++++++-- .../repository/InMemoryDBIntegrationTest.java | 54 ++++++++++++++++++- 10 files changed, 276 insertions(+), 4 deletions(-) create mode 100644 persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyStudentRepository.java create mode 100644 persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyTagRepository.java create mode 100644 persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/KVTag.java create mode 100644 persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/LocationTag.java create mode 100644 persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyStudent.java create mode 100644 persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyTag.java create mode 100644 persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/SkillTag.java diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyStudentRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyStudentRepository.java new file mode 100644 index 0000000000..a03b2950a0 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyStudentRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.inmemory.persistence.dao; + +import org.baeldung.inmemory.persistence.model.ManyStudent; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface ManyStudentRepository extends JpaRepository { + List findByManyTags_Name(String name); +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyTagRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyTagRepository.java new file mode 100644 index 0000000000..b7d991de32 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/ManyTagRepository.java @@ -0,0 +1,7 @@ +package org.baeldung.inmemory.persistence.dao; + +import org.baeldung.inmemory.persistence.model.ManyTag; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ManyTagRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java index f856b78c52..ffe1a68558 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java @@ -15,4 +15,10 @@ public interface StudentRepository extends JpaRepository { @Query("SELECT s FROM Student s JOIN s.tags t WHERE s.name = LOWER(:name) AND t = LOWER(:tag)") List retrieveByNameFilterByTag(@Param("name") String name, @Param("tag") String tag); + @Query("SELECT s FROM Student s JOIN s.skillTags t WHERE t.name = LOWER(:tagName) AND t.value > :tagValue") + List retrieveByNameFilterByMinimumSkillTag(@Param("tagName") String tagName, @Param("tagValue") int tagValue); + + @Query("SELECT s FROM Student s JOIN s.kvTags t WHERE t.key = LOWER(:key)") + List retrieveByKeyTag(@Param("key") String key); + } diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/KVTag.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/KVTag.java new file mode 100644 index 0000000000..ba0071e37b --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/KVTag.java @@ -0,0 +1,33 @@ +package org.baeldung.inmemory.persistence.model; + +import javax.persistence.Embeddable; + +@Embeddable +public class KVTag { + private String key; + private String value; + + public KVTag(){} + + public KVTag(String key, String value) { + super(); + this.key = key; + this.value = value; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/LocationTag.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/LocationTag.java new file mode 100644 index 0000000000..071dc24806 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/LocationTag.java @@ -0,0 +1,39 @@ +package org.baeldung.inmemory.persistence.model; + +import javax.persistence.Embeddable; + +@Embeddable +public class LocationTag { + private String name; + private int xPos; + private int yPos; + + public LocationTag(){} + + public LocationTag(String name, int xPos, int yPos) { + super(); + this.name = name; + this.xPos = xPos; + this.yPos = yPos; + } + + public String getName() { + return name; + } + + public int getxPos() { + return xPos; + } + + public void setxPos(int xPos) { + this.xPos = xPos; + } + + public int getyPos() { + return yPos; + } + + public void setyPos(int yPos) { + this.yPos = yPos; + } +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyStudent.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyStudent.java new file mode 100644 index 0000000000..98778b8f75 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyStudent.java @@ -0,0 +1,34 @@ +package org.baeldung.inmemory.persistence.model; + +import javax.persistence.*; +import java.util.HashSet; +import java.util.Set; + +@Entity +public class ManyStudent { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + private String name; + + @ManyToMany(cascade = CascadeType.ALL) + @JoinTable(name = "manystudent_manytags", + joinColumns = @JoinColumn(name = "manystudent_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "manytag_id", referencedColumnName = "id")) + private Set manyTags = new HashSet<>(); + + public ManyStudent() {} + + public ManyStudent(String name) { + this.name = name; + } + + public Set getManyTags() { + return manyTags; + } + + public void setManyTags(Set manyTags) { + this.manyTags.addAll(manyTags); + } +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyTag.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyTag.java new file mode 100644 index 0000000000..96f9534d43 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyTag.java @@ -0,0 +1,39 @@ +package org.baeldung.inmemory.persistence.model; + +import javax.persistence.*; +import java.util.HashSet; +import java.util.Set; + +@Entity +public class ManyTag { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + private String name; + + @ManyToMany(mappedBy = "manyTags") + private Set students = new HashSet<>(); + + public ManyTag() {} + + public ManyTag(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Set getStudents() { + return students; + } + + public void setStudents(Set students) { + this.students.addAll(students); + } +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/SkillTag.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/SkillTag.java new file mode 100644 index 0000000000..0300d83d50 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/SkillTag.java @@ -0,0 +1,29 @@ +package org.baeldung.inmemory.persistence.model; + +import javax.persistence.Embeddable; + +@Embeddable +public class SkillTag { + private String name; + private int value; + + public SkillTag(){} + + public SkillTag(String name, int value) { + super(); + this.name = name; + this.value = value; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public String getName() { + return name; + } +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java index 2e4e3ea2cb..4751a999a0 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java @@ -1,10 +1,10 @@ package org.baeldung.inmemory.persistence.model; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.Id; +import javax.persistence.*; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; @Entity public class Student { @@ -16,6 +16,12 @@ public class Student { @ElementCollection private List tags = new ArrayList<>(); + @ElementCollection + private List skillTags = new ArrayList<>(); + + @ElementCollection + private List kvTags = new ArrayList<>(); + public Student() { } @@ -48,4 +54,21 @@ public class Student { public void setTags(List tags) { this.tags.addAll(tags); } + + public List getSkillTags() { + return skillTags; + } + + public void setSkillTags(List skillTags) { + this.skillTags.addAll(skillTags); + } + + public List getKVTags() { + return this.kvTags; + } + + public void setKVTags(List kvTags) { + this.kvTags.addAll(kvTags); + } + } diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java index 28d7e3772c..fa957cc9d0 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java @@ -1,8 +1,10 @@ package org.baeldung.persistence.repository; import org.baeldung.config.StudentJpaConfig; +import org.baeldung.inmemory.persistence.dao.ManyStudentRepository; +import org.baeldung.inmemory.persistence.dao.ManyTagRepository; import org.baeldung.inmemory.persistence.dao.StudentRepository; -import org.baeldung.inmemory.persistence.model.Student; +import org.baeldung.inmemory.persistence.model.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; @@ -13,6 +15,7 @@ import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Arrays; +import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals; @@ -24,6 +27,12 @@ public class InMemoryDBIntegrationTest { @Resource private StudentRepository studentRepository; + + @Resource + private ManyStudentRepository manyStudentRepository; + + @Resource + private ManyTagRepository manyTagRepository; private static final long ID = 1; private static final String NAME="john"; @@ -79,4 +88,47 @@ public class InMemoryDBIntegrationTest { assertEquals("name incorrect", NAME, student2.getName()); } + @Test + public void givenStudenWithSkillTags_whenSave_thenGetByNameAndSkillTag() { + Student student = new Student(1, "Will"); + SkillTag skill1 = new SkillTag("java", 5); + student.setSkillTags(Arrays.asList(skill1)); + studentRepository.save(student); + + Student student2 = new Student(2, "Joe"); + SkillTag skill2 = new SkillTag("java", 1); + student2.setSkillTags(Arrays.asList(skill2)); + studentRepository.save(student2); + + List students = studentRepository.retrieveByNameFilterByMinimumSkillTag("java", 3); + assertEquals("size incorrect", 1, students.size()); + } + + @Test + public void givenStudentWithKVTags_whenSave_thenGetByTagOk(){ + Student student = new Student(0, "John"); + student.setKVTags(Arrays.asList(new KVTag("department", "computer science"))); + studentRepository.save(student); + + Student student2 = new Student(1, "James"); + student2.setKVTags(Arrays.asList(new KVTag("department", "humanities"))); + studentRepository.save(student2); + + List students = studentRepository.retrieveByKeyTag("department"); + assertEquals("size incorrect", 2, students.size()); + } + + @Test + public void givenStudentWithManyTags_whenSave_theyGetByTagOk() { + ManyTag tag = new ManyTag("full time"); + manyTagRepository.save(tag); + + ManyStudent student = new ManyStudent("John"); + student.setManyTags(Collections.singleton(tag)); + manyStudentRepository.save(student); + + List students = manyStudentRepository.findByManyTags_Name("full time"); + assertEquals("size incorrect", 1, students.size()); + } + } From f532a2cf0bb5aa4b26f53cd0512e868f85e11b3c Mon Sep 17 00:00:00 2001 From: Marcos Lopez Gonzalez Date: Sun, 25 Feb 2018 21:36:23 +0100 Subject: [PATCH 14/91] BAEL-1551 Jersey filters and interceptors --- jersey/pom.xml | 63 +++++++++++++++++++ .../baeldung/jersey/client/JerseyClient.java | 45 +++++++++++++ .../client/filter/RequestClientFilter.java | 24 +++++++ .../client/filter/ResponseClientFilter.java | 26 ++++++++ .../RequestClientWriterInterceptor.java | 28 +++++++++ .../com/baeldung/jersey/server/Greetings.java | 29 +++++++++ .../jersey/server/config/HelloBinding.java | 11 ++++ .../server/config/HelloDynamicBinding.java | 31 +++++++++ .../jersey/server/config/ServerConfig.java | 14 +++++ .../filter/PrematchingRequestFilter.java | 27 ++++++++ .../server/filter/ResponseServerFilter.java | 23 +++++++ .../RestrictedOperationsRequestFilter.java | 36 +++++++++++ .../RequestServerReaderInterceptor.java | 36 +++++++++++ jersey/src/main/resources/logback.xml | 13 ++++ .../jersey/client/JerseyClientTest.java | 33 ++++++++++ pom.xml | 8 +-- 16 files changed, 443 insertions(+), 4 deletions(-) create mode 100644 jersey/pom.xml create mode 100644 jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/server/Greetings.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java create mode 100644 jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java create mode 100644 jersey/src/main/resources/logback.xml create mode 100644 jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java diff --git a/jersey/pom.xml b/jersey/pom.xml new file mode 100644 index 0000000000..0c8b6b9281 --- /dev/null +++ b/jersey/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + com.baeldung + jersey + 0.0.1-SNAPSHOT + war + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 2.26 + 1.7.25 + 3.2.0 + + + + jersey + + + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + + + + + org.glassfish.jersey.core + jersey-server + ${jersey.version} + + + org.glassfish.jersey.core + jersey-client + ${jersey.version} + + + org.glassfish.jersey.bundles + jaxrs-ri + ${jersey.version} + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + + + + diff --git a/jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java b/jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java new file mode 100644 index 0000000000..88ad891411 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java @@ -0,0 +1,45 @@ +package com.baeldung.jersey.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Response; + +import org.glassfish.jersey.client.ClientConfig; + +import com.baeldung.jersey.client.filter.RequestClientFilter; +import com.baeldung.jersey.client.filter.ResponseClientFilter; +import com.baeldung.jersey.client.interceptor.RequestClientWriterInterceptor; + +public class JerseyClient { + + private static final String URI_GREETINGS = "http://localhost:8080/jersey/greetings"; + + public static String getHelloGreeting() { + return createClient().target(URI_GREETINGS) + .request() + .get(String.class); + } + + public static String getHiGreeting() { + return createClient().target(URI_GREETINGS + "/hi") + .request() + .get(String.class); + } + + public static Response getCustomGreeting() { + return createClient().target(URI_GREETINGS + "/custom") + .request() + .post(Entity.text("custom")); + } + + private static Client createClient() { + ClientConfig config = new ClientConfig(); + config.register(RequestClientFilter.class); + config.register(ResponseClientFilter.class); + config.register(RequestClientWriterInterceptor.class); + + return ClientBuilder.newClient(config); + } + +} diff --git a/jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java b/jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java new file mode 100644 index 0000000000..8c6ac2c5fb --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java @@ -0,0 +1,24 @@ +package com.baeldung.jersey.client.filter; + +import java.io.IOException; + +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import javax.ws.rs.ext.Provider; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Provider +public class RequestClientFilter implements ClientRequestFilter { + + private static final Logger LOG = LoggerFactory.getLogger(RequestClientFilter.class); + + @Override + public void filter(ClientRequestContext requestContext) throws IOException { + LOG.info("Request client filter"); + + requestContext.setProperty("test", "test client request filter"); + } + +} diff --git a/jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java b/jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java new file mode 100644 index 0000000000..1676fa2094 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java @@ -0,0 +1,26 @@ +package com.baeldung.jersey.client.filter; + +import java.io.IOException; + +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.ext.Provider; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Provider +public class ResponseClientFilter implements ClientResponseFilter { + + private static final Logger LOG = LoggerFactory.getLogger(ResponseClientFilter.class); + + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { + LOG.info("Response client filter"); + + responseContext.getHeaders() + .add("X-Test-Client", "Test response client filter"); + } + +} diff --git a/jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java b/jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java new file mode 100644 index 0000000000..7216cf18cc --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java @@ -0,0 +1,28 @@ +package com.baeldung.jersey.client.interceptor; + +import java.io.IOException; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.ext.Provider; +import javax.ws.rs.ext.WriterInterceptor; +import javax.ws.rs.ext.WriterInterceptorContext; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Provider +public class RequestClientWriterInterceptor implements WriterInterceptor { + + private static final Logger LOG = LoggerFactory.getLogger(RequestClientWriterInterceptor.class); + + @Override + public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { + LOG.info("request writer interceptor in the client side"); + + context.getOutputStream() + .write(("Message added in the writer interceptor in the client side").getBytes()); + + context.proceed(); + } + +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java b/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java new file mode 100644 index 0000000000..5e2781ee3c --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java @@ -0,0 +1,29 @@ +package com.baeldung.jersey.server; + +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; + +import com.baeldung.jersey.server.config.HelloBinding; + +@Path("/greetings") +public class Greetings { + + @GET + @HelloBinding + public String getHelloGreeting() { + return "hello"; + } + + @GET + @Path("/hi") + public String getHiGreeting() { + return "hi"; + } + + @POST + @Path("/custom") + public String getCustomGreeting(String name) { + return "hello " + name; + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java b/jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java new file mode 100644 index 0000000000..49b11adeab --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java @@ -0,0 +1,11 @@ +package com.baeldung.jersey.server.config; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +import javax.ws.rs.NameBinding; + +@NameBinding +@Retention(RetentionPolicy.RUNTIME) +public @interface HelloBinding { +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java b/jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java new file mode 100644 index 0000000000..e56cdec140 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java @@ -0,0 +1,31 @@ +package com.baeldung.jersey.server.config; + +import javax.ws.rs.container.DynamicFeature; +import javax.ws.rs.container.ResourceInfo; +import javax.ws.rs.core.FeatureContext; +import javax.ws.rs.ext.Provider; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.jersey.server.Greetings; +import com.baeldung.jersey.server.filter.ResponseServerFilter; + +@Provider +public class HelloDynamicBinding implements DynamicFeature { + + private static final Logger LOG = LoggerFactory.getLogger(HelloDynamicBinding.class); + + @Override + public void configure(ResourceInfo resourceInfo, FeatureContext context) { + LOG.info("Hello dynamic binding"); + + if (Greetings.class.equals(resourceInfo.getResourceClass()) && resourceInfo.getResourceMethod() + .getName() + .contains("HiGreeting")) { + context.register(ResponseServerFilter.class); + } + + } + +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java b/jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java new file mode 100644 index 0000000000..4670cc291c --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java @@ -0,0 +1,14 @@ +package com.baeldung.jersey.server.config; + +import javax.ws.rs.ApplicationPath; + +import org.glassfish.jersey.server.ResourceConfig; + +@ApplicationPath("/*") +public class ServerConfig extends ResourceConfig { + + public ServerConfig() { + packages("com.baeldung.jersey.server"); + } + +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java b/jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java new file mode 100644 index 0000000000..181fa7f043 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java @@ -0,0 +1,27 @@ +package com.baeldung.jersey.server.filter; + +import java.io.IOException; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.PreMatching; +import javax.ws.rs.ext.Provider; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Provider +@PreMatching +public class PrematchingRequestFilter implements ContainerRequestFilter { + + private static final Logger LOG = LoggerFactory.getLogger(PrematchingRequestFilter.class); + + @Override + public void filter(ContainerRequestContext ctx) throws IOException { + LOG.info("prematching filter"); + if (ctx.getMethod() + .equals("DELETE")) { + LOG.info("\"Deleting request"); + } + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java b/jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java new file mode 100644 index 0000000000..de0dcbdce7 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java @@ -0,0 +1,23 @@ +package com.baeldung.jersey.server.filter; + +import java.io.IOException; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ResponseServerFilter implements ContainerResponseFilter { + + private static final Logger LOG = LoggerFactory.getLogger(ResponseServerFilter.class); + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { + LOG.info("Response server filter"); + + responseContext.getHeaders() + .add("X-Test", "Filter test"); + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java b/jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java new file mode 100644 index 0000000000..cb0cd185f7 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java @@ -0,0 +1,36 @@ +package com.baeldung.jersey.server.filter; + +import java.io.IOException; + +import javax.annotation.Priority; +import javax.ws.rs.Priorities; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.jersey.server.config.HelloBinding; + +@Provider +@Priority(Priorities.AUTHORIZATION) +@HelloBinding +public class RestrictedOperationsRequestFilter implements ContainerRequestFilter { + + private static final Logger LOG = LoggerFactory.getLogger(RestrictedOperationsRequestFilter.class); + + @Override + public void filter(ContainerRequestContext ctx) throws IOException { + LOG.info("Restricted operations filter"); + if (ctx.getLanguage() != null && "EN".equals(ctx.getLanguage() + .getLanguage())) { + LOG.info("Aborting request"); + ctx.abortWith(Response.status(Response.Status.FORBIDDEN) + .entity("Cannot access") + .build()); + } + + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java b/jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java new file mode 100644 index 0000000000..e9cc57fc2a --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java @@ -0,0 +1,36 @@ +package com.baeldung.jersey.server.interceptor; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.stream.Collectors; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.ext.Provider; +import javax.ws.rs.ext.ReaderInterceptor; +import javax.ws.rs.ext.ReaderInterceptorContext; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Provider +public class RequestServerReaderInterceptor implements ReaderInterceptor { + + private static final Logger LOG = LoggerFactory.getLogger(RequestServerReaderInterceptor.class); + + @Override + public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException { + LOG.info("Request reader interceptor in the server side"); + + InputStream is = context.getInputStream(); + String body = new BufferedReader(new InputStreamReader(is)).lines() + .collect(Collectors.joining("\n")); + + context.setInputStream(new ByteArrayInputStream((body + " message added in server reader interceptor").getBytes())); + + return context.proceed(); + } + +} diff --git a/jersey/src/main/resources/logback.xml b/jersey/src/main/resources/logback.xml new file mode 100644 index 0000000000..d87a87bf53 --- /dev/null +++ b/jersey/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + \ No newline at end of file diff --git a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java new file mode 100644 index 0000000000..b4bdccfd86 --- /dev/null +++ b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java @@ -0,0 +1,33 @@ +package com.baeldung.jersey.client; + +import javax.ws.rs.core.Response; + +import org.junit.Assert; +import org.junit.Test; + +public class JerseyClientTest { + + private static int HTTP_OK = 200; + + @Test + public void getHelloGreetingTest() { + String response = JerseyClient.getHelloGreeting(); + + Assert.assertEquals("hello", response); + } + + @Test + public void getHiGreetingTest() { + String response = JerseyClient.getHiGreeting(); + + Assert.assertEquals("hi", response); + } + + @Test + public void getCustomGreetingTest() { + Response response = JerseyClient.getCustomGreeting(); + + Assert.assertEquals(HTTP_OK, response.getStatus()); + } + +} diff --git a/pom.xml b/pom.xml index fc0c8f8ba7..271fb847d3 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 com.baeldung parent-modules @@ -281,7 +280,8 @@ lucene vraptor persistence-modules/java-cockroachdb - + jersey + @@ -384,4 +384,4 @@ - + \ No newline at end of file From ee1bca08c5a8d4b73cc350b82620dc3a903c4774 Mon Sep 17 00:00:00 2001 From: Marcos Lopez Gonzalez Date: Sun, 25 Feb 2018 21:49:51 +0100 Subject: [PATCH 15/91] refactor --- .../com/baeldung/jersey/server/Greetings.java | 7 +++++-- .../jersey/client/JerseyClientTest.java | 18 +++++++++--------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java b/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java index 5e2781ee3c..d0ea873db1 100644 --- a/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java +++ b/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java @@ -3,6 +3,8 @@ package com.baeldung.jersey.server; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; import com.baeldung.jersey.server.config.HelloBinding; @@ -23,7 +25,8 @@ public class Greetings { @POST @Path("/custom") - public String getCustomGreeting(String name) { - return "hello " + name; + public Response getCustomGreeting(String name) { + return Response.status(Status.OK.getStatusCode()) + .build(); } } diff --git a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java index b4bdccfd86..ddee736200 100644 --- a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java +++ b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java @@ -8,26 +8,26 @@ import org.junit.Test; public class JerseyClientTest { private static int HTTP_OK = 200; - + @Test - public void getHelloGreetingTest() { + public void givenGreetingResource_whenCallingHelloGreeting_thenHelloReturned() { String response = JerseyClient.getHelloGreeting(); - + Assert.assertEquals("hello", response); } - + @Test - public void getHiGreetingTest() { + public void givenGreetingResource_whenCallingHiGreeting_thenHiReturned() { String response = JerseyClient.getHiGreeting(); - + Assert.assertEquals("hi", response); } - + @Test - public void getCustomGreetingTest() { + public void givenGreetingResource_whenCallingCustomGreeting_thenCustomGreetingReturned() { Response response = JerseyClient.getCustomGreeting(); Assert.assertEquals(HTTP_OK, response.getStatus()); } - + } From bb7f7a0588eb6b72d403683d9cd46bd851ea9018 Mon Sep 17 00:00:00 2001 From: Chris Franklin Date: Mon, 26 Feb 2018 10:40:25 -0500 Subject: [PATCH 16/91] [BAEL-1575] Move tests to separate suite --- .../AdvancedTaggingIntegrationTest.java | 81 +++++++++++++++++++ .../repository/InMemoryDBIntegrationTest.java | 50 ------------ 2 files changed, 81 insertions(+), 50 deletions(-) create mode 100644 persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java new file mode 100644 index 0000000000..2e4f1a0e23 --- /dev/null +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java @@ -0,0 +1,81 @@ +package org.baeldung.persistence.repository; + +import org.baeldung.config.StudentJpaConfig; +import org.baeldung.inmemory.persistence.dao.ManyStudentRepository; +import org.baeldung.inmemory.persistence.dao.ManyTagRepository; +import org.baeldung.inmemory.persistence.dao.StudentRepository; +import org.baeldung.inmemory.persistence.model.KVTag; +import org.baeldung.inmemory.persistence.model.ManyStudent; +import org.baeldung.inmemory.persistence.model.ManyTag; +import org.baeldung.inmemory.persistence.model.SkillTag; +import org.baeldung.inmemory.persistence.model.Student; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { StudentJpaConfig.class }, loader = AnnotationConfigContextLoader.class) +@Transactional +public class AdvancedTaggingIntegrationTest { + @Resource + private StudentRepository studentRepository; + + @Resource + private ManyStudentRepository manyStudentRepository; + + @Resource + private ManyTagRepository manyTagRepository; + + @Test + public void givenStudentWithSkillTags_whenSave_thenGetByNameAndSkillTag() { + Student student = new Student(1, "Will"); + SkillTag skill1 = new SkillTag("java", 5); + student.setSkillTags(Arrays.asList(skill1)); + studentRepository.save(student); + + Student student2 = new Student(2, "Joe"); + SkillTag skill2 = new SkillTag("java", 1); + student2.setSkillTags(Arrays.asList(skill2)); + studentRepository.save(student2); + + List students = studentRepository.retrieveByNameFilterByMinimumSkillTag("java", 3); + assertEquals("size incorrect", 1, students.size()); + } + + @Test + public void givenStudentWithKVTags_whenSave_thenGetByTagOk(){ + Student student = new Student(0, "John"); + student.setKVTags(Arrays.asList(new KVTag("department", "computer science"))); + studentRepository.save(student); + + Student student2 = new Student(1, "James"); + student2.setKVTags(Arrays.asList(new KVTag("department", "humanities"))); + studentRepository.save(student2); + + List students = studentRepository.retrieveByKeyTag("department"); + assertEquals("size incorrect", 2, students.size()); + } + + @Test + public void givenStudentWithManyTags_whenSave_theyGetByTagOk() { + ManyTag tag = new ManyTag("full time"); + manyTagRepository.save(tag); + + ManyStudent student = new ManyStudent("John"); + student.setManyTags(Collections.singleton(tag)); + manyStudentRepository.save(student); + + List students = manyStudentRepository.findByManyTags_Name("full time"); + assertEquals("size incorrect", 1, students.size()); + } +} diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java index fa957cc9d0..49067c8af4 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java @@ -1,8 +1,6 @@ package org.baeldung.persistence.repository; import org.baeldung.config.StudentJpaConfig; -import org.baeldung.inmemory.persistence.dao.ManyStudentRepository; -import org.baeldung.inmemory.persistence.dao.ManyTagRepository; import org.baeldung.inmemory.persistence.dao.StudentRepository; import org.baeldung.inmemory.persistence.model.*; import org.junit.Test; @@ -15,7 +13,6 @@ import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Arrays; -import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals; @@ -27,12 +24,6 @@ public class InMemoryDBIntegrationTest { @Resource private StudentRepository studentRepository; - - @Resource - private ManyStudentRepository manyStudentRepository; - - @Resource - private ManyTagRepository manyTagRepository; private static final long ID = 1; private static final String NAME="john"; @@ -88,47 +79,6 @@ public class InMemoryDBIntegrationTest { assertEquals("name incorrect", NAME, student2.getName()); } - @Test - public void givenStudenWithSkillTags_whenSave_thenGetByNameAndSkillTag() { - Student student = new Student(1, "Will"); - SkillTag skill1 = new SkillTag("java", 5); - student.setSkillTags(Arrays.asList(skill1)); - studentRepository.save(student); - Student student2 = new Student(2, "Joe"); - SkillTag skill2 = new SkillTag("java", 1); - student2.setSkillTags(Arrays.asList(skill2)); - studentRepository.save(student2); - - List students = studentRepository.retrieveByNameFilterByMinimumSkillTag("java", 3); - assertEquals("size incorrect", 1, students.size()); - } - - @Test - public void givenStudentWithKVTags_whenSave_thenGetByTagOk(){ - Student student = new Student(0, "John"); - student.setKVTags(Arrays.asList(new KVTag("department", "computer science"))); - studentRepository.save(student); - - Student student2 = new Student(1, "James"); - student2.setKVTags(Arrays.asList(new KVTag("department", "humanities"))); - studentRepository.save(student2); - - List students = studentRepository.retrieveByKeyTag("department"); - assertEquals("size incorrect", 2, students.size()); - } - - @Test - public void givenStudentWithManyTags_whenSave_theyGetByTagOk() { - ManyTag tag = new ManyTag("full time"); - manyTagRepository.save(tag); - - ManyStudent student = new ManyStudent("John"); - student.setManyTags(Collections.singleton(tag)); - manyStudentRepository.save(student); - - List students = manyStudentRepository.findByManyTags_Name("full time"); - assertEquals("size incorrect", 1, students.size()); - } } From 8e0cececdb3a3823c665f4363427c7217cc03cf8 Mon Sep 17 00:00:00 2001 From: Chris Franklin Date: Mon, 26 Feb 2018 10:42:39 -0500 Subject: [PATCH 17/91] [BAEL-1575] Cleanup original test --- .../persistence/repository/InMemoryDBIntegrationTest.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java index 49067c8af4..28d7e3772c 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java @@ -2,7 +2,7 @@ package org.baeldung.persistence.repository; import org.baeldung.config.StudentJpaConfig; import org.baeldung.inmemory.persistence.dao.StudentRepository; -import org.baeldung.inmemory.persistence.model.*; +import org.baeldung.inmemory.persistence.model.Student; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; @@ -79,6 +79,4 @@ public class InMemoryDBIntegrationTest { assertEquals("name incorrect", NAME, student2.getName()); } - - } From d1c884c9f11262e94ece53dd03cb4a8d8fba0c50 Mon Sep 17 00:00:00 2001 From: Marcos Date: Mon, 26 Feb 2018 17:29:41 +0100 Subject: [PATCH 18/91] format --- jersey/src/main/resources/logback.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jersey/src/main/resources/logback.xml b/jersey/src/main/resources/logback.xml index d87a87bf53..db70a9efd5 100644 --- a/jersey/src/main/resources/logback.xml +++ b/jersey/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - %date [%thread] %-5level %logger{36} - %message%n + %date [%thread] %-5level %logger{36} - %message%n From c7e08524496ef1e5ce84f7373981e9fea652c76c Mon Sep 17 00:00:00 2001 From: Nguyen Nam Thai Date: Tue, 27 Feb 2018 08:55:16 +0700 Subject: [PATCH 19/91] Second commit for TDD List implementation --- .../com/baeldung/java/list/CustomList.java | 123 ++++++++---------- .../java/list/CustomListUnitTest.java | 92 +++++++------ 2 files changed, 105 insertions(+), 110 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/java/list/CustomList.java b/core-java/src/main/java/com/baeldung/java/list/CustomList.java index bc1321b1a3..8b91fca32f 100644 --- a/core-java/src/main/java/com/baeldung/java/list/CustomList.java +++ b/core-java/src/main/java/com/baeldung/java/list/CustomList.java @@ -9,6 +9,58 @@ import java.util.ListIterator; public class CustomList implements List { private Object[] internal = {}; + @Override + public boolean isEmpty() { + // the first cycle + // return true; + + // the second cycle + // if (internal.length != 0) { + // return false; + // } else { + // return true; + // } + + // refactoring + return internal.length == 0; + } + + @Override + public int size() { + // the first cycle + // if (isEmpty()) { + // return 0; + // } else { + // return internal.length; + // } + + // refactoring + return internal.length; + } + + @SuppressWarnings("unchecked") + @Override + public E get(int index) { + // the first cycle + // return (E) internal[0]; + + // improvement + return (E) internal[index]; + } + + @Override + public boolean add(E element) { + // the first cycle + // internal = new Object[] { element }; + // return true; + + // the second cycle + Object[] temp = Arrays.copyOf(internal, internal.length + 1); + temp[internal.length] = element; + internal = temp; + return true; + } + @Override public void add(int index, E element) { throw new UnsupportedOperationException(); @@ -44,40 +96,8 @@ public class CustomList implements List { throw new UnsupportedOperationException(); } - @Override - public int size() { - return internal.length; - } - - @Override - public boolean isEmpty() { - return internal.length == 0; - } - - @Override - public boolean add(E element) { - // the first cycle - // internal = new Object[1]; - // internal[0] = element; - // return true; - - Object[] temp = new Object[internal.length + 1]; - System.arraycopy(internal, 0, temp, 0, internal.length); - temp[internal.length] = element; - internal = temp; - return true; - } - - @SuppressWarnings("unchecked") - @Override - public E get(int index) { - return (E) internal[index]; - } - @Override public boolean contains(Object object) { - // return false - for (Object element : internal) { if (object.equals(element)) { return true; @@ -88,14 +108,6 @@ public class CustomList implements List { @Override public boolean containsAll(Collection collection) { - // the first cycle - // for (Object element : collection) { - // if (element.equals(internal[0])) { - // return true; - // } - // } - // return false; - for (Object element : collection) if (!contains(element)) { return false; @@ -118,12 +130,6 @@ public class CustomList implements List { @Override public int indexOf(Object object) { - // the first cycle - // if (object.equals(internal[0])) { - // return 0; - // } - // return -1; - for (int i = 0; i < internal.length; i++) { if (object.equals(internal[i])) { return i; @@ -134,12 +140,6 @@ public class CustomList implements List { @Override public int lastIndexOf(Object object) { - // the first cycle - // if (object.equals(internal[0])) { - // return 0; - // } - // return -1; - for (int i = internal.length - 1; i >= 0; i--) { if (object.equals(internal[i])) { return i; @@ -151,9 +151,6 @@ public class CustomList implements List { @SuppressWarnings("unchecked") @Override public List subList(int fromIndex, int toIndex) { - // the first cycle - // return (List) Arrays.asList(internal); - Object[] temp = new Object[toIndex - fromIndex]; System.arraycopy(internal, fromIndex, temp, 0, temp.length); return (List) Arrays.asList(temp); @@ -167,16 +164,6 @@ public class CustomList implements List { @SuppressWarnings("unchecked") @Override public T[] toArray(T[] array) { - // the first cycle - // array[0] = (T) internal[0]; - // return array; - - // the second cycle - // if (array.length < internal.length) { - // return (T[]) Arrays.copyOf(internal, internal.length, array.getClass()); - // } - // return (T[]) Arrays.copyOf(internal, internal.length, array.getClass()); - if (array.length < internal.length) { return (T[]) Arrays.copyOf(internal, internal.length, array.getClass()); } @@ -209,18 +196,12 @@ public class CustomList implements List { @Override public boolean hasNext() { - // the first cycle - // return true; - return index != internal.length; } @SuppressWarnings("unchecked") @Override public E next() { - // the first cycle - // return (E) CustomList.this.internal[0]; - E element = (E) CustomList.this.internal[index]; index++; return element; diff --git a/core-java/src/test/java/com/baeldung/java/list/CustomListUnitTest.java b/core-java/src/test/java/com/baeldung/java/list/CustomListUnitTest.java index 3ee3195e80..9ea42e88e8 100644 --- a/core-java/src/test/java/com/baeldung/java/list/CustomListUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java/list/CustomListUnitTest.java @@ -14,6 +14,58 @@ import java.util.List; import org.junit.Test; public class CustomListUnitTest { + @Test + public void givenEmptyList_whenIsEmpty_thenTrueIsReturned() { + List list = new CustomList<>(); + + assertTrue(list.isEmpty()); + } + + @Test + public void givenNonEmptyList_whenIsEmpty_thenFalseIsReturned() { + List list = new CustomList<>(); + list.add(null); + + assertFalse(list.isEmpty()); + } + + @Test + public void givenListWithAnElement_whenSize_thenOneIsReturned() { + List list = new CustomList<>(); + list.add(null); + + assertEquals(1, list.size()); + } + + @Test + public void givenListWithAnElement_whenGet_thenThatElementIsReturned() { + List list = new CustomList<>(); + list.add("baeldung"); + Object element = list.get(0); + + assertEquals("baeldung", element); + } + + @Test + public void givenEmptyList_whenElementIsAdded_thenGetReturnsThatElement() { + List list = new CustomList<>(); + boolean succeeded = list.add(null); + + assertTrue(succeeded); + } + + @Test + public void givenListWithAnElement_whenAnotherIsAdded_thenGetReturnsBoth() { + List list = new CustomList<>(); + list.add("baeldung"); + list.add(".com"); + Object element1 = list.get(0); + Object element2 = list.get(1); + + assertEquals("baeldung", element1); + assertEquals(".com", element2); + } + @Test(expected = UnsupportedOperationException.class) public void whenAddToSpecifiedIndex_thenExceptionIsThrown() { new CustomList<>().add(0, null); @@ -64,44 +116,6 @@ public class CustomListUnitTest { list.retainAll(collection); } - @Test - public void givenEmptyList_whenSize_thenZeroIsReturned() { - List list = new CustomList<>(); - - assertEquals(0, list.size()); - } - - @Test - public void givenEmptyList_whenIsEmpty_thenTrueIsReturned() { - List list = new CustomList<>(); - - assertTrue(list.isEmpty()); - } - - @Test - public void givenEmptyList_whenElementIsAdded_thenGetReturnsThatElement() { - List list = new CustomList<>(); - boolean succeeded = list.add("baeldung"); - Object element = list.get(0); - - assertTrue(succeeded); - assertEquals("baeldung", element); - } - - @Test - public void givenListWithAnElement_whenAnotherIsAdded_thenGetReturnsBoth() { - List list = new CustomList<>(); - boolean succeeded1 = list.add("baeldung"); - boolean succeeded2 = list.add(".com"); - Object element1 = list.get(0); - Object element2 = list.get(1); - - assertTrue(succeeded1); - assertTrue(succeeded2); - assertEquals("baeldung", element1); - assertEquals(".com", element2); - } - @Test public void givenEmptyList_whenContains_thenFalseIsReturned() { List list = new CustomList<>(); @@ -271,7 +285,7 @@ public class CustomListUnitTest { } @Test - public void whenIteratorNextIsCalledTwice_thenTheSecondReturnsFalse() { + public void whenIteratorHasNextIsCalledTwice_thenTheSecondReturnsFalse() { List list = new CustomList<>(); list.add("baeldung"); Iterator iterator = list.iterator(); From 2f4d6e7e16e73ab70f53bcf10614217edc2e10f5 Mon Sep 17 00:00:00 2001 From: Marcos Lopez Gonzalez Date: Tue, 27 Feb 2018 17:59:07 +0100 Subject: [PATCH 20/91] format --- jersey/src/main/resources/logback.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jersey/src/main/resources/logback.xml b/jersey/src/main/resources/logback.xml index db70a9efd5..d87a87bf53 100644 --- a/jersey/src/main/resources/logback.xml +++ b/jersey/src/main/resources/logback.xml @@ -2,7 +2,7 @@ - %date [%thread] %-5level %logger{36} - %message%n + %date [%thread] %-5level %logger{36} - %message%n From 660904aa684d16b8e983daddb1b741947bcfeb8f Mon Sep 17 00:00:00 2001 From: Marcos Lopez Gonzalez Date: Tue, 27 Feb 2018 19:05:32 +0100 Subject: [PATCH 21/91] tests skipped --- .../test/java/com/baeldung/jersey/client/JerseyClientTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java index ddee736200..72ba4cc5b9 100644 --- a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java +++ b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java @@ -3,8 +3,10 @@ package com.baeldung.jersey.client; import javax.ws.rs.core.Response; import org.junit.Assert; +import org.junit.Ignore; import org.junit.Test; +@Ignore public class JerseyClientTest { private static int HTTP_OK = 200; From fabcbbb51b846ddd683dd90fd485f01cb8c54c16 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Wed, 28 Feb 2018 17:26:19 +0200 Subject: [PATCH 22/91] temporarily disabling a plugin --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index beb377a40b..79d8168f1c 100644 --- a/pom.xml +++ b/pom.xml @@ -83,7 +83,7 @@ httpclient hystrix - image-processing + immutables influxdb From e4f5a22e928780985684be95976e9152710a9f23 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Wed, 28 Feb 2018 18:16:32 +0200 Subject: [PATCH 23/91] pom cleanup work --- core-groovy/pom.xml | 3 +- ethereumj/pom.xml | 26 +++++----- libraries/helloWorld.docx | Bin 76895 -> 76887 bytes .../log4j/src/main/resources/logback.xml | 2 +- parent-boot-5/pom.xml | 5 +- spring-boot-bootstrap/pom.xml | 4 +- .../spring-swagger-codegen-app/pom.xml | 2 +- vavr/pom.xml | 49 ++++++++---------- 8 files changed, 42 insertions(+), 49 deletions(-) diff --git a/core-groovy/pom.xml b/core-groovy/pom.xml index eb9932e0cf..961a4ba125 100644 --- a/core-groovy/pom.xml +++ b/core-groovy/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 core-groovy diff --git a/ethereumj/pom.xml b/ethereumj/pom.xml index c9f5924d7a..2744ad6dd5 100644 --- a/ethereumj/pom.xml +++ b/ethereumj/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 com.baeldung.ethereumj ethereumj @@ -8,16 +7,11 @@ 1.0.0 ethereumj - - UTF-8 - 1.8 - 8.5.4 - - - org.springframework.boot - spring-boot-starter-parent - 1.5.6.RELEASE + parent-boot-5 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-5 @@ -38,14 +32,13 @@ org.springframework.boot spring-boot-starter-tomcat - + org.springframework.boot spring-boot-starter-test - 1.5.6.RELEASE test @@ -107,4 +100,11 @@ + + + UTF-8 + 1.8 + 8.5.4 + + \ No newline at end of file diff --git a/libraries/helloWorld.docx b/libraries/helloWorld.docx index 09e71a4d4ec07142de51e5d046b0ac8326d7e7f5..6e0a372dad8c2da5c7739237c17315706b5b4ef2 100644 GIT binary patch delta 4339 zcmZ8lWmptU*WP7mkdRuWV_9GqB!oql5|9P~X%^{{kOqle8YCoCIwd6~l}1WZN(3Zy zX;`|Ecs`%U_xj$LKXcDL_jS(vm^tUn`7wh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`UaA4T!xCumsBdom^^?^>Zo ze9~zdC@l)^=4H`MQ5s2Kr0l$Eoilo`)Go^(sXj+0uUhpoa?We2>h+zS$8Ixl@5j-I zwb2jPOr;9Pg16p0=6v)^ODjsb#(;WnS>sLaZA?YKKZ0IL)< zDrCHB@K9iIDqVY2`R%Eysot`~`b)ZjR z%r}HAR|*~8bbI0z_Rkc@9^IrCd!mPFbQhGE$bd>e}Fmayv5C?QcDPUe{*CMKySXQ;G zq^mj2NM%LG7a>%UvwY55iVTxRv*|R*S`6&s3+YdH^Ha3t2ars8-PCY&5kFEGjL3Ym zGX$cX81ZZUt{BIj#i|h+I5xs@NW94d&O{wtg<&A;bvzlD6Hk&%YOa#L8bky|W^kJ4 zWN4V-?pX7fpl}W}IAkNK*(0BDc~1uSfL!?dAvQhqsvDbLvHZo^B?C0E9S>uC3x{*w zO*y8~+Vr;2L3y7gLphtEZlvjO6+@&)d{nKS?{IbQs_tzAW6Q1I?(;BKGo44qjVPbt z;f52shxy`W=<2RGDeXST^KYL%HNacDAXZg-oJCukNqQy8pJ!O2IT{`2MQzvZwRi_w zk-Ir)jVC5r$m{}v`0!R#FL*6=_x@eNl`)LvnOFb-1L40*I4p{yDT)I4p8W4wK)Nb7 zaP=R=!vmc82jM`0a{sYHf#L*z%?$p2)~1I+ffD~1+MqyMEHeBQC_ba3t|kzR0`T8K z!=K0JF5pj*BLD!NJ@K>?^m^*&g7gybb#?i-^Ph=>|MUfvr(5v?nVJ5|#$-!V)P)=f zD5d}c*#3tUnx4xG6#1JpyXCH4^4oa&TmLtbLi+yyM~bMomdyH1`1M;!f9rpREnR>Q M$cB5(1N^=Bf249HRR910 diff --git a/logging-modules/log4j/src/main/resources/logback.xml b/logging-modules/log4j/src/main/resources/logback.xml index f567962cb6..097f6694f0 100644 --- a/logging-modules/log4j/src/main/resources/logback.xml +++ b/logging-modules/log4j/src/main/resources/logback.xml @@ -78,7 +78,7 @@ - + diff --git a/parent-boot-5/pom.xml b/parent-boot-5/pom.xml index 55ac0957ff..0e3936a73a 100644 --- a/parent-boot-5/pom.xml +++ b/parent-boot-5/pom.xml @@ -21,7 +21,7 @@ spring-boot-starter-parent org.springframework.boot - 1.5.9.RELEASE + 1.5.10.RELEASE @@ -60,9 +60,6 @@ **/*IntegrationTest.java **/*LongRunningUnitTest.java **/*ManualTest.java - **/JdbcTest.java - **/AutoconfigurationTest.java - **/*EntryPointsTest.java **/*LiveTest.java diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 5ad8330a89..21c0ea60a8 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -24,12 +24,12 @@ org.springframework.boot spring-boot-starter-data-jpa - 1.5.5.RELEASE + 1.5.10.RELEASE org.springframework.boot spring-boot-dependencies - 1.5.6.RELEASE + 1.5.10.RELEASE pom import diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml index f42fc5c2e2..b7b898237f 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml @@ -9,7 +9,7 @@ org.springframework.boot spring-boot-starter-parent - 1.5.6.RELEASE + 1.5.10.RELEASE diff --git a/vavr/pom.xml b/vavr/pom.xml index f9fed7d4fc..1c515b5881 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -1,17 +1,15 @@ - + 4.0.0 com.baeldung vavr 1.0 vavr - - org.springframework.boot - spring-boot-starter-parent - 1.5.6.RELEASE - - + + parent-boot-5 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-5 @@ -26,7 +24,7 @@ junit ${junit.version} - + org.springframework.boot spring-boot-starter-data-jpa @@ -42,15 +40,15 @@ spring-boot-starter-test test - + - org.awaitility - awaitility - ${awaitility.version} - test - + org.awaitility + awaitility + ${awaitility.version} + test + - + spring-snapshot @@ -66,20 +64,13 @@ https://repo.spring.io/libs-snapshot - - + + spring-snapshots http://repo.spring.io/snapshot - - - 1.8 - 0.9.1 - 4.12 - 3.0.0 - @@ -97,10 +88,16 @@ **/JdbcTest.java **/*LiveTest.java - + + 1.8 + 0.9.1 + 4.12 + 3.0.0 + + \ No newline at end of file From 1c7db2e99ecf66e463f753e6dea5567d51d4d3cb Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Wed, 28 Feb 2018 18:23:07 +0200 Subject: [PATCH 24/91] pom cleanup work --- ethereumj/pom.xml | 1 - vavr/pom.xml | 6 ------ 2 files changed, 7 deletions(-) diff --git a/ethereumj/pom.xml b/ethereumj/pom.xml index 2744ad6dd5..e20d7ddc52 100644 --- a/ethereumj/pom.xml +++ b/ethereumj/pom.xml @@ -32,7 +32,6 @@ org.springframework.boot spring-boot-starter-tomcat - diff --git a/vavr/pom.xml b/vavr/pom.xml index 1c515b5881..712d87054c 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -19,12 +19,6 @@ ${vavr.version} - - junit - junit - ${junit.version} - - org.springframework.boot spring-boot-starter-data-jpa From 3cd948b9fa128979fe1a19e6a4461fdb9bc9db17 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Wed, 28 Feb 2018 18:33:34 +0200 Subject: [PATCH 25/91] further pom cleanup --- pom.xml | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/pom.xml b/pom.xml index 79d8168f1c..21f9e7cff5 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,5 @@ - + 4.0.0 com.baeldung parent-modules @@ -15,7 +14,7 @@ true false false - + 4.12 1.3 2.8.9 @@ -51,7 +50,7 @@ core-java-8 core-groovy core-java-concurrency - + couchbase deltaspike @@ -59,7 +58,7 @@ ethereumj - + feign @@ -79,7 +78,7 @@ handling-spring-static-resources hazelcast hbase - + httpclient hystrix @@ -88,11 +87,11 @@ influxdb jackson - + vavr - java-lite - java-rmi - java-vavr-stream + java-lite + java-rmi + java-vavr-stream javax-servlets javaxval jaxb @@ -116,17 +115,15 @@ logging-modules/log4j2 logging-modules/logback lombok - + mapstruct - + mesos-marathon testing-modules/mockito testing-modules/mockito-2 testing-modules/mocks mustache - mvn-wrapper + mvn-wrapper noexception orientdb osgi @@ -146,14 +143,13 @@ resteasy rxjava spring-swagger-codegen - testing-modules/selenium-junit-testng persistence-modules/solr spark-java - + spring-5 spring-5-reactive spring-5-mvc - spring-5-security + spring-activiti spring-akka spring-amqp @@ -163,7 +159,7 @@ spring-batch spring-bom spring-boot - spring-boot-keycloak + spring-boot-keycloak spring-boot-bootstrap spring-boot-admin spring-boot-security @@ -252,7 +248,7 @@ spring-vertx spring-jinq - spring-rest-embedded-tomcat + spring-rest-embedded-tomcat testing-modules/testing @@ -280,7 +276,7 @@ saas deeplearning4j lucene - vraptor + vraptor persistence-modules/java-cockroachdb @@ -307,7 +303,7 @@ ${org.slf4j.version} - + junit junit From 54cc61e9f8f38fd675756c49b2cb18d4fbc79b19 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Wed, 28 Feb 2018 18:55:45 +0200 Subject: [PATCH 26/91] pom work --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 21f9e7cff5..3092c0fa40 100644 --- a/pom.xml +++ b/pom.xml @@ -188,7 +188,7 @@ spring-integration spring-jenkins-pipeline spring-jersey - jmeter + spring-jms spring-jooq persistence-modules/spring-jpa From 550590063d022b056e7fef813c2ce24912ebe661 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Wed, 28 Feb 2018 20:17:01 +0200 Subject: [PATCH 27/91] pom fix --- ethereumj/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ethereumj/pom.xml b/ethereumj/pom.xml index e20d7ddc52..9676106e38 100644 --- a/ethereumj/pom.xml +++ b/ethereumj/pom.xml @@ -11,7 +11,7 @@ parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../parent-boot-5 From 76d7e9c49b36fa03d6444d24e74b3c34f6e97302 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Wed, 28 Feb 2018 20:40:10 +0200 Subject: [PATCH 28/91] pom cleanup --- spring-boot-property-exp/pom.xml | 23 +++++--------- .../property-exp-custom-config/pom.xml | 30 +++++++++--------- .../property-exp-default-config/pom.xml | 31 ++++++++----------- vavr/pom.xml | 2 +- 4 files changed, 36 insertions(+), 50 deletions(-) diff --git a/spring-boot-property-exp/pom.xml b/spring-boot-property-exp/pom.xml index 0c54d57db1..1a1e31385e 100644 --- a/spring-boot-property-exp/pom.xml +++ b/spring-boot-property-exp/pom.xml @@ -1,6 +1,11 @@ - + + 4.0.0 + spring-boot-property-exp + + com.baeldung + spring-boot-property-exp + 0.0.1-SNAPSHOT + pom parent-modules @@ -8,17 +13,6 @@ 1.0.0-SNAPSHOT - 4.0.0 - - com.baeldung - spring-boot-property-exp - 0.0.1-SNAPSHOT - - pom - - spring-boot-property-exp - http://maven.apache.org - UTF-8 @@ -28,5 +22,4 @@ property-exp-custom-config - diff --git a/spring-boot-property-exp/property-exp-custom-config/pom.xml b/spring-boot-property-exp/property-exp-custom-config/pom.xml index 7822b31cf2..019e2362a1 100644 --- a/spring-boot-property-exp/property-exp-custom-config/pom.xml +++ b/spring-boot-property-exp/property-exp-custom-config/pom.xml @@ -1,32 +1,26 @@ - - - spring-boot-property-exp - com.baeldung - 0.0.1-SNAPSHOT - + 4.0.0 + property-exp-custom com.baeldung property-exp-custom-config 0.0.1-SNAPSHOT jar - property-exp-custom - http://maven.apache.org - - - UTF-8 - Custom Property Value - + + spring-boot-property-exp + com.baeldung + 0.0.1-SNAPSHOT + + org.springframework.boot spring-boot-starter - 1.5.4.RELEASE + 1.5.10.RELEASE + @@ -73,5 +67,9 @@ + + UTF-8 + Custom Property Value + diff --git a/spring-boot-property-exp/property-exp-default-config/pom.xml b/spring-boot-property-exp/property-exp-default-config/pom.xml index 0625916d32..5dc47d287d 100644 --- a/spring-boot-property-exp/property-exp-default-config/pom.xml +++ b/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -1,27 +1,17 @@ - - + 4.0.0 - - - org.springframework.boot - spring-boot-starter-parent - 1.5.4.RELEASE - - + property-exp-default + com.baeldung property-exp-default-config 0.0.1-SNAPSHOT jar - property-exp-default - http://maven.apache.org - - - UTF-8 - Custom Property Value - + + org.springframework.boot + spring-boot-starter-parent + 1.5.10.RELEASE + @@ -42,4 +32,9 @@ + + UTF-8 + Custom Property Value + + diff --git a/vavr/pom.xml b/vavr/pom.xml index 712d87054c..28747af3ee 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -9,7 +9,7 @@ parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../parent-boot-5 From 07111d1edc5598c217fe7ee2b49d12a138687d61 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 28 Feb 2018 20:44:57 +0200 Subject: [PATCH 29/91] move user endpoint (#3730) * move user endpoint * formatting * formatting * formatting * formatting * change url name * Update PersonInfoController.java * Update PersonInfoController.java --- .../controller/CloudSiteController.java | 4 ++-- .../src/main/resources/application.yml | 4 ++-- .../controller/PersonInfoController.java | 6 +++--- .../controller/ResourceController.java | 0 .../src/main/resources/application.yml | 1 - .../config/ResourceServerConfigurer.java | 21 ------------------- 6 files changed, 7 insertions(+), 29 deletions(-) rename spring-cloud/spring-cloud-security/{auth-server => auth-resource}/src/main/java/com/baeldung/controller/ResourceController.java (100%) delete mode 100644 spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/ResourceServerConfigurer.java diff --git a/spring-cloud/spring-cloud-security/auth-client/src/main/java/com/baeldung/controller/CloudSiteController.java b/spring-cloud/spring-cloud-security/auth-client/src/main/java/com/baeldung/controller/CloudSiteController.java index b6bfd0bcf6..c77a5e02c5 100644 --- a/spring-cloud/spring-cloud-security/auth-client/src/main/java/com/baeldung/controller/CloudSiteController.java +++ b/spring-cloud/spring-cloud-security/auth-client/src/main/java/com/baeldung/controller/CloudSiteController.java @@ -19,10 +19,10 @@ public class CloudSiteController { return "Hello From Baeldung!"; } - @GetMapping("/person") + @GetMapping("/personInfo") public ModelAndView person() { ModelAndView mav = new ModelAndView("personinfo"); - String personResourceUrl = "http://localhost:9000/personResource"; + String personResourceUrl = "http://localhost:9000/person"; mav.addObject("person", restOperations.getForObject(personResourceUrl, String.class)); return mav; } diff --git a/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.yml b/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.yml index 06a950d270..2a758faeae 100644 --- a/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.yml @@ -13,7 +13,7 @@ security: clientId: authserver clientSecret: passwordforauthserver resource: - userInfoUri: http://localhost:7070/authserver/user + userInfoUri: http://localhost:9000/user person: url: http://localhost:9000/person @@ -27,7 +27,7 @@ zuul: url: http://localhost:9000 user: path: /user/** - url: http://localhost:7070/authserver/user + url: http://localhost:9000/user # Make sure the OAuth2 token is only relayed when using the internal API, # do not pass any authentication to the external API diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/controller/PersonInfoController.java b/spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/controller/PersonInfoController.java index 9e5420da5a..1958c0ebb8 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/controller/PersonInfoController.java +++ b/spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/controller/PersonInfoController.java @@ -10,9 +10,9 @@ import com.baeldung.model.Person; @RestController public class PersonInfoController { - @GetMapping("/personResource") + @GetMapping("/person") @PreAuthorize("hasAnyRole('ADMIN', 'USER')") public @ResponseBody Person personInfo() { return new Person("abir", "Dhaka", "Bangladesh", 29, "Male"); - } -} \ No newline at end of file + } +} diff --git a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/controller/ResourceController.java b/spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/controller/ResourceController.java similarity index 100% rename from spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/controller/ResourceController.java rename to spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/controller/ResourceController.java diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/application.yml b/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/application.yml index 20a3313a60..52e02ba41b 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/application.yml @@ -8,7 +8,6 @@ security: sessions: NEVER oauth2: resource: - userInfoUri: http://localhost:7070/authserver/user jwt: keyValue: | -----BEGIN PUBLIC KEY----- diff --git a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/ResourceServerConfigurer.java b/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/ResourceServerConfigurer.java deleted file mode 100644 index f97544dc59..0000000000 --- a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/ResourceServerConfigurer.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; -import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; - -/** - * Our configuration for the OAuth2 User Info Resource Server. - */ -@Configuration -@EnableResourceServer -public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter { - @Override - public void configure(HttpSecurity http) throws Exception { - http.antMatcher("/user") - .authorizeRequests() - .anyRequest() - .authenticated(); - } -} From d9fddbde78977df213712485014c94b023d7d139 Mon Sep 17 00:00:00 2001 From: Gurinder Singh Date: Thu, 1 Mar 2018 05:51:14 +0530 Subject: [PATCH 30/91] BAEL-1178: changing variable type from String to Integer (#3700) --- .../controller/BasicMathController.java | 2 +- .../controller/EvenOddController.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/main/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathController.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/main/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathController.java index f164af89e6..58e6d5d5b8 100644 --- a/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/main/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathController.java +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/main/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathController.java @@ -16,7 +16,7 @@ public class BasicMathController { private RestTemplate restTemplate; @GetMapping("/calculate") - public String checkOddAndEven(@RequestParam("number") String number) { + public String checkOddAndEven(@RequestParam("number") Integer number) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/json"); diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/main/java/com/baeldung/spring/cloud/springcloudcontractproducer/controller/EvenOddController.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/main/java/com/baeldung/spring/cloud/springcloudcontractproducer/controller/EvenOddController.java index e61cc1120c..b8cc002fb4 100644 --- a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/main/java/com/baeldung/spring/cloud/springcloudcontractproducer/controller/EvenOddController.java +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/main/java/com/baeldung/spring/cloud/springcloudcontractproducer/controller/EvenOddController.java @@ -9,7 +9,7 @@ import org.springframework.web.bind.annotation.RestController; public class EvenOddController { @GetMapping("/validate/prime-number") - public String isNumberPrime(@RequestParam("number") String number) { - return Integer.parseInt(number) % 2 == 0 ? "Even" : "Odd"; + public String isNumberPrime(@RequestParam("number") Integer number) { + return number % 2 == 0 ? "Even" : "Odd"; } } From 00f5648b3910f07f192ac9906da2c16864b4dfc7 Mon Sep 17 00:00:00 2001 From: abialas Date: Thu, 1 Mar 2018 06:40:59 +0100 Subject: [PATCH 31/91] BAEL-1432 (#3743) * BAEL-1412 add java 8 spring data features * BAEL-21 new HTTP API overview * BAEL-21 fix executor * BAEL-1432 add custom gradle task --- gradle/build.gradle | 57 +++++++++++++++++++ .../PrintToolVersionBuildSrcTask.groovy | 22 +++++++ 2 files changed, 79 insertions(+) create mode 100644 gradle/buildSrc/src/main/groovy/com/baeldung/PrintToolVersionBuildSrcTask.groovy diff --git a/gradle/build.gradle b/gradle/build.gradle index dcc592a2b4..2e5d984fba 100644 --- a/gradle/build.gradle +++ b/gradle/build.gradle @@ -33,3 +33,60 @@ task execSecondTest { } println 'This will be executed during the configuration phase as well.' } + +task welcome { + doLast { + println 'Welcome on the Baeldung!' + } +} + +task welcomeWithGroup { + group 'Sample category' + doLast { + println 'Welcome on the Baeldung!' + } +} + +task welcomeWithGroupAndDescription { + group 'Sample category' + description 'Tasks which shows welcome message' + doLast { + println 'Welcome on the Baeldung!' + } +} + +class PrintToolVersionTask extends DefaultTask { + String tool + + @TaskAction + void printToolVersion() { + switch (tool) { + case 'java': + println System.getProperty("java.version") + break + case 'groovy': + println GroovySystem.version + break + default: + throw new IllegalArgumentException("Unknown tool") + } + } +} + +task printJavaVersion(type : PrintToolVersionTask) { + tool 'java' +} + +task printGroovyVersion(type : PrintToolVersionTask) { + tool 'groovy' +} + +import com.baeldung.PrintToolVersionBuildSrcTask + +task printJavaVersionBuildSrc(type : PrintToolVersionBuildSrcTask) { + tool 'java' +} + +task printGroovyVersionBuildSrc(type : PrintToolVersionBuildSrcTask) { + tool 'groovy' +} \ No newline at end of file diff --git a/gradle/buildSrc/src/main/groovy/com/baeldung/PrintToolVersionBuildSrcTask.groovy b/gradle/buildSrc/src/main/groovy/com/baeldung/PrintToolVersionBuildSrcTask.groovy new file mode 100644 index 0000000000..0fbd71db56 --- /dev/null +++ b/gradle/buildSrc/src/main/groovy/com/baeldung/PrintToolVersionBuildSrcTask.groovy @@ -0,0 +1,22 @@ +package com.baeldung + +import org.gradle.api.DefaultTask +import org.gradle.api.tasks.TaskAction + +class PrintToolVersionBuildSrcTask extends DefaultTask { + String tool + + @TaskAction + void printToolVersion() { + switch (tool) { + case 'java': + println System.getProperty("java.version") + break + case 'groovy': + println GroovySystem.version + break + default: + throw new IllegalArgumentException("Unknown tool") + } + } +} \ No newline at end of file From 806cb74ae9748d6e3eb2648819a973e69ed83e40 Mon Sep 17 00:00:00 2001 From: orrym Date: Thu, 1 Mar 2018 16:14:05 +0200 Subject: [PATCH 32/91] BAEL-1572: AWS EC2 examples --- .../java/com/baeldung/ec2/EC2Application.java | 139 ++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 aws/src/main/java/com/baeldung/ec2/EC2Application.java diff --git a/aws/src/main/java/com/baeldung/ec2/EC2Application.java b/aws/src/main/java/com/baeldung/ec2/EC2Application.java new file mode 100644 index 0000000000..bb7d8ca1d7 --- /dev/null +++ b/aws/src/main/java/com/baeldung/ec2/EC2Application.java @@ -0,0 +1,139 @@ +package com.baeldung.ec2; + +import java.util.Arrays; + +import com.amazonaws.auth.AWSCredentials; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.ec2.AmazonEC2; +import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; +import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest; +import com.amazonaws.services.ec2.model.CreateKeyPairRequest; +import com.amazonaws.services.ec2.model.CreateKeyPairResult; +import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest; +import com.amazonaws.services.ec2.model.DescribeInstancesRequest; +import com.amazonaws.services.ec2.model.DescribeInstancesResult; +import com.amazonaws.services.ec2.model.DescribeKeyPairsRequest; +import com.amazonaws.services.ec2.model.DescribeKeyPairsResult; +import com.amazonaws.services.ec2.model.IpPermission; +import com.amazonaws.services.ec2.model.IpRange; +import com.amazonaws.services.ec2.model.MonitorInstancesRequest; +import com.amazonaws.services.ec2.model.RebootInstancesRequest; +import com.amazonaws.services.ec2.model.RunInstancesRequest; +import com.amazonaws.services.ec2.model.StartInstancesRequest; +import com.amazonaws.services.ec2.model.StopInstancesRequest; +import com.amazonaws.services.ec2.model.UnmonitorInstancesRequest; + +public class EC2Application { + + private static final AWSCredentials credentials; + + static { + // put your accesskey and secretkey here + credentials = new BasicAWSCredentials( + "", + "" + ); + } + + public static void main(String[] args) { + + String yourInstanceId = ""; + + // 0) - Set up the client + AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard() + .withCredentials(new AWSStaticCredentialsProvider(credentials)) + .withRegion(Regions.US_EAST_1) + .build(); + + // 1) - Create a security group + CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup") + .withDescription("Baeldung Security Group"); + ec2Client.createSecurityGroup(createSecurityGroupRequest); + + // 2) - Allow HTTP and SSH traffic + IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0"); + + IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 })) + .withIpProtocol("tcp") + .withFromPort(80) + .withToPort(80); + + IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 })) + .withIpProtocol("tcp") + .withFromPort(22) + .withToPort(22); + + AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest() + .withGroupName("BaeldungSecurityGroup") + .withIpPermissions(ipPermission1, ipPermission2); + + ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); + + // 3) - Create KeyPair + CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest() + .withKeyName("baeldung-key-pair"); + CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest); + String privateKey = createKeyPairResult + .getKeyPair() + .getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key + + // 4) - See what key-pairs you've got + DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest(); + DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest); + + // 5) - Launch an Amazon Instance + RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html + .withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html + .withMinCount(1) + .withMaxCount(1) + .withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance + .withSecurityGroups("BaeldungSecurityGroup"); + + ec2Client.runInstances(runInstancesRequest); + + // 6) Monitor Instances + MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest() + .withInstanceIds(yourInstanceId); + + ec2Client.monitorInstances(monitorInstancesRequest); + + UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest() + .withInstanceIds(yourInstanceId); + + ec2Client.unmonitorInstances(unmonitorInstancesRequest); + + // 7) - Reboot an Instance + + RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest() + .withInstanceIds(yourInstanceId); + + ec2Client.rebootInstances(rebootInstancesRequest); + + // 8) - Stop an Instance + StopInstancesRequest stopInstancesRequest = new StopInstancesRequest() + .withInstanceIds(yourInstanceId); + + ec2Client.stopInstances(stopInstancesRequest) + .getStoppingInstances() + .get(0) + .getPreviousState() + .getName(); + + // 9) - Start an Instance + StartInstancesRequest startInstancesRequest = new StartInstancesRequest() + .withInstanceIds("instance-id"); + + ec2Client.startInstances(startInstancesRequest); + + // 10) - Describe an Instance + DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); + DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest); + System.out.println(response.getReservations() + .get(0) + .getInstances() + .get(0) + .getKernelId()); + } +} From d69d08a58929392f48b506b4584ce97b185e49c3 Mon Sep 17 00:00:00 2001 From: Chris Oberle Date: Fri, 2 Mar 2018 07:30:15 -0500 Subject: [PATCH 33/91] BAEL-1533 session attributes in spring mvc * updated spring boot dependency to 2.0.0.RELEASE --- spring-5/pom.xml | 469 ++++++++++++++++++++++------------------------- 1 file changed, 215 insertions(+), 254 deletions(-) diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 3b21f86e60..b4e6e684ad 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -1,254 +1,215 @@ - - - 4.0.0 - - com.baeldung - spring-5 - 0.0.1-SNAPSHOT - jar - - spring-5 - spring 5 sample project about new features - - - org.springframework.boot - spring-boot-starter-parent - 2.0.0.RC2 - - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-validation - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-webflux - - - org.springframework.boot - spring-boot-starter-hateoas - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.projectreactor - reactor-spring - ${reactor-spring.version} - - - javax.json.bind - javax.json.bind-api - ${jsonb-api.version} - - - - - - - - - - - - - - - org.apache.geronimo.specs - geronimo-json_1.1_spec - ${geronimo-json_1.1_spec.version} - - - org.apache.johnzon - johnzon-jsonb - ${johnzon.version} - - - - org.apache.commons - commons-lang3 - - - - - - org.springframework.boot - spring-boot-devtools - runtime - - - com.h2database - h2 - runtime - - - - org.springframework - spring-test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - - - - org.apache.commons - commons-collections4 - 4.1 - test - - - - org.junit.jupiter - junit-jupiter-api - ${junit.jupiter.version} - - - org.junit.jupiter - junit-jupiter-engine - ${junit.jupiter.version} - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - - org.springframework.restdocs - spring-restdocs-mockmvc - test - - - org.springframework.restdocs - spring-restdocs-webtestclient - test - - - org.springframework.restdocs - spring-restdocs-restassured - test - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - com.baeldung.Spring5Application - JAR - - - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*LiveTest.java - - - - - org.asciidoctor - asciidoctor-maven-plugin - ${asciidoctor-plugin.version} - - - generate-docs - package - - process-asciidoc - - - html - book - - ${snippetsDirectory} - - src/docs/asciidocs - target/generated-docs - - - - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - UTF-8 - UTF-8 - 1.8 - 1.0.0 - 5.0.0 - 2.20 - 5.0.2.RELEASE - 1.0.1.RELEASE - 1.1.3 - 1.0 - 1.0 - 1.5.6 - ${project.build.directory}/generated-snippets - - - + + + 4.0.0 + + com.baeldung + spring-5 + 0.0.1-SNAPSHOT + jar + + spring-5 + spring 5 sample project about new features + + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-hateoas + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.projectreactor + reactor-spring + ${reactor-spring.version} + + + javax.json.bind + javax.json.bind-api + + + org.apache.geronimo.specs + geronimo-json_1.1_spec + ${geronimo-json_1.1_spec.version} + + + org.apache.johnzon + johnzon-jsonb + ${johnzon.version} + + + + org.apache.commons + commons-lang3 + + + + + + org.springframework.boot + spring-boot-devtools + runtime + + + com.h2database + h2 + runtime + + + + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + org.apache.commons + commons-collections4 + 4.1 + test + + + + org.junit.jupiter + junit-jupiter-api + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + org.springframework.restdocs + spring-restdocs-mockmvc + test + + + org.springframework.restdocs + spring-restdocs-webtestclient + test + + + org.springframework.restdocs + spring-restdocs-restassured + test + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.Spring5Application + JAR + + + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + methods + true + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + org.asciidoctor + asciidoctor-maven-plugin + ${asciidoctor-plugin.version} + + + generate-docs + package + + process-asciidoc + + + html + book + + ${snippetsDirectory} + + src/docs/asciidocs + target/generated-docs + + + + + + + + + UTF-8 + UTF-8 + 1.8 + 1.0.0 + 2.20 + 1.0.1.RELEASE + 1.1.3 + 1.0 + 1.5.6 + ${project.build.directory}/generated-snippets + + + From c10cb80823dcb18c55ff5363d11bba917c4a860f Mon Sep 17 00:00:00 2001 From: Rokon Uddin Ahmed Date: Fri, 2 Mar 2018 22:40:04 +0600 Subject: [PATCH 34/91] 02.03 (#3747) * Update README.md * Update README.md * Update README.md * Update README.MD * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md --- core-java-8/README.md | 2 ++ core-java/README.md | 7 +++++++ core-kotlin/README.md | 2 ++ java-lite/README.md | 3 ++- java-rmi/README.md | 3 +++ jenkins/README.md | 3 +++ libraries/README.md | 3 +++ persistence-modules/README.md | 2 ++ spring-5-reactive/README.md | 1 + spring-5-security/README.md | 1 + spring-5/README.md | 1 + spring-boot/README.MD | 3 +++ spring-cloud/README.md | 1 + spring-data-elasticsearch/README.md | 1 + spring-security-core/README.md | 1 + spring-security-mvc-custom/README.md | 1 + vavr/README.md | 1 + 17 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 java-rmi/README.md create mode 100644 jenkins/README.md diff --git a/core-java-8/README.md b/core-java-8/README.md index 1b5208961d..949577df19 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -41,3 +41,5 @@ - [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams) - [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) - [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection) +- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner) +- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator) diff --git a/core-java/README.md b/core-java/README.md index 5be4e12592..8bb114b95f 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -129,3 +129,10 @@ - [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize) - [Compiling Java *.class Files with javac](http://www.baeldung.com/javac) - [Method Overloading and Overriding in Java](http://www.baeldung.com/java-method-overload-override) +- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set) +- [Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random) +- [Java TreeMap vs HashMap](http://www.baeldung.com/java-treemap-vs-hashmap) +- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator) +- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java) +- [Introduction to Javadoc](http://www.baeldung.com/javadoc) + diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 1c64817815..7f68648eba 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -18,3 +18,5 @@ - [JUnit 5 for Kotlin Developers](http://www.baeldung.com/junit-5-kotlin) - [Extension Methods in Kotlin](http://www.baeldung.com/kotlin-extension-methods) - [Infix Functions in Kotlin](http://www.baeldung.com/kotlin-infix-functions) +- [Try-with-resources in Kotlin](http://www.baeldung.com/kotlin-try-with-resources) +- [HTTP Requests with Kotlin and khttp](http://www.baeldung.com/kotlin-khttp) diff --git a/java-lite/README.md b/java-lite/README.md index bcb84e186e..13dcd5f8c3 100644 --- a/java-lite/README.md +++ b/java-lite/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: -- [RESTFul CRUD application with JavaLite] () \ No newline at end of file + +- [A Guide to JavaLite – Building a RESTful CRUD application](http://www.baeldung.com/javalite-rest) diff --git a/java-rmi/README.md b/java-rmi/README.md new file mode 100644 index 0000000000..4d12060395 --- /dev/null +++ b/java-rmi/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [Getting Started with Java RMI](http://www.baeldung.com/java-rmi) diff --git a/jenkins/README.md b/jenkins/README.md new file mode 100644 index 0000000000..da60e556df --- /dev/null +++ b/jenkins/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Writing a Jenkins Plugin](http://www.baeldung.com/jenkins-custom-plugin) diff --git a/libraries/README.md b/libraries/README.md index fbf2b4e876..5e4ef6a898 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -60,6 +60,9 @@ - [Guide to google-http-client](http://www.baeldung.com/google-http-client) - [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client) - [Programatically Create, Configure, and Run a Tomcat Server] (http://www.baeldung.com/tomcat-programmatic-setup) +- [A Docker Guide for Java](http://www.baeldung.com/docker-java-api) +- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling) +- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic) diff --git a/persistence-modules/README.md b/persistence-modules/README.md index 13e7f731aa..f05a822c30 100644 --- a/persistence-modules/README.md +++ b/persistence-modules/README.md @@ -5,3 +5,5 @@ ### Relevant Articles: - [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search) +- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) +- [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce) diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index 400e343263..d8b9f89223 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -13,3 +13,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) - [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) - [Spring 5 Testing with @EnabledIf Annotation](https://github.com/eugenp/tutorials/tree/master/spring-5) +- [Reactive WebSockets with Spring 5](http://www.baeldung.com/spring-5-reactive-websockets) diff --git a/spring-5-security/README.md b/spring-5-security/README.md index 1c9fad65e4..d6573ef8b0 100644 --- a/spring-5-security/README.md +++ b/spring-5-security/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Spring Security 5 -OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login) +- [Extra Login Fields with Spring Security](https://github.com/eugenp/tutorials/tree/master/spring-5-security) diff --git a/spring-5/README.md b/spring-5/README.md index 8249fe3813..1ac3cf4577 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -14,3 +14,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) - [Spring 5 Testing with @EnabledIf Annotation](http://www.baeldung.com/sring-5-enabledif) - [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs) +- [Spring Security 5 – OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 7b5fb3c880..e78756cf08 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -29,3 +29,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Getting Started with GraphQL and Spring Boot](http://www.baeldung.com/spring-graphql) - [Guide to Spring Type Conversions](http://www.baeldung.com/spring-type-conversions) - [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql) +- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) +- [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) +- [An Introduction to Kong](http://www.baeldung.com/kong) diff --git a/spring-cloud/README.md b/spring-cloud/README.md index adaf3052e6..3cdbc05f2f 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -20,3 +20,4 @@ - [An Introduction to Spring Cloud Zookeeper](http://www.baeldung.com/spring-cloud-zookeeper) - [Using a Spring Cloud App Starter](http://www.baeldung.com/using-a-spring-cloud-app-starter) - [Spring Cloud Connectors and Heroku](http://www.baeldung.com/spring-cloud-heroku) +- [An Example of Load Balancing with Zuul and Eureka](http://www.baeldung.com/zuul-load-balancing) diff --git a/spring-data-elasticsearch/README.md b/spring-data-elasticsearch/README.md index 0095d66377..5d0b3b84c4 100644 --- a/spring-data-elasticsearch/README.md +++ b/spring-data-elasticsearch/README.md @@ -5,6 +5,7 @@ - [Elasticsearch Queries with Spring Data](http://www.baeldung.com/spring-data-elasticsearch-queries) - [Guide to Elasticsearch in Java](http://www.baeldung.com/elasticsearch-java) +- [Geospatial Support in ElasticSearch](http://www.baeldung.com/elasticsearch-geo-spatial) ### Build the Project with Tests Running ``` diff --git a/spring-security-core/README.md b/spring-security-core/README.md index 3675e7e160..f7b3f6dffe 100644 --- a/spring-security-core/README.md +++ b/spring-security-core/README.md @@ -9,3 +9,4 @@ mvn clean install ### Relevant Articles: - [Intro to @PreFilter and @PostFilter in Spring Security](http://www.baeldung.com/spring-security-prefilter-postfilter) - [Spring Boot Authentication Auditing Support](http://www.baeldung.com/spring-boot-authentication-audit) +- [Introduction to Spring Method Security](http://www.baeldung.com/spring-security-method-security) diff --git a/spring-security-mvc-custom/README.md b/spring-security-mvc-custom/README.md index 2c0be4768e..ca0731a0c3 100644 --- a/spring-security-mvc-custom/README.md +++ b/spring-security-mvc-custom/README.md @@ -12,6 +12,7 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com - [Introduction to Spring MVC HandlerInterceptor](http://www.baeldung.com/spring-mvc-handlerinterceptor) - [Using a Custom Spring MVC’s Handler Interceptor to Manage Sessions](http://www.baeldung.com/spring-mvc-custom-handler-interceptor) - [A Guide to CSRF Protection in Spring Security](http://www.baeldung.com/spring-security-csrf) +- [How to Manually Authenticate User with Spring Security](http://www.baeldung.com/manually-set-user-authentication-spring-security) ### Build the Project ``` diff --git a/vavr/README.md b/vavr/README.md index d39c9f36a1..373f897486 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -9,4 +9,5 @@ - [Guide to Collections API in Vavr](http://www.baeldung.com/vavr-collections) - [Collection Factory Methods for Vavr](http://www.baeldung.com/vavr-collection-factory-methods) - [Introduction to Future in Vavr](http://www.baeldung.com/vavr-future) +- [Introduction to VRaptor in Java](http://www.baeldung.com/vraptor) From 11def8541132152fd824225f22e07b99f4755883 Mon Sep 17 00:00:00 2001 From: linhvovn Date: Sat, 3 Mar 2018 12:13:53 +0800 Subject: [PATCH 35/91] [Bael 1382] - Upgrade to Spring 5.0.3 (#3751) * [tlinh2110-BAEL1382] Add Security in SI * [tlinh2110-BAEL1382] Upgrade to Spring 5 & add Logger * [tlinh2110-BAEL-1382] Update Unit Test * [tlinh2110-BAEL1382] Remove unnecessary logs * [tlinh2110-BAEL1382] Upgrade to Spring 5.0.3 --- spring-integration/pom.xml | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml index 43e45dfd17..e3dd0d3f9a 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -18,7 +18,7 @@ UTF-8 - 5.0.1.RELEASE + 5.0.3.RELEASE 1.1.4.RELEASE 1.4.7 1.1.1 @@ -106,12 +106,6 @@ spring-integration-file ${spring.version} - - - org.springframework.security - spring-security-core - ${spring.version} - org.springframework.security spring-security-config From 25a118deb3ce44f7b8957d212350f4284446bb39 Mon Sep 17 00:00:00 2001 From: ocheja Date: Sun, 4 Mar 2018 01:42:05 +0900 Subject: [PATCH 36/91] Implement examples for ASCII Art in Java (#3753) --- .../java/com/baeldung/asciiart/AsciiArt.java | 62 +++++++++++++++++++ .../com/baeldung/asciiart/AsciiArtTest.java | 20 ++++++ 2 files changed, 82 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/asciiart/AsciiArt.java create mode 100644 core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java diff --git a/core-java/src/main/java/com/baeldung/asciiart/AsciiArt.java b/core-java/src/main/java/com/baeldung/asciiart/AsciiArt.java new file mode 100644 index 0000000000..081717b4fa --- /dev/null +++ b/core-java/src/main/java/com/baeldung/asciiart/AsciiArt.java @@ -0,0 +1,62 @@ +package com.baeldung.asciiart; + +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; + +public class AsciiArt { + + public AsciiArt() { + } + + public void drawString(String text, String artChar, Settings settings) { + BufferedImage image = getImageIntegerMode(settings.width, settings.height); + + Graphics2D graphics2D = getGraphics2D(image.getGraphics(), settings); + graphics2D.drawString(text, 6, ((int) (settings.height * 0.67))); + + for (int y = 0; y < settings.height; y++) { + StringBuilder stringBuilder = new StringBuilder(); + + for (int x = 0; x < settings.width; x++) { + stringBuilder.append(image.getRGB(x, y) == -16777216 ? " " : artChar); + } + + if (stringBuilder.toString() + .trim() + .isEmpty()) { + continue; + } + + System.out.println(stringBuilder); + } + + } + + private BufferedImage getImageIntegerMode(int width, int height) { + return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + } + + private Graphics2D getGraphics2D(Graphics graphics, Settings settings) { + graphics.setFont(settings.font); + + Graphics2D graphics2D = (Graphics2D) graphics; + graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + + return graphics2D; + } + + public class Settings { + public Font font; + public int width; + public int height; + + public Settings(Font font, int width, int height) { + this.font = font; + this.width = width; + this.height = height; + } + } +} diff --git a/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java b/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java new file mode 100644 index 0000000000..103681894e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java @@ -0,0 +1,20 @@ +package com.baeldung.asciiart; + +import java.awt.Font; + +import org.junit.Test; + +import com.baeldung.asciiart.AsciiArt.Settings; + +public class AsciiArtTest { + + @Test + public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() { + AsciiArt asciiArt = new AsciiArt(); + String text = "BAELDUNG"; + Settings settings = asciiArt.new Settings(new Font("SansSerif", Font.BOLD, 24), text.length() * 30, 30); // 30 pixel width per character + + asciiArt.drawString(text, "*", settings); + } + +} From 37223104c43d5920abc592e0c3f1114c18244437 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sat, 3 Mar 2018 20:46:43 -0600 Subject: [PATCH 37/91] BAEL-1178 README (#3763) * BAEL-973: updated README * BAEL-1069: Updated README * BAEL-817: add README file * BAEL-1084: README update * BAEL-960: Update README * BAEL-1155: updated README * BAEL-1041: updated README * BAEL-973: Updated README * BAEL-1187: updated README * BAEL-1183: Update README * BAEL-1133: Updated README * BAEL-1098: README update * BAEL-719: add README.md * BAEL-1272: README update * BAEL-1272: README update * BAEL-1196: Update README * BAEL-1328: Updated README * BAEL-1371: Update README.md * BAEL-1371: Update README.md * BAEL-1278: Update README * BAEL-1326: Update README * BAEL-399: Update README * BAEL-1297: Update README * BAEL-1218: README * BAEL-1148 README update * BAEL-113 README * BAEL-1158 README * BAEL-1539: Update README * BAEL-1507 README update * BAEL-1178 README updated --- spring-cloud/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-cloud/README.md b/spring-cloud/README.md index 3cdbc05f2f..8ad750a809 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -21,3 +21,4 @@ - [Using a Spring Cloud App Starter](http://www.baeldung.com/using-a-spring-cloud-app-starter) - [Spring Cloud Connectors and Heroku](http://www.baeldung.com/spring-cloud-heroku) - [An Example of Load Balancing with Zuul and Eureka](http://www.baeldung.com/zuul-load-balancing) +- [An Intro to Spring Cloud Contract](http://www.baeldung.com/spring-cloud-contract) From 09bb65a846d41f885a99bc753bad67ada1c85de3 Mon Sep 17 00:00:00 2001 From: eelhazati <35301254+eelhazati@users.noreply.github.com> Date: Sun, 4 Mar 2018 10:44:05 +0000 Subject: [PATCH 38/91] BAEL-1570 (#3762) * Create pom.xml * Update pom.xml * Create pom.xml * Update pom.xml * add impl * add app --- java-spi/exchange-rate-api/pom.xml | 14 ++++ .../java/com/baeldung/rate/ExchangeRate.java | 42 ++++++++++++ .../java/com/baeldung/rate/api/Quote.java | 44 +++++++++++++ .../com/baeldung/rate/api/QuoteManager.java | 8 +++ .../exception/ProviderNotFoundException.java | 13 ++++ .../rate/spi/ExchangeRateProvider.java | 7 ++ java-spi/exchange-rate-app/pom.xml | 27 ++++++++ .../java/com.baeldung.rate.app/MainApp.java | 21 ++++++ java-spi/exchange-rate-impl/pom.xml | 42 ++++++++++++ .../com/baeldung/rate/impl/QuoteResponse.java | 26 ++++++++ .../rate/impl/QuoteResponseWrapper.java | 13 ++++ .../YahooFinanceExchangeRateProvider.java | 13 ++++ .../rate/impl/YahooQuoteManagerImpl.java | 65 +++++++++++++++++++ ...com.baeldung.rate.spi.ExchangeRateProvider | 1 + java-spi/pom.xml | 20 ++++++ pom.xml | 1 + 16 files changed, 357 insertions(+) create mode 100644 java-spi/exchange-rate-api/pom.xml create mode 100644 java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/ExchangeRate.java create mode 100644 java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/Quote.java create mode 100644 java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/QuoteManager.java create mode 100644 java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/exception/ProviderNotFoundException.java create mode 100644 java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/spi/ExchangeRateProvider.java create mode 100644 java-spi/exchange-rate-app/pom.xml create mode 100644 java-spi/exchange-rate-app/src/main/java/com.baeldung.rate.app/MainApp.java create mode 100644 java-spi/exchange-rate-impl/pom.xml create mode 100644 java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponse.java create mode 100644 java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponseWrapper.java create mode 100644 java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooFinanceExchangeRateProvider.java create mode 100644 java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java create mode 100644 java-spi/exchange-rate-impl/src/main/resources/META-INF/services/com.baeldung.rate.spi.ExchangeRateProvider create mode 100644 java-spi/pom.xml diff --git a/java-spi/exchange-rate-api/pom.xml b/java-spi/exchange-rate-api/pom.xml new file mode 100644 index 0000000000..27651533a9 --- /dev/null +++ b/java-spi/exchange-rate-api/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + + exchange-rate-api + jar + + + com.baeldung + java-spi + 1.0.0-SNAPSHOT + + + diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/ExchangeRate.java b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/ExchangeRate.java new file mode 100644 index 0000000000..afc7ef92ce --- /dev/null +++ b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/ExchangeRate.java @@ -0,0 +1,42 @@ +package com.baeldung.rate; + +import com.baeldung.rate.exception.ProviderNotFoundException; +import com.baeldung.rate.spi.ExchangeRateProvider; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.ServiceLoader; + +public final class ExchangeRate { + + private static final String DEFAULT_PROVIDER = "com.baeldung.rate.spi.YahooFinanceExchangeRateProvider"; + + //All providers + public static List providers() { + List services = new ArrayList<>(); + ServiceLoader loader = ServiceLoader.load(ExchangeRateProvider.class); + loader.forEach(exchangeRateProvider -> { + services.add(exchangeRateProvider); + }); + return services; + } + + //Default provider + public static ExchangeRateProvider provider() { + return provider(DEFAULT_PROVIDER); + } + + //provider by name + public static ExchangeRateProvider provider(String providerName) { + ServiceLoader loader = ServiceLoader.load(ExchangeRateProvider.class); + Iterator it = loader.iterator(); + while (it.hasNext()) { + ExchangeRateProvider provider = it.next(); + if (providerName.equals(provider.getClass().getName())) { + return provider; + } + } + throw new ProviderNotFoundException("Exchange Rate provider " + providerName + " not found"); + } +} diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/Quote.java b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/Quote.java new file mode 100644 index 0000000000..577af3b618 --- /dev/null +++ b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/Quote.java @@ -0,0 +1,44 @@ +package com.baeldung.rate.api; + +import java.math.BigDecimal; +import java.time.LocalDate; + +public class Quote { + private String currency; + private BigDecimal ask; + private BigDecimal bid; + private LocalDate date; + //... + + public String getCurrency() { + return currency; + } + + public void setCurrency(String currency) { + this.currency = currency; + } + + public BigDecimal getAsk() { + return ask; + } + + public void setAsk(BigDecimal ask) { + this.ask = ask; + } + + public BigDecimal getBid() { + return bid; + } + + public void setBid(BigDecimal bid) { + this.bid = bid; + } + + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } +} \ No newline at end of file diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/QuoteManager.java b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/QuoteManager.java new file mode 100644 index 0000000000..16416eaf65 --- /dev/null +++ b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/QuoteManager.java @@ -0,0 +1,8 @@ +package com.baeldung.rate.api; + +import java.time.LocalDate; +import java.util.List; + +public interface QuoteManager { + List getQuotes(String baseCurrency, LocalDate date); +} diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/exception/ProviderNotFoundException.java b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/exception/ProviderNotFoundException.java new file mode 100644 index 0000000000..3a2d92c4fd --- /dev/null +++ b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/exception/ProviderNotFoundException.java @@ -0,0 +1,13 @@ +package com.baeldung.rate.exception; + +public class ProviderNotFoundException extends RuntimeException { + + public ProviderNotFoundException() { + super(); + } + + public ProviderNotFoundException(String message) { + super(message); + } + +} diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/spi/ExchangeRateProvider.java b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/spi/ExchangeRateProvider.java new file mode 100644 index 0000000000..c3157b2b03 --- /dev/null +++ b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/spi/ExchangeRateProvider.java @@ -0,0 +1,7 @@ +package com.baeldung.rate.spi; + +import com.baeldung.rate.api.QuoteManager; + +public interface ExchangeRateProvider { + QuoteManager create(); +} \ No newline at end of file diff --git a/java-spi/exchange-rate-app/pom.xml b/java-spi/exchange-rate-app/pom.xml new file mode 100644 index 0000000000..7e64cf7438 --- /dev/null +++ b/java-spi/exchange-rate-app/pom.xml @@ -0,0 +1,27 @@ + + 4.0.0 + + exchange-rate-app + jar + + + com.baeldung + java-spi + 1.0.0-SNAPSHOT + + + + + com.baeldung + exchange-rate-api + 1.0.0-SNAPSHOT + + + com.baeldung + exchange-rate-impl + 1.0.0-SNAPSHOT + + + + diff --git a/java-spi/exchange-rate-app/src/main/java/com.baeldung.rate.app/MainApp.java b/java-spi/exchange-rate-app/src/main/java/com.baeldung.rate.app/MainApp.java new file mode 100644 index 0000000000..fd43ed3a85 --- /dev/null +++ b/java-spi/exchange-rate-app/src/main/java/com.baeldung.rate.app/MainApp.java @@ -0,0 +1,21 @@ +package com.baeldung.rate.app; + +import com.baeldung.rate.ExchangeRate; +import com.baeldung.rate.api.Quote; + +import java.time.LocalDate; +import java.util.List; + +public class MainApp { + public static void main(String... args) { + ExchangeRate.providers().forEach(provider -> { + System.out.println("Retreiving USD quotes from provider :" + provider); + List quotes = provider.create().getQuotes("USD", LocalDate.now()); + System.out.println(String.format("%14s%12s|%12s", "","Ask", "Bid")); + System.out.println("----------------------------------------"); + quotes.forEach(quote -> { + System.out.println("USD --> " + quote.getCurrency() + " : " + String.format("%12f|%12f", quote.getAsk(), quote.getBid())); + }); + }); + } +} diff --git a/java-spi/exchange-rate-impl/pom.xml b/java-spi/exchange-rate-impl/pom.xml new file mode 100644 index 0000000000..ec22791351 --- /dev/null +++ b/java-spi/exchange-rate-impl/pom.xml @@ -0,0 +1,42 @@ + + 4.0.0 + + exchange-rate-impl + jar + + + com.baeldung + java-spi + 1.0.0-SNAPSHOT + + + + + com.baeldung + exchange-rate-api + 1.0.0-SNAPSHOT + + + com.squareup.okhttp3 + okhttp + 3.10.0 + + + javax.json.bind + javax.json.bind-api + 1.0 + + + org.eclipse + yasson + 1.0.1 + + + org.glassfish + javax.json + 1.1.2 + + + + diff --git a/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponse.java b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponse.java new file mode 100644 index 0000000000..9ba4fb26b0 --- /dev/null +++ b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponse.java @@ -0,0 +1,26 @@ +package com.baeldung.rate.impl; + +import com.baeldung.rate.api.Quote; + +import java.util.List; + +public class QuoteResponse { + private List result; + private String error; + + public List getResult() { + return result; + } + + public void setResult(List result) { + this.result = result; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } +} diff --git a/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponseWrapper.java b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponseWrapper.java new file mode 100644 index 0000000000..6d7be086f0 --- /dev/null +++ b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponseWrapper.java @@ -0,0 +1,13 @@ +package com.baeldung.rate.impl; + +public class QuoteResponseWrapper { + private QuoteResponse quoteResponse; + + public QuoteResponse getQuoteResponse() { + return quoteResponse; + } + + public void setQuoteResponse(QuoteResponse quoteResponse) { + this.quoteResponse = quoteResponse; + } +} diff --git a/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooFinanceExchangeRateProvider.java b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooFinanceExchangeRateProvider.java new file mode 100644 index 0000000000..9a069cfde4 --- /dev/null +++ b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooFinanceExchangeRateProvider.java @@ -0,0 +1,13 @@ +package com.baeldung.rate.impl; + +import com.baeldung.rate.api.QuoteManager; +import com.baeldung.rate.spi.ExchangeRateProvider; + +public class YahooFinanceExchangeRateProvider implements ExchangeRateProvider { + + @Override + public QuoteManager create() { + return new YahooQuoteManagerImpl(); + } + +} \ No newline at end of file diff --git a/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java new file mode 100644 index 0000000000..8cc68259be --- /dev/null +++ b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java @@ -0,0 +1,65 @@ +package com.baeldung.rate.impl; + +import com.baeldung.rate.api.Quote; +import com.baeldung.rate.api.QuoteManager; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +import javax.json.bind.JsonbBuilder; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.time.LocalDate; +import java.util.Currency; +import java.util.List; + +public class YahooQuoteManagerImpl implements QuoteManager { + + static final String URL_PROVIDER = "https://query1.finance.yahoo.com/v7/finance/quote"; + OkHttpClient client = new OkHttpClient(); + + @Override + public List getQuotes(String baseCurrency, LocalDate date) { + + StringBuilder sb = new StringBuilder(); + Currency.getAvailableCurrencies().forEach(currency -> { + if (!currency.equals(currency.getCurrencyCode())) { + sb.append(baseCurrency).append(currency.getCurrencyCode()).append("=X").append(","); + } + }); + + String value = ""; + try { + value = URLEncoder.encode(sb.toString().substring(0, sb.toString().length() - 1), "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + String queryString = String.format("%s=%s", "symbols", value); + String response = doGetRequest(queryString); + System.out.println(response); + return map(response); + } + + private List map(String response) { + QuoteResponseWrapper qrw = JsonbBuilder.create().fromJson(response, QuoteResponseWrapper.class); + return qrw.getQuoteResponse().getResult(); + } + + String doGetRequest(String queryString) { + String fullUrl = URL_PROVIDER + "?" + queryString; + + System.out.println(fullUrl); + Request request = new Request.Builder() + .url(fullUrl) + .build(); + Response response = null; + try { + response = client.newCall(request).execute(); + return response.body().string(); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/java-spi/exchange-rate-impl/src/main/resources/META-INF/services/com.baeldung.rate.spi.ExchangeRateProvider b/java-spi/exchange-rate-impl/src/main/resources/META-INF/services/com.baeldung.rate.spi.ExchangeRateProvider new file mode 100644 index 0000000000..67ba8a8227 --- /dev/null +++ b/java-spi/exchange-rate-impl/src/main/resources/META-INF/services/com.baeldung.rate.spi.ExchangeRateProvider @@ -0,0 +1 @@ +com.baeldung.rate.impl.YahooFinanceExchangeRateProvider \ No newline at end of file diff --git a/java-spi/pom.xml b/java-spi/pom.xml new file mode 100644 index 0000000000..8eaa184d8d --- /dev/null +++ b/java-spi/pom.xml @@ -0,0 +1,20 @@ + + 4.0.0 + + java-spi + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + exchange-rate-api + exchange-rate-impl + exchange-rate-app + + + diff --git a/pom.xml b/pom.xml index 3092c0fa40..0c72a82d2f 100644 --- a/pom.xml +++ b/pom.xml @@ -278,6 +278,7 @@ lucene vraptor persistence-modules/java-cockroachdb + java-spi From 84a9b2e0d8453ab885baa9a77a7d5bee73c4396b Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 4 Mar 2018 17:04:28 +0200 Subject: [PATCH 39/91] minor cleanup --- .../nio2/watcher/DirectoryWatcherExample.java | 4 +- .../baeldung/copyfiles/FileCopierTest.java | 85 +++++++++---------- .../file/FileOperationsManualTest.java | 1 - .../java/com/baeldung/file/FilesTest.java | 22 ++--- .../test/LookupFSJNDIIntegrationTest.java | 4 +- .../baeldung/java/nio2/PathManualTest.java | 1 - .../BasicAttribsIntegrationTest.java | 1 - .../java8/JavaFolderSizeUnitTest.java | 15 +--- .../MappedByteBufferUnitTest.java | 16 ++-- .../java/io/JavaInputStreamToXUnitTest.java | 4 +- .../java/io/JavaReadFromFileUnitTest.java | 3 +- 11 files changed, 64 insertions(+), 92 deletions(-) diff --git a/core-java-io/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java b/core-java-io/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java index 35955032dc..4c35ffdb22 100644 --- a/core-java-io/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java +++ b/core-java-io/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java @@ -10,7 +10,7 @@ import java.nio.file.WatchKey; import java.nio.file.WatchService; public class DirectoryWatcherExample { - + public static void main(String[] args) throws IOException, InterruptedException { WatchService watchService = FileSystems.getDefault().newWatchService(); Path path = Paths.get(System.getProperty("user.home")); @@ -25,5 +25,5 @@ public class DirectoryWatcherExample { watchService.close(); } - + } diff --git a/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java b/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java index 973436a26a..6d96d2fc0b 100644 --- a/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java +++ b/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java @@ -19,52 +19,51 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.*; public class FileCopierTest { - File original = new File("src/test/resources/original.txt"); + File original = new File("src/test/resources/original.txt"); - @Before - public void init() throws IOException { - if (!original.exists()) - Files.createFile(original.toPath()); - } + @Before + public void init() throws IOException { + if (!original.exists()) + Files.createFile(original.toPath()); + } - @Test - public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { - File copied = new File("src/test/resources/copiedWithIo.txt"); - try (InputStream in = new BufferedInputStream(new FileInputStream(original)); - OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) { - byte[] buffer = new byte[1024]; - int lengthRead; - while ((lengthRead = in.read(buffer)) > 0) { - out.write(buffer, 0, lengthRead); - out.flush(); - } - } - assertThat(copied).exists(); - assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); - } + @Test + public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { + File copied = new File("src/test/resources/copiedWithIo.txt"); + try (InputStream in = new BufferedInputStream(new FileInputStream(original)); OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) { + byte[] buffer = new byte[1024]; + int lengthRead; + while ((lengthRead = in.read(buffer)) > 0) { + out.write(buffer, 0, lengthRead); + out.flush(); + } + } + assertThat(copied).exists(); + assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); + } - @Test - public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { - File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); - FileUtils.copyFile(original, copied); - assertThat(copied).exists(); - assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); - } + @Test + public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { + File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); + FileUtils.copyFile(original, copied); + assertThat(copied).exists(); + assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); + } - @Test - public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException { - Path copied = Paths.get("src/test/resources/copiedWithNio.txt"); - Path originalPath = original.toPath(); - Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING); - assertThat(copied).exists(); - assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied))); - } + @Test + public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException { + Path copied = Paths.get("src/test/resources/copiedWithNio.txt"); + Path originalPath = original.toPath(); + Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING); + assertThat(copied).exists(); + assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied))); + } - @Test - public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException { - File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); - com.google.common.io.Files.copy(original, copied); - assertThat(copied).exists(); - assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); - } + @Test + public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException { + File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); + com.google.common.io.Files.copy(original, copied); + assertThat(copied).exists(); + assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); + } } diff --git a/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java b/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java index ea71d1b5c1..7968967679 100644 --- a/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java +++ b/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java @@ -3,7 +3,6 @@ package com.baeldung.file; import org.apache.commons.io.FileUtils; import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Test; import java.io.BufferedReader; diff --git a/core-java-io/src/test/java/com/baeldung/file/FilesTest.java b/core-java-io/src/test/java/com/baeldung/file/FilesTest.java index c5a5b8a3a1..a35cda8b23 100644 --- a/core-java-io/src/test/java/com/baeldung/file/FilesTest.java +++ b/core-java-io/src/test/java/com/baeldung/file/FilesTest.java @@ -42,19 +42,14 @@ public class FilesTest { CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND); chs.write("Spain\r\n"); - assertThat(StreamUtils.getStringFromInputStream( - new FileInputStream(fileName))) - .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); } - @Test public void whenAppendToFileUsingFiles_thenCorrect() throws IOException { Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND); - assertThat(StreamUtils.getStringFromInputStream( - new FileInputStream(fileName))) - .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); } @Test @@ -62,9 +57,7 @@ public class FilesTest { File file = new File(fileName); FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true); - assertThat(StreamUtils.getStringFromInputStream( - new FileInputStream(fileName))) - .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); } @Test @@ -73,9 +66,7 @@ public class FilesTest { fos.write("Spain\r\n".getBytes()); fos.close(); - assertThat(StreamUtils.getStringFromInputStream( - new FileInputStream(fileName))) - .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); } @Test @@ -86,9 +77,6 @@ public class FilesTest { bw.newLine(); bw.close(); - assertThat( - StreamUtils.getStringFromInputStream( - new FileInputStream(fileName))) - .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n"); + assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n"); } } \ No newline at end of file diff --git a/core-java-io/src/test/java/com/baeldung/filesystem/jndi/test/LookupFSJNDIIntegrationTest.java b/core-java-io/src/test/java/com/baeldung/filesystem/jndi/test/LookupFSJNDIIntegrationTest.java index 330ec3aee3..023a47cb97 100644 --- a/core-java-io/src/test/java/com/baeldung/filesystem/jndi/test/LookupFSJNDIIntegrationTest.java +++ b/core-java-io/src/test/java/com/baeldung/filesystem/jndi/test/LookupFSJNDIIntegrationTest.java @@ -35,7 +35,7 @@ public class LookupFSJNDIIntegrationTest { @Test public void givenInitialContext_whenLokupFileExists_thenSuccess() { - File file = fsjndi.getFile(FILENAME); - assertNotNull("File exists", file); + File file = fsjndi.getFile(FILENAME); + assertNotNull("File exists", file); } } diff --git a/core-java-io/src/test/java/com/baeldung/java/nio2/PathManualTest.java b/core-java-io/src/test/java/com/baeldung/java/nio2/PathManualTest.java index acfb2c08e9..969dff1da2 100644 --- a/core-java-io/src/test/java/com/baeldung/java/nio2/PathManualTest.java +++ b/core-java-io/src/test/java/com/baeldung/java/nio2/PathManualTest.java @@ -9,7 +9,6 @@ import java.net.URI; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Date; import org.junit.Test; diff --git a/core-java-io/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsIntegrationTest.java b/core-java-io/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsIntegrationTest.java index 9f84aa60d6..4b6302e93c 100644 --- a/core-java-io/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsIntegrationTest.java +++ b/core-java-io/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsIntegrationTest.java @@ -20,7 +20,6 @@ public class BasicAttribsIntegrationTest { private static final Logger LOG = LoggerFactory.getLogger(BasicAttribsIntegrationTest.class); - private static final String HOME = System.getProperty("user.home"); private static BasicFileAttributes basicAttribs; diff --git a/core-java-io/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java b/core-java-io/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java index 7f83e379cd..1f3b380772 100644 --- a/core-java-io/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java +++ b/core-java-io/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java @@ -55,12 +55,7 @@ public class JavaFolderSizeUnitTest { @Test public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException { final Path folder = Paths.get(path); - final long size = Files.walk(folder) - .filter(p -> p.toFile() - .isFile()) - .mapToLong(p -> p.toFile() - .length()) - .sum(); + final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum(); assertEquals(EXPECTED_SIZE, size); } @@ -77,12 +72,8 @@ public class JavaFolderSizeUnitTest { public void whenGetFolderSizeUsingGuava_thenCorrect() { final File folder = new File(path); - final Iterable files = com.google.common.io.Files.fileTreeTraverser() - .breadthFirstTraversal(folder); - final long size = StreamSupport.stream(files.spliterator(), false) - .filter(File::isFile) - .mapToLong(File::length) - .sum(); + final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder); + final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum(); assertEquals(EXPECTED_SIZE, size); } diff --git a/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java b/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java index 0a0993a0d7..d0cb4b4675 100644 --- a/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java +++ b/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java @@ -18,14 +18,13 @@ import static org.junit.Assert.assertNotNull; public class MappedByteBufferUnitTest { - @Test public void givenFileChannel_whenReadToTheMappedByteBuffer_thenShouldSuccess() throws Exception { - //given + // given CharBuffer charBuffer = null; Path pathToRead = getFileURIFromResources("fileToRead.txt"); - //when + // when try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToRead, EnumSet.of(StandardOpenOption.READ))) { MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()); @@ -34,20 +33,19 @@ public class MappedByteBufferUnitTest { } } - //then + // then assertNotNull(charBuffer); assertEquals(charBuffer.toString(), "This is a content of the file"); } @Test public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception { - //given + // given CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file"); Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt"); - //when - try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite, - EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) { + // when + try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite, EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) { MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length()); if (mappedByteBuffer != null) { @@ -55,7 +53,7 @@ public class MappedByteBufferUnitTest { } } - //then + // then List fileContent = Files.readAllLines(pathToWrite); assertEquals(fileContent.get(0), "This will be written to the file"); diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java index 0e20e75869..76a78283cc 100644 --- a/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java +++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java @@ -210,7 +210,7 @@ public class JavaInputStreamToXUnitTest { FileUtils.copyInputStreamToFile(initialStream, targetFile); } - + @Test public final void givenUsingPlainJava_whenConvertingAnInputStreamToString_thenCorrect() throws IOException { String originalString = randomAlphabetic(8); @@ -225,7 +225,7 @@ public class JavaInputStreamToXUnitTest { buffer.flush(); byte[] byteArray = buffer.toByteArray(); - + String text = new String(byteArray, StandardCharsets.UTF_8); assertThat(text, equalTo(originalString)); } diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java index 41d0a8a02a..11bb9b0c87 100644 --- a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java +++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java @@ -18,7 +18,6 @@ import static org.junit.Assert.assertTrue; public class JavaReadFromFileUnitTest { - private static final Logger LOG = LoggerFactory.getLogger(JavaReadFromFileUnitTest.class); @Test @@ -107,7 +106,7 @@ public class JavaReadFromFileUnitTest { @Test public void whenReadUTFEncodedFile_thenCorrect() throws IOException { - final String expected_value = "青空"; + final String expected_value = "é�’空"; final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8")); final String currentLine = reader.readLine(); reader.close(); From 535656eeb5b7ad044e70ddfdec69ffb1691a66c2 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 4 Mar 2018 17:17:57 +0200 Subject: [PATCH 40/91] testing work --- core-java-io/.gitignore | 19 ------- .../src/main/resources/targetFile.tmp | 2 - .../MappedByteBufferUnitTest.java | 12 +++-- .../com/baeldung/stream/FileCopyTest.java | 47 ----------------- .../com/baeldung/stream/FileCopyUnitTest.java | 52 +++++++++++++++++++ .../java/io/JavaInputStreamToXUnitTest.java | 20 +++---- .../java/io/JavaXToInputStreamUnitTest.java | 6 +-- .../src/test/resources/targetFile.tmp | 1 + core-java/src/main/resources/targetFile.tmp | 2 - .../test/resources/copyTest/dest/readme.txt | 2 - .../resources/copyTest/src/test_apache.txt | 1 - .../resources/copyTest/src/test_channel.txt | 1 - .../resources/copyTest/src/test_files.txt | 1 - .../resources/copyTest/src/test_stream.txt | 1 - core-java/src/test/resources/fileToRead.txt | 1 - .../src/test/resources/fileToWriteTo.txt | 0 .../resources/testFolder/sample_file_1.in | 1 - .../resources/testFolder/sample_file_2.in | 1 - 18 files changed, 73 insertions(+), 97 deletions(-) delete mode 100644 core-java-io/src/main/resources/targetFile.tmp delete mode 100644 core-java-io/src/test/java/com/baeldung/stream/FileCopyTest.java create mode 100644 core-java-io/src/test/java/com/baeldung/stream/FileCopyUnitTest.java create mode 100644 core-java-io/src/test/resources/targetFile.tmp delete mode 100644 core-java/src/main/resources/targetFile.tmp delete mode 100644 core-java/src/test/resources/copyTest/dest/readme.txt delete mode 100644 core-java/src/test/resources/copyTest/src/test_apache.txt delete mode 100644 core-java/src/test/resources/copyTest/src/test_channel.txt delete mode 100644 core-java/src/test/resources/copyTest/src/test_files.txt delete mode 100644 core-java/src/test/resources/copyTest/src/test_stream.txt delete mode 100644 core-java/src/test/resources/fileToRead.txt delete mode 100644 core-java/src/test/resources/fileToWriteTo.txt delete mode 100644 core-java/src/test/resources/testFolder/sample_file_1.in delete mode 100644 core-java/src/test/resources/testFolder/sample_file_2.in diff --git a/core-java-io/.gitignore b/core-java-io/.gitignore index 3de4cc647e..520f176acc 100644 --- a/core-java-io/.gitignore +++ b/core-java-io/.gitignore @@ -1,26 +1,7 @@ -*.class - 0.* -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* -.resourceCache - -# Packaged files # -*.jar -*.war -*.ear - # Files generated by integration tests *.txt backup-pom.xml /bin/ /temp - -#IntelliJ specific -.idea/ -*.iml \ No newline at end of file diff --git a/core-java-io/src/main/resources/targetFile.tmp b/core-java-io/src/main/resources/targetFile.tmp deleted file mode 100644 index 20f137b416..0000000000 --- a/core-java-io/src/main/resources/targetFile.tmp +++ /dev/null @@ -1,2 +0,0 @@ -line 1 -a second line \ No newline at end of file diff --git a/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java b/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java index d0cb4b4675..bb87529783 100644 --- a/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java +++ b/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java @@ -41,8 +41,8 @@ public class MappedByteBufferUnitTest { @Test public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception { // given - CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file"); - Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt"); + final CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file"); + final Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt"); // when try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite, EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) { @@ -54,13 +54,15 @@ public class MappedByteBufferUnitTest { } // then - List fileContent = Files.readAllLines(pathToWrite); + final List fileContent = Files.readAllLines(pathToWrite); assertEquals(fileContent.get(0), "This will be written to the file"); } - private Path getFileURIFromResources(String fileName) throws Exception { - ClassLoader classLoader = getClass().getClassLoader(); + // + + private final Path getFileURIFromResources(String fileName) throws Exception { + final ClassLoader classLoader = getClass().getClassLoader(); return Paths.get(classLoader.getResource(fileName).toURI()); } } diff --git a/core-java-io/src/test/java/com/baeldung/stream/FileCopyTest.java b/core-java-io/src/test/java/com/baeldung/stream/FileCopyTest.java deleted file mode 100644 index 3b915a3829..0000000000 --- a/core-java-io/src/test/java/com/baeldung/stream/FileCopyTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.stream; - -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; - -import org.junit.Test; - -public class FileCopyTest { - - @Test - public void whenUsingStream_thenCopyFile() throws IOException { - File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt"); - File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt"); - FileCopy.copyFileUsingStream(src, dest); - assertTrue(dest.exists()); - dest.delete(); - } - - @Test - public void whenUsingFiles_thenCopyFile() throws IOException { - File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt"); - File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt"); - FileCopy.copyFileUsingJavaFiles(src, dest); - assertTrue(dest.exists()); - dest.delete(); - } - - @Test - public void whenUsingChannel_thenCopyFile() throws IOException { - File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt"); - File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt"); - FileCopy.copyFileUsingChannel(src, dest); - assertTrue(dest.exists()); - dest.delete(); - } - - @Test - public void whenUsingApache_thenCopyFile() throws IOException { - File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt"); - File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt"); - FileCopy.copyFileUsingApacheCommonsIO(src, dest); - assertTrue(dest.exists()); - dest.delete(); - } -} diff --git a/core-java-io/src/test/java/com/baeldung/stream/FileCopyUnitTest.java b/core-java-io/src/test/java/com/baeldung/stream/FileCopyUnitTest.java new file mode 100644 index 0000000000..b4641083b9 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/stream/FileCopyUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.stream; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; + +public class FileCopyUnitTest { + + @Test + public void whenUsingStream_thenCopyFile() throws IOException { + final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt"); + final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt"); + FileCopy.copyFileUsingStream(src, dest); + + assertTrue(dest.exists()); + dest.delete(); + } + + @Test + public void whenUsingFiles_thenCopyFile() throws IOException { + final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt"); + final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt"); + FileCopy.copyFileUsingJavaFiles(src, dest); + + assertTrue(dest.exists()); + dest.delete(); + } + + @Test + public void whenUsingChannel_thenCopyFile() throws IOException { + final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt"); + final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt"); + FileCopy.copyFileUsingChannel(src, dest); + + assertTrue(dest.exists()); + dest.delete(); + } + + @Test + public void whenUsingApache_thenCopyFile() throws IOException { + final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt"); + final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt"); + FileCopy.copyFileUsingApacheCommonsIO(src, dest); + + assertTrue(dest.exists()); + dest.delete(); + } + +} diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java index 76a78283cc..f1bea1eefb 100644 --- a/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java +++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java @@ -152,11 +152,11 @@ public class JavaInputStreamToXUnitTest { @Test public final void whenConvertingToFile_thenCorrect() throws IOException { - final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); + final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt")); final byte[] buffer = new byte[initialStream.available()]; initialStream.read(buffer); - final File targetFile = new File("src/main/resources/targetFile.tmp"); + final File targetFile = new File("src/test/resources/targetFile.tmp"); final OutputStream outStream = new FileOutputStream(targetFile); outStream.write(buffer); @@ -166,8 +166,8 @@ public class JavaInputStreamToXUnitTest { @Test public final void whenConvertingInProgressToFile_thenCorrect() throws IOException { - final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); - final File targetFile = new File("src/main/resources/targetFile.tmp"); + final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt")); + final File targetFile = new File("src/test/resources/targetFile.tmp"); final OutputStream outStream = new FileOutputStream(targetFile); final byte[] buffer = new byte[8 * 1024]; @@ -182,8 +182,8 @@ public class JavaInputStreamToXUnitTest { @Test public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException { - final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); - final File targetFile = new File("src/main/resources/targetFile.tmp"); + final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt")); + final File targetFile = new File("src/test/resources/targetFile.tmp"); java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); @@ -192,11 +192,11 @@ public class JavaInputStreamToXUnitTest { @Test public final void whenConvertingInputStreamToFile_thenCorrect3() throws IOException { - final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt")); + final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt")); final byte[] buffer = new byte[initialStream.available()]; initialStream.read(buffer); - final File targetFile = new File("src/main/resources/targetFile.tmp"); + final File targetFile = new File("src/test/resources/targetFile.tmp"); Files.write(buffer, targetFile); IOUtils.closeQuietly(initialStream); @@ -204,9 +204,9 @@ public class JavaInputStreamToXUnitTest { @Test public final void whenConvertingInputStreamToFile_thenCorrect4() throws IOException { - final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt")); + final InputStream initialStream = FileUtils.openInputStream(new File("src/test/resources/sample.txt")); - final File targetFile = new File("src/main/resources/targetFile.tmp"); + final File targetFile = new File("src/test/resources/targetFile.tmp"); FileUtils.copyInputStreamToFile(initialStream, targetFile); } diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java index f58d66818b..08a4c673cd 100644 --- a/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java +++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java @@ -68,7 +68,7 @@ public class JavaXToInputStreamUnitTest { @Test public final void givenUsingPlainJava_whenConvertingFileToInputStream_thenCorrect() throws IOException { - final File initialFile = new File("src/main/resources/sample.txt"); + final File initialFile = new File("src/test/resources/sample.txt"); final InputStream targetStream = new FileInputStream(initialFile); IOUtils.closeQuietly(targetStream); @@ -76,7 +76,7 @@ public class JavaXToInputStreamUnitTest { @Test public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException { - final File initialFile = new File("src/main/resources/sample.txt"); + final File initialFile = new File("src/test/resources/sample.txt"); final InputStream targetStream = Files.asByteSource(initialFile).openStream(); IOUtils.closeQuietly(targetStream); @@ -84,7 +84,7 @@ public class JavaXToInputStreamUnitTest { @Test public final void givenUsingCommonsIO_whenConvertingFileToInputStream_thenCorrect() throws IOException { - final File initialFile = new File("src/main/resources/sample.txt"); + final File initialFile = new File("src/test/resources/sample.txt"); final InputStream targetStream = FileUtils.openInputStream(initialFile); IOUtils.closeQuietly(targetStream); diff --git a/core-java-io/src/test/resources/targetFile.tmp b/core-java-io/src/test/resources/targetFile.tmp new file mode 100644 index 0000000000..5e1c309dae --- /dev/null +++ b/core-java-io/src/test/resources/targetFile.tmp @@ -0,0 +1 @@ +Hello World \ No newline at end of file diff --git a/core-java/src/main/resources/targetFile.tmp b/core-java/src/main/resources/targetFile.tmp deleted file mode 100644 index 20f137b416..0000000000 --- a/core-java/src/main/resources/targetFile.tmp +++ /dev/null @@ -1,2 +0,0 @@ -line 1 -a second line \ No newline at end of file diff --git a/core-java/src/test/resources/copyTest/dest/readme.txt b/core-java/src/test/resources/copyTest/dest/readme.txt deleted file mode 100644 index dfda31ee9f..0000000000 --- a/core-java/src/test/resources/copyTest/dest/readme.txt +++ /dev/null @@ -1,2 +0,0 @@ -files will be copied here and then deleted -remove `file.delete()` to see the files here diff --git a/core-java/src/test/resources/copyTest/src/test_apache.txt b/core-java/src/test/resources/copyTest/src/test_apache.txt deleted file mode 100644 index a6b651973d..0000000000 --- a/core-java/src/test/resources/copyTest/src/test_apache.txt +++ /dev/null @@ -1 +0,0 @@ -apache diff --git a/core-java/src/test/resources/copyTest/src/test_channel.txt b/core-java/src/test/resources/copyTest/src/test_channel.txt deleted file mode 100644 index 6dca835871..0000000000 --- a/core-java/src/test/resources/copyTest/src/test_channel.txt +++ /dev/null @@ -1 +0,0 @@ -channel diff --git a/core-java/src/test/resources/copyTest/src/test_files.txt b/core-java/src/test/resources/copyTest/src/test_files.txt deleted file mode 100644 index 027271b9b2..0000000000 --- a/core-java/src/test/resources/copyTest/src/test_files.txt +++ /dev/null @@ -1 +0,0 @@ -files diff --git a/core-java/src/test/resources/copyTest/src/test_stream.txt b/core-java/src/test/resources/copyTest/src/test_stream.txt deleted file mode 100644 index eac9b41cbe..0000000000 --- a/core-java/src/test/resources/copyTest/src/test_stream.txt +++ /dev/null @@ -1 +0,0 @@ -stream diff --git a/core-java/src/test/resources/fileToRead.txt b/core-java/src/test/resources/fileToRead.txt deleted file mode 100644 index 45d73fa10d..0000000000 --- a/core-java/src/test/resources/fileToRead.txt +++ /dev/null @@ -1 +0,0 @@ -This is a content of the file \ No newline at end of file diff --git a/core-java/src/test/resources/fileToWriteTo.txt b/core-java/src/test/resources/fileToWriteTo.txt deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/core-java/src/test/resources/testFolder/sample_file_1.in b/core-java/src/test/resources/testFolder/sample_file_1.in deleted file mode 100644 index 70c379b63f..0000000000 --- a/core-java/src/test/resources/testFolder/sample_file_1.in +++ /dev/null @@ -1 +0,0 @@ -Hello world \ No newline at end of file diff --git a/core-java/src/test/resources/testFolder/sample_file_2.in b/core-java/src/test/resources/testFolder/sample_file_2.in deleted file mode 100644 index 93b493a513..0000000000 --- a/core-java/src/test/resources/testFolder/sample_file_2.in +++ /dev/null @@ -1 +0,0 @@ -Hello world ! \ No newline at end of file From 358f836ecf9eb666f990d8b18f319a2509a04ee4 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 4 Mar 2018 17:22:02 +0200 Subject: [PATCH 41/91] testing work --- core-java-io/pom.xml | 118 ++---------------- .../java/io/JavaReadFromFileUnitTest.java | 1 + 2 files changed, 8 insertions(+), 111 deletions(-) diff --git a/core-java-io/pom.xml b/core-java-io/pom.xml index 9aa8743aa6..b9fdca3502 100644 --- a/core-java-io/pom.xml +++ b/core-java-io/pom.xml @@ -1,5 +1,4 @@ - + 4.0.0 com.baeldung core-java-io @@ -211,16 +210,6 @@ jmh-generator-annprocess 1.19 - - org.springframework - spring-web - 4.3.4.RELEASE - - - org.springframework.boot - spring-boot-starter - 1.5.8.RELEASE - org.hsqldb hsqldb @@ -264,99 +253,6 @@ - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - true - libs/ - org.baeldung.executable.ExecutableMavenJar - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - - - package - - single - - - ${project.basedir} - - - org.baeldung.executable.ExecutableMavenJar - - - - jar-with-dependencies - - - - - - - - org.apache.maven.plugins - maven-shade-plugin - - - - shade - - - true - - - org.baeldung.executable.ExecutableMavenJar - - - - - - - - - com.jolira - onejar-maven-plugin - - - - org.baeldung.executable.ExecutableMavenJar - true - ${project.build.finalName}-onejar.${project.packaging} - - - one-jar - - - - - org.springframework.boot spring-boot-maven-plugin @@ -384,19 +280,19 @@ -Xmx300m -XX:+UseParallelGC -classpath - + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed - + org.apache.maven.plugins maven-javadoc-plugin 3.0.0-M1 1.8 - 1.8 + 1.8 @@ -442,7 +338,7 @@ run-benchmarks - + none exec @@ -452,7 +348,7 @@ java -classpath - + org.openjdk.jmh.Main .* @@ -490,7 +386,7 @@ 1.13 0.6.5 0.9.0 - + 1.3 4.12 diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java index 11bb9b0c87..b56841117e 100644 --- a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java +++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java @@ -111,6 +111,7 @@ public class JavaReadFromFileUnitTest { final String currentLine = reader.readLine(); reader.close(); LOG.debug(currentLine); + assertEquals(expected_value, currentLine); } From 7cc57756e1ae6a70a9b3fe2b1bd315e0d62ff967 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 4 Mar 2018 17:28:06 +0200 Subject: [PATCH 42/91] testing work --- core-java-io/.gitignore | 5 +- .../nio2/async/AsyncFileIntegrationTest.java | 55 +++++++++---------- core-java/src/test/resources/file.txt | 1 - 3 files changed, 28 insertions(+), 33 deletions(-) delete mode 100644 core-java/src/test/resources/file.txt diff --git a/core-java-io/.gitignore b/core-java-io/.gitignore index 520f176acc..13d4d1f833 100644 --- a/core-java-io/.gitignore +++ b/core-java-io/.gitignore @@ -1,7 +1,4 @@ 0.* # Files generated by integration tests -*.txt -backup-pom.xml -/bin/ -/temp +# *.txt diff --git a/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncFileIntegrationTest.java b/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncFileIntegrationTest.java index e2f7a0303a..cf37b92565 100644 --- a/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncFileIntegrationTest.java +++ b/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncFileIntegrationTest.java @@ -17,18 +17,19 @@ import java.util.concurrent.Future; import static org.junit.Assert.assertEquals; public class AsyncFileIntegrationTest { + @Test public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException { - Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString())); - AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ); + final Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString())); + final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ); - ByteBuffer buffer = ByteBuffer.allocate(1024); + final ByteBuffer buffer = ByteBuffer.allocate(1024); - Future operation = fileChannel.read(buffer, 0); + final Future operation = fileChannel.read(buffer, 0); operation.get(); - String fileContent = new String(buffer.array()).trim(); + final String fileContent = new String(buffer.array()).trim(); buffer.clear(); assertEquals(fileContent, "baeldung.com"); @@ -36,18 +37,16 @@ public class AsyncFileIntegrationTest { @Test public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException { - Path path = Paths.get(URI.create(AsyncFileIntegrationTest.class.getResource("/file.txt").toString())); - AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ); + final Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString())); + final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ); - ByteBuffer buffer = ByteBuffer.allocate(1024); + final ByteBuffer buffer = ByteBuffer.allocate(1024); fileChannel.read(buffer, 0, buffer, new CompletionHandler() { - @Override public void completed(Integer result, ByteBuffer attachment) { // result is number of bytes read // attachment is the buffer - } @Override @@ -59,42 +58,40 @@ public class AsyncFileIntegrationTest { @Test public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException { - String fileName = "temp"; - Path path = Paths.get(fileName); - AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE); + final String fileName = "temp"; + final Path path = Paths.get(fileName); + final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE); - ByteBuffer buffer = ByteBuffer.allocate(1024); - long position = 0; + final ByteBuffer buffer = ByteBuffer.allocate(1024); + final long position = 0; buffer.put("hello world".getBytes()); buffer.flip(); - Future operation = fileChannel.write(buffer, position); + final Future operation = fileChannel.write(buffer, position); buffer.clear(); operation.get(); - String content = readContent(path); + final String content = readContent(path); assertEquals("hello world", content); } @Test public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException { - String fileName = UUID.randomUUID().toString(); - Path path = Paths.get(fileName); - AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); + final String fileName = UUID.randomUUID().toString(); + final Path path = Paths.get(fileName); + final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); - ByteBuffer buffer = ByteBuffer.allocate(1024); + final ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put("hello world".getBytes()); buffer.flip(); fileChannel.write(buffer, 0, buffer, new CompletionHandler() { - @Override public void completed(Integer result, ByteBuffer attachment) { // result is number of bytes written // attachment is the buffer - } @Override @@ -104,23 +101,25 @@ public class AsyncFileIntegrationTest { }); } - public static String readContent(Path file) throws ExecutionException, InterruptedException { + // + + private String readContent(Path file) throws ExecutionException, InterruptedException { AsynchronousFileChannel fileChannel = null; try { fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ); } catch (IOException e) { - // TODO Auto-generated catch block e.printStackTrace(); } - ByteBuffer buffer = ByteBuffer.allocate(1024); + final ByteBuffer buffer = ByteBuffer.allocate(1024); - Future operation = fileChannel.read(buffer, 0); + final Future operation = fileChannel.read(buffer, 0); operation.get(); - String fileContent = new String(buffer.array()).trim(); + final String fileContent = new String(buffer.array()).trim(); buffer.clear(); return fileContent; } + } \ No newline at end of file diff --git a/core-java/src/test/resources/file.txt b/core-java/src/test/resources/file.txt deleted file mode 100644 index 558d8bbf35..0000000000 --- a/core-java/src/test/resources/file.txt +++ /dev/null @@ -1 +0,0 @@ -baeldung.com \ No newline at end of file From 14bf9a24d55faf31579027ed8857647052877418 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 4 Mar 2018 17:29:04 +0200 Subject: [PATCH 43/91] testing work --- core-java-io/.gitignore | 1 + .../src/test/resources/copiedWithApacheCommons.txt | 0 core-java-io/src/test/resources/copiedWithIo.txt | 0 core-java-io/src/test/resources/copiedWithNio.txt | 0 .../src/test/resources/copyTest/dest/readme.txt | 2 ++ .../test/resources/copyTest/src/test_apache.txt | 1 + .../test/resources/copyTest/src/test_channel.txt | 1 + .../src/test/resources/copyTest/src/test_files.txt | 1 + .../test/resources/copyTest/src/test_stream.txt | 1 + core-java-io/src/test/resources/file.txt | 1 + core-java-io/src/test/resources/fileToRead.txt | 1 + core-java-io/src/test/resources/fileToWriteTo.txt | 0 core-java-io/src/test/resources/initialFile.txt | 1 + core-java-io/src/test/resources/original.txt | 0 core-java-io/src/test/resources/sample.txt | 1 + core-java-io/src/test/resources/targetFile.txt | 1 + core-java-io/src/test/resources/test_write.txt | 1 + core-java-io/src/test/resources/test_write_1.txt | Bin 0 -> 7 bytes core-java-io/src/test/resources/test_write_2.txt | Bin 0 -> 8 bytes core-java-io/src/test/resources/test_write_3.txt | 1 + core-java-io/src/test/resources/test_write_4.txt | Bin 0 -> 18 bytes core-java-io/src/test/resources/test_write_5.txt | 1 + 22 files changed, 15 insertions(+) create mode 100644 core-java-io/src/test/resources/copiedWithApacheCommons.txt create mode 100644 core-java-io/src/test/resources/copiedWithIo.txt create mode 100644 core-java-io/src/test/resources/copiedWithNio.txt create mode 100644 core-java-io/src/test/resources/copyTest/dest/readme.txt create mode 100644 core-java-io/src/test/resources/copyTest/src/test_apache.txt create mode 100644 core-java-io/src/test/resources/copyTest/src/test_channel.txt create mode 100644 core-java-io/src/test/resources/copyTest/src/test_files.txt create mode 100644 core-java-io/src/test/resources/copyTest/src/test_stream.txt create mode 100644 core-java-io/src/test/resources/file.txt create mode 100644 core-java-io/src/test/resources/fileToRead.txt create mode 100644 core-java-io/src/test/resources/fileToWriteTo.txt create mode 100644 core-java-io/src/test/resources/initialFile.txt create mode 100644 core-java-io/src/test/resources/original.txt create mode 100644 core-java-io/src/test/resources/sample.txt create mode 100644 core-java-io/src/test/resources/targetFile.txt create mode 100644 core-java-io/src/test/resources/test_write.txt create mode 100644 core-java-io/src/test/resources/test_write_1.txt create mode 100644 core-java-io/src/test/resources/test_write_2.txt create mode 100644 core-java-io/src/test/resources/test_write_3.txt create mode 100644 core-java-io/src/test/resources/test_write_4.txt create mode 100644 core-java-io/src/test/resources/test_write_5.txt diff --git a/core-java-io/.gitignore b/core-java-io/.gitignore index 13d4d1f833..c61d35324d 100644 --- a/core-java-io/.gitignore +++ b/core-java-io/.gitignore @@ -2,3 +2,4 @@ # Files generated by integration tests # *.txt +/temp \ No newline at end of file diff --git a/core-java-io/src/test/resources/copiedWithApacheCommons.txt b/core-java-io/src/test/resources/copiedWithApacheCommons.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java-io/src/test/resources/copiedWithIo.txt b/core-java-io/src/test/resources/copiedWithIo.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java-io/src/test/resources/copiedWithNio.txt b/core-java-io/src/test/resources/copiedWithNio.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java-io/src/test/resources/copyTest/dest/readme.txt b/core-java-io/src/test/resources/copyTest/dest/readme.txt new file mode 100644 index 0000000000..dfda31ee9f --- /dev/null +++ b/core-java-io/src/test/resources/copyTest/dest/readme.txt @@ -0,0 +1,2 @@ +files will be copied here and then deleted +remove `file.delete()` to see the files here diff --git a/core-java-io/src/test/resources/copyTest/src/test_apache.txt b/core-java-io/src/test/resources/copyTest/src/test_apache.txt new file mode 100644 index 0000000000..a6b651973d --- /dev/null +++ b/core-java-io/src/test/resources/copyTest/src/test_apache.txt @@ -0,0 +1 @@ +apache diff --git a/core-java-io/src/test/resources/copyTest/src/test_channel.txt b/core-java-io/src/test/resources/copyTest/src/test_channel.txt new file mode 100644 index 0000000000..6dca835871 --- /dev/null +++ b/core-java-io/src/test/resources/copyTest/src/test_channel.txt @@ -0,0 +1 @@ +channel diff --git a/core-java-io/src/test/resources/copyTest/src/test_files.txt b/core-java-io/src/test/resources/copyTest/src/test_files.txt new file mode 100644 index 0000000000..027271b9b2 --- /dev/null +++ b/core-java-io/src/test/resources/copyTest/src/test_files.txt @@ -0,0 +1 @@ +files diff --git a/core-java-io/src/test/resources/copyTest/src/test_stream.txt b/core-java-io/src/test/resources/copyTest/src/test_stream.txt new file mode 100644 index 0000000000..eac9b41cbe --- /dev/null +++ b/core-java-io/src/test/resources/copyTest/src/test_stream.txt @@ -0,0 +1 @@ +stream diff --git a/core-java-io/src/test/resources/file.txt b/core-java-io/src/test/resources/file.txt new file mode 100644 index 0000000000..558d8bbf35 --- /dev/null +++ b/core-java-io/src/test/resources/file.txt @@ -0,0 +1 @@ +baeldung.com \ No newline at end of file diff --git a/core-java-io/src/test/resources/fileToRead.txt b/core-java-io/src/test/resources/fileToRead.txt new file mode 100644 index 0000000000..45d73fa10d --- /dev/null +++ b/core-java-io/src/test/resources/fileToRead.txt @@ -0,0 +1 @@ +This is a content of the file \ No newline at end of file diff --git a/core-java-io/src/test/resources/fileToWriteTo.txt b/core-java-io/src/test/resources/fileToWriteTo.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java-io/src/test/resources/initialFile.txt b/core-java-io/src/test/resources/initialFile.txt new file mode 100644 index 0000000000..7d572d5b9d --- /dev/null +++ b/core-java-io/src/test/resources/initialFile.txt @@ -0,0 +1 @@ +With Commons IO \ No newline at end of file diff --git a/core-java-io/src/test/resources/original.txt b/core-java-io/src/test/resources/original.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java-io/src/test/resources/sample.txt b/core-java-io/src/test/resources/sample.txt new file mode 100644 index 0000000000..5e1c309dae --- /dev/null +++ b/core-java-io/src/test/resources/sample.txt @@ -0,0 +1 @@ +Hello World \ No newline at end of file diff --git a/core-java-io/src/test/resources/targetFile.txt b/core-java-io/src/test/resources/targetFile.txt new file mode 100644 index 0000000000..424a8d0d1e --- /dev/null +++ b/core-java-io/src/test/resources/targetFile.txt @@ -0,0 +1 @@ +Some textSome text \ No newline at end of file diff --git a/core-java-io/src/test/resources/test_write.txt b/core-java-io/src/test/resources/test_write.txt new file mode 100644 index 0000000000..a15aad69b5 --- /dev/null +++ b/core-java-io/src/test/resources/test_write.txt @@ -0,0 +1 @@ +Some StringProduct name is iPhone and its price is 1000 $ \ No newline at end of file diff --git a/core-java-io/src/test/resources/test_write_1.txt b/core-java-io/src/test/resources/test_write_1.txt new file mode 100644 index 0000000000000000000000000000000000000000..5727d54bfcb2046f4989fd13cf5dcf408201fa2a GIT binary patch literal 7 OcmZQz^+?Uh$p-)htO5D} literal 0 HcmV?d00001 diff --git a/core-java-io/src/test/resources/test_write_2.txt b/core-java-io/src/test/resources/test_write_2.txt new file mode 100644 index 0000000000000000000000000000000000000000..6a87dfc0750efb79469064e9dded8cea6c93d19c GIT binary patch literal 8 McmZQz00GuJ008a);s5{u literal 0 HcmV?d00001 diff --git a/core-java-io/src/test/resources/test_write_3.txt b/core-java-io/src/test/resources/test_write_3.txt new file mode 100644 index 0000000000..5e1c309dae --- /dev/null +++ b/core-java-io/src/test/resources/test_write_3.txt @@ -0,0 +1 @@ +Hello World \ No newline at end of file diff --git a/core-java-io/src/test/resources/test_write_4.txt b/core-java-io/src/test/resources/test_write_4.txt new file mode 100644 index 0000000000000000000000000000000000000000..f14fca61f68c0cb1d2cb39df0d7fd41a72805d21 GIT binary patch literal 18 ZcmZQ5VMt{tW+-7$V8~&}XGmtq1^^&e1Bw6u literal 0 HcmV?d00001 diff --git a/core-java-io/src/test/resources/test_write_5.txt b/core-java-io/src/test/resources/test_write_5.txt new file mode 100644 index 0000000000..5ab2f8a432 --- /dev/null +++ b/core-java-io/src/test/resources/test_write_5.txt @@ -0,0 +1 @@ +Hello \ No newline at end of file From d2a2a65566b928e9500097b3998f59f184ff87f8 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 4 Mar 2018 17:39:09 +0200 Subject: [PATCH 44/91] cleanup work --- libraries/helloWorld.docx | Bin 76887 -> 76893 bytes .../bouncycastle/BouncyCastleCrypto.java | 16 +- .../main/java/com/baeldung/bytebuddy/Bar.java | 13 +- .../main/java/com/baeldung/bytebuddy/Foo.java | 4 +- .../com/baeldung/caffeine/DataObject.java | 4 +- .../chronicle/queue/ChronicleQueue.java | 4 +- .../commons/beanutils/CourseEntity.java | 2 +- .../commons/beanutils/CourseService.java | 24 +- .../baeldung/commons/chain/AuditFilter.java | 2 +- .../commons/collectionutil/Customer.java | 2 +- .../com/baeldung/commons/dbutils/Email.java | 1 - .../commons/lang3/BuilderMethods.java | 28 +- .../commons/lang3/SampleLazyInitializer.java | 2 +- .../baeldung/commons/lang3/SampleObject.java | 4 +- .../java/com/baeldung/docx/Docx4jExample.java | 10 +- .../com/baeldung/fj/FunctionalJavaIOMain.java | 14 +- .../com/baeldung/fj/FunctionalJavaMain.java | 12 +- .../java/com/baeldung/flink/LineSplitter.java | 4 +- .../java/com/baeldung/flink/WordCount.java | 4 +- .../google/sheets/GoogleAuthorizeUtil.java | 16 +- .../google/sheets/SheetsServiceUtil.java | 5 +- .../googlehttpclientguide/GitHubExample.java | 25 +- .../googlehttpclientguide/GitHubUrl.java | 10 +- .../baeldung/googlehttpclientguide/User.java | 7 +- .../com/baeldung/hikaricp/DataSource.java | 29 +- .../com/baeldung/hikaricp/HikariCPDemo.java | 6 +- .../infinispan/CacheConfiguration.java | 24 +- .../infinispan/service/HelloWorldService.java | 9 +- .../service/TransactionalService.java | 6 +- .../java/com/baeldung/javasisst/Point.java | 1 - .../javasisst/ThreeDimensionalPoint.java | 1 - .../java/com/baeldung/javers/Address.java | 1 - .../baeldung/javers/PersonWithAddress.java | 1 - .../com/baeldung/jdeffered/FilterDemo.java | 4 +- .../java/com/baeldung/jdeffered/PipeDemo.java | 9 +- .../com/baeldung/jdeffered/PromiseDemo.java | 5 +- .../baeldung/jdeffered/ThreadSafeDemo.java | 4 +- .../DeferredManagerWithExecutorDemo.java | 4 +- .../manager/SimpleDeferredManagerDemo.java | 4 +- .../java/com/baeldung/jdo/GuideToJDO.java | 72 ++--- .../java/com/baeldung/jdo/query/MyApp.java | 53 ++-- .../com/baeldung/jdo/query/ProductItem.java | 15 +- .../com/baeldung/jdo/xml/AnnotadedPerson.java | 12 +- .../main/java/com/baeldung/jdo/xml/MyApp.java | 60 ++-- .../java/com/baeldung/jdo/xml/Person.java | 1 - .../java/com/baeldung/jdo/xml/Product.java | 23 +- .../com/baeldung/jetty/BlockingServlet.java | 1 - .../java/com/baeldung/jetty/JettyServer.java | 2 +- .../baeldung/jetty/JettyServerFactory.java | 126 +++++---- .../baeldung/jetty/LoggingRequestHandler.java | 261 +++++++++--------- .../com/baeldung/netty/ChannelHandlerB.java | 3 +- .../java/com/baeldung/netty/NettyServerB.java | 16 +- .../java/com/baeldung/netty/RequestData.java | 5 +- .../java/com/baeldung/netty/ResponseData.java | 4 +- .../java/com/baeldung/neuroph/NeurophXOR.java | 10 +- .../noexception/CustomExceptionHandler.java | 5 +- .../protonpack/StreamUtilsExample.java | 28 +- .../com/baeldung/quartz/QuartzExample.java | 40 +-- .../java/com/baeldung/quartz/SimpleJob.java | 3 +- .../retrofit/basic/GitHubBasicApi.java | 8 +- .../retrofit/basic/GitHubBasicApp.java | 3 +- .../retrofit/basic/GitHubBasicService.java | 26 +- .../baeldung/retrofit/models/Contributor.java | 13 +- .../baeldung/retrofit/models/Repository.java | 9 +- .../com/baeldung/retrofit/rx/GitHubRxApi.java | 8 +- .../com/baeldung/retrofit/rx/GitHubRxApp.java | 3 +- .../baeldung/retrofit/rx/GitHubRxService.java | 16 +- .../retrofitguide/GitHubServiceGenerator.java | 15 +- .../java/com/baeldung/retrofitguide/Main.java | 10 +- .../serenity/membership/Commodity.java | 2 +- .../baeldung/serenity/membership/Member.java | 12 +- .../serenity/membership/MemberGrade.java | 2 +- .../smooks/converter/OrderConverter.java | 1 - .../java/com/baeldung/smooks/model/Item.java | 19 +- .../com/baeldung/smooks/model/Supplier.java | 9 +- .../main/java/com/baeldung/stm/Account.java | 3 +- .../java/com/baeldung/streamex/StreamEX.java | 70 ++--- .../com/baeldung/streamutils/CopyStream.java | 18 +- .../com/baeldung/streamutils/DrainStream.java | 6 +- .../java/com/baeldung/tomcat/MyServlet.java | 5 +- .../baeldung/tomcat/ProgrammaticTomcat.java | 24 +- .../com/baeldung/yarg/DocumentController.java | 14 +- .../AsyncHttpClientTestCase.java | 9 +- .../AsyncServiceLongRunningUnitTest.java | 15 +- .../bouncycastle/BouncyCastleLiveTest.java | 7 +- .../baeldung/bytebuddy/ByteBuddyUnitTest.java | 43 +-- .../baeldung/caffeine/CaffeineUnitTest.java | 52 +--- .../proxy/BeanGeneratorIntegrationTest.java | 15 +- .../baeldung/cglib/proxy/MixinUnitTest.java | 9 +- .../cglib/proxy/ProxyIntegrationTest.java | 18 +- .../queue/ChronicleQueueIntegrationTest.java | 6 +- .../commons/beanutils/CourseServiceTest.java | 6 +- .../collections/CollectionUtilsGuideTest.java | 10 +- .../commons/collections/MapUtilsTest.java | 28 +- .../commons/collections/SetUtilsUnitTest.java | 3 +- .../orderedmap/OrderedMapUnitTest.java | 4 +- .../commons/collections4/BagTests.java | 58 ++-- .../commons/csv/CSVReaderWriterTest.java | 9 +- .../commons/dbutils/DbUtilsUnitTest.java | 20 +- .../commons/io/CommonsIOUnitTest.java | 74 ++--- .../commons/lang3/ArrayUtilsUnitTest.java | 62 ++--- .../commons/math/IntegrationTest.java | 2 +- .../commons/math/LinearAlgebraUnitTest.java | 4 +- .../commons/math/StatisticsUnitTest.java | 4 +- .../test/java/com/baeldung/crdt/CRDTTest.java | 40 ++- .../DistinctWithJavaFunctionUnitTest.java | 12 +- .../DistinctWithStreamexUnitTest.java | 8 +- .../distinct/DistinctWithVavrUnitTest.java | 8 +- .../baeldung/dockerapi/ContainerLiveTest.java | 108 +++----- .../dockerapi/DockerClientLiveTest.java | 41 +-- .../com/baeldung/dockerapi/ImageLiveTest.java | 67 ++--- .../baeldung/dockerapi/NetworkLiveTest.java | 41 +-- .../baeldung/dockerapi/VolumeLiveTest.java | 31 +-- .../CollectPatternTest.java | 3 +- .../ConvertContainerToAnotherTest.java | 3 +- .../eclipsecollections/DetectPatternTest.java | 3 +- .../eclipsecollections/FlatCollectTest.java | 3 +- .../InjectIntoPatternTest.java | 2 +- .../eclipsecollections/LazyIterationTest.java | 3 +- .../PartitionPatternTest.java | 12 +- .../eclipsecollections/RejectPatternTest.java | 6 +- .../eclipsecollections/SelectPatternTest.java | 12 +- .../baeldung/eclipsecollections/ZipTest.java | 3 +- .../eclipsecollections/ZipWithIndexTest.java | 3 +- .../com/baeldung/fj/FunctionalJavaTest.java | 50 ++-- .../flink/WordCountIntegrationTest.java | 95 +++---- .../sheets/GoogleSheetsIntegrationTest.java | 96 ++----- .../baeldung/hll/HLLLongRunningUnitTest.java | 34 +-- .../hoverfly/HoverflyApiIntegrationTest.java | 86 ++---- .../infinispan/ConfigurationTest.java | 19 +- .../service/HelloWorldServiceUnitTest.java | 39 +-- .../service/TransactionalServiceUnitTest.java | 5 +- .../com/baeldung/jasypt/JasyptUnitTest.java | 30 +- .../java/io/JavaDirectoryDeleteUnitTest.java | 5 +- .../baeldung/javassist/JavasisstUnitTest.java | 33 +-- .../javatuples/JavaTuplesUnitTest.java | 2 +- .../com/baeldung/javers/JaversUnitTest.java | 42 ++- .../com/baeldung/jcache/CacheLoaderTest.java | 6 +- .../baeldung/jcache/EntryProcessorTest.java | 3 +- .../baeldung/jcache/EventListenerTest.java | 6 +- ...heTest.java => JCacheIntegrationTest.java} | 2 +- .../jdo/GuideToJDOIntegrationTest.java | 1 - .../baeldung/jetty/JettyIntegrationTest.java | 9 +- .../jetty/JettyServerFactoryUnitTest.java | 118 ++++---- .../test/java/com/baeldung/jool/JOOLTest.java | 143 +++------- .../jsonassert/JsonAssertUnitTest.java | 28 +- .../junitparams/SafeAdditionUtilTest.java | 6 +- .../junitparams/TestDataProvider.java | 4 +- .../kafkastreams/KafkaStreamsLiveTest.java | 11 +- .../lsh/LocalSensitiveHashingUnitTest.java | 14 +- .../mbassador/MBassadorConfigurationTest.java | 4 +- .../baeldung/neuroph/XORIntegrationTest.java | 2 +- .../PactConsumerDrivenContractUnitTest.java | 45 +-- .../pairs/ApacheCommonsPairUnitTest.java | 1 - .../pairs/CoreJavaSimpleEntryUnitTest.java | 8 +- .../pcollections/PCollectionsUnitTest.java | 3 +- .../protonpack/CollectorUtilsTests.java | 19 +- .../baeldung/protonpack/StreamUtilsTests.java | 50 +--- .../basic/GitHubBasicApiLiveTest.java | 37 +-- .../baeldung/retrofit/rx/GitHubRxApiTest.java | 36 +-- .../serenity/GoogleSearchLiveTest.java | 8 +- .../github/GithubRestUserAPISteps.java | 5 +- .../membership/MemberStatusSteps.java | 2 +- .../pageobjects/GoogleSearchPageObject.java | 4 +- .../serenity/screenplay/GoogleSearchPage.java | 8 +- .../screenplay/GoogleSearchResults.java | 5 +- .../serenity/screenplay/SearchForKeyword.java | 9 +- .../serenity/screenplay/StartWith.java | 4 +- ...derClassDirtiesContextIntegrationTest.java | 8 +- ...xtDependencyWorkaroundIntegrationTest.java | 6 +- ...sContextInitWorkaroundIntegrationTest.java | 6 +- ...erMethodDirtiesContextIntegrationTest.java | 6 +- .../AdderMethodRuleIntegrationTest.java | 9 +- .../spring/AdderMockMvcIntegrationTest.java | 3 +- .../spring/AdderServiceIntegrationTest.java | 3 +- ...erSpringSerenityRunnerIntegrationTest.java | 6 +- .../baeldung/serenity/spring/AdderTest.java | 2 +- .../serenity/spring/steps/AdderRestSteps.java | 17 +- .../spring/steps/AdderServiceSteps.java | 3 +- .../serenity/spring/stories/AdderStory.java | 3 +- .../converter/SmooksIntegrationTest.java | 36 +-- .../java/com/baeldung/stm/AccountTest.java | 34 ++- .../baeldung/stream/JoolMergeStreamsTest.java | 13 +- .../com/baeldung/stream/MergeStreamsTest.java | 16 +- .../stream/StreamExMergeStreamsTest.java | 18 +- .../baeldung/streamutils/CopyStreamTest.java | 128 ++++----- .../test/java/com/baeldung/text/DiffTest.java | 4 +- .../text/LongestCommonSubsequenceTest.java | 6 +- .../com/baeldung/text/StrBuilderTest.java | 4 +- .../tomcat/ProgrammaticTomcatTest.java | 13 +- spring-5-reactive-client/pom.xml | 2 +- spring-5-reactive/pom.xml | 2 +- spring-boot/.factorypath | 183 ++++++------ 193 files changed, 1504 insertions(+), 2388 deletions(-) rename libraries/src/test/java/com/baeldung/jcache/{JCacheTest.java => JCacheIntegrationTest.java} (95%) diff --git a/libraries/helloWorld.docx b/libraries/helloWorld.docx index 6e0a372dad8c2da5c7739237c17315706b5b4ef2..28196dc241963b5a6c3a992cc19b883f0e95560a 100644 GIT binary patch delta 4369 zcmZ8lbyU>d)8D08S-QKWT}eT@r9nDGkQSCuI=+C?Al(wu-3^MQOG-#c2urtsG%UV6 z{?7Zp{+>B!&YhY2nK|>vy)$?2%q+&@ECy6d6&-^VgoA?vij20Zh1!GB@78*6F!LWF zv6hHDu>tKN@ab&kXIw(XyncsCZj=}SBsM)(;1@J3$q!|b%ENn0gktKDzkjFrGniESfC9D(M3HN$)Dj!3jo^~oGZsCKjCg}~ zdQ|$dumYqdw}*foydvP|Cbd9Flb%GYnB^8;=XI@BoNV7XNybo1@~#sKScaq|mrTF# z&rv52w=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Af?-l@KMrgOBznEb+f@HS*gKr5Kbu)Q2sZ z-#0lA#@;qNYdnq9iT!Kf4IRHi)U39GbTh+5JxX9R#6bldkzj4@$Y**qw}59C{-@*o z?s+1VP5=O~k^kRw4Nm~SO8^5~=>MMF(>3^kxIaKx066^zklg~x{Uf>slq9>>(fZT8 zrpH{f9DlPZHAiS1006jm?Va_S{%29AFWdsc|0w|X8uPv^wH|_sevZRX(0(poJ1%TJb{{l^B)` certList = new ArrayList(); CMSTypedData cmsData = new CMSProcessableByteArray(data); @@ -51,17 +50,14 @@ public class BouncyCastleCrypto { Store certs = new JcaCertStore(certList); CMSSignedDataGenerator cmsGenerator = new CMSSignedDataGenerator(); ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(signingKey); - cmsGenerator.addSignerInfoGenerator( - new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()) - .build(contentSigner, signingCertificate)); + cmsGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(contentSigner, signingCertificate)); cmsGenerator.addCertificates(certs); CMSSignedData cms = cmsGenerator.generate(cmsData, true); signedMessage = cms.getEncoded(); return signedMessage; } - public static boolean verifSignData(final byte[] signedData) - throws CMSException, IOException, OperatorCreationException, CertificateException { + public static boolean verifSignData(final byte[] signedData) throws CMSException, IOException, OperatorCreationException, CertificateException { ByteArrayInputStream bIn = new ByteArrayInputStream(signedData); ASN1InputStream aIn = new ASN1InputStream(bIn); CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); @@ -81,16 +77,14 @@ public class BouncyCastleCrypto { return true; } - public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate) - throws CertificateEncodingException, CMSException, IOException { + public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate) throws CertificateEncodingException, CMSException, IOException { byte[] encryptedData = null; if (null != data && null != encryptionCertificate) { CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator(); JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate); cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey); CMSTypedData msg = new CMSProcessableByteArray(data); - OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC") - .build(); + OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build(); CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor); encryptedData = cmsEnvelopedData.getEncoded(); } diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java b/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java index d0362a6c92..849e363c4b 100644 --- a/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java +++ b/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java @@ -5,12 +5,17 @@ import net.bytebuddy.implementation.bind.annotation.BindingPriority; public class Bar { @BindingPriority(3) - public static String sayHelloBar() { return "Holla in Bar!"; } + public static String sayHelloBar() { + return "Holla in Bar!"; + } @BindingPriority(2) - public static String sayBar() { return "bar"; } - - public String bar() { return Bar.class.getSimpleName() + " - Bar"; } + public static String sayBar() { + return "bar"; + } + public String bar() { + return Bar.class.getSimpleName() + " - Bar"; + } } diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java b/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java index 4be06785b1..9410fc6a13 100644 --- a/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java +++ b/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java @@ -2,6 +2,8 @@ package com.baeldung.bytebuddy; public class Foo { - public String sayHelloFoo() { return "Hello in Foo!"; } + public String sayHelloFoo() { + return "Hello in Foo!"; + } } diff --git a/libraries/src/main/java/com/baeldung/caffeine/DataObject.java b/libraries/src/main/java/com/baeldung/caffeine/DataObject.java index a90b3e9f21..65c4c6919f 100644 --- a/libraries/src/main/java/com/baeldung/caffeine/DataObject.java +++ b/libraries/src/main/java/com/baeldung/caffeine/DataObject.java @@ -19,9 +19,7 @@ final class DataObject { @Override public String toString() { - return "DataObject{" + - "data='" + data + '\'' + - '}'; + return "DataObject{" + "data='" + data + '\'' + '}'; } public static DataObject get(String data) { diff --git a/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java b/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java index f6bd25c0fe..354291ebd7 100644 --- a/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java +++ b/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java @@ -7,9 +7,7 @@ import net.openhft.chronicle.ExcerptAppender; public class ChronicleQueue { - static void writeToQueue( - Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue) - throws IOException { + static void writeToQueue(Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue) throws IOException { ExcerptAppender appender = chronicle.createAppender(); appender.startExcerpt(); appender.writeUTF(stringValue); diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java index 4a0b59404d..b88ee6624d 100644 --- a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java +++ b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java @@ -24,7 +24,7 @@ public class CourseEntity { public void setCodes(List codes) { this.codes = codes; } - + public void setStudent(String id, Student student) { students.put(id, student); } diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java index 1f566a782a..538fa3accb 100644 --- a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java +++ b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java @@ -8,33 +8,27 @@ import org.apache.commons.beanutils.PropertyUtils; public class CourseService { - public static void setValues(Course course, String name, List codes) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + public static void setValues(Course course, String name, List codes) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { // Setting the simple properties PropertyUtils.setSimpleProperty(course, "name", name); PropertyUtils.setSimpleProperty(course, "codes", codes); } - - public static void setIndexedValue(Course course, int codeIndex, String code) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + + public static void setIndexedValue(Course course, int codeIndex, String code) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { // Setting the indexed properties PropertyUtils.setIndexedProperty(course, "codes[" + codeIndex + "]", code); } - public static void setMappedValue(Course course, String enrollId, Student student) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + public static void setMappedValue(Course course, String enrollId, Student student) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { // Setting the mapped properties PropertyUtils.setMappedProperty(course, "enrolledStudent(" + enrollId + ")", student); } - - public static String getNestedValue(Course course, String enrollId, String nestedPropertyName) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { - return (String) PropertyUtils.getNestedProperty( - course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName); + + public static String getNestedValue(Course course, String enrollId, String nestedPropertyName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + return (String) PropertyUtils.getNestedProperty(course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName); } - - public static void copyProperties(Course course, CourseEntity courseEntity) - throws IllegalAccessException, InvocationTargetException { + + public static void copyProperties(Course course, CourseEntity courseEntity) throws IllegalAccessException, InvocationTargetException { BeanUtils.copyProperties(course, courseEntity); } } diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java b/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java index 973e2d498e..0acb222aa1 100644 --- a/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java +++ b/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java @@ -7,7 +7,7 @@ public class AuditFilter implements Filter { @Override public boolean postprocess(Context context, Exception exception) { - // Send notification to customer & bank. + // Send notification to customer & bank. return false; } diff --git a/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java b/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java index e22f13861e..1c6a8dc4f1 100644 --- a/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java +++ b/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java @@ -73,7 +73,7 @@ public class Customer implements Comparable { this.name = name; this.phone = phone; } - + public Customer(String name) { super(); this.name = name; diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java b/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java index c82798d52d..7f24230c43 100644 --- a/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java +++ b/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java @@ -20,7 +20,6 @@ public class Email { public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; } - public String getAddress() { return address; diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java b/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java index 35cae7426d..74e775383b 100644 --- a/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java +++ b/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java @@ -26,9 +26,7 @@ public class BuilderMethods { @Override public int hashCode() { - return new HashCodeBuilder().append(this.intValue) - .append(this.strSample) - .toHashCode(); + return new HashCodeBuilder().append(this.intValue).append(this.strSample).toHashCode(); } @Override @@ -41,16 +39,12 @@ public class BuilderMethods { } final BuilderMethods otherObject = (BuilderMethods) obj; - return new EqualsBuilder().append(this.intValue, otherObject.intValue) - .append(this.strSample, otherObject.strSample) - .isEquals(); + return new EqualsBuilder().append(this.intValue, otherObject.intValue).append(this.strSample, otherObject.strSample).isEquals(); } @Override public String toString() { - return new ToStringBuilder(this).append("INTVALUE", this.intValue) - .append("STRINGVALUE", this.strSample) - .toString(); + return new ToStringBuilder(this).append("INTVALUE", this.intValue).append("STRINGVALUE", this.strSample).toString(); } public static void main(final String[] arguments) { @@ -58,21 +52,21 @@ public class BuilderMethods { System.out.println(simple1.getName()); System.out.println(simple1.hashCode()); System.out.println(simple1.toString()); - + SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer(); - + try { sampleLazyInitializer.get(); } catch (ConcurrentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } - + SampleBackgroundInitializer sampleBackgroundInitializer = new SampleBackgroundInitializer(); sampleBackgroundInitializer.start(); - + // Proceed with other tasks instead of waiting for the SampleBackgroundInitializer task to finish. - + try { Object result = sampleBackgroundInitializer.get(); } catch (ConcurrentException e) { @@ -81,13 +75,13 @@ public class BuilderMethods { } } -class SampleBackgroundInitializer extends BackgroundInitializer{ +class SampleBackgroundInitializer extends BackgroundInitializer { @Override protected String initialize() throws Exception { return null; } - + // Any complex task that takes some time - + } diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java b/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java index 56a49d2659..52c6e9c9aa 100644 --- a/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java +++ b/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java @@ -3,7 +3,7 @@ package com.baeldung.commons.lang3; import org.apache.commons.lang3.concurrent.LazyInitializer; public class SampleLazyInitializer extends LazyInitializer { - + @Override protected SampleObject initialize() { return new SampleObject(); diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java b/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java index 0e61176732..4595f4c6d0 100644 --- a/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java +++ b/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java @@ -1,7 +1,7 @@ package com.baeldung.commons.lang3; public class SampleObject { - - //Ignored + + // Ignored } diff --git a/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java b/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java index d9c87b3889..97fbf4adc7 100644 --- a/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java +++ b/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java @@ -53,16 +53,12 @@ class Docx4jExample { File image = new File(imagePath); byte[] fileContent = Files.readAllBytes(image.toPath()); - BinaryPartAbstractImage imagePart = BinaryPartAbstractImage - .createImagePart(wordPackage, fileContent); - Inline inline = imagePart.createImageInline( - "Baeldung Image", "Alt Text", 1, 2, false); + BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordPackage, fileContent); + Inline inline = imagePart.createImageInline("Baeldung Image", "Alt Text", 1, 2, false); P Imageparagraph = addImageToParagraph(inline); mainDocumentPart.getContent().add(Imageparagraph); - int writableWidthTwips = wordPackage.getDocumentModel() - .getSections().get(0).getPageDimensions() - .getWritableWidthTwips(); + int writableWidthTwips = wordPackage.getDocumentModel().getSections().get(0).getPageDimensions().getWritableWidthTwips(); int columnNumber = 3; Tbl tbl = TblFactory.createTable(3, 3, writableWidthTwips / columnNumber); List rows = tbl.getContent(); diff --git a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java index ebf0fa4d2d..eaa201d1ba 100644 --- a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java +++ b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java @@ -7,7 +7,7 @@ import fj.data.IO; import fj.data.IOFunctions; public class FunctionalJavaIOMain { - + public static IO printLetters(final String s) { return () -> { for (int i = 0; i < s.length(); i++) { @@ -21,8 +21,7 @@ public class FunctionalJavaIOMain { F> printLetters = i -> printLetters(i); - IO lowerCase = IOFunctions - .stdoutPrintln("What's your first Name ?"); + IO lowerCase = IOFunctions.stdoutPrintln("What's your first Name ?"); IO input = IOFunctions.stdoutPrint("First Name: "); @@ -32,14 +31,11 @@ public class FunctionalJavaIOMain { F toUpperCase = i -> i.toUpperCase(); - F> transformInput = F1Functions - ., String> o(printLetters).f(toUpperCase); + F> transformInput = F1Functions., String> o(printLetters).f(toUpperCase); - IO readAndPrintResult = IOFunctions.bind(readInput, - transformInput); + IO readAndPrintResult = IOFunctions.bind(readInput, transformInput); - IO program = IOFunctions.bind(userInput, - nothing -> readAndPrintResult); + IO program = IOFunctions.bind(userInput, nothing -> readAndPrintResult); IOFunctions.toSafe(program).run(); diff --git a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java index e4d731454d..c6412f2923 100644 --- a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java +++ b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java @@ -11,16 +11,16 @@ import fj.function.Integers; public class FunctionalJavaMain { public static final F isEven = i -> i % 2 == 0; - + public static void main(String[] args) { - + List fList = List.list(3, 4, 5, 6); List evenList = fList.map(isEven); Show.listShow(Show.booleanShow).println(evenList); - + fList = fList.map(i -> i + 1); Show.listShow(Show.intShow).println(fList); - + Array a = Array.array(17, 44, 67, 2, 22, 80, 1, 27); Array b = a.filter(Integers.even); Show.arrayShow(Show.intShow).println(b); @@ -28,11 +28,11 @@ public class FunctionalJavaMain { Array array = Array.array("Welcome", "To", "baeldung"); Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); System.out.println(isExist); - + Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27); int sum = intArray.foldLeft(Integers.add, 0); System.out.println(sum); - + Option n1 = Option.some(1); Option n2 = Option.some(2); diff --git a/libraries/src/main/java/com/baeldung/flink/LineSplitter.java b/libraries/src/main/java/com/baeldung/flink/LineSplitter.java index 8deeeb01c4..f4e322f1e8 100644 --- a/libraries/src/main/java/com/baeldung/flink/LineSplitter.java +++ b/libraries/src/main/java/com/baeldung/flink/LineSplitter.java @@ -13,8 +13,6 @@ public class LineSplitter implements FlatMapFunction> out) { String[] tokens = value.toLowerCase().split("\\W+"); - Stream.of(tokens) - .filter(t -> t.length() > 0) - .forEach(token -> out.collect(new Tuple2<>(token, 1))); + Stream.of(tokens).filter(t -> t.length() > 0).forEach(token -> out.collect(new Tuple2<>(token, 1))); } } \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/flink/WordCount.java b/libraries/src/main/java/com/baeldung/flink/WordCount.java index ab109bdbce..fc5064bafa 100644 --- a/libraries/src/main/java/com/baeldung/flink/WordCount.java +++ b/libraries/src/main/java/com/baeldung/flink/WordCount.java @@ -12,9 +12,7 @@ public class WordCount { public static DataSet> startWordCount(ExecutionEnvironment env, List lines) throws Exception { DataSet text = env.fromCollection(lines); - return text.flatMap(new LineSplitter()) - .groupBy(0) - .aggregate(Aggregations.SUM, 1); + return text.flatMap(new LineSplitter()).groupBy(0).aggregate(Aggregations.SUM, 1); } } \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/google/sheets/GoogleAuthorizeUtil.java b/libraries/src/main/java/com/baeldung/google/sheets/GoogleAuthorizeUtil.java index 650a1d084c..641fae42dd 100644 --- a/libraries/src/main/java/com/baeldung/google/sheets/GoogleAuthorizeUtil.java +++ b/libraries/src/main/java/com/baeldung/google/sheets/GoogleAuthorizeUtil.java @@ -20,21 +20,13 @@ import com.google.api.services.sheets.v4.SheetsScopes; public class GoogleAuthorizeUtil { public static Credential authorize() throws IOException, GeneralSecurityException { InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("/google-sheets-client-secret.json"); - GoogleClientSecrets clientSecrets = GoogleClientSecrets - .load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in)); + GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in)); List scopes = Arrays.asList(SheetsScopes.SPREADSHEETS); - GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow - .Builder(GoogleNetHttpTransport.newTrustedTransport(), - JacksonFactory.getDefaultInstance(), - clientSecrets, - scopes) - .setDataStoreFactory(new MemoryDataStoreFactory()) - .setAccessType("offline") - .build(); - Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()) - .authorize("user"); + GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets, scopes).setDataStoreFactory(new MemoryDataStoreFactory()) + .setAccessType("offline").build(); + Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); return credential; } diff --git a/libraries/src/main/java/com/baeldung/google/sheets/SheetsServiceUtil.java b/libraries/src/main/java/com/baeldung/google/sheets/SheetsServiceUtil.java index bbce96f389..8a78d50551 100644 --- a/libraries/src/main/java/com/baeldung/google/sheets/SheetsServiceUtil.java +++ b/libraries/src/main/java/com/baeldung/google/sheets/SheetsServiceUtil.java @@ -14,10 +14,7 @@ public class SheetsServiceUtil { public static Sheets getSheetsService() throws IOException, GeneralSecurityException { Credential credential = GoogleAuthorizeUtil.authorize(); - return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), - JacksonFactory.getDefaultInstance(), credential) - .setApplicationName(APPLICATION_NAME) - .build(); + return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential).setApplicationName(APPLICATION_NAME).build(); } } diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java index 0618a7294d..3b2c58d1e1 100644 --- a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java @@ -21,30 +21,23 @@ import java.util.concurrent.Future; public class GitHubExample { static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); - //static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport(); + // static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport(); static final JsonFactory JSON_FACTORY = new JacksonFactory(); - //static final JsonFactory JSON_FACTORY = new GsonFactory(); + // static final JsonFactory JSON_FACTORY = new GsonFactory(); private static void run() throws Exception { - HttpRequestFactory requestFactory - = HTTP_TRANSPORT.createRequestFactory( - (HttpRequest request) -> { - request.setParser(new JsonObjectParser(JSON_FACTORY)); - }); + HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory((HttpRequest request) -> { + request.setParser(new JsonObjectParser(JSON_FACTORY)); + }); GitHubUrl url = new GitHubUrl("https://api.github.com/users"); url.per_page = 10; url.page = 1; HttpRequest request = requestFactory.buildGetRequest(url); - ExponentialBackOff backoff = new ExponentialBackOff.Builder() - .setInitialIntervalMillis(500) - .setMaxElapsedTimeMillis(900000) - .setMaxIntervalMillis(6000) - .setMultiplier(1.5) - .setRandomizationFactor(0.5) - .build(); + ExponentialBackOff backoff = new ExponentialBackOff.Builder().setInitialIntervalMillis(500).setMaxElapsedTimeMillis(900000).setMaxIntervalMillis(6000).setMultiplier(1.5).setRandomizationFactor(0.5).build(); request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff)); - Type type = new TypeToken>() {}.getType(); - List users = (List)request.execute().parseAs(type); + Type type = new TypeToken>() { + }.getType(); + List users = (List) request.execute().parseAs(type); System.out.println(users); url.appendRawPath("/eugenp"); request = requestFactory.buildGetRequest(url); diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java index c44de1e145..ea1b83e9fb 100644 --- a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java @@ -3,16 +3,16 @@ package com.baeldung.googlehttpclientguide; import com.google.api.client.http.GenericUrl; import com.google.api.client.util.Key; -public class GitHubUrl extends GenericUrl{ +public class GitHubUrl extends GenericUrl { public GitHubUrl(String encodedUrl) { super(encodedUrl); - } - + } + @Key public int per_page; - + @Key public int page; - + } diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java index bf4ee96b25..88361e158e 100644 --- a/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java @@ -16,7 +16,7 @@ public class User extends GenericJson { private String blog; @Key private String email; - + @Key("subscriptions_url") private String subscriptionsUrl; @@ -71,7 +71,6 @@ public class User extends GenericJson { @Override public String toString() { return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}'; - } - - + } + } diff --git a/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java b/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java index ff4bc939aa..d96c0eb107 100644 --- a/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java +++ b/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java @@ -14,15 +14,15 @@ public class DataSource { private static HikariDataSource ds; static { -// config = new HikariConfig("datasource.properties"); - -// Properties props = new Properties(); -// props.setProperty("dataSourceClassName", "org.h2.Driver"); -// props.setProperty("dataSource.user", ""); -// props.setProperty("dataSource.password", ""); -// props.put("dataSource.logWriter", new PrintWriter(System.out)); -// config = new HikariConfig(props); - + // config = new HikariConfig("datasource.properties"); + + // Properties props = new Properties(); + // props.setProperty("dataSourceClassName", "org.h2.Driver"); + // props.setProperty("dataSource.user", ""); + // props.setProperty("dataSource.password", ""); + // props.put("dataSource.logWriter", new PrintWriter(System.out)); + // config = new HikariConfig(props); + config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'"); config.setUsername(""); config.setPassword(""); @@ -30,13 +30,14 @@ public class DataSource { config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); ds = new HikariDataSource(config); - -// ds.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'"); -// ds.setUsername(""); -// ds.setPassword(""); + + // ds.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'"); + // ds.setUsername(""); + // ds.setPassword(""); } - private DataSource() {} + private DataSource() { + } public static Connection getConnection() throws SQLException { return ds.getConnection(); diff --git a/libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java b/libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java index af36ab7508..57d124fd5d 100644 --- a/libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java +++ b/libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java @@ -12,9 +12,7 @@ public class HikariCPDemo { public static List fetchData() { final String SQL_QUERY = "select * from emp"; List employees = null; - try (Connection con = DataSource.getConnection(); - PreparedStatement pst = con.prepareStatement(SQL_QUERY); - ResultSet rs = pst.executeQuery();) { + try (Connection con = DataSource.getConnection(); PreparedStatement pst = con.prepareStatement(SQL_QUERY); ResultSet rs = pst.executeQuery();) { employees = new ArrayList(); Employee employee; while (rs.next()) { @@ -38,5 +36,5 @@ public class HikariCPDemo { public static void main(String[] args) { fetchData(); } - + } diff --git a/libraries/src/main/java/com/baeldung/infinispan/CacheConfiguration.java b/libraries/src/main/java/com/baeldung/infinispan/CacheConfiguration.java index 58929c0111..eda511d7a7 100644 --- a/libraries/src/main/java/com/baeldung/infinispan/CacheConfiguration.java +++ b/libraries/src/main/java/com/baeldung/infinispan/CacheConfiguration.java @@ -43,8 +43,7 @@ public class CacheConfiguration { return this.buildCache(PASSIVATING_HELLO_WORLD_CACHE, cacheManager, listener, passivatingConfiguration()); } - private Cache buildCache(String cacheName, DefaultCacheManager cacheManager, - CacheListener listener, Configuration configuration) { + private Cache buildCache(String cacheName, DefaultCacheManager cacheManager, CacheListener listener, Configuration configuration) { cacheManager.defineConfiguration(cacheName, configuration); Cache cache = cacheManager.getCache(cacheName); @@ -53,32 +52,19 @@ public class CacheConfiguration { } private Configuration expiringConfiguration() { - return new ConfigurationBuilder().expiration().lifespan(1, TimeUnit.SECONDS) - .build(); + return new ConfigurationBuilder().expiration().lifespan(1, TimeUnit.SECONDS).build(); } private Configuration evictingConfiguration() { - return new ConfigurationBuilder() - .memory().evictionType(EvictionType.COUNT).size(1) - .build(); + return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).build(); } private Configuration passivatingConfiguration() { - return new ConfigurationBuilder() - .memory().evictionType(EvictionType.COUNT).size(1) - .persistence() - .passivation(true) - .addSingleFileStore() - .purgeOnStartup(true) - .location(System.getProperty("java.io.tmpdir")) - .build(); + return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).persistence().passivation(true).addSingleFileStore().purgeOnStartup(true).location(System.getProperty("java.io.tmpdir")).build(); } private Configuration transactionalConfiguration() { - return new ConfigurationBuilder() - .transaction().transactionMode(TransactionMode.TRANSACTIONAL) - .lockingMode(LockingMode.PESSIMISTIC) - .build(); + return new ConfigurationBuilder().transaction().transactionMode(TransactionMode.TRANSACTIONAL).lockingMode(LockingMode.PESSIMISTIC).build(); } } diff --git a/libraries/src/main/java/com/baeldung/infinispan/service/HelloWorldService.java b/libraries/src/main/java/com/baeldung/infinispan/service/HelloWorldService.java index 3ecefcc21a..de30cd5c8e 100644 --- a/libraries/src/main/java/com/baeldung/infinispan/service/HelloWorldService.java +++ b/libraries/src/main/java/com/baeldung/infinispan/service/HelloWorldService.java @@ -15,11 +15,8 @@ public class HelloWorldService { private final Cache evictingHelloWorldCache; private final Cache passivatingHelloWorldCache; - public HelloWorldService(HelloWorldRepository repository, CacheListener listener, - Cache simpleHelloWorldCache, - Cache expiringHelloWorldCache, - Cache evictingHelloWorldCache, - Cache passivatingHelloWorldCache) { + public HelloWorldService(HelloWorldRepository repository, CacheListener listener, Cache simpleHelloWorldCache, Cache expiringHelloWorldCache, Cache evictingHelloWorldCache, + Cache passivatingHelloWorldCache) { this.repository = repository; @@ -66,7 +63,7 @@ public class HelloWorldService { public String findEvictingHelloWorld(String key) { String value = evictingHelloWorldCache.get(key); - if(value == null) { + if (value == null) { value = repository.getHelloWorld(); evictingHelloWorldCache.put(key, value); } diff --git a/libraries/src/main/java/com/baeldung/infinispan/service/TransactionalService.java b/libraries/src/main/java/com/baeldung/infinispan/service/TransactionalService.java index b0dbf5475f..26862b8d65 100644 --- a/libraries/src/main/java/com/baeldung/infinispan/service/TransactionalService.java +++ b/libraries/src/main/java/com/baeldung/infinispan/service/TransactionalService.java @@ -28,8 +28,7 @@ public class TransactionalService { watch.start(); transactionalCache.put(KEY, howManyVisits); watch.stop(); - System.out.println("I was able to set HowManyVisits to " + howManyVisits + - " after waiting " + watch.getTotalTimeSeconds() + " seconds"); + System.out.println("I was able to set HowManyVisits to " + howManyVisits + " after waiting " + watch.getTotalTimeSeconds() + " seconds"); tm.commit(); return howManyVisits; @@ -44,8 +43,7 @@ public class TransactionalService { TransactionManager tm = transactionalCache.getAdvancedCache().getTransactionManager(); tm.begin(); transactionalCache.put(KEY, 1000); - System.out.println("HowManyVisits should now be 1000, " + - "but we are holding the transaction"); + System.out.println("HowManyVisits should now be 1000, " + "but we are holding the transaction"); Thread.sleep(1000L); tm.rollback(); System.out.println("The slow batch suffered a rollback"); diff --git a/libraries/src/main/java/com/baeldung/javasisst/Point.java b/libraries/src/main/java/com/baeldung/javasisst/Point.java index 7e5c1cedd5..7f10e8c371 100644 --- a/libraries/src/main/java/com/baeldung/javasisst/Point.java +++ b/libraries/src/main/java/com/baeldung/javasisst/Point.java @@ -1,6 +1,5 @@ package com.baeldung.javasisst; - public class Point { public int x = 0; public int y = 0; diff --git a/libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java b/libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java index fb24d4b85d..780604738e 100644 --- a/libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java +++ b/libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java @@ -1,6 +1,5 @@ package com.baeldung.javasisst; - public class ThreeDimensionalPoint { public int x = 0; public int y = 0; diff --git a/libraries/src/main/java/com/baeldung/javers/Address.java b/libraries/src/main/java/com/baeldung/javers/Address.java index 14f5907ef6..9b0c119046 100644 --- a/libraries/src/main/java/com/baeldung/javers/Address.java +++ b/libraries/src/main/java/com/baeldung/javers/Address.java @@ -1,6 +1,5 @@ package com.baeldung.javers; - public class Address { private String country; diff --git a/libraries/src/main/java/com/baeldung/javers/PersonWithAddress.java b/libraries/src/main/java/com/baeldung/javers/PersonWithAddress.java index 0b4e33fcb5..16be083d83 100644 --- a/libraries/src/main/java/com/baeldung/javers/PersonWithAddress.java +++ b/libraries/src/main/java/com/baeldung/javers/PersonWithAddress.java @@ -1,6 +1,5 @@ package com.baeldung.javers; - import java.util.List; public class PersonWithAddress { diff --git a/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java index ec2c52d3b5..8da601b0cf 100644 --- a/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java +++ b/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java @@ -7,9 +7,9 @@ import org.jdeferred.impl.DeferredObject; class FilterDemo { private static String modifiedMsg; - + static String filter(String msg) { - + Deferred d = new DeferredObject<>(); Promise p = d.promise(); Promise filtered = p.then((result) -> { diff --git a/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java index 95250cff76..94fe0b70a6 100644 --- a/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java +++ b/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java @@ -19,14 +19,11 @@ class PipeDemo { p.then((DonePipe) result -> { if (result < 90) { - return new DeferredObject() - .resolve(result); + return new DeferredObject().resolve(result); } else { - return new DeferredObject() - .reject(new Exception("Unacceptable value")); + return new DeferredObject().reject(new Exception("Unacceptable value")); } - }).done(r -> status = Result.SUCCESS) - .fail(r -> status = Result.FAILURE); + }).done(r -> status = Result.SUCCESS).fail(r -> status = Result.FAILURE); d.resolve(num); diff --git a/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java index 2a9f83dc35..4efb1ad997 100644 --- a/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java +++ b/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java @@ -11,10 +11,7 @@ class PromiseDemo { Deferred deferred = new DeferredObject<>(); Promise promise = deferred.promise(); - promise.done(result -> System.out.println("Job done")) - .fail(rejection -> System.out.println("Job fail")) - .progress(progress -> System.out.println("Job is in progress")) - .always((state, result, rejection) -> System.out.println("Job execution started")); + promise.done(result -> System.out.println("Job done")).fail(rejection -> System.out.println("Job fail")).progress(progress -> System.out.println("Job is in progress")).always((state, result, rejection) -> System.out.println("Job execution started")); deferred.resolve(jobName); // deferred.notify(""); diff --git a/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java index 22fd51ed92..c48b916b4b 100644 --- a/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java +++ b/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java @@ -12,9 +12,7 @@ public class ThreadSafeDemo { DeferredManager dm = new DefaultDeferredManager(); Deferred deferred = new DeferredObject<>(); Promise p1 = deferred.promise(); - Promise p = dm.when(p1) - .done(r -> System.out.println("done")) - .fail(r -> System.out.println("fail")); + Promise p = dm.when(p1).done(r -> System.out.println("done")).fail(r -> System.out.println("fail")); synchronized (p) { while (p.isPending()) { diff --git a/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java index 2abe9bc10f..68a113d6a2 100644 --- a/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java +++ b/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java @@ -16,9 +16,7 @@ class DeferredManagerWithExecutorDemo { Deferred deferred = new DeferredObject<>(); DeferredManager dm = new DefaultDeferredManager(executor); Promise p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise(); - dm.when(p1, p2, p3) - .done(r -> System.out.println("done")) - .fail(r -> System.out.println("fail")); + dm.when(p1, p2, p3).done(r -> System.out.println("done")).fail(r -> System.out.println("fail")); deferred.resolve("done"); } } diff --git a/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java index dc2e82495f..e1ffa3b6bc 100644 --- a/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java +++ b/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java @@ -7,8 +7,6 @@ class SimpleDeferredManagerDemo { public static void initiate() { DeferredManager dm = new DefaultDeferredManager(); - dm.when(() -> 1) - .done(r -> System.out.println("done")) - .fail(Throwable::printStackTrace); + dm.when(() -> 1).done(r -> System.out.println("done")).fail(Throwable::printStackTrace); } } diff --git a/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java b/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java index 387c8c4e00..bd459f963c 100644 --- a/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java +++ b/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java @@ -42,8 +42,8 @@ public class GuideToJDO { listXMLProducts(); } - public void CreateH2Properties(){ - + public void CreateH2Properties() { + pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); pumd.addClassName("com.baeldung.jdo.Product"); pumd.setExcludeUnlistedClasses(); @@ -51,18 +51,18 @@ public class GuideToJDO { pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence"); pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa"); pumd.addProperty("javax.jdo.option.ConnectionPassword", ""); - pumd.addProperty("datanucleus.autoCreateSchema", "true"); - + pumd.addProperty("datanucleus.autoCreateSchema", "true"); + } - - public void CreateXMLProperties(){ + + public void CreateXMLProperties() { pumdXML = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); pumdXML.addClassName("com.baeldung.jdo.ProductXML"); pumdXML.setExcludeUnlistedClasses(); pumdXML.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myPersistence.xml"); - pumdXML.addProperty("datanucleus.autoCreateSchema", "true"); + pumdXML.addProperty("datanucleus.autoCreateSchema", "true"); } - + public void CreateProducts() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); @@ -91,7 +91,7 @@ public class GuideToJDO { } @SuppressWarnings("rawtypes") - public void UpdateProducts(){ + public void UpdateProducts() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); @@ -105,13 +105,13 @@ public class GuideToJDO { } finally { if (tx.isActive()) { tx.rollback(); - } + } pm.close(); } } - + @SuppressWarnings("rawtypes") - public void DeleteProducts(){ + public void DeleteProducts() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); @@ -125,11 +125,11 @@ public class GuideToJDO { } finally { if (tx.isActive()) { tx.rollback(); - } + } pm.close(); } } - + @SuppressWarnings({ "rawtypes", "unchecked" }) public void ListProducts() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); @@ -155,9 +155,9 @@ public class GuideToJDO { pm.close(); } } - + @SuppressWarnings({ "rawtypes", "unchecked" }) - public void QueryJDOQL (){ + public void QueryJDOQL() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); @@ -177,7 +177,7 @@ public class GuideToJDO { LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price }); } LOGGER.log(Level.INFO, "--------------------------------------------------------------"); - + tx.commit(); } finally { if (tx.isActive()) { @@ -187,28 +187,28 @@ public class GuideToJDO { pm.close(); } } - + @SuppressWarnings({ "rawtypes", "unchecked" }) - public void QuerySQL (){ + public void QuerySQL() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); - //SQL : + // SQL : LOGGER.log(Level.INFO, "SQL --------------------------------------------------------------"); Query query = pm.newQuery("javax.jdo.query.SQL", "SELECT * FROM PRODUCT"); query.setClass(Product.class); List results = query.executeList(); - + Iterator iter = results.iterator(); while (iter.hasNext()) { Product p = iter.next(); LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price }); } LOGGER.log(Level.INFO, "--------------------------------------------------------------"); - + tx.commit(); } finally { if (tx.isActive()) { @@ -218,27 +218,27 @@ public class GuideToJDO { pm.close(); } } - + @SuppressWarnings({ "rawtypes", "unchecked" }) - public void QueryJPQL (){ + public void QueryJPQL() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); - //JPQL : + // JPQL : LOGGER.log(Level.INFO, "JPQL --------------------------------------------------------------"); - Query q = pm.newQuery("JPQL", "SELECT p FROM "+Product.class.getName()+" p WHERE p.name = 'Laptop'"); - List results = (List)q.execute(); - + Query q = pm.newQuery("JPQL", "SELECT p FROM " + Product.class.getName() + " p WHERE p.name = 'Laptop'"); + List results = (List) q.execute(); + Iterator iter = results.iterator(); while (iter.hasNext()) { Product p = iter.next(); LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price }); } LOGGER.log(Level.INFO, "--------------------------------------------------------------"); - + tx.commit(); } finally { if (tx.isActive()) { @@ -248,18 +248,18 @@ public class GuideToJDO { pm.close(); } } - - public void persistXML(){ + + public void persistXML() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); - ProductXML productXML = new ProductXML(0,"Tablet", 80.0); + ProductXML productXML = new ProductXML(0, "Tablet", 80.0); pm.makePersistent(productXML); - ProductXML productXML2 = new ProductXML(1,"Phone", 20.0); + ProductXML productXML2 = new ProductXML(1, "Phone", 20.0); pm.makePersistent(productXML2); - ProductXML productXML3 = new ProductXML(2,"Laptop", 200.0); + ProductXML productXML3 = new ProductXML(2, "Laptop", 200.0); pm.makePersistent(productXML3); tx.commit(); } finally { @@ -269,9 +269,9 @@ public class GuideToJDO { pm.close(); } } - + @SuppressWarnings({ "rawtypes", "unchecked" }) - public void listXMLProducts(){ + public void listXMLProducts() { PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); diff --git a/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java b/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java index 384dde48d1..c902083e62 100644 --- a/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java +++ b/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java @@ -26,19 +26,19 @@ public class MyApp { } - public static void createTestData(){ - ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut",5); - ProductItem item2 = new ProductItem("pro2", "price less than 10","InStock", 8); - ProductItem item3 = new ProductItem("pro3", "price more than 10","SoldOut", 15); + public static void createTestData() { + ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut", 5); + ProductItem item2 = new ProductItem("pro2", "price less than 10", "InStock", 8); + ProductItem item3 = new ProductItem("pro3", "price more than 10", "SoldOut", 15); - if( pm != null ){ + if (pm != null) { pm.makePersistent(item1); pm.makePersistent(item2); - pm.makePersistent(item3); + pm.makePersistent(item3); } } - public static void defineDynamicPersistentUnit(){ + public static void defineDynamicPersistentUnit() { PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:mysql://localhost:3306/jdo_db"); @@ -51,53 +51,46 @@ public class MyApp { pm = pmf.getPersistenceManager(); } - public static void queryUsingJDOQL(){ + public static void queryUsingJDOQL() { - Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " - + "WHERE price < threshold PARAMETERS double threshold"); - List explicitParamResults = (List)query.execute(10); + Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " + "WHERE price < threshold PARAMETERS double threshold"); + List explicitParamResults = (List) query.execute(10); - query = pm.newQuery("SELECT FROM " - + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); + query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); query.setParameters("double threshold"); - List explicitParamResults2 = (List)query.execute(10); + List explicitParamResults2 = (List) query.execute(10); - query = pm.newQuery("SELECT FROM " - + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); - List implicitParamResults = (List)query.execute(10); + query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); + List implicitParamResults = (List) query.execute(10); } - public static void queryUsingTypedJDOQL(){ + public static void queryUsingTypedJDOQL() { JDOQLTypedQuery tq = pm.newJDOQLTypedQuery(ProductItem.class); QProductItem cand = QProductItem.candidate(); - tq=tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro"))); + tq = tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro"))); List results = tq.executeList(); } - public static void queryUsingSQL(){ + public static void queryUsingSQL() { - Query query = pm.newQuery("javax.jdo.query.SQL","select * from " - + "product_item where price < ? and status = ?"); + Query query = pm.newQuery("javax.jdo.query.SQL", "select * from " + "product_item where price < ? and status = ?"); query.setClass(ProductItem.class); - query.setParameters(10,"InStock"); + query.setParameters(10, "InStock"); List results = query.executeList(); } - public static void queryUsingJPQL(){ - Query query = pm.newQuery("JPQL","select i from " - + "com.baeldung.jdo.query.ProductItem i where i.price < 10" - + " and i.status = 'InStock'"); + public static void queryUsingJPQL() { + Query query = pm.newQuery("JPQL", "select i from " + "com.baeldung.jdo.query.ProductItem i where i.price < 10" + " and i.status = 'InStock'"); List results = (List) query.execute(); } - public static void namedQuery(){ - Query query = pm.newNamedQuery( - ProductItem.class, "PriceBelow10"); + public static void namedQuery() { + Query query = pm.newNamedQuery(ProductItem.class, "PriceBelow10"); List results = query.executeList(); } diff --git a/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java b/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java index 52221a7d97..3343febb89 100644 --- a/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java +++ b/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java @@ -10,25 +10,24 @@ import javax.jdo.annotations.PrimaryKey; public class ProductItem { @PrimaryKey - @Persistent(valueStrategy=IdGeneratorStrategy.INCREMENT) + @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT) int id; String name; String description; String status; double price; - public ProductItem(){ + public ProductItem() { } - public ProductItem(String name,String description,String status,double price){ - this.name=name; + public ProductItem(String name, String description, String status, double price) { + this.name = name; this.description = description; this.status = status; this.price = price; } - public int getId() { return id; } @@ -40,18 +39,23 @@ public class ProductItem { public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + public double getPrice() { return price; } + public void setPrice(double price) { this.price = price; } @@ -64,5 +68,4 @@ public class ProductItem { this.status = status; } - } diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java b/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java index 53e86524a5..d2518586b4 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java +++ b/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java @@ -12,10 +12,7 @@ import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; -@PersistenceCapable( - schema="/myproduct/people", - table="person" - ) +@PersistenceCapable(schema = "/myproduct/people", table = "person") public class AnnotadedPerson { @XmlAttribute private long personNum; @@ -24,12 +21,11 @@ public class AnnotadedPerson { private String firstName; private String lastName; - @XmlElementWrapper(name="phone-numbers") - @XmlElement(name="phone-number") - @Element(types=String.class) + @XmlElementWrapper(name = "phone-numbers") + @XmlElement(name = "phone-number") + @Element(types = String.class) private List phoneNumbers = new ArrayList(); - public AnnotadedPerson(long personNum, String firstName, String lastName) { super(); this.personNum = personNum; diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java b/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java index 97ec49eec1..c75d3695f7 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java +++ b/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java @@ -17,35 +17,35 @@ public class MyApp { private static PersistenceManagerFactory pmf; private static PersistenceManager pm; - public static void main( String[] args ) { - - //persist product object using dynamic persistence unit + public static void main(String[] args) { + + // persist product object using dynamic persistence unit defineDynamicPersistentUnit(); - Product product = new Product("id1","Sony Discman", "A standard discman from Sony", 49.99); + Product product = new Product("id1", "Sony Discman", "A standard discman from Sony", 49.99); persistObject(product); closePersistenceManager(); - - //persist AnnotatedPerson object using named pmf + + // persist AnnotatedPerson object using named pmf defineNamedPersistenceManagerFactory("XmlDatastore"); - AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320,"annotated","person"); + AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320, "annotated", "person"); annotatedPerson.getPhoneNumbers().add("999999999"); annotatedPerson.getPhoneNumbers().add("000000000"); persistObject(annotatedPerson); queryAnnotatedPersonsInXML(); closePersistenceManager(); - - //persist Person object using PMF created by properties file + + // persist Person object using PMF created by properties file definePersistenceManagerFactoryUsingPropertiesFile("META-INF\\datanucleus.properties"); - Person person = new Person(654321,"bealdung","author"); + Person person = new Person(654321, "bealdung", "author"); person.getPhoneNumbers().add("123456789"); person.getPhoneNumbers().add("987654321"); persistObject(person); queryPersonsInXML(); closePersistenceManager(); - } + } + + public static void defineDynamicPersistentUnit() { - public static void defineDynamicPersistentUnit(){ - PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml"); pumd.addProperty("datanucleus.schema.autoCreateAll", "true"); @@ -55,27 +55,27 @@ public class MyApp { pm = pmf.getPersistenceManager(); } - public static void defineNamedPersistenceManagerFactory(String pmfName){ - + public static void defineNamedPersistenceManagerFactory(String pmfName) { + pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore"); pm = pmf.getPersistenceManager(); } - public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath){ - + public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath) { + pmf = JDOHelper.getPersistenceManagerFactory(filePath); pm = pmf.getPersistenceManager(); } - public static void closePersistenceManager(){ - - if(pm!=null && !pm.isClosed()){ + public static void closePersistenceManager() { + + if (pm != null && !pm.isClosed()) { pm.close(); } } - public static void persistObject(Object obj){ - + public static void persistObject(Object obj) { + Transaction tx = pm.currentTransaction(); try { @@ -88,18 +88,18 @@ public class MyApp { } } } - - public static void queryPersonsInXML(){ - + + public static void queryPersonsInXML() { + Query query = pm.newQuery(Person.class); List result = query.executeList(); - System.out.println("name: "+result.get(0).getFirstName()); + System.out.println("name: " + result.get(0).getFirstName()); } - - public static void queryAnnotatedPersonsInXML(){ - + + public static void queryAnnotatedPersonsInXML() { + Query query = pm.newQuery(AnnotadedPerson.class); List result = query.executeList(); - System.out.println("name: "+result.get(0).getFirstName()); + System.out.println("name: " + result.get(0).getFirstName()); } } diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/Person.java b/libraries/src/main/java/com/baeldung/jdo/xml/Person.java index e3ec5c6bab..b5750a2069 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/Person.java +++ b/libraries/src/main/java/com/baeldung/jdo/xml/Person.java @@ -12,7 +12,6 @@ import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; - @PersistenceCapable public class Person { private long personNum; diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/Product.java b/libraries/src/main/java/com/baeldung/jdo/xml/Product.java index d8d3bb17b2..83eed50624 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/Product.java +++ b/libraries/src/main/java/com/baeldung/jdo/xml/Product.java @@ -14,19 +14,18 @@ public class Product { String name; String description; double price; - - public Product(){ - + + public Product() { + } - - public Product(String id,String name,String description,double price){ + + public Product(String id, String name, String description, double price) { this.id = id; - this.name=name; + this.name = name; this.description = description; this.price = price; } - - + public String getId() { return id; } @@ -38,21 +37,25 @@ public class Product { public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + public double getPrice() { return price; } + public void setPrice(double price) { this.price = price; } - - + } diff --git a/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java b/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java index f1de71beeb..6bc73b055a 100644 --- a/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java +++ b/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java @@ -14,4 +14,3 @@ public class BlockingServlet extends HttpServlet { response.getWriter().println("{ \"status\": \"ok\"}"); } } - diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServer.java b/libraries/src/main/java/com/baeldung/jetty/JettyServer.java index 364b05473a..82428642c1 100644 --- a/libraries/src/main/java/com/baeldung/jetty/JettyServer.java +++ b/libraries/src/main/java/com/baeldung/jetty/JettyServer.java @@ -21,7 +21,7 @@ class JettyServer { server = new Server(threadPool); ServerConnector connector = new ServerConnector(server); connector.setPort(8090); - server.setConnectors(new Connector[]{connector}); + server.setConnectors(new Connector[] { connector }); ServletHandler servletHandler = new ServletHandler(); server.setHandler(servletHandler); diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java b/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java index 00ba84368a..46a2e8102a 100644 --- a/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java +++ b/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java @@ -14,81 +14,79 @@ import org.eclipse.jetty.webapp.WebAppContext; */ public class JettyServerFactory { - /** - * Exposed context of the app. - */ - public final static String APP_PATH = "/myApp"; - - /** - * The server port. - */ - public final static int SERVER_PORT = 13133; + /** + * Exposed context of the app. + */ + public final static String APP_PATH = "/myApp"; - /** - * Private constructor to avoid instantiation. - */ - private JettyServerFactory() { - } + /** + * The server port. + */ + public final static int SERVER_PORT = 13133; - /** - * Returns a simple server listening on port 80 with a timeout of 30 seconds - * for connections and no handlers. - * - * @return a server - */ - public static Server createBaseServer() { - Server server = new Server(); + /** + * Private constructor to avoid instantiation. + */ + private JettyServerFactory() { + } - // Adds a connector for port 80 with a timeout of 30 seconds. - ServerConnector connector = new ServerConnector(server); - connector.setPort(SERVER_PORT); - connector.setHost("127.0.0.1"); - connector.setIdleTimeout(30000); - server.addConnector(connector); + /** + * Returns a simple server listening on port 80 with a timeout of 30 seconds + * for connections and no handlers. + * + * @return a server + */ + public static Server createBaseServer() { + Server server = new Server(); - return server; - } + // Adds a connector for port 80 with a timeout of 30 seconds. + ServerConnector connector = new ServerConnector(server); + connector.setPort(SERVER_PORT); + connector.setHost("127.0.0.1"); + connector.setIdleTimeout(30000); + server.addConnector(connector); - /** - * Creates a server which delegates the request handling to a web - * application. - * - * @return a server - */ - public static Server createWebAppServer() { - // Adds an handler to a server and returns it. - Server server = createBaseServer(); - String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war") - .getPath(); - Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH); - server.setHandler(webAppHandler); + return server; + } - return server; - } + /** + * Creates a server which delegates the request handling to a web + * application. + * + * @return a server + */ + public static Server createWebAppServer() { + // Adds an handler to a server and returns it. + Server server = createBaseServer(); + String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath(); + Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH); + server.setHandler(webAppHandler); - /** - * Creates a server which delegates the request handling to both a logging - * handler and to a web application, in this order. - * - * @return a server - */ - public static Server createMultiHandlerServer() { - Server server = createBaseServer(); + return server; + } - // Creates the handlers and adds them to the server. - HandlerCollection handlers = new HandlerCollection(); + /** + * Creates a server which delegates the request handling to both a logging + * handler and to a web application, in this order. + * + * @return a server + */ + public static Server createMultiHandlerServer() { + Server server = createBaseServer(); - String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war") - .getPath(); - Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH); - handlers.addHandler(customRequestHandler); + // Creates the handlers and adds them to the server. + HandlerCollection handlers = new HandlerCollection(); - Handler loggingRequestHandler = new LoggingRequestHandler(); - handlers.addHandler(loggingRequestHandler); + String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath(); + Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH); + handlers.addHandler(customRequestHandler); - server.setHandler(handlers); + Handler loggingRequestHandler = new LoggingRequestHandler(); + handlers.addHandler(loggingRequestHandler); - return server; - } + server.setHandler(handlers); + + return server; + } } \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java b/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java index a38759c903..a5c6d09c16 100644 --- a/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java +++ b/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java @@ -19,150 +19,149 @@ import org.slf4j.LoggerFactory; */ public class LoggingRequestHandler implements Handler { - /** - * Logger. - */ - private final static Logger LOG = LoggerFactory.getLogger(LoggingRequestHandler.class); + /** + * Logger. + */ + private final static Logger LOG = LoggerFactory.getLogger(LoggingRequestHandler.class); - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#addLifeCycleListener(org. - * eclipse.jetty.util.component.LifeCycle.Listener) - */ - @Override - public void addLifeCycleListener(Listener arg0) { - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#addLifeCycleListener(org. + * eclipse.jetty.util.component.LifeCycle.Listener) + */ + @Override + public void addLifeCycleListener(Listener arg0) { + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#isFailed() - */ - @Override - public boolean isFailed() { - return false; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#isFailed() + */ + @Override + public boolean isFailed() { + return false; + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#isRunning() - */ - @Override - public boolean isRunning() { - return true; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#isRunning() + */ + @Override + public boolean isRunning() { + return true; + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#isStarted() - */ - @Override - public boolean isStarted() { - return true; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#isStarted() + */ + @Override + public boolean isStarted() { + return true; + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#isStarting() - */ - @Override - public boolean isStarting() { - return false; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#isStarting() + */ + @Override + public boolean isStarting() { + return false; + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#isStopped() - */ - @Override - public boolean isStopped() { - return false; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#isStopped() + */ + @Override + public boolean isStopped() { + return false; + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#isStopping() - */ - @Override - public boolean isStopping() { - return false; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#isStopping() + */ + @Override + public boolean isStopping() { + return false; + } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.jetty.util.component.LifeCycle#removeLifeCycleListener(org. - * eclipse.jetty.util.component.LifeCycle.Listener) - */ - @Override - public void removeLifeCycleListener(Listener arg0) { - } + /* + * (non-Javadoc) + * + * @see + * org.eclipse.jetty.util.component.LifeCycle#removeLifeCycleListener(org. + * eclipse.jetty.util.component.LifeCycle.Listener) + */ + @Override + public void removeLifeCycleListener(Listener arg0) { + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#start() - */ - @Override - public void start() throws Exception { - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#start() + */ + @Override + public void start() throws Exception { + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.util.component.LifeCycle#stop() - */ - @Override - public void stop() throws Exception { - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.util.component.LifeCycle#stop() + */ + @Override + public void stop() throws Exception { + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.server.Handler#destroy() - */ - @Override - public void destroy() { - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.server.Handler#destroy() + */ + @Override + public void destroy() { + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.server.Handler#getServer() - */ - @Override - public Server getServer() { - return null; - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.server.Handler#getServer() + */ + @Override + public Server getServer() { + return null; + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.server.Handler#handle(java.lang.String, - * org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse) - */ - @Override - public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3) - throws IOException, ServletException { - LOG.info("Received a new request"); - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.server.Handler#handle(java.lang.String, + * org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse) + */ + @Override + public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3) throws IOException, ServletException { + LOG.info("Received a new request"); + } - /* - * (non-Javadoc) - * - * @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server. - * Server) - */ - @Override - public void setServer(Server server) { - } + /* + * (non-Javadoc) + * + * @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server. + * Server) + */ + @Override + public void setServer(Server server) { + } } diff --git a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java b/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java index c5bdeb1013..abb6bf7dd9 100644 --- a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java +++ b/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java @@ -5,7 +5,6 @@ import io.netty.channel.ChannelInboundHandlerAdapter; import java.util.logging.Logger; - public class ChannelHandlerB extends ChannelInboundHandlerAdapter { private Logger logger = Logger.getLogger(getClass().getName()); @@ -14,7 +13,7 @@ public class ChannelHandlerB extends ChannelInboundHandlerAdapter { public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.info("Exception Handled in ChannelHandler B"); logger.info(cause.getLocalizedMessage()); - //do more exception handling + // do more exception handling ctx.close(); } } diff --git a/libraries/src/main/java/com/baeldung/netty/NettyServerB.java b/libraries/src/main/java/com/baeldung/netty/NettyServerB.java index c8004623c2..49a6aa6bfd 100644 --- a/libraries/src/main/java/com/baeldung/netty/NettyServerB.java +++ b/libraries/src/main/java/com/baeldung/netty/NettyServerB.java @@ -9,7 +9,7 @@ import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; -public class NettyServerB { +public class NettyServerB { private int port; @@ -24,15 +24,11 @@ public class NettyServerB { try { ServerBootstrap b = new ServerBootstrap(); - b.group(bossGroup, workerGroup) - .channel(NioServerSocketChannel.class) - .childHandler(new ChannelInitializer() { - public void initChannel(SocketChannel ch) throws Exception { - ch.pipeline().addLast(new ChannelHandlerA(), new ChannelHandlerB()); - } - }) - .option(ChannelOption.SO_BACKLOG, 128) - .childOption(ChannelOption.SO_KEEPALIVE, true); + b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() { + public void initChannel(SocketChannel ch) throws Exception { + ch.pipeline().addLast(new ChannelHandlerA(), new ChannelHandlerB()); + } + }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); // (7) f.channel().closeFuture().sync(); } finally { diff --git a/libraries/src/main/java/com/baeldung/netty/RequestData.java b/libraries/src/main/java/com/baeldung/netty/RequestData.java index 402aa1ef91..475c0a4dc1 100644 --- a/libraries/src/main/java/com/baeldung/netty/RequestData.java +++ b/libraries/src/main/java/com/baeldung/netty/RequestData.java @@ -22,9 +22,6 @@ public class RequestData { @Override public String toString() { - return "RequestData{" + - "intValue=" + intValue + - ", stringValue='" + stringValue + '\'' + - '}'; + return "RequestData{" + "intValue=" + intValue + ", stringValue='" + stringValue + '\'' + '}'; } } diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseData.java b/libraries/src/main/java/com/baeldung/netty/ResponseData.java index 51d1adaafb..8849e8a4cb 100644 --- a/libraries/src/main/java/com/baeldung/netty/ResponseData.java +++ b/libraries/src/main/java/com/baeldung/netty/ResponseData.java @@ -13,8 +13,6 @@ public class ResponseData { @Override public String toString() { - return "ResponseData{" + - "intValue=" + intValue + - '}'; + return "ResponseData{" + "intValue=" + intValue + '}'; } } diff --git a/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java index fb6a01d4c1..4cb11c3c05 100644 --- a/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java +++ b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java @@ -41,7 +41,7 @@ public class NeurophXOR { ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2)); ann.addLayer(3, outputLayer); ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3)); - ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount()-1), false); + ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount() - 1), false); ann.setInputNeurons(inputLayer.getNeurons()); ann.setOutputNeurons(outputLayer.getNeurons()); @@ -55,13 +55,13 @@ public class NeurophXOR { int outputSize = 1; DataSet ds = new DataSet(inputSize, outputSize); - DataSetRow rOne = new DataSetRow(new double[] {0, 1}, new double[] {1}); + DataSetRow rOne = new DataSetRow(new double[] { 0, 1 }, new double[] { 1 }); ds.addRow(rOne); - DataSetRow rTwo = new DataSetRow(new double[] {1, 1}, new double[] {0}); + DataSetRow rTwo = new DataSetRow(new double[] { 1, 1 }, new double[] { 0 }); ds.addRow(rTwo); - DataSetRow rThree = new DataSetRow(new double[] {0, 0}, new double[] {0}); + DataSetRow rThree = new DataSetRow(new double[] { 0, 0 }, new double[] { 0 }); ds.addRow(rThree); - DataSetRow rFour = new DataSetRow(new double[] {1, 0}, new double[] {1}); + DataSetRow rFour = new DataSetRow(new double[] { 1, 0 }, new double[] { 1 }); ds.addRow(rFour); BackPropagation backPropagation = new BackPropagation(); diff --git a/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java b/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java index 59e13efaa0..48abe35287 100644 --- a/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java +++ b/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java @@ -11,10 +11,7 @@ public class CustomExceptionHandler extends ExceptionHandler { @Override public boolean handle(Throwable throwable) { - if (throwable.getClass() - .isAssignableFrom(RuntimeException.class) - || throwable.getClass() - .isAssignableFrom(Error.class)) { + if (throwable.getClass().isAssignableFrom(RuntimeException.class) || throwable.getClass().isAssignableFrom(Error.class)) { return false; } else { logger.error("Caught Exception ", throwable); diff --git a/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java b/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java index eead34af71..b872696510 100644 --- a/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java +++ b/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java @@ -20,18 +20,14 @@ public class StreamUtilsExample { public void zipAStreamWithIndex() { Stream source = Stream.of("Foo", "Bar", "Baz"); - List> zipped = StreamUtils - .zipWithIndex(source) - .collect(Collectors.toList()); + List> zipped = StreamUtils.zipWithIndex(source).collect(Collectors.toList()); } public void zipAPairOfStreams() { Stream streamA = Stream.of("A", "B", "C"); Stream streamB = Stream.of("Apple", "Banana", "Carrot"); - List zipped = StreamUtils - .zip(streamA, streamB, (a, b) -> a + " is for " + b) - .collect(Collectors.toList()); + List zipped = StreamUtils.zip(streamA, streamB, (a, b) -> a + " is for " + b).collect(Collectors.toList()); } public void zipThreeStreams() { @@ -39,9 +35,7 @@ public class StreamUtilsExample { Stream streamB = Stream.of("aggravating", "banausic", "complaisant"); Stream streamC = Stream.of("Apple", "Banana", "Carrot"); - List zipped = StreamUtils - .zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c) - .collect(Collectors.toList()); + List zipped = StreamUtils.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c).collect(Collectors.toList()); } public void mergeThreeStreams() { @@ -79,24 +73,16 @@ public class StreamUtilsExample { public void windowedStream() { Stream integerStream = Stream.of(1, 2, 3, 4, 5); - List> windows = StreamUtils - .windowed(integerStream, 2) - .collect(toList()); - List> windowsWithSkipIndex = StreamUtils - .windowed(integerStream, 3, 2) - .collect(toList()); - List> windowsWithSkipIndexAndAllowLowerSize = StreamUtils - .windowed(integerStream, 2, 2, true) - .collect(toList()); + List> windows = StreamUtils.windowed(integerStream, 2).collect(toList()); + List> windowsWithSkipIndex = StreamUtils.windowed(integerStream, 3, 2).collect(toList()); + List> windowsWithSkipIndexAndAllowLowerSize = StreamUtils.windowed(integerStream, 2, 2, true).collect(toList()); } public void groupRunsStreams() { Stream integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5); - List> runs = StreamUtils - .groupRuns(integerStream) - .collect(toList()); + List> runs = StreamUtils.groupRuns(integerStream).collect(toList()); } public void aggreagateOnBiElementPredicate() { diff --git a/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java b/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java index 4757d912f8..b55517b6d1 100644 --- a/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java +++ b/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java @@ -19,45 +19,17 @@ public class QuartzExample { Scheduler sched = schedFact.getScheduler(); - JobDetail job = JobBuilder.newJob(SimpleJob.class) - .withIdentity("myJob", "group1") - .usingJobData("jobSays", "Hello World!") - .usingJobData("myFloatValue", 3.141f) - .build(); + JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("myJob", "group1").usingJobData("jobSays", "Hello World!").usingJobData("myFloatValue", 3.141f).build(); - Trigger trigger = TriggerBuilder.newTrigger() - .withIdentity("myTrigger", "group1") - .startNow() - .withSchedule(SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(40) - .repeatForever()) - .build(); + Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTrigger", "group1").startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build(); - JobDetail jobA = JobBuilder.newJob(JobA.class) - .withIdentity("jobA", "group2") - .build(); + JobDetail jobA = JobBuilder.newJob(JobA.class).withIdentity("jobA", "group2").build(); - JobDetail jobB = JobBuilder.newJob(JobB.class) - .withIdentity("jobB", "group2") - .build(); + JobDetail jobB = JobBuilder.newJob(JobB.class).withIdentity("jobB", "group2").build(); - Trigger triggerA = TriggerBuilder.newTrigger() - .withIdentity("triggerA", "group2") - .startNow() - .withPriority(15) - .withSchedule(SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(40) - .repeatForever()) - .build(); + Trigger triggerA = TriggerBuilder.newTrigger().withIdentity("triggerA", "group2").startNow().withPriority(15).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build(); - Trigger triggerB = TriggerBuilder.newTrigger() - .withIdentity("triggerB", "group2") - .startNow() - .withPriority(10) - .withSchedule(SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(20) - .repeatForever()) - .build(); + Trigger triggerB = TriggerBuilder.newTrigger().withIdentity("triggerB", "group2").startNow().withPriority(10).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(20).repeatForever()).build(); sched.scheduleJob(job, trigger); sched.scheduleJob(jobA, triggerA); diff --git a/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java b/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java index 554d3b9358..03730ee6e5 100644 --- a/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java +++ b/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java @@ -8,8 +8,7 @@ import org.quartz.JobExecutionException; public class SimpleJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { - JobDataMap dataMap = context.getJobDetail() - .getJobDataMap(); + JobDataMap dataMap = context.getJobDetail().getJobDataMap(); String jobSays = dataMap.getString("jobSays"); float myFloatValue = dataMap.getFloat("myFloatValue"); diff --git a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java index 4e071d3384..2b5c1f6f62 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java +++ b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java @@ -18,7 +18,7 @@ public interface GitHubBasicApi { */ @GET("users/{user}/repos") Call> listRepos(@Path("user") String user); - + /** * List Contributors of a GitHub Repository * @param user GitHub Account @@ -26,8 +26,6 @@ public interface GitHubBasicApi { * @return GitHub Repository Contributors */ @GET("repos/{user}/{repo}/contributors") - Call> listRepoContributors( - @Path("user") String user, - @Path("repo") String repo); - + Call> listRepoContributors(@Path("user") String user, @Path("repo") String repo); + } diff --git a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java index 6b2cd14252..df0d90af7f 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java +++ b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java @@ -7,8 +7,7 @@ public class GitHubBasicApp { public static void main(String[] args) throws IOException { String userName = "eugenp"; - List topContributors = new GitHubBasicService() - .getTopContributors(userName); + List topContributors = new GitHubBasicService().getTopContributors(userName); topContributors.forEach(System.out::println); } } diff --git a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java index 20256fb540..ff6ef82183 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java +++ b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java @@ -16,45 +16,29 @@ class GitHubBasicService { private GitHubBasicApi gitHubApi; GitHubBasicService() { - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://api.github.com/") - .addConverterFactory(GsonConverterFactory.create()) - .build(); + Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).build(); gitHubApi = retrofit.create(GitHubBasicApi.class); } List getTopContributors(String userName) throws IOException { - List repos = gitHubApi - .listRepos(userName) - .execute() - .body(); + List repos = gitHubApi.listRepos(userName).execute().body(); repos = repos != null ? repos : Collections.emptyList(); - return repos.stream() - .flatMap(repo -> getContributors(userName, repo)) - .sorted((a, b) -> b.getContributions() - a.getContributions()) - .map(Contributor::getName) - .distinct() - .sorted() - .collect(Collectors.toList()); + return repos.stream().flatMap(repo -> getContributors(userName, repo)).sorted((a, b) -> b.getContributions() - a.getContributions()).map(Contributor::getName).distinct().sorted().collect(Collectors.toList()); } private Stream getContributors(String userName, Repository repo) { List contributors = null; try { - contributors = gitHubApi - .listRepoContributors(userName, repo.getName()) - .execute() - .body(); + contributors = gitHubApi.listRepoContributors(userName, repo.getName()).execute().body(); } catch (IOException e) { e.printStackTrace(); } contributors = contributors != null ? contributors : Collections.emptyList(); - return contributors.stream() - .filter(c -> c.getContributions() > 100); + return contributors.stream().filter(c -> c.getContributions() > 100); } } diff --git a/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java b/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java index 2f8697f603..f98b19de96 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java +++ b/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java @@ -3,28 +3,31 @@ package com.baeldung.retrofit.models; import com.google.gson.annotations.SerializedName; public class Contributor { - + @SerializedName("login") private String name; - + private Integer contributions; - + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public Integer getContributions() { return contributions; } + public void setContributions(Integer contributions) { this.contributions = contributions; } - + @Override public String toString() { return "Contributer [name=" + name + ", contributions=" + contributions + "]"; } - + } diff --git a/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java b/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java index f12fcdf8f2..6bc91eb772 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java +++ b/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java @@ -1,20 +1,23 @@ package com.baeldung.retrofit.models; public class Repository { - + private String name; - + private String description; - + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } diff --git a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java index 4e40aff448..aa0f550115 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java +++ b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java @@ -18,7 +18,7 @@ public interface GitHubRxApi { */ @GET("users/{user}/repos") Observable> listRepos(@Path("user") String user); - + /** * List Contributors of a GitHub Repository * @param user GitHub Account @@ -26,8 +26,6 @@ public interface GitHubRxApi { * @return GitHub Repository Contributors */ @GET("repos/{user}/{repo}/contributors") - Observable> listRepoContributors( - @Path("user") String user, - @Path("repo") String repo); - + Observable> listRepoContributors(@Path("user") String user, @Path("repo") String repo); + } diff --git a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java index b136a1e40b..4941a65717 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java +++ b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java @@ -6,7 +6,6 @@ public class GitHubRxApp { public static void main(String[] args) throws IOException { String userName = "eugenp"; - new GitHubRxService().getTopContributors(userName) - .subscribe(System.out::println); + new GitHubRxService().getTopContributors(userName).subscribe(System.out::println); } } diff --git a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java index 2ad50a9f39..f2c5114149 100644 --- a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java +++ b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java @@ -11,23 +11,13 @@ class GitHubRxService { private GitHubRxApi gitHubApi; GitHubRxService() { - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://api.github.com/") - .addConverterFactory(GsonConverterFactory.create()) - .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) - .build(); + Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); gitHubApi = retrofit.create(GitHubRxApi.class); } Observable getTopContributors(String userName) { - return gitHubApi.listRepos(userName) - .flatMapIterable(x -> x) - .flatMap(repo -> gitHubApi.listRepoContributors(userName, repo.getName())) - .flatMapIterable(x -> x) - .filter(c -> c.getContributions() > 100) - .sorted((a, b) -> b.getContributions() - a.getContributions()) - .map(Contributor::getName) - .distinct(); + return gitHubApi.listRepos(userName).flatMapIterable(x -> x).flatMap(repo -> gitHubApi.listRepoContributors(userName, repo.getName())).flatMapIterable(x -> x).filter(c -> c.getContributions() > 100) + .sorted((a, b) -> b.getContributions() - a.getContributions()).map(Contributor::getName).distinct(); } } diff --git a/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java b/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java index d32891be9e..dc6bfbddb1 100644 --- a/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java +++ b/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java @@ -13,19 +13,13 @@ public class GitHubServiceGenerator { private static final String BASE_URL = "https://api.github.com/"; - private static Retrofit.Builder builder - = new Retrofit.Builder() - .baseUrl(BASE_URL) - .addConverterFactory(GsonConverterFactory.create()); + private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()); private static Retrofit retrofit = builder.build(); - private static OkHttpClient.Builder httpClient - = new OkHttpClient.Builder(); + private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); - private static HttpLoggingInterceptor logging - = new HttpLoggingInterceptor() - .setLevel(HttpLoggingInterceptor.Level.BASIC); + private static HttpLoggingInterceptor logging = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC); public static S createService(Class serviceClass) { if (!httpClient.interceptors().contains(logging)) { @@ -43,8 +37,7 @@ public class GitHubServiceGenerator { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request original = chain.request(); - Request.Builder builder = original.newBuilder() - .header("Authorization", token); + Request.Builder builder = original.newBuilder().header("Authorization", token); Request request = builder.build(); return chain.proceed(request); } diff --git a/libraries/src/main/java/com/baeldung/retrofitguide/Main.java b/libraries/src/main/java/com/baeldung/retrofitguide/Main.java index 8a674f634b..be7e15e3c9 100644 --- a/libraries/src/main/java/com/baeldung/retrofitguide/Main.java +++ b/libraries/src/main/java/com/baeldung/retrofitguide/Main.java @@ -11,15 +11,11 @@ import retrofit2.converter.gson.GsonConverterFactory; public class Main { public static void main(String[] args) { - //Manual creation + // Manual creation OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://api.github.com/") - .addConverterFactory(GsonConverterFactory.create()) - .client(httpClient.build()) - .build(); + Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).client(httpClient.build()).build(); UserService service = retrofit.create(UserService.class); - //Using GitHubServiceGenerator + // Using GitHubServiceGenerator service = GitHubServiceGenerator.createService(UserService.class); Call callSync = service.getUser("eugenp"); Call callAsync = service.getUser("eugenp"); diff --git a/libraries/src/main/java/com/baeldung/serenity/membership/Commodity.java b/libraries/src/main/java/com/baeldung/serenity/membership/Commodity.java index 208b73d4af..c889871b3d 100644 --- a/libraries/src/main/java/com/baeldung/serenity/membership/Commodity.java +++ b/libraries/src/main/java/com/baeldung/serenity/membership/Commodity.java @@ -9,7 +9,7 @@ public enum Commodity { public final int price; - Commodity(int price){ + Commodity(int price) { this.price = price; } diff --git a/libraries/src/main/java/com/baeldung/serenity/membership/Member.java b/libraries/src/main/java/com/baeldung/serenity/membership/Member.java index 6e7c4db08e..f2f443020d 100644 --- a/libraries/src/main/java/com/baeldung/serenity/membership/Member.java +++ b/libraries/src/main/java/com/baeldung/serenity/membership/Member.java @@ -12,7 +12,8 @@ public class Member { private int points; private Member(int points) { - if (points < 0) throw new IllegalArgumentException("points must not be negative!"); + if (points < 0) + throw new IllegalArgumentException("points must not be negative!"); this.points = points; } @@ -22,9 +23,12 @@ public class Member { } public MemberGrade getGrade() { - if (points < 1000) return Bronze; - else if (points >= 1000 && points < 5000) return Silver; - else return Gold; + if (points < 1000) + return Bronze; + else if (points >= 1000 && points < 5000) + return Silver; + else + return Gold; } public void spend(int moneySpent) { diff --git a/libraries/src/main/java/com/baeldung/serenity/membership/MemberGrade.java b/libraries/src/main/java/com/baeldung/serenity/membership/MemberGrade.java index 7bb6f76495..389749c2ca 100644 --- a/libraries/src/main/java/com/baeldung/serenity/membership/MemberGrade.java +++ b/libraries/src/main/java/com/baeldung/serenity/membership/MemberGrade.java @@ -3,7 +3,7 @@ package com.baeldung.serenity.membership; /** * @author aiet */ -public enum MemberGrade { +public enum MemberGrade { Bronze, Silver, Gold; diff --git a/libraries/src/main/java/com/baeldung/smooks/converter/OrderConverter.java b/libraries/src/main/java/com/baeldung/smooks/converter/OrderConverter.java index d11f5a29b2..fa317f93b7 100644 --- a/libraries/src/main/java/com/baeldung/smooks/converter/OrderConverter.java +++ b/libraries/src/main/java/com/baeldung/smooks/converter/OrderConverter.java @@ -21,7 +21,6 @@ public class OrderConverter { smooks.close(); } } - public String convertOrderXMLtoEDIFACT(String path) throws IOException, SAXException { return convertDocumentWithTempalte(path, "/smooks/smooks-transform-edi.xml"); diff --git a/libraries/src/main/java/com/baeldung/smooks/model/Item.java b/libraries/src/main/java/com/baeldung/smooks/model/Item.java index a7f7783b3f..3e1f4a7ef4 100644 --- a/libraries/src/main/java/com/baeldung/smooks/model/Item.java +++ b/libraries/src/main/java/com/baeldung/smooks/model/Item.java @@ -15,7 +15,6 @@ public class Item { private Double price; private Integer quantity; - public String getCode() { return code; } @@ -42,13 +41,17 @@ public class Item { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Item item = (Item) o; - if (code != null ? !code.equals(item.code) : item.code != null) return false; - if (price != null ? !price.equals(item.price) : item.price != null) return false; + if (code != null ? !code.equals(item.code) : item.code != null) + return false; + if (price != null ? !price.equals(item.price) : item.price != null) + return false; return quantity != null ? quantity.equals(item.quantity) : item.quantity == null; } @@ -62,10 +65,6 @@ public class Item { @Override public String toString() { - return "Item{" + - "code='" + code + '\'' + - ", price=" + price + - ", quantity=" + quantity + - '}'; + return "Item{" + "code='" + code + '\'' + ", price=" + price + ", quantity=" + quantity + '}'; } } diff --git a/libraries/src/main/java/com/baeldung/smooks/model/Supplier.java b/libraries/src/main/java/com/baeldung/smooks/model/Supplier.java index 31a9e1f43f..827a0fc907 100644 --- a/libraries/src/main/java/com/baeldung/smooks/model/Supplier.java +++ b/libraries/src/main/java/com/baeldung/smooks/model/Supplier.java @@ -31,12 +31,15 @@ public class Supplier { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Supplier supplier = (Supplier) o; - if (name != null ? !name.equals(supplier.name) : supplier.name != null) return false; + if (name != null ? !name.equals(supplier.name) : supplier.name != null) + return false; return phoneNumber != null ? phoneNumber.equals(supplier.phoneNumber) : supplier.phoneNumber == null; } diff --git a/libraries/src/main/java/com/baeldung/stm/Account.java b/libraries/src/main/java/com/baeldung/stm/Account.java index 8b17f87120..4dc2c492df 100644 --- a/libraries/src/main/java/com/baeldung/stm/Account.java +++ b/libraries/src/main/java/com/baeldung/stm/Account.java @@ -44,7 +44,6 @@ public class Account { @Override public String toString() { - return StmUtils.atomic((TxnCallable) - txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn)); + return StmUtils.atomic((TxnCallable) txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn)); } } \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/streamex/StreamEX.java b/libraries/src/main/java/com/baeldung/streamex/StreamEX.java index 7cbfec4421..56a3860f05 100644 --- a/libraries/src/main/java/com/baeldung/streamex/StreamEX.java +++ b/libraries/src/main/java/com/baeldung/streamex/StreamEX.java @@ -15,69 +15,43 @@ import one.util.streamex.StreamEx; public class StreamEX { public static void main(String[] args) { - //Collector shortcut methods (toList, toSet, groupingBy, joining, etc.) - List users = Arrays.asList( - new User("name"), new User(), new User()); - users.stream() - .map(User::getName) - .collect(Collectors.toList()); - List userNames = StreamEx.of(users) - .map(User::getName) - .toList(); - Map> role2users = StreamEx.of(users) - .groupingBy(User::getRole); - StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3" - //Selecting stream elements of specific type + // Collector shortcut methods (toList, toSet, groupingBy, joining, etc.) + List users = Arrays.asList(new User("name"), new User(), new User()); + users.stream().map(User::getName).collect(Collectors.toList()); + List userNames = StreamEx.of(users).map(User::getName).toList(); + Map> role2users = StreamEx.of(users).groupingBy(User::getRole); + StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3" + // Selecting stream elements of specific type List usersAndRoles = Arrays.asList(new User(), new Role()); - List roles = IntStreamEx.range(usersAndRoles.size()) - .mapToObj(usersAndRoles::get) - .select(Role.class) - .toList(); + List roles = IntStreamEx.range(usersAndRoles.size()).mapToObj(usersAndRoles::get).select(Role.class).toList(); System.out.println(roles); - //adding elements to Stream - List appendedUsers = StreamEx.of(users) - .map(User::getName) - .prepend("(none)") - .append("LAST") - .toList(); + // adding elements to Stream + List appendedUsers = StreamEx.of(users).map(User::getName).prepend("(none)").append("LAST").toList(); System.out.println(appendedUsers); - //Removing unwanted elements and using the stream as Iterable: - for (String line : StreamEx.of(users).map(User::getName) - .nonNull()) { + // Removing unwanted elements and using the stream as Iterable: + for (String line : StreamEx.of(users).map(User::getName).nonNull()) { System.out.println(line); } - //Selecting map keys by value predicate: + // Selecting map keys by value predicate: Map nameToRole = new HashMap<>(); nameToRole.put("first", new Role()); nameToRole.put("second", null); - Set nonNullRoles = StreamEx. - ofKeys(nameToRole, Objects::nonNull) - .toSet(); + Set nonNullRoles = StreamEx.ofKeys(nameToRole, Objects::nonNull).toSet(); System.out.println(nonNullRoles); - //Operating on key-value pairs: + // Operating on key-value pairs: Map> users2roles = transformMap(role2users); - Map mapToString = EntryStream.of(users2roles) - .mapKeys(String::valueOf) - .mapValues(String::valueOf) - .toMap(); - //Support of byte/char/short/float types: - short[] src = {1, 2, 3}; - char[] output = IntStreamEx.of(src) - .map(x -> x * 5) - .toCharArray(); + Map mapToString = EntryStream.of(users2roles).mapKeys(String::valueOf).mapValues(String::valueOf).toMap(); + // Support of byte/char/short/float types: + short[] src = { 1, 2, 3 }; + char[] output = IntStreamEx.of(src).map(x -> x * 5).toCharArray(); } public double[] getDiffBetweenPairs(double... numbers) { - return DoubleStreamEx.of(numbers) - .pairMap((a, b) -> b - a).toArray(); + return DoubleStreamEx.of(numbers).pairMap((a, b) -> b - a).toArray(); } - public static Map> transformMap( - Map> role2users) { - Map> users2roles = EntryStream.of(role2users) - .flatMapValues(List::stream) - .invert() - .grouping(); + public static Map> transformMap(Map> role2users) { + Map> users2roles = EntryStream.of(role2users).flatMapValues(List::stream).invert().grouping(); return users2roles; } diff --git a/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java index 430759f3a0..d9097188b3 100644 --- a/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java +++ b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java @@ -9,14 +9,14 @@ import org.apache.commons.io.IOUtils; import org.springframework.util.StreamUtils; public class CopyStream { - public static String getStringFromInputStream(InputStream input) throws IOException { - StringWriter writer = new StringWriter(); - IOUtils.copy(input, writer, "UTF-8"); - return writer.toString(); - } + public static String getStringFromInputStream(InputStream input) throws IOException { + StringWriter writer = new StringWriter(); + IOUtils.copy(input, writer, "UTF-8"); + return writer.toString(); + } - public InputStream getNonClosingInputStream() throws IOException { - InputStream in = new FileInputStream("src/test/resources/input.txt"); - return StreamUtils.nonClosing(in); - } + public InputStream getNonClosingInputStream() throws IOException { + InputStream in = new FileInputStream("src/test/resources/input.txt"); + return StreamUtils.nonClosing(in); + } } diff --git a/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java index 6ee4a1ef3a..1ce67a075a 100644 --- a/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java +++ b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java @@ -5,7 +5,7 @@ import java.io.InputStream; import org.springframework.util.StreamUtils; public class DrainStream { - public InputStream getInputStream() { - return StreamUtils.emptyInput(); - } + public InputStream getInputStream() { + return StreamUtils.emptyInput(); + } } diff --git a/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java b/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java index 4bbf3c03a7..1b48e2d90b 100644 --- a/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java +++ b/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java @@ -9,10 +9,7 @@ import java.io.IOException; /** * Created by adi on 1/10/18. */ -@WebServlet( - name = "com.baeldung.tomcat.programmatic.MyServlet", - urlPatterns = {"/my-servlet"} -) +@WebServlet(name = "com.baeldung.tomcat.programmatic.MyServlet", urlPatterns = { "/my-servlet" }) public class MyServlet extends HttpServlet { @Override diff --git a/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java b/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java index b84b6b5c6d..6c4fed6d07 100644 --- a/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java +++ b/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java @@ -15,29 +15,27 @@ public class ProgrammaticTomcat { private Tomcat tomcat = null; - //uncomment for live test - // public static void main(String[] args) throws LifecycleException, ServletException, URISyntaxException, IOException { - // startTomcat(); - // } + // uncomment for live test + // public static void main(String[] args) throws LifecycleException, ServletException, URISyntaxException, IOException { + // startTomcat(); + // } public void startTomcat() throws LifecycleException { tomcat = new Tomcat(); tomcat.setPort(8080); tomcat.setHostname("localhost"); String appBase = "."; - tomcat - .getHost() - .setAppBase(appBase); + tomcat.getHost().setAppBase(appBase); File docBase = new File(System.getProperty("java.io.tmpdir")); Context context = tomcat.addContext("", docBase.getAbsolutePath()); - //add a servlet + // add a servlet Class servletClass = MyServlet.class; Tomcat.addServlet(context, servletClass.getSimpleName(), servletClass.getName()); context.addServletMappingDecoded("/my-servlet/*", servletClass.getSimpleName()); - //add a filter and filterMapping + // add a filter and filterMapping Class filterClass = MyFilter.class; FilterDef myFilterDef = new FilterDef(); myFilterDef.setFilterClass(filterClass.getName()); @@ -50,10 +48,10 @@ public class ProgrammaticTomcat { context.addFilterMap(myFilterMap); tomcat.start(); - //uncomment for live test - // tomcat - // .getServer() - // .await(); + // uncomment for live test + // tomcat + // .getServer() + // .await(); } public void stopTomcat() throws LifecycleException { diff --git a/libraries/src/main/java/com/baeldung/yarg/DocumentController.java b/libraries/src/main/java/com/baeldung/yarg/DocumentController.java index 0e1bbca561..ff0d452108 100644 --- a/libraries/src/main/java/com/baeldung/yarg/DocumentController.java +++ b/libraries/src/main/java/com/baeldung/yarg/DocumentController.java @@ -30,25 +30,17 @@ public class DocumentController { @RequestMapping(path = "/generate/doc", method = RequestMethod.GET) public void generateDocument(HttpServletResponse response) throws IOException { ReportBuilder reportBuilder = new ReportBuilder(); - ReportTemplateBuilder reportTemplateBuilder = new ReportTemplateBuilder() - .documentPath("./src/main/resources/Letter.docx") - .documentName("Letter.docx") - .outputType(ReportOutputType.docx) - .readFileFromPath(); + ReportTemplateBuilder reportTemplateBuilder = new ReportTemplateBuilder().documentPath("./src/main/resources/Letter.docx").documentName("Letter.docx").outputType(ReportOutputType.docx).readFileFromPath(); reportBuilder.template(reportTemplateBuilder.build()); BandBuilder bandBuilder = new BandBuilder(); String json = FileUtils.readFileToString(new File("./src/main/resources/Data.json")); - ReportBand main = bandBuilder.name("Main") - .query("Main", "parameter=param1 $.main", "json") - .build(); + ReportBand main = bandBuilder.name("Main").query("Main", "parameter=param1 $.main", "json").build(); reportBuilder.band(main); Report report = reportBuilder.build(); Reporting reporting = new Reporting(); reporting.setFormatterFactory(new DefaultFormatterFactory()); - reporting.setLoaderFactory( - new DefaultLoaderFactory() - .setJsonDataLoader(new JsonDataLoader())); + reporting.setLoaderFactory(new DefaultLoaderFactory().setJsonDataLoader(new JsonDataLoader())); response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); reporting.runReport(new RunParams(report).param("param1", json), response.getOutputStream()); } diff --git a/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientTestCase.java b/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientTestCase.java index 1398c2ba41..7ff81c20c3 100644 --- a/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientTestCase.java +++ b/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientTestCase.java @@ -186,17 +186,12 @@ public class AsyncHttpClientTestCase { WebSocket WEBSOCKET_CLIENT = null; try { - WEBSOCKET_CLIENT = Dsl.asyncHttpClient() - .prepareGet("ws://localhost:5590/websocket") - .addHeader("header_name", "header_value") - .addQueryParam("key", "value") - .setRequestTimeout(5000) - .execute(wsHandler).get(); + WEBSOCKET_CLIENT = Dsl.asyncHttpClient().prepareGet("ws://localhost:5590/websocket").addHeader("header_name", "header_value").addQueryParam("key", "value").setRequestTimeout(5000).execute(wsHandler).get(); if (WEBSOCKET_CLIENT.isOpen()) { WEBSOCKET_CLIENT.sendPingFrame(); WEBSOCKET_CLIENT.sendTextFrame("test message"); - WEBSOCKET_CLIENT.sendBinaryFrame(new byte[]{'t', 'e', 's', 't'}); + WEBSOCKET_CLIENT.sendBinaryFrame(new byte[] { 't', 'e', 's', 't' }); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); diff --git a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java index 7ca656efbf..87c0b13bcc 100644 --- a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java +++ b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java @@ -35,10 +35,7 @@ public class AsyncServiceLongRunningUnitTest { public void givenAsyncService_whenInitialize_thenInitOccurs2() { asyncService.initialize(); Callable isInitialized = asyncService::isInitialized; - await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS) - .atMost(Duration.FIVE_SECONDS) - .with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS) - .until(isInitialized); + await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS).atMost(Duration.FIVE_SECONDS).with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS).until(isInitialized); } @Test @@ -60,9 +57,7 @@ public class AsyncServiceLongRunningUnitTest { @Test public void givenAsyncService_whenInitialize_thenInitOccurs3() { asyncService.initialize(); - await().until(fieldIn(asyncService) - .ofType(boolean.class) - .andWithName("initialized"), equalTo(true)); + await().until(fieldIn(asyncService).ofType(boolean.class).andWithName("initialized"), equalTo(true)); } @Test @@ -77,10 +72,6 @@ public class AsyncServiceLongRunningUnitTest { @Test public void givenAsyncService_whenGetValue_thenExceptionIgnored() { asyncService.initialize(); - given().ignoreException(IllegalStateException.class) - .await() - .atMost(Duration.FIVE_SECONDS) - .atLeast(Duration.FIVE_HUNDRED_MILLISECONDS) - .until(asyncService::getValue, equalTo(0L)); + given().ignoreException(IllegalStateException.class).await().atMost(Duration.FIVE_SECONDS).atLeast(Duration.FIVE_HUNDRED_MILLISECONDS).until(asyncService::getValue, equalTo(0L)); } } diff --git a/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java b/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java index 3965eeecd4..009119d97a 100644 --- a/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java +++ b/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java @@ -28,14 +28,11 @@ public class BouncyCastleLiveTest { char[] keyPassword = "password".toCharArray(); @Test - public void givenCryptographicResource_whenOperationSuccess_returnTrue() - throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException, - KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException { + public void givenCryptographicResource_whenOperationSuccess_returnTrue() throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException, KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException { Security.addProvider(new BouncyCastleProvider()); CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC"); - X509Certificate certificate = (X509Certificate) certFactory - .generateCertificate(new FileInputStream(certificatePath)); + X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(new FileInputStream(certificatePath)); KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(new FileInputStream(privateKeyPath), p12Password); PrivateKey privateKey = (PrivateKey) keystore.getKey("baeldung", keyPassword); diff --git a/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java b/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java index 6b7364a0a5..5f721025c3 100644 --- a/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java +++ b/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java @@ -21,14 +21,9 @@ public class ByteBuddyUnitTest { @Test public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException { - DynamicType.Unloaded unloadedType = new ByteBuddy() - .subclass(Object.class) - .method(ElementMatchers.isToString()) - .intercept(FixedValue.value("Hello World ByteBuddy!")) - .make(); + DynamicType.Unloaded unloadedType = new ByteBuddy().subclass(Object.class).method(ElementMatchers.isToString()).intercept(FixedValue.value("Hello World ByteBuddy!")).make(); - Class dynamicType = unloadedType.load(getClass().getClassLoader()) - .getLoaded(); + Class dynamicType = unloadedType.load(getClass().getClassLoader()).getLoaded(); assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!"); } @@ -36,12 +31,7 @@ public class ByteBuddyUnitTest { @Test public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception { ByteBuddyAgent.install(); - new ByteBuddy() - .redefine(Foo.class) - .method(named("sayHelloFoo")) - .intercept(FixedValue.value("Hello Foo Redefined")) - .make() - .load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent()); + new ByteBuddy().redefine(Foo.class).method(named("sayHelloFoo")).intercept(FixedValue.value("Hello Foo Redefined")).make().load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent()); Foo f = new Foo(); assertEquals(f.sayHelloFoo(), "Hello Foo Redefined"); } @@ -49,34 +39,16 @@ public class ByteBuddyUnitTest { @Test public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException { - String r = new ByteBuddy() - .subclass(Foo.class) - .method( - named("sayHelloFoo") - .and(isDeclaredBy(Foo.class) - .and(returns(String.class))) - ) - .intercept(MethodDelegation.to(Bar.class)) - .make() - .load(getClass().getClassLoader()) - .getLoaded() - .newInstance() - .sayHelloFoo(); + String r = new ByteBuddy().subclass(Foo.class).method(named("sayHelloFoo").and(isDeclaredBy(Foo.class).and(returns(String.class)))).intercept(MethodDelegation.to(Bar.class)).make().load(getClass().getClassLoader()).getLoaded().newInstance() + .sayHelloFoo(); assertEquals(r, Bar.sayHelloBar()); } @Test public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception { - Class type = new ByteBuddy() - .subclass(Object.class) - .name("MyClassName") - .defineMethod("custom", String.class, Modifier.PUBLIC) - .intercept(MethodDelegation.to(Bar.class)) - .defineField("x", String.class, Modifier.PUBLIC) - .make() - .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) - .getLoaded(); + Class type = new ByteBuddy().subclass(Object.class).name("MyClassName").defineMethod("custom", String.class, Modifier.PUBLIC).intercept(MethodDelegation.to(Bar.class)).defineField("x", String.class, Modifier.PUBLIC).make() + .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded(); Method m = type.getDeclaredMethod("custom", null); @@ -85,5 +57,4 @@ public class ByteBuddyUnitTest { } - } diff --git a/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java b/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java index 56dbda5974..d523d0ff8b 100644 --- a/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java +++ b/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java @@ -16,10 +16,7 @@ public class CaffeineUnitTest { @Test public void givenCache_whenPopulate_thenValueStored() { - Cache cache = Caffeine.newBuilder() - .expireAfterWrite(1, TimeUnit.MINUTES) - .maximumSize(100) - .build(); + Cache cache = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).maximumSize(100).build(); String key = "A"; DataObject dataObject = cache.getIfPresent(key); @@ -44,10 +41,7 @@ public class CaffeineUnitTest { @Test public void givenLoadingCache_whenGet_thenValuePopulated() { - LoadingCache cache = Caffeine.newBuilder() - .maximumSize(100) - .expireAfterWrite(1, TimeUnit.MINUTES) - .build(k -> DataObject.get("Data for " + k)); + LoadingCache cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k)); String key = "A"; DataObject dataObject = cache.get(key); @@ -63,10 +57,7 @@ public class CaffeineUnitTest { @Test public void givenAsyncLoadingCache_whenGet_thenValuePopulated() { - AsyncLoadingCache cache = Caffeine.newBuilder() - .maximumSize(100) - .expireAfterWrite(1, TimeUnit.MINUTES) - .buildAsync(k -> DataObject.get("Data for " + k)); + AsyncLoadingCache cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).buildAsync(k -> DataObject.get("Data for " + k)); String key = "A"; cache.get(key).thenAccept(dataObject -> { @@ -74,16 +65,12 @@ public class CaffeineUnitTest { assertEquals("Data for " + key, dataObject.getData()); }); - cache.getAll(Arrays.asList("A", "B", "C")) - .thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size())); + cache.getAll(Arrays.asList("A", "B", "C")).thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size())); } @Test public void givenLoadingCacheWithSmallSize_whenPut_thenSizeIsConstant() { - LoadingCache cache = Caffeine.newBuilder() - .maximumSize(1) - .refreshAfterWrite(10, TimeUnit.MINUTES) - .build(k -> DataObject.get("Data for " + k)); + LoadingCache cache = Caffeine.newBuilder().maximumSize(1).refreshAfterWrite(10, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k)); assertEquals(0, cache.estimatedSize()); @@ -99,10 +86,7 @@ public class CaffeineUnitTest { @Test public void givenLoadingCacheWithWeigher_whenPut_thenSizeIsConstant() { - LoadingCache cache = Caffeine.newBuilder() - .maximumWeight(10) - .weigher((k,v) -> 5) - .build(k -> DataObject.get("Data for " + k)); + LoadingCache cache = Caffeine.newBuilder().maximumWeight(10).weigher((k, v) -> 5).build(k -> DataObject.get("Data for " + k)); assertEquals(0, cache.estimatedSize()); @@ -122,20 +106,11 @@ public class CaffeineUnitTest { @Test public void givenTimeEvictionCache_whenTimeLeft_thenValueEvicted() { - LoadingCache cache = Caffeine.newBuilder() - .expireAfterAccess(5, TimeUnit.MINUTES) - .build(k -> DataObject.get("Data for " + k)); + LoadingCache cache = Caffeine.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k)); - cache = Caffeine.newBuilder() - .expireAfterWrite(10, TimeUnit.SECONDS) - .weakKeys() - .weakValues() - .build(k -> DataObject.get("Data for " + k)); + cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).weakKeys().weakValues().build(k -> DataObject.get("Data for " + k)); - cache = Caffeine.newBuilder() - .expireAfterWrite(10, TimeUnit.SECONDS) - .softValues() - .build(k -> DataObject.get("Data for " + k)); + cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).softValues().build(k -> DataObject.get("Data for " + k)); cache = Caffeine.newBuilder().expireAfter(new Expiry() { @Override @@ -154,17 +129,12 @@ public class CaffeineUnitTest { } }).build(k -> DataObject.get("Data for " + k)); - cache = Caffeine.newBuilder() - .refreshAfterWrite(1, TimeUnit.MINUTES) - .build(k -> DataObject.get("Data for " + k)); + cache = Caffeine.newBuilder().refreshAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k)); } @Test public void givenCache_whenStatsEnabled_thenStatsRecorded() { - LoadingCache cache = Caffeine.newBuilder() - .maximumSize(100) - .recordStats() - .build(k -> DataObject.get("Data for " + k)); + LoadingCache cache = Caffeine.newBuilder().maximumSize(100).recordStats().build(k -> DataObject.get("Data for " + k)); cache.get("A"); cache.get("A"); diff --git a/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java b/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java index 1224d73724..080444d7b1 100644 --- a/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.cglib.proxy; - import net.sf.cglib.beans.BeanGenerator; import org.junit.Test; @@ -12,21 +11,17 @@ public class BeanGeneratorIntegrationTest { @Test public void givenBeanCreator_whenAddProperty_thenClassShouldHaveFieldValue() throws Exception { - //given + // given BeanGenerator beanGenerator = new BeanGenerator(); - //when + // when beanGenerator.addProperty("name", String.class); Object myBean = beanGenerator.create(); - Method setter = myBean - .getClass() - .getMethod("setName", String.class); + Method setter = myBean.getClass().getMethod("setName", String.class); setter.invoke(myBean, "some string value set by a cglib"); - //then - Method getter = myBean - .getClass() - .getMethod("getName"); + // then + Method getter = myBean.getClass().getMethod("getName"); assertEquals("some string value set by a cglib", getter.invoke(myBean)); } } diff --git a/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java b/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java index 93b34bf92b..fc2f6cc1e1 100644 --- a/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java +++ b/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java @@ -14,14 +14,11 @@ public class MixinUnitTest { @Test public void givenTwoClasses_whenMixedIntoOne_thenMixinShouldHaveMethodsFromBothClasses() throws Exception { - //when - Mixin mixin = Mixin.create( - new Class[]{Interface1.class, Interface2.class, MixinInterface.class}, - new Object[]{new Class1(), new Class2()} - ); + // when + Mixin mixin = Mixin.create(new Class[] { Interface1.class, Interface2.class, MixinInterface.class }, new Object[] { new Class1(), new Class2() }); MixinInterface mixinDelegate = (MixinInterface) mixin; - //then + // then assertEquals("first behaviour", mixinDelegate.first()); assertEquals("second behaviour", mixinDelegate.second()); } diff --git a/libraries/src/test/java/com/baeldung/cglib/proxy/ProxyIntegrationTest.java b/libraries/src/test/java/com/baeldung/cglib/proxy/ProxyIntegrationTest.java index c22a148d4f..d5c8a1b589 100644 --- a/libraries/src/test/java/com/baeldung/cglib/proxy/ProxyIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/cglib/proxy/ProxyIntegrationTest.java @@ -10,34 +10,34 @@ import static org.junit.Assert.assertEquals; public class ProxyIntegrationTest { @Test public void givenPersonService_whenSayHello_thenReturnResult() { - //given + // given PersonService personService = new PersonService(); - //when + // when String res = personService.sayHello("Tom"); - //then + // then assertEquals(res, "Hello Tom"); } @Test public void givenEnhancerProxy_whenExtendPersonService_thenInterceptMethod() throws Exception { - //given + // given Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(PersonService.class); enhancer.setCallback((FixedValue) () -> "Hello Tom!"); PersonService proxy = (PersonService) enhancer.create(); - //when + // when String res = proxy.sayHello(null); - //then + // then assertEquals("Hello Tom!", res); } @Test public void givenEnhancer_whenExecuteMethodOnProxy_thenInterceptOnlyStringReturnTypeMethod() throws Exception { - //given + // given Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(PersonService.class); enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> { @@ -48,10 +48,10 @@ public class ProxyIntegrationTest { } }); - //when + // when PersonService proxy = (PersonService) enhancer.create(); - //then + // then assertEquals("Hello Tom!", proxy.sayHello(null)); int lengthOfName = proxy.lengthOfName("Mary"); assertEquals(4, lengthOfName); diff --git a/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java b/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java index 9c0a0ac910..00e9500318 100644 --- a/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java @@ -14,12 +14,12 @@ import net.openhft.chronicle.ExcerptTailer; import net.openhft.chronicle.tools.ChronicleTools; public class ChronicleQueueIntegrationTest { - + @Test public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException { File queueDir = Files.createTempDirectory("chronicle-queue").toFile(); ChronicleTools.deleteOnExit(queueDir.getPath()); - + Chronicle chronicle = ChronicleQueueBuilder.indexed(queueDir).build(); String stringVal = "Hello World"; int intVal = 101; @@ -37,7 +37,7 @@ public class ChronicleQueueIntegrationTest { } tailer.finish(); tailer.close(); - chronicle.close(); + chronicle.close(); } } diff --git a/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java b/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java index 5407477a00..fd09f4d9f6 100644 --- a/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java +++ b/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java @@ -10,8 +10,7 @@ import org.junit.Test; public class CourseServiceTest { @Test - public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues() - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Course course = new Course(); String name = "Computer Science"; List codes = Arrays.asList("CS", "CS01"); @@ -36,8 +35,7 @@ public class CourseServiceTest { } @Test - public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWithSameName() - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWithSameName() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Course course = new Course(); course.setName("Computer Science"); course.setCodes(Arrays.asList("CS")); diff --git a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java b/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java index aa8b799c9d..f34f431d8e 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java @@ -1,6 +1,5 @@ package com.baeldung.commons.collections; - import com.baeldung.commons.collectionutil.Address; import com.baeldung.commons.collectionutil.Customer; import org.apache.commons.collections4.CollectionUtils; @@ -21,7 +20,6 @@ import static org.junit.Assert.assertTrue; public class CollectionUtilsGuideTest { - Customer customer1 = new Customer(1, "Daniel", 123456l, "locality1", "city1", "1234"); Customer customer4 = new Customer(4, "Bob", 456789l, "locality4", "city4", "4567"); List list1, list2, list3, linkedList1; @@ -77,8 +75,8 @@ public class CollectionUtilsGuideTest { } }); - //filterInverse does the opposite. It removes the element from the list if the Predicate returns true - //select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection + // filterInverse does the opposite. It removes the element from the list if the Predicate returns true + // select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection assertTrue(isModified && linkedList1.size() == 2); } @@ -88,8 +86,8 @@ public class CollectionUtilsGuideTest { List emptyList = new ArrayList<>(); List nullList = null; - //Very handy at times where we want to check if a collection is not null and not empty too. - //isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading + // Very handy at times where we want to check if a collection is not null and not empty too. + // isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading assertTrue(CollectionUtils.isNotEmpty(list1)); assertTrue(CollectionUtils.isEmpty(nullList)); assertTrue(CollectionUtils.isEmpty(emptyList)); diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java index 4685d84781..0033d0786e 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java @@ -27,16 +27,8 @@ import static org.junit.Assert.assertTrue; public class MapUtilsTest { - private String[][] color2DArray = new String[][]{ - {"RED", "#FF0000"}, - {"GREEN", "#00FF00"}, - {"BLUE", "#0000FF"} - }; - private String[] color1DArray = new String[]{ - "RED", "#FF0000", - "GREEN", "#00FF00", - "BLUE", "#0000FF" - }; + private String[][] color2DArray = new String[][] { { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } }; + private String[] color1DArray = new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF" }; private Map colorMap; @Before @@ -92,34 +84,26 @@ public class MapUtilsTest { Map invColorMap = MapUtils.invertMap(this.colorMap); int size = invColorMap.size(); - Assertions.assertThat(invColorMap) - .hasSameSizeAs(colorMap) - .containsKeys(this.colorMap.values().toArray(new String[size])) - .containsValues(this.colorMap.keySet().toArray(new String[size])); + Assertions.assertThat(invColorMap).hasSameSizeAs(colorMap).containsKeys(this.colorMap.values().toArray(new String[size])).containsValues(this.colorMap.keySet().toArray(new String[size])); } @Test(expected = IllegalArgumentException.class) public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() { - Map rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll( - new HashMap(), - this.color1DArray)); + Map rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll(new HashMap(), this.color1DArray)); rgbMap.put("ORANGE", "#FFA500"); } @Test(expected = IllegalArgumentException.class) public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() { - Map uniqValuesMap - = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate()); + Map uniqValuesMap = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate()); uniqValuesMap.put("NEW_RED", "#FF0000"); } @Test public void whenCreateLazyMap_theMapIsCreated() { - Map intStrMap = MapUtils.lazyMap( - new HashMap(), - TransformerUtils.stringValueTransformer()); + Map intStrMap = MapUtils.lazyMap(new HashMap(), TransformerUtils.stringValueTransformer()); assertThat(intStrMap, is(anEmptyMap())); diff --git a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java index 7d214bc5c5..aa73ed6109 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java @@ -17,8 +17,7 @@ public class SetUtilsUnitTest { public void givenSetAndPredicate_whenPredicatedSet_thenValidateSet_and_throw_IllegalArgumentException() { Set sourceSet = new HashSet<>(); sourceSet.addAll(Arrays.asList("London", "Lagos", "Err Source1")); - Set validatingSet - = SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L")); + Set validatingSet = SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L")); validatingSet.add("Err Source2"); } diff --git a/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java index 7a05228e51..c64143cba7 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java @@ -14,8 +14,8 @@ import static org.junit.Assert.assertEquals; public class OrderedMapUnitTest { - private String[] names = {"Emily", "Mathew", "Rose", "John", "Anna"}; - private Integer[] ages = {37, 28, 40, 36, 21}; + private String[] names = { "Emily", "Mathew", "Rose", "John", "Anna" }; + private Integer[] ages = { 37, 28, 40, 36, 21 }; private int RUNNERS_COUNT = names.length; diff --git a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java index 55fadcbf85..4408dcc195 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java +++ b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java @@ -15,94 +15,88 @@ import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; public class BagTests { - + @Test public void givenMultipleCopies_whenAdded_theCountIsKept() { - Bag bag = new HashBag<>( - Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); - + Bag bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); + assertThat(bag.getCount(1), equalTo(2)); } - + @Test public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() { Collection collection = new ArrayList<>(); - + // Collection contract defines that add() should return true assertThat(collection.add(9), is(true)); - + // Even when element is already in the collection collection.add(1); assertThat(collection.add(1), is(true)); - + Bag bag = new HashBag<>(); - + // Bag returns true on adding a new element assertThat(bag.add(9), is(true)); - + bag.add(1); // But breaks the contract with false when it has to increment the count assertThat(bag.add(1), is(not(true))); } - + @Test public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() { Bag bag = CollectionBag.collectionBag(new HashBag<>()); - + bag.add(1); // This time the behavior is compliant to the Java Collection assertThat(bag.add(1), is((true))); } - + @Test public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() { Bag bag = new HashBag<>(); - + // Adding 1 for 5 times bag.add(1, 5); assertThat(bag.getCount(1), equalTo(5)); } - + @Test public void givenMultipleCopies_whenRemove_allAreRemoved() { - Bag bag = new HashBag<>( - Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); - + Bag bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); + // From 3 we delete 1, 2 remain bag.remove(3, 1); assertThat(bag.getCount(3), equalTo(2)); - + // From 2 we delete all bag.remove(1); assertThat(bag.getCount(1), equalTo(0)); } - + @Test public void givenTree_whenDuplicateElementsAdded_thenSort() { - TreeBag bag = new TreeBag<>( - Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })); - + TreeBag bag = new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })); + assertThat(bag.first(), equalTo(1)); assertThat(bag.getCount(bag.first()), equalTo(2)); assertThat(bag.last(), equalTo(7)); assertThat(bag.getCount(bag.last()), equalTo(3)); } - + @Test public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() { - SortedBag bag = CollectionSortedBag - .collectionSortedBag(new TreeBag<>()); - + SortedBag bag = CollectionSortedBag.collectionSortedBag(new TreeBag<>()); + bag.add(1); assertThat(bag.add(1), is((true))); } - + @Test public void givenSortedBag_whenDuplicateElementsAdded_thenSort() { - SynchronizedSortedBag bag = SynchronizedSortedBag - .synchronizedSortedBag(new TreeBag<>( - Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }))); - + SynchronizedSortedBag bag = SynchronizedSortedBag.synchronizedSortedBag(new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }))); + assertThat(bag.first(), equalTo(1)); assertThat(bag.getCount(bag.first()), equalTo(2)); assertThat(bag.last(), equalTo(7)); diff --git a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java index 6f47b89396..6210bb51a9 100644 --- a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java +++ b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java @@ -29,10 +29,7 @@ public class CSVReaderWriterTest { @Test public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException { Reader in = new FileReader("src/test/resources/book.csv"); - Iterable records = CSVFormat.DEFAULT - .withHeader(HEADERS) - .withFirstRecordAsHeader() - .parse(in); + Iterable records = CSVFormat.DEFAULT.withHeader(HEADERS).withFirstRecordAsHeader().parse(in); for (CSVRecord record : records) { String author = record.get("author"); String title = record.get("title"); @@ -52,9 +49,7 @@ public class CSVReaderWriterTest { } }); } - assertEquals(EXPECTED_FILESTREAM, sw - .toString() - .trim()); + assertEquals(EXPECTED_FILESTREAM, sw.toString().trim()); } } diff --git a/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java index bc7623589c..02cec7d53a 100644 --- a/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java @@ -47,10 +47,8 @@ public class DbUtilsUnitTest { List> list = runner.query(connection, "SELECT * FROM employee", beanListHandler); assertEquals(list.size(), 5); - assertEquals(list.get(0) - .get("firstname"), "John"); - assertEquals(list.get(4) - .get("firstname"), "Christian"); + assertEquals(list.get(0).get("firstname"), "John"); + assertEquals(list.get(4).get("firstname"), "Christian"); } @Test @@ -61,10 +59,8 @@ public class DbUtilsUnitTest { List employeeList = runner.query(connection, "SELECT * FROM employee", beanListHandler); assertEquals(employeeList.size(), 5); - assertEquals(employeeList.get(0) - .getFirstName(), "John"); - assertEquals(employeeList.get(4) - .getFirstName(), "Christian"); + assertEquals(employeeList.get(0).getFirstName(), "John"); + assertEquals(employeeList.get(4).getFirstName(), "Christian"); } @Test @@ -85,12 +81,8 @@ public class DbUtilsUnitTest { QueryRunner runner = new QueryRunner(); List employees = runner.query(connection, "SELECT * FROM employee", employeeHandler); - assertEquals(employees.get(0) - .getEmails() - .size(), 2); - assertEquals(employees.get(2) - .getEmails() - .size(), 3); + assertEquals(employees.get(0).getEmails().size(), 2); + assertEquals(employees.get(2).getEmails().size(), 3); assertNotNull(employees.get(0).getEmails().get(0).getEmployeeId()); } diff --git a/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java b/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java index 3c82c30d9b..7481e5a1a3 100644 --- a/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java @@ -25,30 +25,23 @@ import java.nio.charset.Charset; public class CommonsIOUnitTest { @Test - public void whenCopyANDReadFileTesttxt_thenMatchExpectedData() - throws IOException { + public void whenCopyANDReadFileTesttxt_thenMatchExpectedData() throws IOException { String expectedData = "Hello World from fileTest.txt!!!"; - File file = FileUtils.getFile(getClass().getClassLoader() - .getResource("fileTest.txt") - .getPath()); + File file = FileUtils.getFile(getClass().getClassLoader().getResource("fileTest.txt").getPath()); File tempDir = FileUtils.getTempDirectory(); FileUtils.copyFileToDirectory(file, tempDir); File newTempFile = FileUtils.getFile(tempDir, file.getName()); - String data = FileUtils.readFileToString(newTempFile, - Charset.defaultCharset()); + String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset()); Assert.assertEquals(expectedData, data.trim()); } @Test - public void whenUsingFileNameUtils_thenshowdifferentFileOperations() - throws IOException { + public void whenUsingFileNameUtils_thenshowdifferentFileOperations() throws IOException { - String path = getClass().getClassLoader() - .getResource("fileTest.txt") - .getPath(); + String path = getClass().getClassLoader().getResource("fileTest.txt").getPath(); String fullPath = FilenameUtils.getFullPath(path); String extension = FilenameUtils.getExtension(path); @@ -60,70 +53,54 @@ public class CommonsIOUnitTest { } @Test - public void whenUsingFileSystemUtils_thenDriveFreeSpace() - throws IOException { + public void whenUsingFileSystemUtils_thenDriveFreeSpace() throws IOException { long freeSpace = FileSystemUtils.freeSpaceKb("/"); } @SuppressWarnings("resource") @Test - public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams() - throws IOException { + public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams() throws IOException { final String str = "Hello World."; ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes()); ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream(); - - FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1,outputStream2); + + FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1, outputStream2); new TeeInputStream(inputStream, teeOutputStream, true).read(new byte[str.length()]); - + Assert.assertEquals(str, String.valueOf(outputStream1)); Assert.assertEquals(str, String.valueOf(outputStream2)); - } + } @Test - public void whenGetFilewithNameFileFilter_thenFindfileTesttxt() - throws IOException { + public void whenGetFilewithNameFileFilter_thenFindfileTesttxt() throws IOException { final String testFile = "fileTest.txt"; - String path = getClass().getClassLoader() - .getResource(testFile) - .getPath(); + String path = getClass().getClassLoader().getResource(testFile).getPath(); File dir = FileUtils.getFile(FilenameUtils.getFullPath(path)); String[] possibleNames = { "NotThisOne", testFile }; - Assert.assertEquals(testFile, - dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]); + Assert.assertEquals(testFile, dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]); } @Test - public void whenGetFilewith_ANDFileFilter_thenFindsampletxt() - throws IOException { + public void whenGetFilewith_ANDFileFilter_thenFindsampletxt() throws IOException { - String path = getClass().getClassLoader() - .getResource("fileTest.txt") - .getPath(); + String path = getClass().getClassLoader().getResource("fileTest.txt").getPath(); File dir = FileUtils.getFile(FilenameUtils.getFullPath(path)); - Assert.assertEquals("sample.txt", - dir.list(new AndFileFilter( - new WildcardFileFilter("*ple*", IOCase.INSENSITIVE), - new SuffixFileFilter("txt")))[0]); + Assert.assertEquals("sample.txt", dir.list(new AndFileFilter(new WildcardFileFilter("*ple*", IOCase.INSENSITIVE), new SuffixFileFilter("txt")))[0]); } @Test - public void whenSortDirWithPathFileComparator_thenFirstFileaaatxt() - throws IOException { + public void whenSortDirWithPathFileComparator_thenFirstFileaaatxt() throws IOException { - PathFileComparator pathFileComparator = new PathFileComparator( - IOCase.INSENSITIVE); - String path = FilenameUtils.getFullPath(getClass().getClassLoader() - .getResource("fileTest.txt") - .getPath()); + PathFileComparator pathFileComparator = new PathFileComparator(IOCase.INSENSITIVE); + String path = FilenameUtils.getFullPath(getClass().getClassLoader().getResource("fileTest.txt").getPath()); File dir = new File(path); File[] files = dir.listFiles(); @@ -133,16 +110,11 @@ public class CommonsIOUnitTest { } @Test - public void whenSizeFileComparator_thenLargerFile() - throws IOException { + public void whenSizeFileComparator_thenLargerFile() throws IOException { SizeFileComparator sizeFileComparator = new SizeFileComparator(); - File largerFile = FileUtils.getFile(getClass().getClassLoader() - .getResource("fileTest.txt") - .getPath()); - File smallerFile = FileUtils.getFile(getClass().getClassLoader() - .getResource("sample.txt") - .getPath()); + File largerFile = FileUtils.getFile(getClass().getClassLoader().getResource("fileTest.txt").getPath()); + File smallerFile = FileUtils.getFile(getClass().getClassLoader().getResource("sample.txt").getPath()); int i = sizeFileComparator.compare(largerFile, smallerFile); diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java index 97db4ddbe4..f34008fb1f 100644 --- a/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java @@ -9,71 +9,71 @@ import static org.junit.Assert.assertEquals; public class ArrayUtilsUnitTest { @Test public void givenArray_whenAddingElementAtSpecifiedPosition_thenCorrect() { - int[] oldArray = {2, 3, 4, 5}; + int[] oldArray = { 2, 3, 4, 5 }; int[] newArray = ArrayUtils.add(oldArray, 0, 1); - int[] expectedArray = {1, 2, 3, 4, 5}; + int[] expectedArray = { 1, 2, 3, 4, 5 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenAddingElementAtTheEnd_thenCorrect() { - int[] oldArray = {2, 3, 4, 5}; + int[] oldArray = { 2, 3, 4, 5 }; int[] newArray = ArrayUtils.add(oldArray, 1); - int[] expectedArray = {2, 3, 4, 5, 1}; + int[] expectedArray = { 2, 3, 4, 5, 1 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenAddingAllElementsAtTheEnd_thenCorrect() { - int[] oldArray = {0, 1, 2}; + int[] oldArray = { 0, 1, 2 }; int[] newArray = ArrayUtils.addAll(oldArray, 3, 4, 5); - int[] expectedArray = {0, 1, 2, 3, 4, 5}; + int[] expectedArray = { 0, 1, 2, 3, 4, 5 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingElementAtSpecifiedPosition_thenCorrect() { - int[] oldArray = {1, 2, 3, 4, 5}; + int[] oldArray = { 1, 2, 3, 4, 5 }; int[] newArray = ArrayUtils.remove(oldArray, 1); - int[] expectedArray = {1, 3, 4, 5}; + int[] expectedArray = { 1, 3, 4, 5 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingAllElementsAtSpecifiedPositions_thenCorrect() { - int[] oldArray = {1, 2, 3, 4, 5}; + int[] oldArray = { 1, 2, 3, 4, 5 }; int[] newArray = ArrayUtils.removeAll(oldArray, 1, 3); - int[] expectedArray = {1, 3, 5}; + int[] expectedArray = { 1, 3, 5 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingAnElement_thenCorrect() { - int[] oldArray = {1, 2, 3, 3, 4}; + int[] oldArray = { 1, 2, 3, 3, 4 }; int[] newArray = ArrayUtils.removeElement(oldArray, 3); - int[] expectedArray = {1, 2, 3, 4}; + int[] expectedArray = { 1, 2, 3, 4 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingElements_thenCorrect() { - int[] oldArray = {1, 2, 3, 3, 4}; + int[] oldArray = { 1, 2, 3, 3, 4 }; int[] newArray = ArrayUtils.removeElements(oldArray, 2, 3, 5); - int[] expectedArray = {1, 3, 4}; + int[] expectedArray = { 1, 3, 4 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenRemovingAllElementOccurences_thenCorrect() { - int[] oldArray = {1, 2, 2, 2, 3}; + int[] oldArray = { 1, 2, 2, 2, 3 }; int[] newArray = ArrayUtils.removeAllOccurences(oldArray, 2); - int[] expectedArray = {1, 3}; + int[] expectedArray = { 1, 3 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenCheckingExistingElement_thenCorrect() { - int[] array = {1, 3, 5, 7, 9}; + int[] array = { 1, 3, 5, 7, 9 }; boolean evenContained = ArrayUtils.contains(array, 2); boolean oddContained = ArrayUtils.contains(array, 7); assertEquals(false, evenContained); @@ -82,57 +82,57 @@ public class ArrayUtilsUnitTest { @Test public void givenArray_whenReversingElementsWithinARange_thenCorrect() { - int[] originalArray = {1, 2, 3, 4, 5}; + int[] originalArray = { 1, 2, 3, 4, 5 }; ArrayUtils.reverse(originalArray, 1, 4); - int[] expectedArray = {1, 4, 3, 2, 5}; + int[] expectedArray = { 1, 4, 3, 2, 5 }; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenReversingAllElements_thenCorrect() { - int[] originalArray = {1, 2, 3, 4, 5}; + int[] originalArray = { 1, 2, 3, 4, 5 }; ArrayUtils.reverse(originalArray); - int[] expectedArray = {5, 4, 3, 2, 1}; + int[] expectedArray = { 5, 4, 3, 2, 1 }; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenShiftingElementsWithinARange_thenCorrect() { - int[] originalArray = {1, 2, 3, 4, 5}; + int[] originalArray = { 1, 2, 3, 4, 5 }; ArrayUtils.shift(originalArray, 1, 4, 1); - int[] expectedArray = {1, 4, 2, 3, 5}; + int[] expectedArray = { 1, 4, 2, 3, 5 }; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenShiftingAllElements_thenCorrect() { - int[] originalArray = {1, 2, 3, 4, 5}; + int[] originalArray = { 1, 2, 3, 4, 5 }; ArrayUtils.shift(originalArray, 1); - int[] expectedArray = {5, 1, 2, 3, 4}; + int[] expectedArray = { 5, 1, 2, 3, 4 }; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenExtractingElements_thenCorrect() { - int[] oldArray = {1, 2, 3, 4, 5}; + int[] oldArray = { 1, 2, 3, 4, 5 }; int[] newArray = ArrayUtils.subarray(oldArray, 2, 7); - int[] expectedArray = {3, 4, 5}; + int[] expectedArray = { 3, 4, 5 }; assertArrayEquals(expectedArray, newArray); } @Test public void givenArray_whenSwapingElementsWithinARange_thenCorrect() { - int[] originalArray = {1, 2, 3, 4, 5}; + int[] originalArray = { 1, 2, 3, 4, 5 }; ArrayUtils.swap(originalArray, 0, 3, 2); - int[] expectedArray = {4, 5, 3, 1, 2}; + int[] expectedArray = { 4, 5, 3, 1, 2 }; assertArrayEquals(expectedArray, originalArray); } @Test public void givenArray_whenSwapingElementsAtSpecifiedPositions_thenCorrect() { - int[] originalArray = {1, 2, 3, 4, 5}; + int[] originalArray = { 1, 2, 3, 4, 5 }; ArrayUtils.swap(originalArray, 0, 3); - int[] expectedArray = {4, 2, 3, 1, 5}; + int[] expectedArray = { 4, 2, 3, 1, 5 }; assertArrayEquals(expectedArray, originalArray); } } diff --git a/libraries/src/test/java/com/baeldung/commons/math/IntegrationTest.java b/libraries/src/test/java/com/baeldung/commons/math/IntegrationTest.java index 65c1a0db8e..7e047577e5 100644 --- a/libraries/src/test/java/com/baeldung/commons/math/IntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/commons/math/IntegrationTest.java @@ -15,7 +15,7 @@ public class IntegrationTest { final double i = integrator.integrate(100, function, 0, 10); - Assert.assertEquals(16 + 2d/3d, i, 1e-7); + Assert.assertEquals(16 + 2d / 3d, i, 1e-7); } } diff --git a/libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java b/libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java index 278f54a67f..49bf33baa5 100644 --- a/libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java @@ -8,9 +8,7 @@ public class LinearAlgebraUnitTest { @Test public void whenDecompositionSolverSolve_thenCorrect() { - RealMatrix a = - new Array2DRowRealMatrix(new double[][] { { 2, 3, -2 }, { -1, 7, 6 }, { 4, -3, -5 } }, - false); + RealMatrix a = new Array2DRowRealMatrix(new double[][] { { 2, 3, -2 }, { -1, 7, 6 }, { 4, -3, -5 } }, false); RealVector b = new ArrayRealVector(new double[] { 1, -2, 1 }, false); DecompositionSolver solver = new LUDecomposition(a).getSolver(); diff --git a/libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java index 025880fc12..3069446c3c 100644 --- a/libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java @@ -12,10 +12,10 @@ public class StatisticsUnitTest { @Before public void setUp() { - values = new double[] {65, 51 , 16, 11 , 6519, 191 ,0 , 98, 19854, 1, 32}; + values = new double[] { 65, 51, 16, 11, 6519, 191, 0, 98, 19854, 1, 32 }; descriptiveStatistics = new DescriptiveStatistics(); - for(double v : values) { + for (double v : values) { descriptiveStatistics.addValue(v); } } diff --git a/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java b/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java index 8309e755ce..3d3c952863 100644 --- a/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java +++ b/libraries/src/test/java/com/baeldung/crdt/CRDTTest.java @@ -13,42 +13,41 @@ public class CRDTTest { @Test public void givenGrowOnlySet_whenTwoReplicasDiverge_thenShouldMergeItWithoutAConflict() { - //given + // given final LocalCrdtStore crdtStore1 = new LocalCrdtStore(); final LocalCrdtStore crdtStore2 = new LocalCrdtStore(); crdtStore1.connect(crdtStore2); final GSet replica1 = crdtStore1.createGSet("ID_1"); - final GSet replica2 = crdtStore2.findGSet("ID_1").get(); + final GSet replica2 = crdtStore2. findGSet("ID_1").get(); - //when + // when replica1.add("apple"); replica2.add("banana"); - //then + // then assertThat(replica1).contains("apple", "banana"); assertThat(replica2).contains("apple", "banana"); - //when + // when crdtStore1.disconnect(crdtStore2); replica1.add("strawberry"); replica2.add("pear"); - assertThat(replica1).contains("apple", "banana", "strawberry"); assertThat(replica2).contains("apple", "banana", "pear"); crdtStore1.connect(crdtStore2); - //then + // then assertThat(replica1).contains("apple", "banana", "strawberry", "pear"); assertThat(replica2).contains("apple", "banana", "strawberry", "pear"); } @Test public void givenIncrementOnlyCounter_whenTwoReplicasDiverge_thenShouldMergeIt() { - //given + // given final LocalCrdtStore crdtStore1 = new LocalCrdtStore(); final LocalCrdtStore crdtStore2 = new LocalCrdtStore(); crdtStore1.connect(crdtStore2); @@ -56,21 +55,20 @@ public class CRDTTest { final GCounter replica1 = crdtStore1.createGCounter("ID_1"); final GCounter replica2 = crdtStore2.findGCounter("ID_1").get(); - //when + // when replica1.increment(); replica2.increment(2L); - //then + // then assertThat(replica1.get()).isEqualTo(3L); assertThat(replica2.get()).isEqualTo(3L); - //when + // when crdtStore1.disconnect(crdtStore2); replica1.increment(3L); replica2.increment(5L); - assertThat(replica1.get()).isEqualTo(6L); assertThat(replica2.get()).isEqualTo(8L); @@ -91,15 +89,15 @@ public class CRDTTest { final PNCounter replica1 = crdtStore1.createPNCounter("ID_1"); final PNCounter replica2 = crdtStore2.findPNCounter("ID_1").get(); - //when + // when replica1.increment(); replica2.decrement(2L); - //then + // then assertThat(replica1.get()).isEqualTo(-1L); assertThat(replica2.get()).isEqualTo(-1L); - //when + // when crdtStore1.disconnect(crdtStore2); replica1.decrement(3L); @@ -110,22 +108,22 @@ public class CRDTTest { crdtStore1.connect(crdtStore2); - //then + // then assertThat(replica1.get()).isEqualTo(1L); assertThat(replica2.get()).isEqualTo(1L); } @Test public void givenLastWriteWinsStrategy_whenReplicasDiverge_thenAfterMergeShouldKeepOnlyLastValue() { - //given + // given final LocalCrdtStore crdtStore1 = new LocalCrdtStore("N_1"); final LocalCrdtStore crdtStore2 = new LocalCrdtStore("N_2"); crdtStore1.connect(crdtStore2); final LWWRegister replica1 = crdtStore1.createLWWRegister("ID_1"); - final LWWRegister replica2 = crdtStore2.findLWWRegister("ID_1").get(); + final LWWRegister replica2 = crdtStore2. findLWWRegister("ID_1").get(); - //when + // when replica1.set("apple"); replica2.set("banana"); @@ -133,20 +131,18 @@ public class CRDTTest { assertThat(replica1.get()).isEqualTo("banana"); assertThat(replica2.get()).isEqualTo("banana"); - // when crdtStore1.disconnect(crdtStore2); replica1.set("strawberry"); replica2.set("pear"); - assertThat(replica1.get()).isEqualTo("strawberry"); assertThat(replica2.get()).isEqualTo("pear"); crdtStore1.connect(crdtStore2); - //then + // then assertThat(replica1.get()).isEqualTo("pear"); assertThat(replica2.get()).isEqualTo("pear"); } diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java index 68775fac66..936fd3e839 100644 --- a/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java @@ -19,25 +19,19 @@ public class DistinctWithJavaFunctionUnitTest { @Test public void whenFilterListByName_thenSizeShouldBe4() { - List personListFiltered = personList.stream() - .filter(distinctByKey(p -> p.getName())) - .collect(Collectors.toList()); + List personListFiltered = personList.stream().filter(distinctByKey(p -> p.getName())).collect(Collectors.toList()); assertTrue(personListFiltered.size() == 4); } @Test public void whenFilterListByAge_thenSizeShouldBe2() { - List personListFiltered = personList.stream() - .filter(distinctByKey(p -> p.getAge())) - .collect(Collectors.toList()); + List personListFiltered = personList.stream().filter(distinctByKey(p -> p.getAge())).collect(Collectors.toList()); assertTrue(personListFiltered.size() == 2); } @Test public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() { - List personListFiltered = personList.stream() - .distinct() - .collect(Collectors.toList()); + List personListFiltered = personList.stream().distinct().collect(Collectors.toList()); assertTrue(personListFiltered.size() == 5); } diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java index f50c76a486..c06a5d7e8b 100644 --- a/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java @@ -19,17 +19,13 @@ public class DistinctWithStreamexUnitTest { @Test public void whenFilterListByName_thenSizeShouldBe4() { - List personListFiltered = StreamEx.of(personList) - .distinct(Person::getName) - .toList(); + List personListFiltered = StreamEx.of(personList).distinct(Person::getName).toList(); assertTrue(personListFiltered.size() == 4); } @Test public void whenFilterListByAge_thenSizeShouldBe2() { - List personListFiltered = StreamEx.of(personList) - .distinct(Person::getAge) - .toList(); + List personListFiltered = StreamEx.of(personList).distinct(Person::getAge).toList(); assertTrue(personListFiltered.size() == 2); } diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java index b4025cd313..24593273a1 100644 --- a/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java @@ -17,17 +17,13 @@ public class DistinctWithVavrUnitTest { @Test public void whenFilterListByName_thenSizeShouldBe4() { - List personListFiltered = io.vavr.collection.List.ofAll(personList) - .distinctBy(Person::getName) - .toJavaList(); + List personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getName).toJavaList(); assertTrue(personListFiltered.size() == 4); } @Test public void whenFilterListByAge_thenSizeShouldBe2() { - List personListFiltered = io.vavr.collection.List.ofAll(personList) - .distinctBy(Person::getAge) - .toJavaList(); + List personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getAge).toJavaList(); assertTrue(personListFiltered.size() == 2); } diff --git a/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java index 531e7e7c5b..e6f0fd1c31 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java +++ b/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java @@ -27,138 +27,96 @@ public class ContainerLiveTest { @Test public void whenListingRunningContainers_thenReturnNonEmptyList() { - //when + // when List containers = dockerClient.listContainersCmd().exec(); - //then + // then assertThat(containers.size(), is(not(0))); } @Test public void whenListingExitedContainers_thenReturnNonEmptyList() { - //when - List containers = dockerClient.listContainersCmd() - .withShowSize(true) - .withShowAll(true) - .withStatusFilter("exited") - .exec(); + // when + List containers = dockerClient.listContainersCmd().withShowSize(true).withShowAll(true).withStatusFilter("exited").exec(); - //then + // then assertThat(containers.size(), is(not(0))); } @Test public void whenCreatingContainer_thenMustReturnContainerId() { - //when - CreateContainerResponse container - = dockerClient.createContainerCmd("mongo:3.6") - .withCmd("--bind_ip_all") - .withName("mongo") - .withHostName("baeldung") - .withEnv("MONGO_LATEST_VERSION=3.6") - .withPortBindings(PortBinding.parse("9999:27017")) - .exec(); + // when + CreateContainerResponse container = dockerClient.createContainerCmd("mongo:3.6").withCmd("--bind_ip_all").withName("mongo").withHostName("baeldung").withEnv("MONGO_LATEST_VERSION=3.6").withPortBindings(PortBinding.parse("9999:27017")).exec(); - //then + // then assertThat(container.getId(), is(not(null))); } - @Test public void whenHavingContainer_thenRunContainer() throws InterruptedException { - //when - CreateContainerResponse container - = dockerClient.createContainerCmd("alpine:3.6") - .withCmd("sleep", "10000") - .exec(); + // when + CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec(); Thread.sleep(3000); - //then - dockerClient.startContainerCmd(container.getId()) - .exec(); + // then + dockerClient.startContainerCmd(container.getId()).exec(); - dockerClient.stopContainerCmd(container.getId()) - .exec(); + dockerClient.stopContainerCmd(container.getId()).exec(); } @Test public void whenRunningContainer_thenStopContainer() throws InterruptedException { - //when - CreateContainerResponse container - = dockerClient.createContainerCmd("alpine:3.6") - .withCmd("sleep", "10000") - .exec(); + // when + CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec(); Thread.sleep(3000); - dockerClient.startContainerCmd(container.getId()) - .exec(); + dockerClient.startContainerCmd(container.getId()).exec(); - //then - dockerClient.stopContainerCmd(container.getId()) - .exec(); + // then + dockerClient.stopContainerCmd(container.getId()).exec(); } @Test public void whenRunningContainer_thenKillContainer() throws InterruptedException { - //when - CreateContainerResponse container - = dockerClient.createContainerCmd("alpine:3.6") - .withCmd("sleep", "10000") - .exec(); + // when + CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec(); - dockerClient.startContainerCmd(container.getId()) - .exec(); + dockerClient.startContainerCmd(container.getId()).exec(); Thread.sleep(3000); - dockerClient.stopContainerCmd(container.getId()) - .exec(); + dockerClient.stopContainerCmd(container.getId()).exec(); - //then - dockerClient.killContainerCmd(container.getId()) - .exec(); + // then + dockerClient.killContainerCmd(container.getId()).exec(); } @Test public void whenHavingContainer_thenInspectContainer() { - //when - CreateContainerResponse container - = dockerClient.createContainerCmd("alpine:3.6") - .withCmd("sleep", "10000") - .exec(); + // when + CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec(); - //then - InspectContainerResponse containerResponse - = dockerClient.inspectContainerCmd(container.getId()) - .exec(); + // then + InspectContainerResponse containerResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); assertThat(containerResponse.getId(), is(container.getId())); } - @Test public void givenContainer_whenCommittingContainer_thenMustReturnImageId() { - //given - CreateContainerResponse container - = dockerClient.createContainerCmd("alpine:3.6") - .withCmd("sleep", "10000") - .exec(); + // given + CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec(); - //when - String imageId = dockerClient.commitCmd(container.getId()) - .withEnv("SNAPSHOT_YEAR=2018") - .withMessage("add git support") - .withCmd("sleep", "10000") - .withRepository("alpine") - .withTag("3.6.v2").exec(); + // when + String imageId = dockerClient.commitCmd(container.getId()).withEnv("SNAPSHOT_YEAR=2018").withMessage("add git support").withCmd("sleep", "10000").withRepository("alpine").withTag("3.6.v2").exec(); - //then + // then assertThat(imageId, is(not(null))); } diff --git a/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java index 1023298e25..bedcc66c53 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java +++ b/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java @@ -14,52 +14,40 @@ public class DockerClientLiveTest { @Test public void whenCreatingDockerClient_thenReturnDefaultInstance() { - //when - DefaultDockerClientConfig.Builder config - = DefaultDockerClientConfig.createDefaultConfigBuilder(); + // when + DefaultDockerClientConfig.Builder config = DefaultDockerClientConfig.createDefaultConfigBuilder(); DockerClient dockerClient = DockerClientBuilder.getInstance(config).build(); - //then + // then assertNotNull(dockerClient); } @Test public void whenCreatingDockerClientWithDockerHost_thenReturnInstance() { - //when - DockerClient dockerClient - = DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375") - .build(); + // when + DockerClient dockerClient = DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375").build(); - //then + // then assertNotNull(dockerClient); } @Test public void whenCreatingAdvanceDockerClient_thenReturnInstance() { - //when - DefaultDockerClientConfig config - = DefaultDockerClientConfig.createDefaultConfigBuilder() - .withRegistryEmail("info@bealdung.com") - .withRegistryUrl("register.bealdung.io/v2/") - .withRegistryPassword("strongpassword") - .withRegistryUsername("bealdung") - .withDockerCertPath("/home/bealdung/public/.docker/certs") - .withDockerConfig("/home/bealdung/public/.docker/") - .withDockerTlsVerify("1") - .withDockerHost("tcp://docker.beauldung.com:2376") - .build(); + // when + DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withRegistryEmail("info@bealdung.com").withRegistryUrl("register.bealdung.io/v2/").withRegistryPassword("strongpassword").withRegistryUsername("bealdung") + .withDockerCertPath("/home/bealdung/public/.docker/certs").withDockerConfig("/home/bealdung/public/.docker/").withDockerTlsVerify("1").withDockerHost("tcp://docker.beauldung.com:2376").build(); DockerClient dockerClient = DockerClientBuilder.getInstance(config).build(); - //then + // then assertNotNull(dockerClient); } @Test public void whenCreatingDockerClientWithProperties_thenReturnInstance() { - //when + // when Properties properties = new Properties(); properties.setProperty("registry.email", "info@bealdung.com"); properties.setProperty("registry.url", "register.bealdung.io/v2/"); @@ -70,14 +58,11 @@ public class DockerClientLiveTest { properties.setProperty("DOCKER_TLS_VERIFY", "1"); properties.setProperty("DOCKER_HOST", "tcp://docker.bealdung.com:2376"); - DefaultDockerClientConfig config - = DefaultDockerClientConfig.createDefaultConfigBuilder() - .withProperties(properties) - .build(); + DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withProperties(properties).build(); DockerClient dockerClient = DockerClientBuilder.getInstance(config).build(); - //then + // then assertNotNull(dockerClient); } } diff --git a/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java index ef894b2773..7e8cd6a354 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java +++ b/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java @@ -33,99 +33,84 @@ public class ImageLiveTest { @Test public void whenListingImages_thenReturnNonEmptyList() { - //when + // when List images = dockerClient.listImagesCmd().exec(); - //then + // then assertThat(images.size(), is(not(0))); } @Test public void whenListingImagesWithIntermediateImages_thenReturnNonEmptyList() { - //when - List images = dockerClient.listImagesCmd() - .withShowAll(true).exec(); + // when + List images = dockerClient.listImagesCmd().withShowAll(true).exec(); - //then + // then assertThat(images.size(), is(not(0))); } @Test public void whenListingDanglingImages_thenReturnNonNullList() { - //when - List images = dockerClient.listImagesCmd() - .withDanglingFilter(true).exec(); + // when + List images = dockerClient.listImagesCmd().withDanglingFilter(true).exec(); - //then + // then assertThat(images, is(not(null))); } @Test public void whenBuildingImage_thenMustReturnImageId() { - //when - String imageId = dockerClient.buildImageCmd() - .withDockerfile(new File("src/test/resources/dockerapi/Dockerfile")) - .withPull(true) - .withNoCache(true) - .withTag("alpine:git") - .exec(new BuildImageResultCallback()) - .awaitImageId(); + // when + String imageId = dockerClient.buildImageCmd().withDockerfile(new File("src/test/resources/dockerapi/Dockerfile")).withPull(true).withNoCache(true).withTag("alpine:git").exec(new BuildImageResultCallback()).awaitImageId(); - //then + // then assertThat(imageId, is(not(null))); } @Test public void givenListOfImages_whenInspectImage_thenMustReturnObject() { - //given + // given List images = dockerClient.listImagesCmd().exec(); Image image = images.get(0); - //when - InspectImageResponse imageResponse - = dockerClient.inspectImageCmd(image.getId()).exec(); + // when + InspectImageResponse imageResponse = dockerClient.inspectImageCmd(image.getId()).exec(); - //then + // then assertThat(imageResponse.getId(), is(image.getId())); } @Test public void givenListOfImages_whenTagImage_thenListMustIncrement() { - //given + // given List images = dockerClient.listImagesCmd().exec(); Image image = images.get(0); - //when + // when dockerClient.tagImageCmd(image.getId(), "baeldung/alpine", "3.6.v2").exec(); - //then + // then List imagesNow = dockerClient.listImagesCmd().exec(); assertThat(imagesNow.size(), is(greaterThan(images.size()))); } public void pushingAnImage() throws InterruptedException { - dockerClient.pushImageCmd("baeldung/alpine") - .withTag("3.6.v2") - .exec(new PushImageResultCallback()) - .awaitCompletion(90, TimeUnit.SECONDS); + dockerClient.pushImageCmd("baeldung/alpine").withTag("3.6.v2").exec(new PushImageResultCallback()).awaitCompletion(90, TimeUnit.SECONDS); } @Test public void whenPullingImage_thenImageListNotEmpty() throws InterruptedException { - //when - dockerClient.pullImageCmd("alpine") - .withTag("latest") - .exec(new PullImageResultCallback()) - .awaitCompletion(30, TimeUnit.SECONDS); + // when + dockerClient.pullImageCmd("alpine").withTag("latest").exec(new PullImageResultCallback()).awaitCompletion(30, TimeUnit.SECONDS); - //then + // then List images = dockerClient.listImagesCmd().exec(); assertThat(images.size(), is(not(0))); } @@ -133,12 +118,12 @@ public class ImageLiveTest { @Test public void whenRemovingImage_thenImageListDecrease() { - //when + // when List images = dockerClient.listImagesCmd().exec(); Image image = images.get(0); dockerClient.removeImageCmd(image.getId()).exec(); - //then + // then List imagesNow = dockerClient.listImagesCmd().exec(); assertThat(imagesNow.size(), is(lessThan(images.size()))); } @@ -146,10 +131,10 @@ public class ImageLiveTest { @Test public void whenSearchingImage_thenMustReturn25Items() { - //when + // when List items = dockerClient.searchImagesCmd("Java").exec(); - //then + // then assertThat(items.size(), is(25)); } } diff --git a/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java index 2031a3ebb4..1acbf00e3c 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java +++ b/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java @@ -27,64 +27,51 @@ public class NetworkLiveTest { @Test public void whenListingNetworks_thenSizeMustBeGreaterThanZero() { - //when + // when List networks = dockerClient.listNetworksCmd().exec(); - //then + // then assertThat(networks.size(), is(greaterThan(0))); } @Test public void whenCreatingNetwork_thenRetrieveResponse() { - //when - CreateNetworkResponse networkResponse - = dockerClient.createNetworkCmd() - .withName("baeldungDefault") - .withDriver("bridge").exec(); + // when + CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungDefault").withDriver("bridge").exec(); - //then + // then assertThat(networkResponse, is(not(null))); } @Test public void whenCreatingAdvanceNetwork_thenRetrieveResponse() { - //when - CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd() - .withName("baeldungAdvanced") - .withIpam(new Ipam() - .withConfig(new Ipam.Config() - .withSubnet("172.36.0.0/16") - .withIpRange("172.36.5.0/24"))) - .withDriver("bridge").exec(); + // when + CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungAdvanced").withIpam(new Ipam().withConfig(new Ipam.Config().withSubnet("172.36.0.0/16").withIpRange("172.36.5.0/24"))).withDriver("bridge").exec(); - //then + // then assertThat(networkResponse, is(not(null))); } @Test public void whenInspectingNetwork_thenSizeMustBeGreaterThanZero() { - //when + // when String networkName = "bridge"; - Network network - = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec(); + Network network = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec(); - //then + // then assertThat(network.getName(), is(networkName)); } @Test public void whenCreatingNetwork_thenRemove() throws InterruptedException { - //when - CreateNetworkResponse networkResponse - = dockerClient.createNetworkCmd() - .withName("baeldungDefault") - .withDriver("bridge").exec(); + // when + CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungDefault").withDriver("bridge").exec(); - //then + // then Thread.sleep(4000); dockerClient.removeNetworkCmd(networkResponse.getId()).exec(); } diff --git a/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java index 060af0728c..9e60a76b33 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java +++ b/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java @@ -27,10 +27,10 @@ public class VolumeLiveTest { @Test public void whenListingVolumes_thenSizeMustBeGreaterThanZero() { - //when + // when ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec(); - //then + // then List volumes = volumesResponse.getVolumes(); assertThat(volumes.size(), is(greaterThan(0))); } @@ -38,48 +38,45 @@ public class VolumeLiveTest { @Test public void givenVolumes_whenInspectingVolume_thenReturnNonNullResponse() { - //given + // given ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec(); List volumes = volumesResponse.getVolumes(); InspectVolumeResponse volume = volumes.get(0); - //when - InspectVolumeResponse volumeResponse - = dockerClient.inspectVolumeCmd(volume.getName()).exec(); + // when + InspectVolumeResponse volumeResponse = dockerClient.inspectVolumeCmd(volume.getName()).exec(); - //then + // then assertThat(volumeResponse, is(not(null))); } @Test public void whenCreatingUnnamedVolume_thenGetVolumeId() { - //when + // when CreateVolumeResponse unnamedVolume = dockerClient.createVolumeCmd().exec(); - //then + // then assertThat(unnamedVolume.getName(), is(not(null))); } @Test public void whenCreatingNamedVolume_thenGetVolumeId() { - //when - CreateVolumeResponse namedVolume - = dockerClient.createVolumeCmd().withName("myNamedVolume").exec(); + // when + CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("myNamedVolume").exec(); - //then + // then assertThat(namedVolume.getName(), is(not(null))); } @Test public void whenGettingNamedVolume_thenRemove() throws InterruptedException { - //when - CreateVolumeResponse namedVolume - = dockerClient.createVolumeCmd().withName("anotherNamedVolume").exec(); + // when + CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("anotherNamedVolume").exec(); - //then + // then Thread.sleep(4000); dockerClient.removeVolumeCmd(namedVolume.getName()).exec(); } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java index ee384c2f9d..b1aaceb09b 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java @@ -17,7 +17,6 @@ public class CollectPatternTest { MutableList lastNames = students.collect(Student::getLastName); - Assertions.assertThat(lastNames) - .containsExactly("Hopkins", "Adams"); + Assertions.assertThat(lastNames).containsExactly("Hopkins", "Adams"); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java index 4655431872..e279314034 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java @@ -12,7 +12,6 @@ public class ConvertContainerToAnotherTest { public void whenConvertContainerToAnother_thenCorrect() { MutableList cars = (MutableList) ConvertContainerToAnother.convertToList(); - Assertions.assertThat(cars) - .containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes")); + Assertions.assertThat(cars).containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes")); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java index c5b5e1c412..4ef7348a0d 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java @@ -20,7 +20,6 @@ public class DetectPatternTest { public void whenDetect_thenCorrect() { Integer result = list.detect(Predicates.greaterThan(30)); - Assertions.assertThat(result) - .isEqualTo(41); + Assertions.assertThat(result).isEqualTo(41); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java index 021c72e91e..3091f90908 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java @@ -44,7 +44,6 @@ public class FlatCollectTest { public void whenFlatCollect_thenCorrect() { MutableList addresses = students.flatCollect(Student::getAddresses); - Assertions.assertThat(addresses) - .containsExactlyElementsOf(this.expectedAddresses); + Assertions.assertThat(addresses).containsExactlyElementsOf(this.expectedAddresses); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java index bcd34021b1..01a8fcaef4 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java @@ -17,7 +17,7 @@ public class InjectIntoPatternTest { Integer v = list.get(i); result = result + v.intValue(); } - + assertEquals(15, result); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java index 9c216ecc87..bcb816c34a 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java @@ -18,7 +18,6 @@ public class LazyIterationTest { LazyIterable lazyStudents = students.asLazy(); LazyIterable lastNames = lazyStudents.collect(Student::getLastName); - Assertions.assertThat(lastNames) - .containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez")); + Assertions.assertThat(lastNames).containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez")); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java index c055413cd9..8ef18004aa 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java @@ -31,14 +31,10 @@ public class PartitionPatternTest { return each > 30; } }); - MutableList greaterThanThirty = partitionedFolks.getSelected() - .sortThis(); - MutableList smallerThanThirty = partitionedFolks.getRejected() - .sortThis(); + MutableList greaterThanThirty = partitionedFolks.getSelected().sortThis(); + MutableList smallerThanThirty = partitionedFolks.getRejected().sortThis(); - Assertions.assertThat(smallerThanThirty) - .containsExactly(1, 5, 8, 17, 23); - Assertions.assertThat(greaterThanThirty) - .containsExactly(31, 38, 41); + Assertions.assertThat(smallerThanThirty).containsExactly(1, 5, 8, 17, 23); + Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java index 1666c86333..bd743d56e8 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java @@ -20,10 +20,8 @@ public class RejectPatternTest { @Test public void whenReject_thenCorrect() { - MutableList notGreaterThanThirty = list.reject(Predicates.greaterThan(30)) - .sortThis(); + MutableList notGreaterThanThirty = list.reject(Predicates.greaterThan(30)).sortThis(); - Assertions.assertThat(notGreaterThanThirty) - .containsExactlyElementsOf(this.expectedList); + Assertions.assertThat(notGreaterThanThirty).containsExactlyElementsOf(this.expectedList); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java index d79c864fc5..154be08f08 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java @@ -18,17 +18,14 @@ public class SelectPatternTest { @Test public void givenListwhenSelect_thenCorrect() { - MutableList greaterThanThirty = list.select(Predicates.greaterThan(30)) - .sortThis(); + MutableList greaterThanThirty = list.select(Predicates.greaterThan(30)).sortThis(); - Assertions.assertThat(greaterThanThirty) - .containsExactly(31, 38, 41); + Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41); } @SuppressWarnings("rawtypes") public MutableList selectUsingLambda() { - return list.select(each -> each > 30) - .sortThis(); + return list.select(each -> each > 30).sortThis(); } @SuppressWarnings("unchecked") @@ -36,7 +33,6 @@ public class SelectPatternTest { public void givenListwhenSelectUsingLambda_thenCorrect() { MutableList greaterThanThirty = selectUsingLambda(); - Assertions.assertThat(greaterThanThirty) - .containsExactly(31, 38, 41); + Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java index 29f0c23954..2b5aa06289 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java @@ -28,7 +28,6 @@ public class ZipTest { MutableList cars = Lists.mutable.with("Porsche", "Volvo", "Toyota"); MutableList> pairs = numbers.zip(cars); - Assertions.assertThat(pairs) - .containsExactlyElementsOf(this.expectedPairs); + Assertions.assertThat(pairs).containsExactlyElementsOf(this.expectedPairs); } } diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java index a2d8be44ec..724f693011 100644 --- a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java @@ -27,7 +27,6 @@ public class ZipWithIndexTest { MutableList cars = FastList.newListWith("Porsche", "Volvo", "Toyota"); MutableList> pairs = cars.zipWithIndex(); - Assertions.assertThat(pairs) - .containsExactlyElementsOf(this.expectedPairs); + Assertions.assertThat(pairs).containsExactlyElementsOf(this.expectedPairs); } } diff --git a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java index 04ab6e43be..33952c8669 100644 --- a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java +++ b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaTest.java @@ -12,49 +12,49 @@ import fj.function.Characters; import fj.function.Integers; public class FunctionalJavaTest { - - public static final F isEven = i -> i % 2 == 0; - + + public static final F isEven = i -> i % 2 == 0; + @Test public void calculateEvenNumbers_givenIntList_returnTrue() { - List fList = List.list(3, 4, 5, 6); + List fList = List.list(3, 4, 5, 6); List evenList = fList.map(isEven); List evenListTrueResult = List.list(false, true, false, true); List evenListFalseResult = List.list(true, false, false, true); assertEquals(evenList.equals(evenListTrueResult), true); assertEquals(evenList.equals(evenListFalseResult), false); } - + @Test public void mapList_givenIntList_returnResult() { - List fList = List.list(3, 4, 5, 6); - fList = fList.map(i -> i + 100); - List resultList = List.list(103, 104, 105, 106); - List falseResultList = List.list(15, 504, 105, 106); - assertEquals(fList.equals(resultList), true); - assertEquals(fList.equals(falseResultList), false); + List fList = List.list(3, 4, 5, 6); + fList = fList.map(i -> i + 100); + List resultList = List.list(103, 104, 105, 106); + List falseResultList = List.list(15, 504, 105, 106); + assertEquals(fList.equals(resultList), true); + assertEquals(fList.equals(falseResultList), false); } - + @Test public void filterList_givenIntList_returnResult() { - Array array = Array.array(3, 4, 5, 6); - Array filteredArray = array.filter(Integers.even); - Array result = Array.array(4, 6); - Array wrongResult = Array.array(3, 5); - assertEquals(filteredArray.equals(result), true); - assertEquals(filteredArray.equals(wrongResult), false); + Array array = Array.array(3, 4, 5, 6); + Array filteredArray = array.filter(Integers.even); + Array result = Array.array(4, 6); + Array wrongResult = Array.array(3, 5); + assertEquals(filteredArray.equals(result), true); + assertEquals(filteredArray.equals(wrongResult), false); } - + @Test public void checkForLowerCase_givenStringArray_returnResult() { - Array array = Array.array("Welcome", "To", "baeldung"); - Array array2 = Array.array("Welcome", "To", "Baeldung"); + Array array = Array.array("Welcome", "To", "baeldung"); + Array array2 = Array.array("Welcome", "To", "Baeldung"); Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); Boolean isExist2 = array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); assertEquals(isExist, true); assertEquals(isExist2, false); } - + @Test public void checkOptions_givenOptions_returnResult() { Option n1 = Option.some(1); @@ -64,16 +64,16 @@ public class FunctionalJavaTest { Option result1 = n1.bind(f1); Option result2 = n2.bind(f1); - + assertEquals(result1, Option.none()); assertEquals(result2, Option.some(102)); } - + @Test public void foldLeft_givenArray_returnResult() { Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27); int sum = intArray.foldLeft(Integers.add, 0); assertEquals(sum, 260); } - + } diff --git a/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java b/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java index f864c5f017..5c788e86d6 100644 --- a/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/flink/WordCountIntegrationTest.java @@ -20,51 +20,45 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; - public class WordCountIntegrationTest { private final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); @Test public void givenDataSet_whenExecuteWordCount_thenReturnWordCount() throws Exception { - //given + // given List lines = Arrays.asList("This is a first sentence", "This is a second sentence with a one word"); - //when + // when DataSet> result = WordCount.startWordCount(env, lines); - //then + // then List> collect = result.collect(); - assertThat(collect).containsExactlyInAnyOrder( - new Tuple2<>("a", 3), new Tuple2<>("sentence", 2), new Tuple2<>("word", 1), - new Tuple2<>("is", 2), new Tuple2<>("this", 2), new Tuple2<>("second", 1), - new Tuple2<>("first", 1), new Tuple2<>("with", 1), new Tuple2<>("one", 1)); + assertThat(collect).containsExactlyInAnyOrder(new Tuple2<>("a", 3), new Tuple2<>("sentence", 2), new Tuple2<>("word", 1), new Tuple2<>("is", 2), new Tuple2<>("this", 2), new Tuple2<>("second", 1), new Tuple2<>("first", 1), new Tuple2<>("with", 1), + new Tuple2<>("one", 1)); } @Test public void givenListOfAmounts_whenUseMapReduce_thenSumAmountsThatAreOnlyAboveThreshold() throws Exception { - //given + // given DataSet amounts = env.fromElements(1, 29, 40, 50); int threshold = 30; - //when - List collect = amounts - .filter(a -> a > threshold) - .reduce((integer, t1) -> integer + t1) - .collect(); + // when + List collect = amounts.filter(a -> a > threshold).reduce((integer, t1) -> integer + t1).collect(); - //then + // then assertThat(collect.get(0)).isEqualTo(90); } @Test public void givenDataSetOfComplexObjects_whenMapToGetOneField_thenReturnedListHaveProperElements() throws Exception { - //given + // given DataSet personDataSource = env.fromCollection(Arrays.asList(new Person(23, "Tom"), new Person(75, "Michael"))); - //when + // when List ages = personDataSource.map(p -> p.age).collect(); - //then + // then assertThat(ages).hasSize(2); assertThat(ages).contains(23, 75); @@ -72,44 +66,33 @@ public class WordCountIntegrationTest { @Test public void givenDataSet_whenSortItByOneField_thenShouldReturnSortedDataSet() throws Exception { - //given + // given Tuple2 secondPerson = new Tuple2<>(4, "Tom"); Tuple2 thirdPerson = new Tuple2<>(5, "Scott"); Tuple2 fourthPerson = new Tuple2<>(200, "Michael"); Tuple2 firstPerson = new Tuple2<>(1, "Jack"); - DataSet> transactions = env.fromElements(fourthPerson, secondPerson, - thirdPerson, firstPerson); + DataSet> transactions = env.fromElements(fourthPerson, secondPerson, thirdPerson, firstPerson); + // when + List> sorted = transactions.sortPartition(new IdKeySelectorTransaction(), Order.ASCENDING).collect(); - //when - List> sorted = transactions - .sortPartition(new IdKeySelectorTransaction(), Order.ASCENDING) - .collect(); - - //then + // then assertThat(sorted).containsExactly(firstPerson, secondPerson, thirdPerson, fourthPerson); } - @Test public void giveTwoDataSets_whenJoinUsingId_thenProduceJoinedData() throws Exception { - //given + // given Tuple3 address = new Tuple3<>(1, "5th Avenue", "London"); DataSet> addresses = env.fromElements(address); Tuple2 firstTransaction = new Tuple2<>(1, "Transaction_1"); - DataSet> transactions = - env.fromElements(firstTransaction, new Tuple2<>(12, "Transaction_2")); + DataSet> transactions = env.fromElements(firstTransaction, new Tuple2<>(12, "Transaction_2")); + // when + List, Tuple3>> joined = transactions.join(addresses).where(new IdKeySelectorTransaction()).equalTo(new IdKeySelectorAddress()).collect(); - //when - List, Tuple3>> joined = - transactions.join(addresses) - .where(new IdKeySelectorTransaction()) - .equalTo(new IdKeySelectorAddress()) - .collect(); - - //then + // then assertThat(joined).hasSize(1); assertThat(joined).contains(new Tuple2<>(firstTransaction, address)); @@ -117,48 +100,40 @@ public class WordCountIntegrationTest { @Test public void givenStreamOfEvents_whenProcessEvents_thenShouldPrintResultsOnSinkOperation() throws Exception { - //given + // given final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); - DataStream text - = env.fromElements("This is a first sentence", "This is a second sentence with a one word"); - + DataStream text = env.fromElements("This is a first sentence", "This is a second sentence with a one word"); SingleOutputStreamOperator upperCase = text.map(String::toUpperCase); upperCase.print(); - //when + // when env.execute(); } - @Test public void givenStreamOfEvents_whenProcessEvents_thenShouldApplyWindowingOnTransformation() throws Exception { - //given + // given final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); - SingleOutputStreamOperator> windowed = env.fromElements( - new Tuple2<>(16, ZonedDateTime.now().plusMinutes(25).toInstant().getEpochSecond()), - new Tuple2<>(15, ZonedDateTime.now().plusMinutes(2).toInstant().getEpochSecond()) - ).assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor>(Time.seconds(20)) { - @Override - public long extractTimestamp(Tuple2 element) { - return element.f1 * 1000; - } - }); + SingleOutputStreamOperator> windowed = env.fromElements(new Tuple2<>(16, ZonedDateTime.now().plusMinutes(25).toInstant().getEpochSecond()), new Tuple2<>(15, ZonedDateTime.now().plusMinutes(2).toInstant().getEpochSecond())) + .assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor>(Time.seconds(20)) { + @Override + public long extractTimestamp(Tuple2 element) { + return element.f1 * 1000; + } + }); - SingleOutputStreamOperator> reduced = windowed - .windowAll(TumblingEventTimeWindows.of(Time.seconds(5))) - .maxBy(0, true); + SingleOutputStreamOperator> reduced = windowed.windowAll(TumblingEventTimeWindows.of(Time.seconds(5))).maxBy(0, true); reduced.print(); - //when + // when env.execute(); } - private static class IdKeySelectorTransaction implements KeySelector, Integer> { @Override public Integer getKey(Tuple2 value) { diff --git a/libraries/src/test/java/com/baeldung/google/sheets/GoogleSheetsIntegrationTest.java b/libraries/src/test/java/com/baeldung/google/sheets/GoogleSheetsIntegrationTest.java index 5280073be2..ba1861937b 100644 --- a/libraries/src/test/java/com/baeldung/google/sheets/GoogleSheetsIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/google/sheets/GoogleSheetsIntegrationTest.java @@ -30,7 +30,7 @@ public class GoogleSheetsIntegrationTest { private static Sheets sheetsService; - // this id can be replaced with your spreadsheet id + // this id can be replaced with your spreadsheet id // otherwise be advised that multiple people may run this test and update the public spreadsheet private static final String SPREADSHEET_ID = "1sILuxZUnyl_7-MlNThjt765oWshN3Xs-PPLfqYe4DhI"; @@ -41,100 +41,56 @@ public class GoogleSheetsIntegrationTest { @Test public void whenWriteSheet_thenReadSheetOk() throws IOException { - ValueRange body = new ValueRange() - .setValues(Arrays.asList( - Arrays.asList("Expenses January"), - Arrays.asList("books", "30"), - Arrays.asList("pens", "10"), - Arrays.asList("Expenses February"), - Arrays.asList("clothes", "20"), - Arrays.asList("shoes", "5"))); - UpdateValuesResponse result = sheetsService.spreadsheets().values() - .update(SPREADSHEET_ID, "A1", body) - .setValueInputOption("RAW") - .execute(); - - List data = new ArrayList<>(); - data.add(new ValueRange() - .setRange("D1") - .setValues(Arrays.asList( - Arrays.asList("January Total", "=B2+B3")))); - data.add(new ValueRange() - .setRange("D4") - .setValues(Arrays.asList( - Arrays.asList("February Total", "=B5+B6")))); + ValueRange body = new ValueRange().setValues(Arrays.asList(Arrays.asList("Expenses January"), Arrays.asList("books", "30"), Arrays.asList("pens", "10"), Arrays.asList("Expenses February"), Arrays.asList("clothes", "20"), Arrays.asList("shoes", "5"))); + UpdateValuesResponse result = sheetsService.spreadsheets().values().update(SPREADSHEET_ID, "A1", body).setValueInputOption("RAW").execute(); + + List data = new ArrayList<>(); + data.add(new ValueRange().setRange("D1").setValues(Arrays.asList(Arrays.asList("January Total", "=B2+B3")))); + data.add(new ValueRange().setRange("D4").setValues(Arrays.asList(Arrays.asList("February Total", "=B5+B6")))); + + BatchUpdateValuesRequest batchBody = new BatchUpdateValuesRequest().setValueInputOption("USER_ENTERED").setData(data); + BatchUpdateValuesResponse batchResult = sheetsService.spreadsheets().values().batchUpdate(SPREADSHEET_ID, batchBody).execute(); + + List ranges = Arrays.asList("E1", "E4"); + BatchGetValuesResponse readResult = sheetsService.spreadsheets().values().batchGet(SPREADSHEET_ID).setRanges(ranges).execute(); - BatchUpdateValuesRequest batchBody = new BatchUpdateValuesRequest() - .setValueInputOption("USER_ENTERED") - .setData(data); - BatchUpdateValuesResponse batchResult = - sheetsService.spreadsheets().values() - .batchUpdate(SPREADSHEET_ID, batchBody) - .execute(); - - List ranges = Arrays.asList("E1","E4"); - BatchGetValuesResponse readResult = - sheetsService.spreadsheets().values() - .batchGet(SPREADSHEET_ID) - .setRanges(ranges) - .execute(); - ValueRange januaryTotal = readResult.getValueRanges().get(0); assertThat(januaryTotal.getValues().get(0).get(0)).isEqualTo("40"); ValueRange febTotal = readResult.getValueRanges().get(1); assertThat(febTotal.getValues().get(0).get(0)).isEqualTo("25"); - ValueRange appendBody = new ValueRange() - .setValues(Arrays.asList( - Arrays.asList("Total", "=E1+E4"))); - AppendValuesResponse appendResult = - sheetsService.spreadsheets().values() - .append(SPREADSHEET_ID, "A1", appendBody) - .setValueInputOption("USER_ENTERED") - .setInsertDataOption("INSERT_ROWS") - .setIncludeValuesInResponse(true) - .execute(); + ValueRange appendBody = new ValueRange().setValues(Arrays.asList(Arrays.asList("Total", "=E1+E4"))); + AppendValuesResponse appendResult = sheetsService.spreadsheets().values().append(SPREADSHEET_ID, "A1", appendBody).setValueInputOption("USER_ENTERED").setInsertDataOption("INSERT_ROWS").setIncludeValuesInResponse(true).execute(); ValueRange total = appendResult.getUpdates().getUpdatedData(); assertThat(total.getValues().get(0).get(1)).isEqualTo("65"); } - @Test public void whenUpdateSpreadSheetTitle_thenOk() throws IOException { - - UpdateSpreadsheetPropertiesRequest updateRequest = new UpdateSpreadsheetPropertiesRequest() - .setFields("*") - .setProperties(new SpreadsheetProperties().setTitle("Expenses")); - - CopyPasteRequest copyRequest = new CopyPasteRequest() - .setSource(new GridRange().setSheetId(0) - .setStartColumnIndex(0).setEndColumnIndex(2) - .setStartRowIndex(0).setEndRowIndex(1)) - .setDestination(new GridRange().setSheetId(1) - .setStartColumnIndex(0).setEndColumnIndex(2) - .setStartRowIndex(0).setEndRowIndex(1)) - .setPasteType("PASTE_VALUES"); - + + UpdateSpreadsheetPropertiesRequest updateRequest = new UpdateSpreadsheetPropertiesRequest().setFields("*").setProperties(new SpreadsheetProperties().setTitle("Expenses")); + + CopyPasteRequest copyRequest = new CopyPasteRequest().setSource(new GridRange().setSheetId(0).setStartColumnIndex(0).setEndColumnIndex(2).setStartRowIndex(0).setEndRowIndex(1)) + .setDestination(new GridRange().setSheetId(1).setStartColumnIndex(0).setEndColumnIndex(2).setStartRowIndex(0).setEndRowIndex(1)).setPasteType("PASTE_VALUES"); + List requests = new ArrayList<>(); - + requests.add(new Request().setCopyPaste(copyRequest)); requests.add(new Request().setUpdateSpreadsheetProperties(updateRequest)); - BatchUpdateSpreadsheetRequest body = - new BatchUpdateSpreadsheetRequest().setRequests(requests); + BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests); sheetsService.spreadsheets().batchUpdate(SPREADSHEET_ID, body).execute(); } - + @Test public void whenCreateSpreadSheet_thenIdOk() throws IOException { - Spreadsheet spreadSheet = new Spreadsheet() - .setProperties(new SpreadsheetProperties().setTitle("My Spreadsheet")); + Spreadsheet spreadSheet = new Spreadsheet().setProperties(new SpreadsheetProperties().setTitle("My Spreadsheet")); Spreadsheet result = sheetsService.spreadsheets().create(spreadSheet).execute(); - assertThat(result.getSpreadsheetId()).isNotNull(); + assertThat(result.getSpreadsheetId()).isNotNull(); } } diff --git a/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java b/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java index 5ecd4442d8..f762096811 100644 --- a/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java +++ b/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.hll; - import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import net.agkn.hll.HLL; @@ -15,47 +14,44 @@ public class HLLLongRunningUnitTest { @Test public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() { - //given + // given long numberOfElements = 100_000_000; long toleratedDifference = 1_000_000; HashFunction hashFunction = Hashing.murmur3_128(); HLL hll = new HLL(14, 5); - //when + // when LongStream.range(0, numberOfElements).forEach(element -> { - long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); - hll.addRaw(hashedValue); - } - ); + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + hll.addRaw(hashedValue); + }); - //then + // then long cardinality = hll.cardinality(); assertThat(cardinality).isCloseTo(numberOfElements, Offset.offset(toleratedDifference)); } @Test public void givenTwoHLLs_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinalityForUnionOfHLLs() { - //given + // given long numberOfElements = 100_000_000; long toleratedDifference = 1_000_000; HashFunction hashFunction = Hashing.murmur3_128(); HLL firstHll = new HLL(15, 5); HLL secondHLL = new HLL(15, 5); - //when + // when LongStream.range(0, numberOfElements).forEach(element -> { - long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); - firstHll.addRaw(hashedValue); - } - ); + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + firstHll.addRaw(hashedValue); + }); LongStream.range(numberOfElements, numberOfElements * 2).forEach(element -> { - long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); - secondHLL.addRaw(hashedValue); - } - ); + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + secondHLL.addRaw(hashedValue); + }); - //then + // then firstHll.union(secondHLL); long cardinality = firstHll.cardinality(); assertThat(cardinality).isCloseTo(numberOfElements * 2, Offset.offset(toleratedDifference * 2)); diff --git a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java index 167aef5ec6..09d31eac21 100644 --- a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java @@ -33,38 +33,21 @@ import io.specto.hoverfly.junit.rule.HoverflyRule; public class HoverflyApiIntegrationTest { - private static final SimulationSource source = dsl( - service("http://www.baeldung.com") - .get("/api/courses/1") - .willReturn(success().body( - jsonWithSingleQuotes("{'id':'1','name':'HCI'}"))) - - .post("/api/courses") - .willReturn(success()) - - .andDelay(3, TimeUnit.SECONDS) - .forMethod("POST"), - - service(matches("www.*dung.com")) - .get(startsWith("/api/student")) - .queryParam("page", any()) - .willReturn(success()) - - .post(equalsTo("/api/student")) - .body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}"))) - .willReturn(success()) - - .put("/api/student/1") - .body(matchesJsonPath("$.name")) - .willReturn(success()) - - .post("/api/student") - .body(equalsToXml("2John")) - .willReturn(success()) - - .put("/api/student/2") - .body(matchesXPath("/student/name")) - .willReturn(success())); + private static final SimulationSource source = dsl(service("http://www.baeldung.com").get("/api/courses/1").willReturn(success().body(jsonWithSingleQuotes("{'id':'1','name':'HCI'}"))) + + .post("/api/courses").willReturn(success()) + + .andDelay(3, TimeUnit.SECONDS).forMethod("POST"), + + service(matches("www.*dung.com")).get(startsWith("/api/student")).queryParam("page", any()).willReturn(success()) + + .post(equalsTo("/api/student")).body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}"))).willReturn(success()) + + .put("/api/student/1").body(matchesJsonPath("$.name")).willReturn(success()) + + .post("/api/student").body(equalsToXml("2John")).willReturn(success()) + + .put("/api/student/2").body(matchesXPath("/student/name")).willReturn(success())); @ClassRule public static final HoverflyRule rule = HoverflyRule.inSimulationMode(source); @@ -72,19 +55,17 @@ public class HoverflyApiIntegrationTest { @Test public void givenGetCourseById_whenRequestSimulated_thenAPICalledSuccessfully() throws URISyntaxException { - final ResponseEntity courseResponse = restTemplate.getForEntity( - "http://www.baeldung.com/api/courses/1", String.class); - + final ResponseEntity courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/courses/1", String.class); + assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody()); } - + @Test public void givenPostCourse_whenDelayInRequest_thenResponseIsDelayed() throws URISyntaxException { StopWatch stopWatch = new StopWatch(); stopWatch.start(); - final ResponseEntity postResponse = restTemplate.postForEntity( - "http://www.baeldung.com/api/courses", null, Void.class); + final ResponseEntity postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/courses", null, Void.class); stopWatch.stop(); long postTime = stopWatch.getTime(); @@ -94,45 +75,36 @@ public class HoverflyApiIntegrationTest { @Test public void givenGetStudent_whenRequestMatcher_thenAPICalledSuccessfully() throws URISyntaxException { - final ResponseEntity courseResponse = restTemplate.getForEntity( - "http://www.baeldung.com/api/student?page=3", Void.class); - + final ResponseEntity courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/student?page=3", Void.class); + assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); } - + @Test public void givenPostStudent_whenBodyRequestMatcherJson_thenResponseContainsEqualJson() throws URISyntaxException { - final ResponseEntity postResponse = restTemplate.postForEntity( - "http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class); + final ResponseEntity postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class); assertEquals(HttpStatus.OK, postResponse.getStatusCode()); } - + @Test public void givenPutStudent_whenJsonPathMatcher_thenRequestJsonContainsElementInPath() throws URISyntaxException { - RequestEntity putRequest = RequestEntity - .put(new URI("http://www.baeldung.com/api/student/1")) - .body("{\"id\":\"1\",\"name\":\"Trevor\"}"); + RequestEntity putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/1")).body("{\"id\":\"1\",\"name\":\"Trevor\"}"); ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); assertEquals(HttpStatus.OK, putResponse.getStatusCode()); } - + @Test public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException { - final ResponseEntity postResponse = restTemplate.postForEntity( - "http://www.baeldung.com/api/student", "2John", Void.class); + final ResponseEntity postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "2John", Void.class); assertEquals(HttpStatus.OK, postResponse.getStatusCode()); } - - + @Test public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException { - RequestEntity putRequest = RequestEntity - .put(new URI("http://www.baeldung.com/api/student/2")) - .body("" - + "2Monica"); + RequestEntity putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/2")).body("" + "2Monica"); ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); assertEquals(HttpStatus.OK, putResponse.getStatusCode()); diff --git a/libraries/src/test/java/com/baeldung/infinispan/ConfigurationTest.java b/libraries/src/test/java/com/baeldung/infinispan/ConfigurationTest.java index c9ebe77679..9210b18f0c 100644 --- a/libraries/src/test/java/com/baeldung/infinispan/ConfigurationTest.java +++ b/libraries/src/test/java/com/baeldung/infinispan/ConfigurationTest.java @@ -27,24 +27,17 @@ public class ConfigurationTest { cacheManager = configuration.cacheManager(); - Cache transactionalCache = - configuration.transactionalCache(cacheManager, listener); + Cache transactionalCache = configuration.transactionalCache(cacheManager, listener); - Cache simpleHelloWorldCache = - configuration.simpleHelloWorldCache(cacheManager, listener); + Cache simpleHelloWorldCache = configuration.simpleHelloWorldCache(cacheManager, listener); - Cache expiringHelloWorldCache = - configuration.expiringHelloWorldCache(cacheManager, listener); + Cache expiringHelloWorldCache = configuration.expiringHelloWorldCache(cacheManager, listener); - Cache evictingHelloWorldCache = - configuration.evictingHelloWorldCache(cacheManager, listener); + Cache evictingHelloWorldCache = configuration.evictingHelloWorldCache(cacheManager, listener); - Cache passivatingHelloWorldCache = - configuration.passivatingHelloWorldCache(cacheManager, listener); + Cache passivatingHelloWorldCache = configuration.passivatingHelloWorldCache(cacheManager, listener); - this.helloWorldService = new HelloWorldService(repository, - listener, simpleHelloWorldCache, expiringHelloWorldCache, evictingHelloWorldCache, - passivatingHelloWorldCache); + this.helloWorldService = new HelloWorldService(repository, listener, simpleHelloWorldCache, expiringHelloWorldCache, evictingHelloWorldCache, passivatingHelloWorldCache); this.transactionalService = new TransactionalService(transactionalCache); } diff --git a/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java b/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java index c9ecd57995..232186fedb 100644 --- a/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java +++ b/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java @@ -12,59 +12,46 @@ public class HelloWorldServiceUnitTest extends ConfigurationTest { @Test public void whenGetIsCalledTwoTimes_thenTheSecondShouldHitTheCache() { - assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())).isGreaterThanOrEqualTo(1000); - assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())) - .isLessThan(100); + assertThat(timeThis(() -> helloWorldService.findSimpleHelloWorld())).isLessThan(100); } @Test public void whenGetIsCalledTwoTimesQuickly_thenTheSecondShouldHitTheCache() { - assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000); - assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())) - .isLessThan(100); + assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isLessThan(100); } @Test - public void whenGetIsCalledTwoTimesSparsely_thenNeitherShouldHitTheCache() - throws InterruptedException { + public void whenGetIsCalledTwoTimesSparsely_thenNeitherShouldHitTheCache() throws InterruptedException { - assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000); Thread.sleep(1100); - assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000); } @Test public void givenOneEntryIsConfigured_whenTwoAreAdded_thenFirstShouldntBeAvailable() { - assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); - assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 2"))) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 2"))).isGreaterThanOrEqualTo(1000); - assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); } @Test public void givenOneEntryIsConfigured_whenTwoAreAdded_thenTheFirstShouldBeAvailable() { - assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); - assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 2"))) - .isGreaterThanOrEqualTo(1000); + assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 2"))).isGreaterThanOrEqualTo(1000); - assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))) - .isLessThan(100); + assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))).isLessThan(100); } diff --git a/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceUnitTest.java b/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceUnitTest.java index 99efacd18a..49681dd893 100644 --- a/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceUnitTest.java +++ b/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceUnitTest.java @@ -13,10 +13,9 @@ public class TransactionalServiceUnitTest extends ConfigurationTest { Thread backgroundThread = new Thread(backGroundJob); transactionalService.getQuickHowManyVisits(); backgroundThread.start(); - Thread.sleep(100); //lets wait our thread warm up + Thread.sleep(100); // lets wait our thread warm up - assertThat(timeThis(() -> transactionalService.getQuickHowManyVisits())) - .isGreaterThan(500).isLessThan(1000); + assertThat(timeThis(() -> transactionalService.getQuickHowManyVisits())).isGreaterThan(500).isLessThan(1000); } } diff --git a/libraries/src/test/java/com/baeldung/jasypt/JasyptUnitTest.java b/libraries/src/test/java/com/baeldung/jasypt/JasyptUnitTest.java index 5e65c585aa..d67c2a5cb2 100644 --- a/libraries/src/test/java/com/baeldung/jasypt/JasyptUnitTest.java +++ b/libraries/src/test/java/com/baeldung/jasypt/JasyptUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.jasypt; - import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.util.password.BasicPasswordEncryptor; @@ -17,16 +16,16 @@ public class JasyptUnitTest { @Test public void givenTextPrivateData_whenDecrypt_thenCompareToEncrypted() { - //given + // given BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); String privateData = "secret-data"; textEncryptor.setPasswordCharArray("some-random-data".toCharArray()); - //when + // when String myEncryptedText = textEncryptor.encrypt(privateData); - assertNotSame(privateData, myEncryptedText); //myEncryptedText can be save in db + assertNotSame(privateData, myEncryptedText); // myEncryptedText can be save in db - //then + // then String plainText = textEncryptor.decrypt(myEncryptedText); assertEquals(plainText, privateData); } @@ -37,10 +36,10 @@ public class JasyptUnitTest { BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor(); String encryptedPassword = passwordEncryptor.encryptPassword(password); - //when + // when boolean result = passwordEncryptor.checkPassword("secret-pass", encryptedPassword); - //then + // then assertTrue(result); } @@ -50,28 +49,27 @@ public class JasyptUnitTest { BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor(); String encryptedPassword = passwordEncryptor.encryptPassword(password); - //when + // when boolean result = passwordEncryptor.checkPassword("secret-pass-not-same", encryptedPassword); - //then + // then assertFalse(result); } - @Test @Ignore("should have installed local_policy.jar") public void givenTextPrivateData_whenDecrypt_thenCompareToEncryptedWithCustomAlgorithm() { - //given + // given StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); String privateData = "secret-data"; encryptor.setPassword("some-random-data"); encryptor.setAlgorithm("PBEWithMD5AndTripleDES"); - //when + // when String encryptedText = encryptor.encrypt("secret-pass"); assertNotSame(privateData, encryptedText); - //then + // then String plainText = encryptor.decrypt(encryptedText); assertEquals(plainText, privateData); } @@ -79,18 +77,18 @@ public class JasyptUnitTest { @Test @Ignore("should have installed local_policy.jar") public void givenTextPrivateData_whenDecryptOnHighPerformance_thenDecrypt() { - //given + // given String privateData = "secret-data"; PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); encryptor.setPoolSize(4); encryptor.setPassword("some-random-data"); encryptor.setAlgorithm("PBEWithMD5AndTripleDES"); - //when + // when String encryptedText = encryptor.encrypt(privateData); assertNotSame(privateData, encryptedText); - //then + // then String plainText = encryptor.decrypt(encryptedText); assertEquals(plainText, privateData); } diff --git a/libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java b/libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java index 1cd390b873..53d9d11bbb 100644 --- a/libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java +++ b/libraries/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java @@ -110,10 +110,7 @@ public class JavaDirectoryDeleteUnitTest { public void givenDirectory_whenDeletedWithFilesWalk_thenIsGone() throws IOException { Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); - Files.walk(pathToBeDeleted) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); + Files.walk(pathToBeDeleted).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); } diff --git a/libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java b/libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java index 30c034aa5e..2dae2adc51 100644 --- a/libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java +++ b/libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.javassist; - import javassist.CannotCompileException; import javassist.ClassPool; import javassist.NotFoundException; @@ -33,20 +32,20 @@ import static org.junit.Assert.assertTrue; public class JavasisstUnitTest { @Test public void givenJavasisstAPI_whenConstructClass_thenGenerateAClassFile() throws CannotCompileException, IOException, ClassNotFoundException, IllegalAccessException, InstantiationException { - //given + // given String classNameWithPackage = "com.baeldung.JavassistGeneratedClass"; ClassFile cf = new ClassFile(false, classNameWithPackage, null); - cf.setInterfaces(new String[]{"java.lang.Cloneable"}); + cf.setInterfaces(new String[] { "java.lang.Cloneable" }); FieldInfo f = new FieldInfo(cf.getConstPool(), "id", "I"); f.setAccessFlags(AccessFlag.PUBLIC); cf.addField(f); - //when + // when String className = "JavassistGeneratedClass.class"; cf.write(new DataOutputStream(new FileOutputStream(className))); - //then + // then ClassPool classPool = ClassPool.getDefault(); Field[] fields = classPool.makeClass(cf).toClass().getFields(); assertEquals(fields[0].getName(), "id"); @@ -57,14 +56,14 @@ public class JavasisstUnitTest { @Test public void givenJavaClass_whenLoadAtByJavassist_thenTraversWholeClass() throws NotFoundException, CannotCompileException, BadBytecode { - //given + // given ClassPool cp = ClassPool.getDefault(); ClassFile cf = cp.get("com.baeldung.javasisst.Point").getClassFile(); MethodInfo minfo = cf.getMethod("move"); CodeAttribute ca = minfo.getCodeAttribute(); CodeIterator ci = ca.iterator(); - //when + // when List operations = new LinkedList<>(); while (ci.hasNext()) { int index = ci.next(); @@ -72,23 +71,21 @@ public class JavasisstUnitTest { operations.add(Mnemonic.OPCODE[op]); } - //then - assertEquals(operations, - Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return")); + // then + assertEquals(operations, Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return")); } @Test public void givenTableOfInstructions_whenAddNewInstruction_thenShouldConstructProperSequence() throws NotFoundException, BadBytecode, CannotCompileException, IllegalAccessException, InstantiationException { - //given + // given ClassFile cf = ClassPool.getDefault().get("com.baeldung.javasisst.ThreeDimensionalPoint").getClassFile(); - //when + // when FieldInfo f = new FieldInfo(cf.getConstPool(), "id", "I"); f.setAccessFlags(AccessFlag.PUBLIC); cf.addField(f); - ClassPool classPool = ClassPool.getDefault(); Field[] fields = classPool.makeClass(cf).toClass().getFields(); List fieldsList = Stream.of(fields).map(Field::getName).collect(Collectors.toList()); @@ -98,19 +95,19 @@ public class JavasisstUnitTest { @Test public void givenLoadedClass_whenAddConstructorToClass_shouldCreateClassWithConstructor() throws NotFoundException, CannotCompileException, BadBytecode { - //given + // given ClassFile cf = ClassPool.getDefault().get("com.baeldung.javasisst.Point").getClassFile(); Bytecode code = new Bytecode(cf.getConstPool()); code.addAload(0); code.addInvokespecial("java/lang/Object", MethodInfo.nameInit, "()V"); code.addReturn(null); - //when + // when MethodInfo minfo = new MethodInfo(cf.getConstPool(), MethodInfo.nameInit, "()V"); minfo.setCodeAttribute(code.toCodeAttribute()); cf.addMethod(minfo); - //then + // then CodeIterator ci = code.toCodeAttribute().iterator(); List operations = new LinkedList<>(); while (ci.hasNext()) { @@ -119,9 +116,7 @@ public class JavasisstUnitTest { operations.add(Mnemonic.OPCODE[op]); } - assertEquals(operations, - Arrays.asList("aload_0", "invokespecial", "return")); - + assertEquals(operations, Arrays.asList("aload_0", "invokespecial", "return")); } } diff --git a/libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java b/libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java index a341d5957a..73dfbae3b2 100644 --- a/libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java +++ b/libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java @@ -26,7 +26,7 @@ public class JavaTuplesUnitTest { Pair pairFromList = Pair.fromIterable(collectionOfNames, 2); - String[] names = new String[]{"john", "doe", "anne"}; + String[] names = new String[] { "john", "doe", "anne" }; Triplet triplet2 = Triplet.fromArray(names); } diff --git a/libraries/src/test/java/com/baeldung/javers/JaversUnitTest.java b/libraries/src/test/java/com/baeldung/javers/JaversUnitTest.java index 3cdb833953..a8a7df659b 100644 --- a/libraries/src/test/java/com/baeldung/javers/JaversUnitTest.java +++ b/libraries/src/test/java/com/baeldung/javers/JaversUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.javers; - import org.javers.common.collections.Lists; import org.javers.core.Javers; import org.javers.core.JaversBuilder; @@ -21,16 +20,16 @@ public class JaversUnitTest { @Test public void givenPersonObject_whenApplyModificationOnIt_thenShouldDetectChange() { - //given + // given Javers javers = JaversBuilder.javers().build(); Person person = new Person(1, "Michael Program"); Person personAfterModification = new Person(1, "Michael Java"); - //when + // when Diff diff = javers.compare(person, personAfterModification); - //then + // then ValueChange change = diff.getChangesByType(ValueChange.class).get(0); assertThat(diff.getChanges()).hasSize(1); @@ -39,22 +38,20 @@ public class JaversUnitTest { assertThat(change.getRight()).isEqualTo("Michael Java"); } - @Test public void givenListOfPersons_whenCompare_ThenShouldDetectChanges() { - //given + // given Javers javers = JaversBuilder.javers().build(); Person personThatWillBeRemoved = new Person(2, "Thomas Link"); List oldList = Lists.asList(new Person(1, "Michael Program"), personThatWillBeRemoved); List newList = Lists.asList(new Person(1, "Michael Not Program")); - //when + // when Diff diff = javers.compareCollections(oldList, newList, Person.class); - //then + // then assertThat(diff.getChanges()).hasSize(3); - ValueChange valueChange = diff.getChangesByType(ValueChange.class).get(0); assertThat(valueChange.getPropertyName()).isEqualTo("name"); assertThat(valueChange.getLeft()).isEqualTo("Michael Program"); @@ -70,43 +67,36 @@ public class JaversUnitTest { @Test public void givenListOfPerson_whenPersonHasNewAddress_thenDetectThatChange() { - //given + // given Javers javers = JaversBuilder.javers().build(); - PersonWithAddress person = - new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); + PersonWithAddress person = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); - PersonWithAddress personWithNewAddress = - new PersonWithAddress(1, "Tom", - Arrays.asList(new Address("England"), new Address("USA"))); + PersonWithAddress personWithNewAddress = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"), new Address("USA"))); - - //when + // when Diff diff = javers.compare(person, personWithNewAddress); List objectsByChangeType = diff.getObjectsByChangeType(NewObject.class); - //then + // then assertThat(objectsByChangeType).hasSize(1); assertThat(objectsByChangeType.get(0).equals(new Address("USA"))); } @Test public void givenListOfPerson_whenPersonRemovedAddress_thenDetectThatChange() { - //given + // given Javers javers = JaversBuilder.javers().build(); - PersonWithAddress person = - new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); + PersonWithAddress person = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); - PersonWithAddress personWithNewAddress = - new PersonWithAddress(1, "Tom", Collections.emptyList()); + PersonWithAddress personWithNewAddress = new PersonWithAddress(1, "Tom", Collections.emptyList()); - - //when + // when Diff diff = javers.compare(person, personWithNewAddress); List objectsByChangeType = diff.getObjectsByChangeType(ObjectRemoved.class); - //then + // then assertThat(objectsByChangeType).hasSize(1); assertThat(objectsByChangeType.get(0).equals(new Address("England"))); } diff --git a/libraries/src/test/java/com/baeldung/jcache/CacheLoaderTest.java b/libraries/src/test/java/com/baeldung/jcache/CacheLoaderTest.java index da4f51674f..a4747785cd 100644 --- a/libraries/src/test/java/com/baeldung/jcache/CacheLoaderTest.java +++ b/libraries/src/test/java/com/baeldung/jcache/CacheLoaderTest.java @@ -23,15 +23,13 @@ public class CacheLoaderTest { public void setup() { CachingProvider cachingProvider = Caching.getCachingProvider(); CacheManager cacheManager = cachingProvider.getCacheManager(); - MutableConfiguration config = new MutableConfiguration().setReadThrough(true) - .setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>(new SimpleCacheLoader())); + MutableConfiguration config = new MutableConfiguration().setReadThrough(true).setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>(new SimpleCacheLoader())); this.cache = cacheManager.createCache("SimpleCache", config); } @After public void tearDown() { - Caching.getCachingProvider() - .getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); } @Test diff --git a/libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java b/libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java index eb40e63ef0..ab35d23768 100644 --- a/libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java +++ b/libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java @@ -29,8 +29,7 @@ public class EntryProcessorTest { @After public void tearDown() { - Caching.getCachingProvider() - .getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); } @Test diff --git a/libraries/src/test/java/com/baeldung/jcache/EventListenerTest.java b/libraries/src/test/java/com/baeldung/jcache/EventListenerTest.java index be83e572d8..e32e4ad3cc 100644 --- a/libraries/src/test/java/com/baeldung/jcache/EventListenerTest.java +++ b/libraries/src/test/java/com/baeldung/jcache/EventListenerTest.java @@ -33,14 +33,12 @@ public class EventListenerTest { @After public void tearDown() { - Caching.getCachingProvider() - .getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); } @Test public void whenRunEvent_thenCorrect() throws InterruptedException { - this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(FactoryBuilder - .factoryOf(this.listener), null, false, true); + this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(FactoryBuilder.factoryOf(this.listener), null, false, true); this.cache.registerCacheEntryListener(this.listenerConfiguration); assertEquals(false, this.listener.getCreated()); diff --git a/libraries/src/test/java/com/baeldung/jcache/JCacheTest.java b/libraries/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java similarity index 95% rename from libraries/src/test/java/com/baeldung/jcache/JCacheTest.java rename to libraries/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java index c98539a9ec..fac3d32bcb 100644 --- a/libraries/src/test/java/com/baeldung/jcache/JCacheTest.java +++ b/libraries/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java @@ -10,7 +10,7 @@ import javax.cache.spi.CachingProvider; import static org.junit.Assert.assertEquals; -public class JCacheTest { +public class JCacheIntegrationTest { @Test public void instantiateCache() { diff --git a/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java b/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java index e916a229f7..03e63c2580 100644 --- a/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java @@ -106,5 +106,4 @@ public class GuideToJDOIntegrationTest { } } - } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java b/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java index 28d4f57e77..e6af244752 100644 --- a/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.jetty; - import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; @@ -32,26 +31,26 @@ public class JettyIntegrationTest { @Test public void givenServer_whenSendRequestToBlockingServlet_thenReturnStatusOK() throws Exception { - //given + // given String url = "http://localhost:8090/status"; HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); - //then + // then assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); } @Test public void givenServer_whenSendRequestToNonBlockingServlet_thenReturnStatusOK() throws Exception { - //when + // when String url = "http://localhost:8090/heavy/async"; HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); - //then + // then assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); String responseContent = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); assertThat(responseContent).isEqualTo("This is some heavy resource that will be served in an async way"); diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java b/libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java index 849ba24f55..75b86e46b2 100644 --- a/libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java +++ b/libraries/src/test/java/com/baeldung/jetty/JettyServerFactoryUnitTest.java @@ -18,69 +18,69 @@ import org.junit.Test; */ public class JettyServerFactoryUnitTest { - /** - * Tests that when a base server is provided a request returns a status 404. - * - * @throws Exception - */ - @Test - public void givenBaseServer_whenHttpRequest_thenStatus404() throws Exception { - Server server = JettyServerFactory.createBaseServer(); - server.start(); - - int statusCode = sendGetRequest(); - - Assert.assertEquals(404, statusCode); - server.stop(); - } + /** + * Tests that when a base server is provided a request returns a status 404. + * + * @throws Exception + */ + @Test + public void givenBaseServer_whenHttpRequest_thenStatus404() throws Exception { + Server server = JettyServerFactory.createBaseServer(); + server.start(); - /** - * Tests that when a web app server is provided a request returns a status - * 200. - * - * @throws Exception - */ - @Test - public void givenWebAppServer_whenHttpRequest_thenStatus200() throws Exception { - Server server = JettyServerFactory.createWebAppServer(); - server.start(); + int statusCode = sendGetRequest(); - int statusCode = sendGetRequest(); - - Assert.assertEquals(200, statusCode); - server.stop(); - } + Assert.assertEquals(404, statusCode); + server.stop(); + } - /** - * Tests that when a multi handler server is provided a request returns a - * status 200. - * - * @throws Exception - */ - @Test - public void givenMultiHandlerServerServer_whenHttpRequest_thenStatus200() throws Exception { - Server server = JettyServerFactory.createMultiHandlerServer(); - server.start(); + /** + * Tests that when a web app server is provided a request returns a status + * 200. + * + * @throws Exception + */ + @Test + public void givenWebAppServer_whenHttpRequest_thenStatus200() throws Exception { + Server server = JettyServerFactory.createWebAppServer(); + server.start(); - int statusCode = sendGetRequest(); - - Assert.assertEquals(200, statusCode); - server.stop(); - } + int statusCode = sendGetRequest(); - /** - * Sends a default HTTP GET request to the server and returns the response - * status code. - * - * @return the status code of the response - * @throws Exception - */ - private int sendGetRequest() throws Exception { - HttpHost target = new HttpHost("localhost", JettyServerFactory.SERVER_PORT); - HttpRequest request = new HttpGet(JettyServerFactory.APP_PATH); - HttpClient client = HttpClientBuilder.create().build(); - HttpResponse response = client.execute(target, request); - return response.getStatusLine().getStatusCode(); - } + Assert.assertEquals(200, statusCode); + server.stop(); + } + + /** + * Tests that when a multi handler server is provided a request returns a + * status 200. + * + * @throws Exception + */ + @Test + public void givenMultiHandlerServerServer_whenHttpRequest_thenStatus200() throws Exception { + Server server = JettyServerFactory.createMultiHandlerServer(); + server.start(); + + int statusCode = sendGetRequest(); + + Assert.assertEquals(200, statusCode); + server.stop(); + } + + /** + * Sends a default HTTP GET request to the server and returns the response + * status code. + * + * @return the status code of the response + * @throws Exception + */ + private int sendGetRequest() throws Exception { + HttpHost target = new HttpHost("localhost", JettyServerFactory.SERVER_PORT); + HttpRequest request = new HttpGet(JettyServerFactory.APP_PATH); + HttpClient client = HttpClientBuilder.create().build(); + HttpResponse response = client.execute(target, request); + return response.getStatusLine().getStatusCode(); + } } diff --git a/libraries/src/test/java/com/baeldung/jool/JOOLTest.java b/libraries/src/test/java/com/baeldung/jool/JOOLTest.java index ba20e153fd..2cb393abd3 100644 --- a/libraries/src/test/java/com/baeldung/jool/JOOLTest.java +++ b/libraries/src/test/java/com/baeldung/jool/JOOLTest.java @@ -28,86 +28,53 @@ public class JOOLTest { assertEquals(concat, Arrays.asList(1, 2, 3, 4, 5, 6)); - assertTrue(Seq.of(1, 2, 3, 4).contains(2)); - assertTrue(Seq.of(1, 2, 3, 4).containsAll(2, 3)); - assertTrue(Seq.of(1, 2, 3, 4).containsAny(2, 5)); } @Test public void givenStreams_whenJoin_shouldHaveElementsFromTwoStreams() { - //given + // given Stream left = Stream.of(1, 2, 4); Stream right = Stream.of(1, 2, 3); - //when + // when List rightCollected = right.collect(Collectors.toList()); List collect = left.filter(rightCollected::contains).collect(Collectors.toList()); - //then + // then assertEquals(collect, Arrays.asList(1, 2)); } @Test public void givenSeq_whenJoin_shouldHaveElementsFromBothSeq() { - assertEquals( - Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2)) - ); + assertEquals(Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2))); + assertEquals(Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null))); - assertEquals( - Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null)) - ); + assertEquals(Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3))); - assertEquals( - Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3)) - ); - - assertEquals( - Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), - Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B")) - ); + assertEquals(Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B"))); } @Test public void givenSeq_whenManipulateSeq_seqShouldHaveNewElementsInIt() { - assertEquals( - Seq.of(1, 2, 3).cycle().limit(9).toList(), - Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3) - ); + assertEquals(Seq.of(1, 2, 3).cycle().limit(9).toList(), Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3)); - assertEquals( - Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), - tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)) - ); + assertEquals(Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3))); - assertEquals( - Seq.of(1, 2, 3, 4).intersperse(0).toList(), - Arrays.asList(1, 0, 2, 0, 3, 0, 4) - ); + assertEquals(Seq.of(1, 2, 3, 4).intersperse(0).toList(), Arrays.asList(1, 0, 2, 0, 3, 0, 4)); - assertEquals( - Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), - 5 - ); + assertEquals(Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), 5); - assertEquals( - Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), - tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) + assertEquals(Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) ); - assertEquals( - Seq.of(1, 2, 3, 4).reverse().toList(), - Arrays.asList(4, 3, 2, 1) - ); + assertEquals(Seq.of(1, 2, 3, 4).reverse().toList(), Arrays.asList(4, 3, 2, 1)); } @Test @@ -117,66 +84,38 @@ public class JOOLTest { expectedAfterGroupBy.put(1, Arrays.asList(1, 3)); expectedAfterGroupBy.put(0, Arrays.asList(2, 4)); - assertEquals( - Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), - expectedAfterGroupBy - ); + assertEquals(Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), expectedAfterGroupBy); + assertEquals(Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), "!abc"); - assertEquals( - Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), - "!abc" - ); - - - assertEquals( - Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), - "abc!" - ); + assertEquals(Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), "abc!"); } @Test public void givenSeq_whenUsingSeqWhile_shouldBehaveAsWhileLoop() { - assertEquals( - Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), - Arrays.asList(3, 4, 5) - ); + assertEquals(Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), Arrays.asList(3, 4, 5)); - assertEquals( - Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), - Arrays.asList(3, 4, 5) - ); + assertEquals(Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), Arrays.asList(3, 4, 5)); } @Test public void givenSeq_whenZip_shouldHaveZippedSeq() { - assertEquals( - Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), - Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c")) - ); + assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c"))); - assertEquals( - Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), - Arrays.asList("1:a", "2:b", "3:c") - ); + assertEquals(Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), Arrays.asList("1:a", "2:b", "3:c")); - - assertEquals( - Seq.of("a", "b", "c").zipWithIndex().toList(), - Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L)) - ); + assertEquals(Seq.of("a", "b", "c").zipWithIndex().toList(), Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L))); } - public Integer methodThatThrowsChecked(String arg) throws Exception { return arg.length(); } @Test public void givenOperationThatThrowsCheckedException_whenExecuteAndNeedToWrapCheckedIntoUnchecked_shouldPass() { - //when + // when List collect = Stream.of("a", "b", "c").map(elem -> { try { return methodThatThrowsChecked(elem); @@ -186,55 +125,43 @@ public class JOOLTest { } }).collect(Collectors.toList()); - //then - assertEquals( - collect, - Arrays.asList(1, 1, 1) - ); + // then + assertEquals(collect, Arrays.asList(1, 1, 1)); } - @Test public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() { - //when - List collect = Stream.of("a", "b", "c") - .map(Unchecked.function(this::methodThatThrowsChecked)) - .collect(Collectors.toList()); + // when + List collect = Stream.of("a", "b", "c").map(Unchecked.function(this::methodThatThrowsChecked)).collect(Collectors.toList()); - //then - assertEquals( - collect, - Arrays.asList(1, 1, 1) - ); + // then + assertEquals(collect, Arrays.asList(1, 1, 1)); } @Test public void givenFunction_whenAppliedPartially_shouldAddNumberToPartialArgument() { - //given + // given Function2 addTwoNumbers = (v1, v2) -> v1 + v2; addTwoNumbers.toBiFunction(); Function1 addToTwo = addTwoNumbers.applyPartially(2); - //when + // when Integer result = addToTwo.apply(5); - //then + // then assertEquals(result, (Integer) 7); } @Test public void givenSeqOfTuples_whenTransformToLowerNumberOfTuples_shouldHaveProperResult() { - //given + // given Seq> personDetails = Seq.of(tuple("michael", "similar", 49), tuple("jodie", "variable", 43)); Tuple2 tuple = tuple("winter", "summer"); - //when + // when List> result = personDetails.map(t -> t.limit2().concat(tuple)).toList(); - //then - assertEquals( - result, - Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer")) - ); + // then + assertEquals(result, Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer"))); } } diff --git a/libraries/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java b/libraries/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java index bdbc101b15..ce9638c4af 100644 --- a/libraries/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java +++ b/libraries/src/test/java/com/baeldung/jsonassert/JsonAssertUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.jsonassert; - import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; @@ -62,10 +61,8 @@ public class JsonAssertUnitTest { @Test public void givenNestedObjects_whenAssertEquals_thenPass() throws JSONException { - String result = "{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " - + "state:\"LA\", zip:91601}}"; - JSONAssert.assertEquals("{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " - + "state:\"LA\", zip:91601}}", result, false); + String result = "{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " + "state:\"LA\", zip:91601}}"; + JSONAssert.assertEquals("{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " + "state:\"LA\", zip:91601}}", result, false); } @Test @@ -98,32 +95,19 @@ public class JsonAssertUnitTest { @Test public void whenComparingSizeOfArray_thenPass() throws JSONException { String names = "{names:[Alex, Barbera, Charlie, Xavier]}"; - JSONAssert.assertEquals( - "{names:[4]}", - names, - new ArraySizeComparator(JSONCompareMode.LENIENT)); + JSONAssert.assertEquals("{names:[4]}", names, new ArraySizeComparator(JSONCompareMode.LENIENT)); } @Test public void whenComparingContentsOfArray_thenPass() throws JSONException { String ratings = "{ratings:[3.2,3.5,4.1,5,1]}"; - JSONAssert.assertEquals( - "{ratings:[1,5]}", - ratings, - new ArraySizeComparator(JSONCompareMode.LENIENT)); + JSONAssert.assertEquals("{ratings:[1,5]}", ratings, new ArraySizeComparator(JSONCompareMode.LENIENT)); } @Test public void givenValueMatcher_whenComparingUsingRegex_thenPass() throws IllegalArgumentException, JSONException { - JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}", - new CustomComparator( - JSONCompareMode.STRICT, - new Customization("entry.id", - new RegularExpressionValueMatcher("\\d")))); + JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}", new CustomComparator(JSONCompareMode.STRICT, new Customization("entry.id", new RegularExpressionValueMatcher("\\d")))); - JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}", - new CustomComparator(JSONCompareMode.STRICT, - new Customization("entry.id", - new RegularExpressionValueMatcher("\\d")))); + JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}", new CustomComparator(JSONCompareMode.STRICT, new Customization("entry.id", new RegularExpressionValueMatcher("\\d")))); } } diff --git a/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java b/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java index 1c95956761..c8718aef8d 100644 --- a/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java +++ b/libraries/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java @@ -14,7 +14,7 @@ public class SafeAdditionUtilTest { private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil(); @Test - @Parameters({"1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15"}) + @Parameters({ "1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15" }) public void whenCalledWithAnnotationProvidedParams_thenSafeAddAndReturn(int a, int b, int expectedValue) { assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); } @@ -26,7 +26,7 @@ public class SafeAdditionUtilTest { } private Object[] parametersToTestAdd() { - return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; + return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; } @Test @@ -36,7 +36,7 @@ public class SafeAdditionUtilTest { } private Object[] parametersForWhenCalledWithnoParam_thenLoadByNameSafeAddAndReturn() { - return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; + return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; } @Test diff --git a/libraries/src/test/java/com/baeldung/junitparams/TestDataProvider.java b/libraries/src/test/java/com/baeldung/junitparams/TestDataProvider.java index 08a472502e..d318345a56 100644 --- a/libraries/src/test/java/com/baeldung/junitparams/TestDataProvider.java +++ b/libraries/src/test/java/com/baeldung/junitparams/TestDataProvider.java @@ -3,11 +3,11 @@ package com.baeldung.junitparams; public class TestDataProvider { public static Object[] provideBasicData() { - return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{15, -5, 10}, new Object[]{-5, -10, -15}}; + return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { 15, -5, 10 }, new Object[] { -5, -10, -15 } }; } public static Object[] provideEdgeCaseData() { - return new Object[]{new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -2, Integer.MIN_VALUE},}; + return new Object[] { new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -2, Integer.MIN_VALUE }, }; } } diff --git a/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java b/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java index 32568e9ea5..4406494d30 100644 --- a/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java +++ b/libraries/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java @@ -22,7 +22,7 @@ public class KafkaStreamsLiveTest { @Test @Ignore("it needs to have kafka broker running on local") public void shouldTestKafkaStreams() throws InterruptedException { - //given + // given String inputTopic = "inputTopic"; Properties streamsConfiguration = new Properties(); @@ -35,15 +35,12 @@ public class KafkaStreamsLiveTest { // Use a temporary directory for storing state, which will be automatically removed after the test. streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getAbsolutePath()); - //when + // when KStreamBuilder builder = new KStreamBuilder(); KStream textLines = builder.stream(inputTopic); Pattern pattern = Pattern.compile("\\W+", Pattern.UNICODE_CHARACTER_CLASS); - KTable wordCounts = textLines - .flatMapValues(value -> Arrays.asList(pattern.split(value.toLowerCase()))) - .groupBy((key, word) -> word) - .count(); + KTable wordCounts = textLines.flatMapValues(value -> Arrays.asList(pattern.split(value.toLowerCase()))).groupBy((key, word) -> word).count(); wordCounts.foreach((word, count) -> System.out.println("word: " + word + " -> " + count)); @@ -55,7 +52,7 @@ public class KafkaStreamsLiveTest { KafkaStreams streams = new KafkaStreams(builder, streamsConfiguration); streams.start(); - //then + // then Thread.sleep(30000); streams.close(); } diff --git a/libraries/src/test/java/com/baeldung/lsh/LocalSensitiveHashingUnitTest.java b/libraries/src/test/java/com/baeldung/lsh/LocalSensitiveHashingUnitTest.java index fbcda2a70d..5928765aaa 100644 --- a/libraries/src/test/java/com/baeldung/lsh/LocalSensitiveHashingUnitTest.java +++ b/libraries/src/test/java/com/baeldung/lsh/LocalSensitiveHashingUnitTest.java @@ -8,16 +8,15 @@ import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; - public class LocalSensitiveHashingUnitTest { @Ignore("for simplicity of the example number of input vectors is very low, that's why LSH may yield non deterministic results") @Test() public void givenNVectors_whenPerformLSH_thenShouldCalculateSameHashForSimilarVectors() { - //given - boolean[] vector1 = new boolean[]{true, true, true, true, true}; - boolean[] vector2 = new boolean[]{false, false, false, true, false}; - boolean[] vector3 = new boolean[]{false, false, true, true, false}; + // given + boolean[] vector1 = new boolean[] { true, true, true, true, true }; + boolean[] vector2 = new boolean[] { false, false, false, true, false }; + boolean[] vector3 = new boolean[] { false, false, true, true, false }; int sizeOfVectors = 5; int numberOfBuckets = 10; @@ -25,7 +24,7 @@ public class LocalSensitiveHashingUnitTest { LSHMinHash lsh = new LSHMinHash(stages, numberOfBuckets, sizeOfVectors); - //when + // when int[] firstHash = lsh.hash(vector1); int[] secondHash = lsh.hash(vector2); int[] thirdHash = lsh.hash(vector3); @@ -34,7 +33,7 @@ public class LocalSensitiveHashingUnitTest { System.out.println(Arrays.toString(secondHash)); System.out.println(Arrays.toString(thirdHash)); - //then + // then int lastIndexOfResult = stages - 1; assertThat(firstHash[lastIndexOfResult]).isNotEqualTo(secondHash[lastIndexOfResult]); assertThat(firstHash[lastIndexOfResult]).isNotEqualTo(thirdHash[lastIndexOfResult]); @@ -45,4 +44,3 @@ public class LocalSensitiveHashingUnitTest { return Math.abs(secondHash - thirdHash) < numberOfBuckets / 2; } } - diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java index fe9c130d93..afbebb15c9 100644 --- a/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java @@ -25,8 +25,8 @@ public class MBassadorConfigurationTest implements IPublicationErrorHandler { @Before public void prepareTests() { - dispatcher = new MBassador(this); - dispatcher.subscribe(this); + dispatcher = new MBassador(this); + dispatcher.subscribe(this); } @Test diff --git a/libraries/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java b/libraries/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java index 5da1d166f6..ea5c09a4d8 100644 --- a/libraries/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java @@ -10,7 +10,7 @@ import static org.junit.Assert.*; public class XORIntegrationTest { private NeuralNetwork ann = null; - private void print(String input, double output, double actual) { + private void print(String input, double output, double actual) { System.out.println("Testing: " + input + " Expected: " + actual + " Result: " + output); } diff --git a/libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java b/libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java index cc3b441aa4..70d3e41579 100644 --- a/libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java +++ b/libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.pact; - import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRuleMk2; import au.com.dius.pact.consumer.PactVerification; @@ -23,61 +22,37 @@ import static org.assertj.core.api.Assertions.assertThat; public class PactConsumerDrivenContractUnitTest { @Rule - public PactProviderRuleMk2 mockProvider - = new PactProviderRuleMk2("test_provider", "localhost", 8080, this); + public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("test_provider", "localhost", 8080, this); @Pact(consumer = "test_consumer") public RequestResponsePact createPact(PactDslWithProvider builder) { Map headers = new HashMap(); headers.put("Content-Type", "application/json"); - return builder - .given("test GET") - .uponReceiving("GET REQUEST") - .path("/pact") - .method("GET") - .willRespondWith() - .status(200) - .headers(headers) - .body("{\"condition\": true, \"name\": \"tom\"}") - .given("test POST") - .uponReceiving("POST REQUEST") - .method("POST") - .headers(headers) - .body("{\"name\": \"Michael\"}") - .path("/pact") - .willRespondWith() - .status(201) - .toPact(); + return builder.given("test GET").uponReceiving("GET REQUEST").path("/pact").method("GET").willRespondWith().status(200).headers(headers).body("{\"condition\": true, \"name\": \"tom\"}").given("test POST").uponReceiving("POST REQUEST").method("POST") + .headers(headers).body("{\"name\": \"Michael\"}").path("/pact").willRespondWith().status(201).toPact(); } - @Test @PactVerification() public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() { - //when - ResponseEntity response - = new RestTemplate().getForEntity(mockProvider.getUrl() + "/pact", String.class); + // when + ResponseEntity response = new RestTemplate().getForEntity(mockProvider.getUrl() + "/pact", String.class); - //then + // then assertThat(response.getStatusCode().value()).isEqualTo(200); assertThat(response.getHeaders().get("Content-Type").contains("application/json")).isTrue(); assertThat(response.getBody()).contains("condition", "true", "name", "tom"); - //and + // and HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); String jsonBody = "{\"name\": \"Michael\"}"; - //when - ResponseEntity postResponse = new RestTemplate().exchange( - mockProvider.getUrl() + "/pact", - HttpMethod.POST, - new HttpEntity<>(jsonBody, httpHeaders), - String.class - ); + // when + ResponseEntity postResponse = new RestTemplate().exchange(mockProvider.getUrl() + "/pact", HttpMethod.POST, new HttpEntity<>(jsonBody, httpHeaders), String.class); - //then + // then assertThat(postResponse.getStatusCode().value()).isEqualTo(201); } diff --git a/libraries/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java b/libraries/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java index 0e6242b8a3..205f0e545e 100644 --- a/libraries/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java +++ b/libraries/src/test/java/com/baeldung/pairs/ApacheCommonsPairUnitTest.java @@ -46,5 +46,4 @@ public class ApacheCommonsPairUnitTest { immutablePair.setValue("Another One"); } - } diff --git a/libraries/src/test/java/com/baeldung/pairs/CoreJavaSimpleEntryUnitTest.java b/libraries/src/test/java/com/baeldung/pairs/CoreJavaSimpleEntryUnitTest.java index ca425339fa..4271d4e003 100644 --- a/libraries/src/test/java/com/baeldung/pairs/CoreJavaSimpleEntryUnitTest.java +++ b/libraries/src/test/java/com/baeldung/pairs/CoreJavaSimpleEntryUnitTest.java @@ -17,15 +17,15 @@ public class CoreJavaSimpleEntryUnitTest { assertEquals(key.intValue(), 1); assertEquals(value, "one"); } - + @Test(expected = UnsupportedOperationException.class) public void givenSimpleImmutableEntry_whenSetValue_thenException() { AbstractMap.SimpleImmutableEntry entry = new AbstractMap.SimpleImmutableEntry(1, "one"); - + entry.setValue("two"); - + } - + @Test public void givenSimpleImmutableEntry_whenGetValue_thenOk() { AbstractMap.SimpleImmutableEntry entry = new AbstractMap.SimpleImmutableEntry(1, "one"); diff --git a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java index acc7718ea8..1a75624439 100644 --- a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java @@ -86,8 +86,7 @@ public class PCollectionsUnitTest { @Test public void whenMapPSetMethods_thenPerformOperations() { - MapPSet pSet = HashTreePSet.empty() - .plusAll(Arrays.asList("e1", "e2", "e3", "e4")); + MapPSet pSet = HashTreePSet.empty().plusAll(Arrays.asList("e1", "e2", "e3", "e4")); assertEquals(pSet.size(), 4); MapPSet pSet1 = pSet.minus("e4"); diff --git a/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java b/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java index cf6a1e5ec5..e9d5b8ede5 100644 --- a/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java +++ b/libraries/src/test/java/com/baeldung/protonpack/CollectorUtilsTests.java @@ -35,32 +35,21 @@ public class CollectorUtilsTests { @Test public void givenEmptyStream_withCollectorUnique_shouldReturnEmpty() { - assertThat(Stream - .empty() - .collect(CollectorUtils.unique()), equalTo(Optional.empty())); + assertThat(Stream.empty().collect(CollectorUtils.unique()), equalTo(Optional.empty())); } @Test public void givenIntegerStream_withCollectorUnique_shouldReturnUniqueValue() { - assertThat(Stream - .of(1, 2, 3) - .filter(i -> i > 2) - .collect(CollectorUtils.unique()), equalTo(Optional.of(3))); + assertThat(Stream.of(1, 2, 3).filter(i -> i > 2).collect(CollectorUtils.unique()), equalTo(Optional.of(3))); } @Test public void givenIntegerStream_withUniqueNullable_shouldReturnUniqueValue() { - assertThat(Stream - .of(1, 2, 3) - .filter(i -> i > 2) - .collect(CollectorUtils.uniqueNullable()), equalTo(3)); + assertThat(Stream.of(1, 2, 3).filter(i -> i > 2).collect(CollectorUtils.uniqueNullable()), equalTo(3)); } @Test(expected = NonUniqueValueException.class) public void givenIntegerStream_withCollectorUnique_shouldThrowNonUniqueValueException() { - Stream - .of(1, 2, 3) - .filter(i -> i > 1) - .collect(CollectorUtils.unique()); + Stream.of(1, 2, 3).filter(i -> i > 1).collect(CollectorUtils.unique()); } } diff --git a/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java b/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java index 37ca71287f..ccd43b7777 100644 --- a/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java +++ b/libraries/src/test/java/com/baeldung/protonpack/StreamUtilsTests.java @@ -24,9 +24,7 @@ public class StreamUtilsTests { public void givenStream_whenZipWithIndex_shouldReturnZippedStreamWithIndex() { Stream source = Stream.of("Foo", "Bar", "Baz"); - List> zipped = StreamUtils - .zipWithIndex(source) - .collect(Collectors.toList()); + List> zipped = StreamUtils.zipWithIndex(source).collect(Collectors.toList()); assertThat(zipped, contains(Indexed.index(0, "Foo"), Indexed.index(1, "Bar"), Indexed.index(2, "Baz"))); } @@ -36,9 +34,7 @@ public class StreamUtilsTests { Stream streamA = Stream.of("A", "B", "C"); Stream streamB = Stream.of("Apple", "Banana", "Carrot"); - List zipped = StreamUtils - .zip(streamA, streamB, (a, b) -> a + " is for " + b) - .collect(Collectors.toList()); + List zipped = StreamUtils.zip(streamA, streamB, (a, b) -> a + " is for " + b).collect(Collectors.toList()); assertThat(zipped, contains("A is for Apple", "B is for Banana", "C is for Carrot")); } @@ -49,15 +45,13 @@ public class StreamUtilsTests { Stream streamB = Stream.of("aggravating", "banausic", "complaisant"); Stream streamC = Stream.of("Apple", "Banana", "Carrot"); - List zipped = StreamUtils - .zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c) - .collect(Collectors.toList()); + List zipped = StreamUtils.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c).collect(Collectors.toList()); assertThat(zipped, contains("A is for aggravating Apple", "B is for banausic Banana", "C is for complaisant Carrot")); } @Test - //givenThreeStreams_whenMerge_shouldReturnMergedStream + // givenThreeStreams_whenMerge_shouldReturnMergedStream public void givenThreeStreams_whenMerge_shouldReturnMergedStream() { Stream streamA = Stream.of("A", "B", "C"); Stream streamB = Stream.of("apple", "banana", "carrot", "date"); @@ -69,7 +63,7 @@ public class StreamUtilsTests { } @Test - //givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream + // givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream public void givenThreeStreams_whenInterleave_shouldReturnRoundRobinInterleavingStream() { Stream streamA = Stream.of("Peter", "Paul", "Mary"); Stream streamB = Stream.of("A", "B", "C", "D", "E"); @@ -81,7 +75,7 @@ public class StreamUtilsTests { } @Test - //givenInfiniteStream_whenTakeWhile10_shouldReturnStreamOfSize10 + // givenInfiniteStream_whenTakeWhile10_shouldReturnStreamOfSize10 public void givenInfiniteStream_whenTakeWhile10_shouldReturnStream() { Stream infiniteInts = Stream.iterate(0, i -> i + 1); Stream finiteInts = StreamUtils.takeWhile(infiniteInts, i -> i < 10); @@ -125,9 +119,7 @@ public class StreamUtilsTests { @Test public void giveIntegerStream_whenGroupRuns_shouldReturnListGroupItems() { Stream integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5); - List> runs = StreamUtils - .groupRuns(integerStream) - .collect(toList()); + List> runs = StreamUtils.groupRuns(integerStream).collect(toList()); assertThat(runs, contains(asList(1, 1), asList(2, 2), asList(3), asList(4), asList(5))); } @@ -143,21 +135,17 @@ public class StreamUtilsTests { public void givenIntegerStream_whenWindowed_shouldReturnListOfListOfItemsOfWindowSize() { Stream integerStream = Stream.of(1, 2, 3, 4, 5); - List> windows = StreamUtils - .windowed(integerStream, 2) - .collect(toList()); + List> windows = StreamUtils.windowed(integerStream, 2).collect(toList()); assertThat(windows, contains(asList(1, 2), asList(2, 3), asList(3, 4), asList(4, 5))); } @Test - //givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip + // givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip public void givenIntegerStream_whenWindowedWithWindowSizeAndSkip_shouldReturnListOfListOfWindowSizeAddingASkip() { Stream integerStream = Stream.of(1, 2, 3, 4, 5); - List> windows = StreamUtils - .windowed(integerStream, 3, 2) - .collect(toList()); + List> windows = StreamUtils.windowed(integerStream, 3, 2).collect(toList()); assertThat(windows, contains(asList(1, 2, 3), asList(3, 4, 5))); } @@ -166,15 +154,9 @@ public class StreamUtilsTests { public void givenEmptyStream_whenWindowed_shouldReturnIterableWithSizeZero() { ArrayList ints = new ArrayList<>(); - ints - .stream() - .collect(maxBy((a, b) -> a - .toString() - .compareTo(b.toString()))); + ints.stream().collect(maxBy((a, b) -> a.toString().compareTo(b.toString()))); - List> windows = StreamUtils - .windowed(ints.stream(), 2) - .collect(toList()); + List> windows = StreamUtils.windowed(ints.stream(), 2).collect(toList()); assertThat(windows, iterableWithSize(0)); } @@ -183,18 +165,14 @@ public class StreamUtilsTests { public void givenIntegerStream_whenWindowedWithWindowSizeAndSkipAndAllowLesserSize_shouldReturnListOfListOfInteger() { Stream integerStream = Stream.of(1, 2, 3, 4, 5); - List> windows = StreamUtils - .windowed(integerStream, 2, 2, true) - .collect(toList()); + List> windows = StreamUtils.windowed(integerStream, 2, 2, true).collect(toList()); assertThat(windows, contains(asList(1, 2), asList(3, 4), asList(5))); } @Test public void givenLimit_withIndices_shouldReturnLongStreamUptoLimit() { - LongStream indices = StreamUtils - .indices() - .limit(500); + LongStream indices = StreamUtils.indices().limit(500); assertThat(indices.count(), equalTo(500)); } diff --git a/libraries/src/test/java/com/baeldung/retrofit/basic/GitHubBasicApiLiveTest.java b/libraries/src/test/java/com/baeldung/retrofit/basic/GitHubBasicApiLiveTest.java index 7170d35aa5..46325d4d23 100644 --- a/libraries/src/test/java/com/baeldung/retrofit/basic/GitHubBasicApiLiveTest.java +++ b/libraries/src/test/java/com/baeldung/retrofit/basic/GitHubBasicApiLiveTest.java @@ -17,46 +17,33 @@ import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class GitHubBasicApiLiveTest { - + GitHubBasicApi gitHub; - + @Before public void init() { - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://api.github.com/") - .addConverterFactory(GsonConverterFactory.create()) - .build(); - + Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).build(); + gitHub = retrofit.create(GitHubBasicApi.class); } - + @Test public void whenListRepos_thenExpectReposThatContainTutorials() { try { - List repos = gitHub - .listRepos("eugenp") - .execute() - .body(); - - assertThat(repos) - .isNotEmpty() - .extracting(Repository::getName).contains("tutorials"); + List repos = gitHub.listRepos("eugenp").execute().body(); + + assertThat(repos).isNotEmpty().extracting(Repository::getName).contains("tutorials"); } catch (IOException e) { fail("Can not communicate with GitHub API"); } } - + @Test public void whenListRepoContributers_thenExpectContributorsThatContainEugenp() { try { - List contributors = gitHub - .listRepoContributors("eugenp", "tutorials") - .execute() - .body(); - - assertThat(contributors) - .isNotEmpty() - .extracting(Contributor::getName).contains("eugenp"); + List contributors = gitHub.listRepoContributors("eugenp", "tutorials").execute().body(); + + assertThat(contributors).isNotEmpty().extracting(Contributor::getName).contains("eugenp"); } catch (IOException e) { fail("Can not communicate with GitHub API"); } diff --git a/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java b/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java index c2fbd9bf60..48161fa3ee 100644 --- a/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java +++ b/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java @@ -14,40 +14,28 @@ import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class GitHubRxApiTest { - + GitHubRxApi gitHub; - + @Before public void init() { - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://api.github.com/") - .addConverterFactory(GsonConverterFactory.create()) - .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) - .build(); - + Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); + gitHub = retrofit.create(GitHubRxApi.class); } - + @Test public void whenListRepos_thenExpectReposThatContainTutorials() { - gitHub - .listRepos("eugenp") - .subscribe( repos -> { - assertThat(repos) - .isNotEmpty() - .extracting(Repository::getName).contains("tutorials"); - }); + gitHub.listRepos("eugenp").subscribe(repos -> { + assertThat(repos).isNotEmpty().extracting(Repository::getName).contains("tutorials"); + }); } - + @Test public void whenListRepoContributers_thenExpectContributorsThatContainEugenp() { - gitHub - .listRepoContributors("eugenp", "tutorials") - .subscribe(contributors -> { - assertThat(contributors) - .isNotEmpty() - .extracting(Contributor::getName).contains("eugenp"); - }); + gitHub.listRepoContributors("eugenp", "tutorials").subscribe(contributors -> { + assertThat(contributors).isNotEmpty().extracting(Contributor::getName).contains("eugenp"); + }); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/GoogleSearchLiveTest.java b/libraries/src/test/java/com/baeldung/serenity/GoogleSearchLiveTest.java index 1ebbd49e79..57bb7c1242 100644 --- a/libraries/src/test/java/com/baeldung/serenity/GoogleSearchLiveTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/GoogleSearchLiveTest.java @@ -23,15 +23,11 @@ public class GoogleSearchLiveTest { public void whenGoogleBaeldungThenShouldSeeEugen() { browser.get("https://www.google.com/ncr"); - browser - .findElement(By.name("q")) - .sendKeys("baeldung", Keys.ENTER); + browser.findElement(By.name("q")).sendKeys("baeldung", Keys.ENTER); new WebDriverWait(browser, 5).until(visibilityOfElementLocated(By.cssSelector("._ksh"))); - assertThat(browser - .findElement(By.cssSelector("._ksh")) - .getText(), containsString("Eugen (Baeldung)")); + assertThat(browser.findElement(By.cssSelector("._ksh")).getText(), containsString("Eugen (Baeldung)")); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/github/GithubRestUserAPISteps.java b/libraries/src/test/java/com/baeldung/serenity/github/GithubRestUserAPISteps.java index 2ba5b1c8ed..887b4cde7d 100644 --- a/libraries/src/test/java/com/baeldung/serenity/github/GithubRestUserAPISteps.java +++ b/libraries/src/test/java/com/baeldung/serenity/github/GithubRestUserAPISteps.java @@ -43,9 +43,6 @@ public class GithubRestUserAPISteps { private static HttpResponse getGithubUserProfile(String api, String username) throws IOException { HttpUriRequest request = new HttpGet(String.format(api, username)); - return HttpClientBuilder - .create() - .build() - .execute(request); + return HttpClientBuilder.create().build().execute(request); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/membership/MemberStatusSteps.java b/libraries/src/test/java/com/baeldung/serenity/membership/MemberStatusSteps.java index 49ed8cae7d..a398c614c4 100644 --- a/libraries/src/test/java/com/baeldung/serenity/membership/MemberStatusSteps.java +++ b/libraries/src/test/java/com/baeldung/serenity/membership/MemberStatusSteps.java @@ -33,7 +33,7 @@ public class MemberStatusSteps { @Pending @Step("When the member exchange {}") public void aMemberExchangeA(Commodity commodity) { - //TODO + // TODO } @Pending diff --git a/libraries/src/test/java/com/baeldung/serenity/pageobjects/GoogleSearchPageObject.java b/libraries/src/test/java/com/baeldung/serenity/pageobjects/GoogleSearchPageObject.java index bdba8a69bc..d922ea8c85 100644 --- a/libraries/src/test/java/com/baeldung/serenity/pageobjects/GoogleSearchPageObject.java +++ b/libraries/src/test/java/com/baeldung/serenity/pageobjects/GoogleSearchPageObject.java @@ -24,9 +24,7 @@ public class GoogleSearchPageObject extends PageObject { } public void resultMatches(String expected) { - withTimeoutOf(5, SECONDS) - .waitFor(result) - .waitUntilVisible(); + withTimeoutOf(5, SECONDS).waitFor(result).waitUntilVisible(); assertThat(result.getText(), containsString(expected)); } diff --git a/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchPage.java b/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchPage.java index b60c929c05..5663484a5b 100644 --- a/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchPage.java +++ b/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchPage.java @@ -10,12 +10,8 @@ import net.thucydides.core.annotations.DefaultUrl; @DefaultUrl("https://www.google.com/ncr") class GoogleSearchPage extends PageObject { - static final Target SEARCH_RESULT_TITLES = Target - .the("search results") - .locatedBy("._ksh"); + static final Target SEARCH_RESULT_TITLES = Target.the("search results").locatedBy("._ksh"); - static final Target SEARCH_INPUT_BOX = Target - .the("search input box") - .locatedBy("#lst-ib"); + static final Target SEARCH_INPUT_BOX = Target.the("search input box").locatedBy("#lst-ib"); } diff --git a/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchResults.java b/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchResults.java index 38990e13b6..67a27e5855 100644 --- a/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchResults.java +++ b/libraries/src/test/java/com/baeldung/serenity/screenplay/GoogleSearchResults.java @@ -13,9 +13,6 @@ public class GoogleSearchResults implements Question> { } public List answeredBy(Actor actor) { - return Text - .of(GoogleSearchPage.SEARCH_RESULT_TITLES) - .viewedBy(actor) - .asList(); + return Text.of(GoogleSearchPage.SEARCH_RESULT_TITLES).viewedBy(actor).asList(); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/screenplay/SearchForKeyword.java b/libraries/src/test/java/com/baeldung/serenity/screenplay/SearchForKeyword.java index 1628ef8ed7..2464c439cf 100644 --- a/libraries/src/test/java/com/baeldung/serenity/screenplay/SearchForKeyword.java +++ b/libraries/src/test/java/com/baeldung/serenity/screenplay/SearchForKeyword.java @@ -11,10 +11,7 @@ public class SearchForKeyword implements Task { @Step("{0} searches for '#keyword'") public void performAs(T actor) { - actor.attemptsTo(Enter - .theValue(keyword) - .into(GoogleSearchPage.SEARCH_INPUT_BOX) - .thenHit(Keys.RETURN)); + actor.attemptsTo(Enter.theValue(keyword).into(GoogleSearchPage.SEARCH_INPUT_BOX).thenHit(Keys.RETURN)); } private String keyword; @@ -24,9 +21,7 @@ public class SearchForKeyword implements Task { } public static Task of(String keyword) { - return Instrumented - .instanceOf(SearchForKeyword.class) - .withProperties(keyword); + return Instrumented.instanceOf(SearchForKeyword.class).withProperties(keyword); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/screenplay/StartWith.java b/libraries/src/test/java/com/baeldung/serenity/screenplay/StartWith.java index 52c6d07fda..d6e45beb26 100644 --- a/libraries/src/test/java/com/baeldung/serenity/screenplay/StartWith.java +++ b/libraries/src/test/java/com/baeldung/serenity/screenplay/StartWith.java @@ -17,9 +17,7 @@ public class StartWith implements Task { @Step("{0} starts a google search") public void performAs(T t) { - t.attemptsTo(Open - .browserOn() - .the(googleSearchPage)); + t.attemptsTo(Open.browserOn().the(googleSearchPage)); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderClassDirtiesContextIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderClassDirtiesContextIntegrationTest.java index 82dbad0f11..7eb658ca23 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderClassDirtiesContextIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderClassDirtiesContextIntegrationTest.java @@ -15,9 +15,7 @@ import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt; import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS; @RunWith(Suite.class) -@Suite.SuiteClasses({ - AdderClassDirtiesContextIntegrationTest.DirtiesContextTest.class, AdderClassDirtiesContextIntegrationTest.AnotherDirtiesContextTest.class -}) +@Suite.SuiteClasses({ AdderClassDirtiesContextIntegrationTest.DirtiesContextTest.class, AdderClassDirtiesContextIntegrationTest.AnotherDirtiesContextTest.class }) public class AdderClassDirtiesContextIntegrationTest { @RunWith(SerenityRunner.class) @@ -52,7 +50,7 @@ public class AdderClassDirtiesContextIntegrationTest { @Test public void givenNumber_whenAdd_thenSumWrong() { - super.whenAdd_thenSummedUp(); //expecting zero + super.whenAdd_thenSummedUp(); // expecting zero adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt()); super.whenAccumulate_thenSummedUp(); super.whenAdd_thenSumWrong(); @@ -64,7 +62,7 @@ public class AdderClassDirtiesContextIntegrationTest { @Test public void givenNumber_whenAdd_thenSumWrong() { - super.whenAdd_thenSummedUp(); //expecting zero + super.whenAdd_thenSummedUp(); // expecting zero adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt()); super.whenAccumulate_thenSummedUp(); super.whenAdd_thenSumWrong(); diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest.java index 6524ade190..ecb601b94b 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest.java @@ -25,7 +25,8 @@ public class AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest { private AdderConstructorDependencySteps adderSteps; - @Autowired private AdderService adderService; + @Autowired + private AdderService adderService; @Before public void init() { @@ -38,7 +39,8 @@ public class AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest { adderSteps.summedUp(); } - @Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule(); + @Rule + public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule(); @DirtiesContext @Test diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextInitWorkaroundIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextInitWorkaroundIntegrationTest.java index 87c66f03d9..7221aa7a17 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextInitWorkaroundIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextInitWorkaroundIntegrationTest.java @@ -23,7 +23,8 @@ import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt; @ContextConfiguration(classes = AdderService.class) public class AdderMethodDirtiesContextInitWorkaroundIntegrationTest { - @Steps private AdderServiceSteps adderServiceSteps; + @Steps + private AdderServiceSteps adderServiceSteps; @Before public void init() { @@ -36,7 +37,8 @@ public class AdderMethodDirtiesContextInitWorkaroundIntegrationTest { adderServiceSteps.summedUp(); } - @Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule(); + @Rule + public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule(); @DirtiesContext @Test diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java index 263ffc9854..fc7067520d 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java @@ -22,7 +22,8 @@ import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt; @ContextConfiguration(classes = AdderService.class) public class AdderMethodDirtiesContextIntegrationTest { - @Steps private AdderServiceSteps adderServiceSteps; + @Steps + private AdderServiceSteps adderServiceSteps; @Test public void _1_givenNumber_whenAdd_thenSumWrong() { @@ -30,7 +31,8 @@ public class AdderMethodDirtiesContextIntegrationTest { adderServiceSteps.sumWrong(); } - @Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule(); + @Rule + public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule(); @DirtiesContext @Test diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodRuleIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodRuleIntegrationTest.java index bbf07a2b95..1b3668b756 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodRuleIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodRuleIntegrationTest.java @@ -41,11 +41,14 @@ public class AdderMethodRuleIntegrationTest { LOG.info("adder after test: {}", adder); } - @Rule public SpringIntegrationMethodRule springMethodIntegration = new SpringIntegrationMethodRule(); + @Rule + public SpringIntegrationMethodRule springMethodIntegration = new SpringIntegrationMethodRule(); - @Steps private AdderSteps adderSteps; + @Steps + private AdderSteps adderSteps; - @Value("#{props['adder']}") private int adder; + @Value("#{props['adder']}") + private int adder; private static int staticAdder; diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMockMvcIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMockMvcIntegrationTest.java index 2b2777f0ed..d4cf9fc924 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMockMvcIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMockMvcIntegrationTest.java @@ -21,7 +21,8 @@ public class AdderMockMvcIntegrationTest { RestAssuredMockMvc.standaloneSetup(new PlainAdderController()); } - @Steps AdderRestSteps steps; + @Steps + AdderRestSteps steps; @Test public void givenNumber_whenAdd_thenSummedUp() throws Exception { diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderServiceIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderServiceIntegrationTest.java index 5f2aae8e3f..8b307973ba 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderServiceIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderServiceIntegrationTest.java @@ -14,7 +14,8 @@ import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt; @RunWith(SerenityRunner.class) public class AdderServiceIntegrationTest { - @Steps private AdderServiceSteps adderServiceSteps; + @Steps + private AdderServiceSteps adderServiceSteps; @Test public void givenNumber_whenAdd_thenSummedUp() { diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderSpringSerenityRunnerIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderSpringSerenityRunnerIntegrationTest.java index cdabc17980..ddbfd0cfc2 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderSpringSerenityRunnerIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderSpringSerenityRunnerIntegrationTest.java @@ -15,9 +15,11 @@ import org.springframework.test.context.ContextConfiguration; @ContextConfiguration(locations = "classpath:adder-beans.xml") public class AdderSpringSerenityRunnerIntegrationTest { - @Steps private AdderSteps adderSteps; + @Steps + private AdderSteps adderSteps; - @Value("#{props['adder']}") private int adder; + @Value("#{props['adder']}") + private int adder; @Test public void givenNumber_whenAdd_thenSummedUp() { diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderTest.java index 771f389cb1..3144771e70 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderTest.java @@ -6,7 +6,7 @@ import org.jbehave.core.annotations.BeforeStory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; -@ContextConfiguration(classes = {AdderController.class, AdderService.class}) +@ContextConfiguration(classes = { AdderController.class, AdderService.class }) public class AdderTest extends SerenityStory { @Autowired diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderRestSteps.java b/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderRestSteps.java index 0d77ed0849..a38a584645 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderRestSteps.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderRestSteps.java @@ -18,29 +18,18 @@ public class AdderRestSteps { @Step("get the current number") public void givenCurrentNumber() throws UnsupportedEncodingException { - currentNum = Integer.valueOf(given() - .when() - .get("/adder/current") - .mvcResult() - .getResponse() - .getContentAsString()); + currentNum = Integer.valueOf(given().when().get("/adder/current").mvcResult().getResponse().getContentAsString()); } @Step("adding {0}") public void whenAddNumber(int num) { - mockMvcResponse = given() - .queryParam("num", num) - .when() - .post("/adder"); + mockMvcResponse = given().queryParam("num", num).when().post("/adder"); currentNum += num; } @Step("got the sum") public void thenSummedUp() { - mockMvcResponse - .then() - .statusCode(200) - .body(equalTo(currentNum + "")); + mockMvcResponse.then().statusCode(200).body(equalTo(currentNum + "")); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderServiceSteps.java b/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderServiceSteps.java index b8c2854bf0..227526b8b4 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderServiceSteps.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/steps/AdderServiceSteps.java @@ -13,7 +13,8 @@ import static org.junit.Assert.assertNotEquals; @ContextConfiguration(classes = AdderService.class) public class AdderServiceSteps { - @Autowired private AdderService adderService; + @Autowired + private AdderService adderService; private int givenNumber; private int base; diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/stories/AdderStory.java b/libraries/src/test/java/com/baeldung/serenity/spring/stories/AdderStory.java index b9fa8f1ae0..491c11a38c 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/stories/AdderStory.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/stories/AdderStory.java @@ -11,7 +11,8 @@ import org.jbehave.core.annotations.When; */ public class AdderStory { - @Steps AdderRestSteps restSteps; + @Steps + AdderRestSteps restSteps; @Given("a number") public void givenANumber() throws Exception { diff --git a/libraries/src/test/java/com/baeldung/smooks/converter/SmooksIntegrationTest.java b/libraries/src/test/java/com/baeldung/smooks/converter/SmooksIntegrationTest.java index 4d2cb71329..69af042427 100644 --- a/libraries/src/test/java/com/baeldung/smooks/converter/SmooksIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/smooks/converter/SmooksIntegrationTest.java @@ -10,22 +10,11 @@ import java.text.SimpleDateFormat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; - public class SmooksIntegrationTest { - private static final String EDIFACT_MESSAGE = - "UNA:+.? '\r\n" + - "UNH+771+IN_PROGRESS+2018-01-14'\r\n" + - "CTA+CompanyX+1234567'\r\n" + - "LIN+1+PX1234+9.99'\r\n" + - "LIN+2+RX990+120.32'\r\n"; - private static final String EMAIL_MESSAGE = - "Hi,\r\n" + - "Order number #771 created on 2018-01-14 is currently in IN_PROGRESS status.\r\n" + - "Consider contact supplier \"CompanyX\" with phone number: \"1234567\".\r\n" + - "Order items:\r\n" + - "1 X PX1234 (total price 9.99)\r\n" + - "2 X RX990 (total price 240.64)\r\n"; + private static final String EDIFACT_MESSAGE = "UNA:+.? '\r\n" + "UNH+771+IN_PROGRESS+2018-01-14'\r\n" + "CTA+CompanyX+1234567'\r\n" + "LIN+1+PX1234+9.99'\r\n" + "LIN+2+RX990+120.32'\r\n"; + private static final String EMAIL_MESSAGE = "Hi,\r\n" + "Order number #771 created on 2018-01-14 is currently in IN_PROGRESS status.\r\n" + "Consider contact supplier \"CompanyX\" with phone number: \"1234567\".\r\n" + "Order items:\r\n" + + "1 X PX1234 (total price 9.99)\r\n" + "2 X RX990 (total price 240.64)\r\n"; @Test public void givenOrderXML_whenConvert_thenPOJOsConstructedCorrectly() throws Exception { @@ -33,14 +22,11 @@ public class SmooksIntegrationTest { OrderConverter xmlToJavaOrderConverter = new OrderConverter(); Order order = xmlToJavaOrderConverter.convertOrderXMLToOrderObject("/smooks/order.xml"); - assertThat(order.getNumber(),is(771L)); - assertThat(order.getStatus(),is(Status.IN_PROGRESS)); - assertThat(order.getCreationDate(),is(new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-14"))); - assertThat(order.getSupplier(),is(new Supplier("CompanyX","1234567"))); - assertThat(order.getItems(),containsInAnyOrder( - new Item("PX1234",9.99,1), - new Item("RX990",120.32,2)) - ); + assertThat(order.getNumber(), is(771L)); + assertThat(order.getStatus(), is(Status.IN_PROGRESS)); + assertThat(order.getCreationDate(), is(new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-14"))); + assertThat(order.getSupplier(), is(new Supplier("CompanyX", "1234567"))); + assertThat(order.getItems(), containsInAnyOrder(new Item("PX1234", 9.99, 1), new Item("RX990", 120.32, 2))); } @@ -51,20 +37,20 @@ public class SmooksIntegrationTest { assertThat(validationResult.getErrors(), hasSize(1)); // 1234567 didn't match ^[0-9\\-\\+]{9,15}$ - assertThat(validationResult.getErrors().get(0).getFailRuleResult().getRuleName(),is("supplierPhone")); + assertThat(validationResult.getErrors().get(0).getFailRuleResult().getRuleName(), is("supplierPhone")); } @Test public void givenOrderXML_whenApplyEDITemplate_thenConvertedToEDIFACT() throws Exception { OrderConverter orderConverter = new OrderConverter(); String edifact = orderConverter.convertOrderXMLtoEDIFACT("/smooks/order.xml"); - assertThat(edifact,is(EDIFACT_MESSAGE)); + assertThat(edifact, is(EDIFACT_MESSAGE)); } @Test public void givenOrderXML_whenApplyEmailTemplate_thenConvertedToEmailMessage() throws Exception { OrderConverter orderConverter = new OrderConverter(); String emailMessage = orderConverter.convertOrderXMLtoEmailMessage("/smooks/order.xml"); - assertThat(emailMessage,is(EMAIL_MESSAGE)); + assertThat(emailMessage, is(EMAIL_MESSAGE)); } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stm/AccountTest.java b/libraries/src/test/java/com/baeldung/stm/AccountTest.java index be3edf058c..eb8693b096 100644 --- a/libraries/src/test/java/com/baeldung/stm/AccountTest.java +++ b/libraries/src/test/java/com/baeldung/stm/AccountTest.java @@ -1,6 +1,5 @@ package com.baeldung.stm; - import org.junit.Test; import java.util.concurrent.CountDownLatch; @@ -16,34 +15,34 @@ public class AccountTest { @Test public void givenAccount_whenDecrement_thenShouldReturnProperValue() { - //given + // given Account a = new Account(10); - //when + // when a.adjustBy(-5); - //then + // then assertThat(a.getBalance()).isEqualTo(5); } @Test(expected = IllegalArgumentException.class) public void givenAccount_whenDecrementTooMuch_thenShouldThrow() { - //given + // given Account a = new Account(10); - //when + // when a.adjustBy(-11); } @Test public void givenTwoThreads_whenBothApplyOperation_thenShouldThrow() throws InterruptedException { - //given + // given ExecutorService ex = Executors.newFixedThreadPool(2); Account a = new Account(10); CountDownLatch countDownLatch = new CountDownLatch(1); AtomicBoolean exceptionThrown = new AtomicBoolean(false); - //when + // when ex.submit(() -> { try { countDownLatch.await(); @@ -74,44 +73,44 @@ public class AccountTest { ex.awaitTermination(1, TimeUnit.SECONDS); ex.shutdown(); - //then + // then assertTrue(exceptionThrown.get()); } @Test public void givenTwoAccounts_whenFailedWhileTransferring_thenShouldRollbackTransaction() { - //given + // given final Account a = new Account(10); final Account b = new Account(10); - //when + // when a.transferTo(b, 5); - //then + // then assertThat(a.getBalance()).isEqualTo(5); assertThat(b.getBalance()).isEqualTo(15); - //and + // and try { a.transferTo(b, 20); } catch (final IllegalArgumentException e) { System.out.println("failed to transfer money"); } - //then + // then assertThat(a.getBalance()).isEqualTo(5); assertThat(b.getBalance()).isEqualTo(15); } @Test public void givenTwoThreads_whenBothTryToTransfer_thenShouldNotDeadlock() throws InterruptedException { - //given + // given ExecutorService ex = Executors.newFixedThreadPool(2); final Account a = new Account(10); final Account b = new Account(10); CountDownLatch countDownLatch = new CountDownLatch(1); - //when + // when ex.submit(() -> { try { countDownLatch.await(); @@ -134,10 +133,9 @@ public class AccountTest { ex.awaitTermination(1, TimeUnit.SECONDS); ex.shutdown(); - //then + // then assertThat(a.getBalance()).isEqualTo(1); assertThat(b.getBalance()).isEqualTo(19); } - } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java b/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java index e14a91ce67..4cda0b5940 100644 --- a/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java +++ b/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsTest.java @@ -16,11 +16,9 @@ public class JoolMergeStreamsTest { Stream seq1 = Stream.of(1, 3, 5); Stream seq2 = Stream.of(2, 4, 6); - Stream resultingSeq = Seq.ofType(seq1, Integer.class) - .append(seq2); + Stream resultingSeq = Seq.ofType(seq1, Integer.class).append(seq2); - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), - resultingSeq.collect(Collectors.toList())); + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingSeq.collect(Collectors.toList())); } @Test @@ -29,11 +27,8 @@ public class JoolMergeStreamsTest { Stream openingBracketSeq = Stream.of("["); Stream closingBracketSeq = Stream.of("]"); - Stream resultingStream = Seq.ofType(seq, String.class) - .append(closingBracketSeq) - .prepend(openingBracketSeq); + Stream resultingStream = Seq.ofType(seq, String.class).append(closingBracketSeq).prepend(openingBracketSeq); - Assert.assertEquals(Arrays.asList("[", "foo", "bar", "]"), - resultingStream.collect(Collectors.toList())); + Assert.assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList())); } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java b/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java index 23110947b6..b8748abe03 100644 --- a/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java +++ b/libraries/src/test/java/com/baeldung/stream/MergeStreamsTest.java @@ -16,11 +16,9 @@ public class MergeStreamsTest { Stream stream1 = Stream.of(1, 3, 5); Stream stream2 = Stream.of(2, 4, 6); - Stream resultingStream = Stream.concat(stream1, - stream2); + Stream resultingStream = Stream.concat(stream1, stream2); - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), - resultingStream.collect(Collectors.toList())); + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList())); } @Test @@ -29,12 +27,9 @@ public class MergeStreamsTest { Stream stream2 = Stream.of(2, 4, 6); Stream stream3 = Stream.of(18, 15, 36); - Stream resultingStream = Stream.concat(Stream.concat(stream1, - stream2), - stream3); + Stream resultingStream = Stream.concat(Stream.concat(stream1, stream2), stream3); - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36), - resultingStream.collect(Collectors.toList())); + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36), resultingStream.collect(Collectors.toList())); } @Test @@ -46,8 +41,7 @@ public class MergeStreamsTest { Stream resultingStream = Stream.of(stream1, stream2, stream3, stream4).flatMap(Function.identity()); - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), - resultingStream.collect(Collectors.toList())); + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList())); } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java b/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java index 5104ec0682..e5392dff2a 100644 --- a/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java +++ b/libraries/src/test/java/com/baeldung/stream/StreamExMergeStreamsTest.java @@ -18,8 +18,7 @@ public class StreamExMergeStreamsTest { Stream resultingStream = StreamEx.of(stream1).append(stream2); - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), - resultingStream.collect(Collectors.toList())); + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList())); } @Test @@ -29,13 +28,9 @@ public class StreamExMergeStreamsTest { Stream stream3 = Stream.of(18, 15, 36); Stream stream4 = Stream.of(99); - Stream resultingStream = StreamEx.of(stream1) - .append(stream2) - .append(stream3) - .append(stream4); + Stream resultingStream = StreamEx.of(stream1).append(stream2).append(stream3).append(stream4); - assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), - resultingStream.collect(Collectors.toList())); + assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList())); } @@ -45,11 +40,8 @@ public class StreamExMergeStreamsTest { Stream openingBracketStream = Stream.of("["); Stream closingBracketStream = Stream.of("]"); - Stream resultingStream = StreamEx.of(stream1) - .append(closingBracketStream) - .prepend(openingBracketStream); + Stream resultingStream = StreamEx.of(stream1).append(closingBracketStream).prepend(openingBracketStream); - assertEquals(Arrays.asList("[", "foo", "bar", "]"), - resultingStream.collect(Collectors.toList())); + assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList())); } } diff --git a/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java index 9a65075e5b..3ed797ccaa 100644 --- a/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java +++ b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java @@ -18,83 +18,83 @@ import static com.baeldung.streamutils.CopyStream.getStringFromInputStream; public class CopyStreamTest { - @Test - public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - String outputFileName = "src/test/resources/output.txt"; - File outputFile = new File(outputFileName); - InputStream in = new FileInputStream(inputFileName); - OutputStream out = new FileOutputStream(outputFileName); + @Test + public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); - StreamUtils.copy(in, out); + StreamUtils.copy(in, out); - assertTrue(outputFile.exists()); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - Assert.assertEquals(inputFileContent, outputFileContent); - } + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(inputFileContent, outputFileContent); + } - @Test - public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - String outputFileName = "src/test/resources/output.txt"; - File outputFile = new File(outputFileName); - InputStream in = new FileInputStream(inputFileName); - OutputStream out = new FileOutputStream(outputFileName); + @Test + public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); - StreamUtils.copyRange(in, out, 1, 10); + StreamUtils.copyRange(in, out, 1, 10); - assertTrue(outputFile.exists()); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - Assert.assertEquals(inputFileContent.substring(1, 11), outputFileContent); - } + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(inputFileContent.substring(1, 11), outputFileContent); + } - @Test - public void whenCopyStringToOutputStream_thenCorrect() throws IOException { - String string = "Should be copied to OutputStream."; - String outputFileName = "src/test/resources/output.txt"; - File outputFile = new File(outputFileName); - OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + @Test + public void whenCopyStringToOutputStream_thenCorrect() throws IOException { + String string = "Should be copied to OutputStream."; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); - StreamUtils.copy(string, StandardCharsets.UTF_8, out); + StreamUtils.copy(string, StandardCharsets.UTF_8, out); - assertTrue(outputFile.exists()); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - Assert.assertEquals(outputFileContent, string); - } + assertTrue(outputFile.exists()); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(outputFileContent, string); + } - @Test - public void whenCopyInputStreamToString_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - InputStream is = new FileInputStream(inputFileName); - String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); + @Test + public void whenCopyInputStreamToString_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream is = new FileInputStream(inputFileName); + String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - Assert.assertEquals(inputFileContent, content); - } + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + Assert.assertEquals(inputFileContent, content); + } - @Test - public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException { - String outputFileName = "src/test/resources/output.txt"; - String string = "Should be copied to OutputStream."; - byte[] byteArray = string.getBytes(); - OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + @Test + public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException { + String outputFileName = "src/test/resources/output.txt"; + String string = "Should be copied to OutputStream."; + byte[] byteArray = string.getBytes(); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); - StreamUtils.copy(byteArray, out); - String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); - Assert.assertEquals(outputFileContent, string); - } + StreamUtils.copy(byteArray, out); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(outputFileContent, string); + } - @Test - public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException { - String inputFileName = "src/test/resources/input.txt"; - InputStream in = new FileInputStream(inputFileName); - byte[] out = StreamUtils.copyToByteArray(in); + @Test + public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream in = new FileInputStream(inputFileName); + byte[] out = StreamUtils.copyToByteArray(in); - String content = new String(out); - String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); - Assert.assertEquals(inputFileContent, content); - } + String content = new String(out); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + Assert.assertEquals(inputFileContent, content); + } } diff --git a/libraries/src/test/java/com/baeldung/text/DiffTest.java b/libraries/src/test/java/com/baeldung/text/DiffTest.java index 95370013b6..932fc96f21 100644 --- a/libraries/src/test/java/com/baeldung/text/DiffTest.java +++ b/libraries/src/test/java/com/baeldung/text/DiffTest.java @@ -6,13 +6,13 @@ import org.junit.Assert; import org.junit.Test; public class DiffTest { - + @Test public void whenEditScript_thenCorrect() { StringsComparator cmp = new StringsComparator("ABCFGH", "BCDEFG"); EditScript script = cmp.getScript(); int mod = script.getModifications(); - + Assert.assertEquals(4, mod); } } diff --git a/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java b/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java index 80ca0cfbba..e0a00afd84 100644 --- a/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java +++ b/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceTest.java @@ -11,15 +11,15 @@ public class LongestCommonSubsequenceTest { public void whenCompare_thenCorrect() { LongestCommonSubsequence lcs = new LongestCommonSubsequence(); int countLcs = lcs.apply("New York", "New Hampshire"); - + Assert.assertEquals(5, countLcs); } - + @Test public void whenCalculateDistance_thenCorrect() { LongestCommonSubsequenceDistance lcsd = new LongestCommonSubsequenceDistance(); int countLcsd = lcsd.apply("New York", "New Hampshire"); - + Assert.assertEquals(11, countLcsd); } } diff --git a/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java b/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java index f08b43f69b..4ebf00e1ed 100644 --- a/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java +++ b/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java @@ -13,12 +13,12 @@ public class StrBuilderTest { Assert.assertEquals(new StrBuilder("new StrBuilder!"), strBuilder); } - + @Test public void whenCleared_thenEmpty() { StrBuilder strBuilder = new StrBuilder("example StrBuilder!"); strBuilder.clear(); - + Assert.assertEquals(new StrBuilder(""), strBuilder); } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatTest.java b/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatTest.java index d559c3d408..6ce11d1895 100644 --- a/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatTest.java +++ b/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatTest.java @@ -13,7 +13,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; - import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -37,19 +36,13 @@ public class ProgrammaticTomcatTest { @Test public void givenTomcatStarted_whenAccessServlet_responseIsTestAndResponseHeaderIsSet() throws Exception { - CloseableHttpClient httpClient = HttpClientBuilder - .create() - .build(); + CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpGet getServlet = new HttpGet("http://localhost:8080/my-servlet"); HttpResponse response = httpClient.execute(getServlet); - assertEquals(HttpStatus.SC_OK, response - .getStatusLine() - .getStatusCode()); + assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - String myHeaderValue = response - .getFirstHeader("myHeader") - .getValue(); + String myHeaderValue = response.getFirstHeader("myHeader").getValue(); assertEquals("myHeaderValue", myHeaderValue); HttpEntity responseEntity = response.getEntity(); diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 22a027a58e..8e84c0f364 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -7,7 +7,7 @@ 0.0.1-SNAPSHOT jar - spring-5 + spring-5-reactive-client spring 5 sample project about new features diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index 5065457c4b..abd8e42cf5 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -7,7 +7,7 @@ 0.0.1-SNAPSHOT jar - spring-5 + spring-5-reactive spring 5 sample project about new features diff --git a/spring-boot/.factorypath b/spring-boot/.factorypath index aa15485f5c..60dbd696eb 100644 --- a/spring-boot/.factorypath +++ b/spring-boot/.factorypath @@ -1,149 +1,154 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - - - - + + + + + + + + + + + + + + + - + - - + + + + + - - - - - - + + + + + + + - - + - + - - - - + + + + + - - - - - - - - + + + + + + + + + + + + - + - + + + + + + + + + + + + + + + + + + - - - - + + + + - - - - - + + + + + - - - - + + + + + + + + + + - + - - - + + + + - + From 4a489e4afc4ea8620571336d8b25a45472b8b342 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 4 Mar 2018 17:42:36 +0200 Subject: [PATCH 45/91] unused import cleanup --- .../test/java/com/baeldung/geotools/GeoToolsUnitTest.java | 2 +- libraries/log4j.properties | 1 + .../eclipsecollections/ConvertContainerToAnother.java | 1 - .../com/baeldung/googlehttpclientguide/GitHubExample.java | 2 -- .../src/main/java/com/baeldung/hikaricp/DataSource.java | 2 -- libraries/src/main/java/com/baeldung/jdo/query/MyApp.java | 1 - .../src/main/java/com/baeldung/jdo/query/ProductItem.java | 1 - .../main/java/com/baeldung/jdo/xml/AnnotadedPerson.java | 2 -- libraries/src/main/java/com/baeldung/jdo/xml/Person.java | 6 ------ libraries/src/main/java/com/baeldung/jdo/xml/Product.java | 3 --- .../com/baeldung/commons/collections/MapUtilsTest.java | 8 -------- .../src/test/java/com/baeldung/date/DateDiffUnitTest.java | 1 - .../infinispan/service/HelloWorldServiceUnitTest.java | 3 --- .../java/com/baeldung/jetty/JettyIntegrationTest.java | 2 -- .../baeldung/mbassador/MBassadorAsyncInvocationTest.java | 2 -- .../baeldung/mbassador/MBassadorConfigurationTest.java | 2 -- .../main/java/com/baeldung/restdocs/CRUDController.java | 1 - .../baeldung/web/reactive/client/WebClientController.java | 2 -- 18 files changed, 2 insertions(+), 40 deletions(-) diff --git a/geotools/src/test/java/com/baeldung/geotools/GeoToolsUnitTest.java b/geotools/src/test/java/com/baeldung/geotools/GeoToolsUnitTest.java index 053932b2a7..4a63c44c8b 100644 --- a/geotools/src/test/java/com/baeldung/geotools/GeoToolsUnitTest.java +++ b/geotools/src/test/java/com/baeldung/geotools/GeoToolsUnitTest.java @@ -3,7 +3,6 @@ package com.baeldung.geotools; import static org.junit.Assert.assertNotNull; import org.geotools.feature.DefaultFeatureCollection; -import org.geotools.feature.simple.SimpleFeatureBuilder; import org.junit.Test; import org.opengis.feature.simple.SimpleFeatureType; @@ -19,4 +18,5 @@ public class GeoToolsUnitTest { assertNotNull(collection); } + } diff --git a/libraries/log4j.properties b/libraries/log4j.properties index e69de29bb2..2173c5d96f 100644 --- a/libraries/log4j.properties +++ b/libraries/log4j.properties @@ -0,0 +1 @@ +log4j.rootLogger=INFO, stdout diff --git a/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java b/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java index 069baeab9f..9d1b011e0e 100644 --- a/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java +++ b/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java @@ -2,7 +2,6 @@ package com.baeldung.eclipsecollections; import java.util.List; -import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.set.mutable.UnifiedSet; public class ConvertContainerToAnother { diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java index 3b2c58d1e1..fce47c6ada 100644 --- a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java @@ -4,9 +4,7 @@ import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; -import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; -import com.google.api.client.http.apache.ApacheHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; diff --git a/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java b/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java index d96c0eb107..e8d3b4ff96 100644 --- a/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java +++ b/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java @@ -1,9 +1,7 @@ package com.baeldung.hikaricp; -import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; -import java.util.Properties; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; diff --git a/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java b/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java index c902083e62..235142d16e 100644 --- a/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java +++ b/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java @@ -66,7 +66,6 @@ public class MyApp { } public static void queryUsingTypedJDOQL() { - JDOQLTypedQuery tq = pm.newJDOQLTypedQuery(ProductItem.class); QProductItem cand = QProductItem.candidate(); tq = tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro"))); diff --git a/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java b/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java index 3343febb89..fbe999ba2a 100644 --- a/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java +++ b/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java @@ -1,7 +1,6 @@ package com.baeldung.jdo.query; import javax.jdo.annotations.IdGeneratorStrategy; -import javax.jdo.annotations.PersistenceAware; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java b/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java index d2518586b4..acfc26627a 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java +++ b/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java @@ -1,9 +1,7 @@ package com.baeldung.jdo.xml; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import javax.jdo.annotations.Element; import javax.jdo.annotations.PersistenceCapable; diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/Person.java b/libraries/src/main/java/com/baeldung/jdo/xml/Person.java index b5750a2069..0678201afd 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/Person.java +++ b/libraries/src/main/java/com/baeldung/jdo/xml/Person.java @@ -1,16 +1,10 @@ package com.baeldung.jdo.xml; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import javax.jdo.annotations.Element; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.PrimaryKey; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; @PersistenceCapable public class Person { diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/Product.java b/libraries/src/main/java/com/baeldung/jdo/xml/Product.java index 83eed50624..1e46f212cb 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/Product.java +++ b/libraries/src/main/java/com/baeldung/jdo/xml/Product.java @@ -1,9 +1,6 @@ package com.baeldung.jdo.xml; -import javax.jdo.annotations.IdGeneratorStrategy; -import javax.jdo.annotations.PersistenceAware; import javax.jdo.annotations.PersistenceCapable; -import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; @PersistenceCapable diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java index 0033d0786e..988335b7d1 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java @@ -1,6 +1,5 @@ package com.baeldung.commons.collections; -import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.MapUtils; import org.apache.commons.collections4.PredicateUtils; import org.apache.commons.collections4.TransformerUtils; @@ -8,22 +7,15 @@ import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.Collection; import java.util.HashMap; import java.util.Map; -import java.util.Set; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.collection.IsMapWithSize.aMapWithSize; import static org.hamcrest.collection.IsMapWithSize.anEmptyMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; public class MapUtilsTest { diff --git a/libraries/src/test/java/com/baeldung/date/DateDiffUnitTest.java b/libraries/src/test/java/com/baeldung/date/DateDiffUnitTest.java index 14d3f925f5..545009a2a9 100644 --- a/libraries/src/test/java/com/baeldung/date/DateDiffUnitTest.java +++ b/libraries/src/test/java/com/baeldung/date/DateDiffUnitTest.java @@ -5,7 +5,6 @@ import org.junit.Test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Duration; -import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Date; import java.util.Locale; diff --git a/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java b/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java index 232186fedb..9b977358bb 100644 --- a/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java +++ b/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java @@ -3,9 +3,6 @@ package com.baeldung.infinispan.service; import com.baeldung.infinispan.ConfigurationTest; import org.junit.Test; -import java.util.concurrent.Callable; -import java.util.function.Consumer; - import static org.assertj.core.api.Java6Assertions.assertThat; public class HelloWorldServiceUnitTest extends ConfigurationTest { diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java b/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java index e6af244752..b47d3a2e19 100644 --- a/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/jetty/JettyIntegrationTest.java @@ -5,9 +5,7 @@ import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; -import org.junit.After; import org.junit.AfterClass; -import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationTest.java index d0b1cafd71..99ea1aab71 100644 --- a/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationTest.java +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorAsyncInvocationTest.java @@ -5,8 +5,6 @@ import net.engio.mbassy.listener.Handler; import net.engio.mbassy.listener.Invoke; import org.junit.Before; import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicBoolean; diff --git a/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java b/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java index afbebb15c9..9d9a58aee9 100644 --- a/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java +++ b/libraries/src/test/java/com/baeldung/mbassador/MBassadorConfigurationTest.java @@ -6,8 +6,6 @@ import net.engio.mbassy.bus.error.PublicationError; import net.engio.mbassy.listener.Handler; import org.junit.Before; import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.*; diff --git a/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java b/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java index f6183bc79e..429d3f433a 100644 --- a/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java @@ -9,7 +9,6 @@ import javax.validation.Valid; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; -import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; diff --git a/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java b/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java index 1082765c63..a719259328 100644 --- a/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java +++ b/spring-5/src/main/java/com/baeldung/web/reactive/client/WebClientController.java @@ -3,9 +3,7 @@ package com.baeldung.web.reactive.client; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.springframework.http.*; -import org.springframework.http.client.reactive.ClientHttpRequest; import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; From 5fd8e4293e954eb53d510d67e245039443e5af7d Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 4 Mar 2018 17:52:56 +0200 Subject: [PATCH 46/91] cleanup work for tests --- libraries/helloWorld.docx | Bin 76893 -> 76890 bytes ...a => BeanRegistrationIntegrationTest.java} | 2 +- ...Test.java => SecurityIntegrationTest.java} | 18 ++++-------------- ...ssionAttrsApplicationIntegrationTest.java} | 2 +- ...rollerWithScopedProxyIntegrationTest.java} | 2 +- ...WithSessionAttributesIntegrationTest.java} | 2 +- ...java => WebTestClientIntegrationTest.java} | 2 +- ...ava => UserRepositoryIntegrationTest.java} | 2 +- 8 files changed, 10 insertions(+), 20 deletions(-) rename spring-5/src/test/java/com/baeldung/functional/{BeanRegistrationTest.java => BeanRegistrationIntegrationTest.java} (96%) rename spring-5/src/test/java/com/baeldung/security/{SecurityTest.java => SecurityIntegrationTest.java} (65%) rename spring-5/src/test/java/com/baeldung/sessionattrs/{SessionAttrsApplicationTests.java => SessionAttrsApplicationIntegrationTest.java} (85%) rename spring-5/src/test/java/com/baeldung/sessionattrs/{TodoControllerWithScopedProxyTest.java => TodoControllerWithScopedProxyIntegrationTest.java} (95%) rename spring-5/src/test/java/com/baeldung/sessionattrs/{TodoControllerWithSessionAttributesTest.java => TodoControllerWithSessionAttributesIntegrationTest.java} (95%) rename spring-5/src/test/java/com/baeldung/web/client/{WebTestClientTest.java => WebTestClientIntegrationTest.java} (97%) rename spring-boot/src/test/java/org/baeldung/repository/{UserRepositoryTest.java => UserRepositoryIntegrationTest.java} (98%) diff --git a/libraries/helloWorld.docx b/libraries/helloWorld.docx index 28196dc241963b5a6c3a992cc19b883f0e95560a..9dcc7ccfeccd8d3961701210a5458ce63f5779ec 100644 GIT binary patch delta 4413 zcmY*dbyO5i7u}^hWGQJDB$kjaNkOC=l!3w85OlUZH_K1*G0oDh&5?Pm)f%>X-t~q z1S8-P*s9h?;kMV^qmy3ia1?Hfu2@to!@I!|BMR`l@o8Ua^8&RnChDy%nce{@Jvn1W zZPw%tS%)|D)+@V~XJgUCo6ZFJeI2lfn@n@}9FhSkkl8>GF;u#cYa(%14wJj+4L0Z2 z7Fx70TrmXG^%7 z=YRbg$rDpkg87uSK+s5+hZgk-__8^vze7W&4=qUpVV2xCFAEEGYC@Lz#=`O@&$x`~ ztrUY?XC!t)ZEpl(UKP6HvK6puvT{i=E%!4{@G8mS#9tZ<+Ld78T!zHQSv9vnp!rE) z{np`nt9>23$Oi4DafUc0tPJ`eOkJj<>Zv0Y8 zAYw+})CpIZ$Ct0VtC@M?`U>_UFX9EeMzS7pr4k<15D~2%(QGx6On_&JI~<+RPQMm1 zdHj&Knj+i4q|wf_{xqgya5A^o0$cv6kig`EwcUV(^yu@3A>ZqPPuxjTH=WTcx#S1_ zuhIBTwWTD6a5&Q1rd=SC)6uQ>zEBc`7e3bXiPLL2hI1)o4}Vr^eGseLWa0icsDexBh8Hc{|}|H84m-Wmv&Y-B)ZT(Zmx zkkb8X{!>GsKkAePY1X4~Pa5*@po|Z$oSnLY&PdnMO)Ld4#9(jBv64Mnd#R9D7NzGM z(@W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kNOcKcJ!!+sgperzM8 zye%Pl1k+P`UEedY@R&hrla@ud7lo1uF|`W8aM&pSD%K_&Uit~p-syrhU}XWhoNiXb(t-zc#wH)_980d>Y>12dxcC zO7wFbpm$EC&-UILYd41|p_=#m?)d6JnY5Lm+I|v7G~B(L!opO>g!lC*9;ax>1%ZpvC!HoADZj2~)FT z5loFX^LQ4$=F03`SG>(ca7tqM$iyY1nI3);gUt)qwenOYY59yZstMKlkFYA+lN+1; zUXqg&Y1&b&lq2#^%RRdIa7KcRy@`ez`Zmwhn4Fy>NB|(!oT%p^p?or|FiQL65e8Mhyx-d#G%3Gh<7YQVPS7f|t`A=KmDRg74y`u0O}>fx7Wr$a z6puyXe)zefgm5d-dc6^=Ly)x`;d|8Ho|(G6*4A0h>PPS&!dp}D>@pnz1fs(D_XU0z zLD(EY2yQ3%y+TNpV*#)Iv23j1AAc+|8(92roDD399vN+^{FgSThO&VL{)9iXfhobb zsS9ji_P^P`k0cd`9ZUqgKnH<5om?%s-@17_SiR-)a&%Bv0wWND{(pO6sr=85@Ie2R zlHczCfvw!!?4UOP6Rx+V#Opu+1{Dy3K@9&yg8~Ubsrl?+$m>5H&uuv?6#h Date: Sun, 4 Mar 2018 17:53:14 +0200 Subject: [PATCH 47/91] formatting work --- .../components/AttrListener.java | 3 +- .../components/EchoServlet.java | 3 +- .../components/HelloFilter.java | 3 +- .../components/HelloServlet.java | 4 +-- .../MySQLAutoconfiguration.java | 9 ++--- .../ContactInfoValidator.java | 4 +-- .../config/PersistenceConfig.java | 5 +-- ...yBeanNotOfRequiredTypeFailureAnalyzer.java | 8 ++--- .../java/com/baeldung/graphql/AuthorDao.java | 4 +-- .../java/com/baeldung/graphql/Mutation.java | 3 +- .../java/com/baeldung/graphql/PostDao.java | 9 ++--- .../config/MvcConfig.java | 2 +- .../com/baeldung/kong/QueryController.java | 11 +++--- .../configuration/WebMvcConfigure.java | 6 +--- .../servlets/javaee/AnnotationServlet.java | 3 +- .../com/baeldung/toggle/FeaturesAspect.java | 6 ++-- .../java/com/baeldung/toggle/MyFeatures.java | 3 +- .../org/baeldung/boot/config/H2JpaConfig.java | 2 +- .../controller/GenericEntityController.java | 18 +++------- .../converter/GenericBigDecimalConverter.java | 11 +++--- .../converter/StringToEmployeeConverter.java | 1 - .../jsoncomponent/UserCombinedSerializer.java | 3 +- .../jsoncomponent/UserJsonDeserializer.java | 3 +- .../boot/monitor/jmx/MonitoringConfig.java | 3 +- .../org/baeldung/endpoints/MyHealthCheck.java | 8 ++--- .../baeldung/main/SpringBootApplication.java | 2 +- .../baeldung/service/LoginServiceImpl.java | 3 +- .../repository/FooRepositoryImpl.java | 6 ++-- ...otWithServletComponentIntegrationTest.java | 3 +- .../DisplayBeanIntegrationTest.java | 7 ++-- .../java/com/baeldung/intro/AppLiveTest.java | 10 ++---- .../baeldung/kong/KongAdminAPILiveTest.java | 3 +- .../kong/KongLoadBalanceLiveTest.java | 3 +- .../toggle/ToggleIntegrationTest.java | 9 ++--- .../utils/UtilsControllerIntegrationTest.java | 7 ++-- .../MyStompSessionHandlerIntegrationTest.java | 6 ++-- .../SpringBootApplicationIntegrationTest.java | 34 ++++--------------- .../SpringBootMailIntegrationTest.java | 8 ++--- .../DetailsServiceClientIntegrationTest.java | 3 +- .../config/H2TestProfileJPAConfig.java | 2 +- .../CustomConverterIntegrationTest.java | 12 +++---- ...yeeConverterControllerIntegrationTest.java | 6 +--- .../EmployeeControllerIntegrationTest.java | 13 ++----- .../EmployeeRepositoryIntegrationTest.java | 4 +-- ...EmployeeRestControllerIntegrationTest.java | 15 +++----- .../EmployeeServiceImplIntegrationTest.java | 31 ++++++----------- .../ConfigPropertiesIntegrationTest.java | 21 ++++-------- .../UserRepositoryIntegrationTest.java | 6 ++-- 48 files changed, 101 insertions(+), 248 deletions(-) diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java index 95b4a1a191..b1bdc7d781 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java @@ -9,8 +9,7 @@ public class AttrListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { - servletContextEvent.getServletContext() - .setAttribute("servlet-context-attr", "test"); + servletContextEvent.getServletContext().setAttribute("servlet-context-attr", "test"); System.out.println("context init"); } diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java index a2995d1532..d8192c2cb1 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java @@ -16,8 +16,7 @@ public class EchoServlet extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) { try { - Path path = File.createTempFile("echo", "tmp") - .toPath(); + Path path = File.createTempFile("echo", "tmp").toPath(); Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); Files.copy(path, response.getOutputStream()); Files.delete(path); diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java index 650dae9806..146e5ae386 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java @@ -18,8 +18,7 @@ public class HelloFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { - servletResponse.getOutputStream() - .print(filterConfig.getInitParameter("msg")); + servletResponse.getOutputStream().print(filterConfig.getInitParameter("msg")); filterChain.doFilter(servletRequest, servletResponse); } diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java index 3c27b8416f..5269c1bf29 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java @@ -21,9 +21,7 @@ public class HelloServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { try { - response.getOutputStream() - .write(servletConfig.getInitParameter("msg") - .getBytes()); + response.getOutputStream().write(servletConfig.getInitParameter("msg").getBytes()); } catch (IOException e) { e.printStackTrace(); } diff --git a/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java b/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java index 6dd127a8c3..4f4f6fb6af 100644 --- a/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java +++ b/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java @@ -98,13 +98,8 @@ public class MySQLAutoconfiguration { public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate"); - return Arrays.stream(CLASS_NAMES) - .filter(className -> ClassUtils.isPresent(className, context.getClassLoader())) - .map(className -> ConditionOutcome.match(message.found("class") - .items(Style.NORMAL, className))) - .findAny() - .orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes") - .items(Style.NORMAL, Arrays.asList(CLASS_NAMES)))); + return Arrays.stream(CLASS_NAMES).filter(className -> ClassUtils.isPresent(className, context.getClassLoader())).map(className -> ConditionOutcome.match(message.found("class").items(Style.NORMAL, className))).findAny() + .orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES)))); } } diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java index c12c28d00a..0f8300a797 100644 --- a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java +++ b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java @@ -28,9 +28,7 @@ public class ContactInfoValidator implements ConstraintValidator getAuthor(String id) { - return authors.stream() - .filter(author -> id.equals(author.getId())) - .findFirst(); + return authors.stream().filter(author -> id.equals(author.getId())).findFirst(); } } diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java b/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java index 5ccc80dad1..0e16e3c8b7 100644 --- a/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java +++ b/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java @@ -13,8 +13,7 @@ public class Mutation implements GraphQLMutationResolver { public Post writePost(String title, String text, String category, String author) { Post post = new Post(); - post.setId(UUID.randomUUID() - .toString()); + post.setId(UUID.randomUUID().toString()); post.setTitle(title); post.setText(text); post.setCategory(category); diff --git a/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java b/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java index f8d243ee3a..0a755a7cf4 100644 --- a/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java +++ b/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java @@ -11,16 +11,11 @@ public class PostDao { } public List getRecentPosts(int count, int offset) { - return posts.stream() - .skip(offset) - .limit(count) - .collect(Collectors.toList()); + return posts.stream().skip(offset).limit(count).collect(Collectors.toList()); } public List getAuthorPosts(String author) { - return posts.stream() - .filter(post -> author.equals(post.getAuthorId())) - .collect(Collectors.toList()); + return posts.stream().filter(post -> author.equals(post.getAuthorId())).collect(Collectors.toList()); } public void savePost(Post post) { diff --git a/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java b/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java index 478e8d393a..8a0b709e69 100644 --- a/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java +++ b/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java @@ -31,6 +31,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(localeChangeInterceptor()); + registry.addInterceptor(localeChangeInterceptor()); } } diff --git a/spring-boot/src/main/java/com/baeldung/kong/QueryController.java b/spring-boot/src/main/java/com/baeldung/kong/QueryController.java index af63a7e8a1..ec04d0b9ce 100644 --- a/spring-boot/src/main/java/com/baeldung/kong/QueryController.java +++ b/spring-boot/src/main/java/com/baeldung/kong/QueryController.java @@ -15,18 +15,17 @@ public class QueryController { private static int REQUEST_COUNTER = 0; @GetMapping("/reqcount") - public int getReqCount(){ + public int getReqCount() { return REQUEST_COUNTER; } @GetMapping("/{code}") - public String getStockPrice(@PathVariable String code){ + public String getStockPrice(@PathVariable String code) { REQUEST_COUNTER++; - if("BTC".equalsIgnoreCase(code)) + if ("BTC".equalsIgnoreCase(code)) return "10000"; - else return "N/A"; + else + return "N/A"; } - - } diff --git a/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java b/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java index 2d8298338c..8dea814bc7 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java @@ -28,11 +28,7 @@ public class WebMvcConfigure extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**") - .addResourceLocations("/resources/") - .setCachePeriod(3600) - .resourceChain(true) - .addResolver(new PathResourceResolver()); + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); } @Bean diff --git a/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java b/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java index 358ff5af2d..992976ca0e 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java @@ -13,7 +13,6 @@ public class AnnotationServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - request.getRequestDispatcher("/annotationservlet.jsp") - .forward(request, response); + request.getRequestDispatcher("/annotationservlet.jsp").forward(request, response); } } diff --git a/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java b/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java index 9bc643fccc..ed99f65006 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java @@ -14,12 +14,10 @@ public class FeaturesAspect { @Around(value = "@within(featureAssociation) || @annotation(featureAssociation)") public Object checkAspect(ProceedingJoinPoint joinPoint, FeatureAssociation featureAssociation) throws Throwable { - if (featureAssociation.value() - .isActive()) { + if (featureAssociation.value().isActive()) { return joinPoint.proceed(); } else { - LOG.info("Feature " + featureAssociation.value() - .name() + " is not enabled!"); + LOG.info("Feature " + featureAssociation.value().name() + " is not enabled!"); return null; } } diff --git a/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java b/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java index b05ec2bf52..a88ec2166e 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java @@ -17,8 +17,7 @@ public enum MyFeatures implements Feature { EMPLOYEE_MANAGEMENT_FEATURE; public boolean isActive() { - return FeatureContext.getFeatureManager() - .isActive(this); + return FeatureContext.getFeatureManager().isActive(this); } } diff --git a/spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java b/spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java index 4e4b2e06bd..92a6ed7ab0 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java +++ b/spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java @@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration -@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.boot.boottest","org.baeldung.repository" }) +@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.boot.boottest", "org.baeldung.repository" }) @PropertySource("classpath:persistence-generic-entity.properties") @EnableTransactionManagement public class H2JpaConfig { diff --git a/spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java b/spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java index 8b038e0335..817bae8d01 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java +++ b/spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java @@ -39,31 +39,21 @@ public class GenericEntityController { @RequestMapping("/entity/findby/{id}") public GenericEntity findById(@PathVariable Long id) { - return entityList.stream() - .filter(entity -> entity.getId() - .equals(id)) - .findFirst() - .get(); + return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get(); } @GetMapping("/entity/findbydate/{date}") public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) { - return entityList.stream() - .findFirst() - .get(); + return entityList.stream().findFirst().get(); } @GetMapping("/entity/findbymode/{mode}") public GenericEntity findByEnum(@PathVariable("mode") Modes mode) { - return entityList.stream() - .findFirst() - .get(); + return entityList.stream().findFirst().get(); } @GetMapping("/entity/findbyversion") public ResponseEntity findByVersion(@Version String version) { - return version != null ? new ResponseEntity(entityList.stream() - .findFirst() - .get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND); + return version != null ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND); } } diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java b/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java index 7bcbfee45b..f756a25f67 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java +++ b/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java @@ -9,23 +9,20 @@ import java.util.Set; public class GenericBigDecimalConverter implements GenericConverter { @Override - public Set getConvertibleTypes () { + public Set getConvertibleTypes() { - ConvertiblePair[] pairs = new ConvertiblePair[] { - new ConvertiblePair(Number.class, BigDecimal.class), - new ConvertiblePair(String.class, BigDecimal.class)}; + ConvertiblePair[] pairs = new ConvertiblePair[] { new ConvertiblePair(Number.class, BigDecimal.class), new ConvertiblePair(String.class, BigDecimal.class) }; return ImmutableSet.copyOf(pairs); } @Override - public Object convert (Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (sourceType.getType() == BigDecimal.class) { return source; } - if(sourceType.getType() == String.class) { + if (sourceType.getType() == String.class) { String number = (String) source; return new BigDecimal(number); } else { diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java index de9cf3f55a..b07e11e01a 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java +++ b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java @@ -1,6 +1,5 @@ package org.baeldung.boot.converter; - import com.baeldung.toggle.Employee; import org.springframework.core.convert.converter.Converter; diff --git a/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserCombinedSerializer.java b/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserCombinedSerializer.java index 4d3a2cf99e..f4d7505342 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserCombinedSerializer.java +++ b/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserCombinedSerializer.java @@ -36,8 +36,7 @@ public class UserCombinedSerializer { public static class UserJsonDeserializer extends JsonDeserializer { @Override public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { - TreeNode treeNode = jsonParser.getCodec() - .readTree(jsonParser); + TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser); TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor"); return new User(Color.web(favoriteColor.asText())); } diff --git a/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializer.java b/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializer.java index ad82ca06c0..f7bd822c8a 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializer.java +++ b/spring-boot/src/main/java/org/baeldung/boot/jsoncomponent/UserJsonDeserializer.java @@ -15,8 +15,7 @@ import java.io.IOException; public class UserJsonDeserializer extends JsonDeserializer { @Override public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { - TreeNode treeNode = jsonParser.getCodec() - .readTree(jsonParser); + TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser); TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor"); return new User(Color.web(favoriteColor.asText())); } diff --git a/spring-boot/src/main/java/org/baeldung/boot/monitor/jmx/MonitoringConfig.java b/spring-boot/src/main/java/org/baeldung/boot/monitor/jmx/MonitoringConfig.java index d2e8fc228f..28c6ac5953 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/monitor/jmx/MonitoringConfig.java +++ b/spring-boot/src/main/java/org/baeldung/boot/monitor/jmx/MonitoringConfig.java @@ -14,8 +14,7 @@ public class MonitoringConfig { @Bean public JmxReporter jmxReporter() { - JmxReporter reporter = JmxReporter.forRegistry(registry) - .build(); + JmxReporter reporter = JmxReporter.forRegistry(registry).build(); reporter.start(); return reporter; } diff --git a/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java b/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java index 68fbffda6e..1a175aed48 100644 --- a/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java +++ b/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java @@ -10,13 +10,9 @@ public class MyHealthCheck implements HealthIndicator { public Health health() { int errorCode = check(); // perform some specific health check if (errorCode != 0) { - return Health.down() - .withDetail("Error Code", errorCode) - .withDetail("Description", "You custom MyHealthCheck endpoint is down") - .build(); + return Health.down().withDetail("Error Code", errorCode).withDetail("Description", "You custom MyHealthCheck endpoint is down").build(); } - return Health.up() - .build(); + return Health.up().build(); } public int check() { diff --git a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java index f9bdb67a10..5cc697be65 100644 --- a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java +++ b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java @@ -21,7 +21,7 @@ import java.util.concurrent.Executors; @RestController @EnableAutoConfiguration(exclude = MySQLAutoconfiguration.class) -@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources","org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.boot.config"}) +@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.boot.config" }) public class SpringBootApplication { private static ApplicationContext applicationContext; diff --git a/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java b/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java index 6d89f7f695..ed0090f8e4 100644 --- a/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java +++ b/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java @@ -16,8 +16,7 @@ public class LoginServiceImpl implements LoginService { public boolean login(String userName, char[] password) { boolean success; - if (userName.equals("admin") && "secret".toCharArray() - .equals(password)) { + if (userName.equals("admin") && "secret".toCharArray().equals(password)) { counterService.increment("counter.login.success"); success = true; } else { diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java index 11df542d05..52407a2117 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java +++ b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java @@ -14,14 +14,12 @@ public class FooRepositoryImpl implements FooRepository { @Override public void save(Foo foo) { - sessionFactory.getCurrentSession() - .saveOrUpdate(foo); + sessionFactory.getCurrentSession().saveOrUpdate(foo); } @Override public Foo get(Integer id) { - return sessionFactory.getCurrentSession() - .get(Foo.class, id); + return sessionFactory.getCurrentSession().get(Foo.class, id); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index b2b14f766e..6d958ea637 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -40,8 +40,7 @@ public class SpringBootWithServletComponentIntegrationTest { FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); assertNotNull(filterRegistration); - assertTrue(filterRegistration.getServletNameMappings() - .contains("echo servlet")); + assertTrue(filterRegistration.getServletNameMappings().contains("echo servlet")); } @Autowired diff --git a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java index 8bd9c20c5e..afe7f8df31 100644 --- a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java @@ -60,11 +60,8 @@ public class DisplayBeanIntegrationTest { @SuppressWarnings("rawtypes") ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class); - List> allBeans = (List) ((Map) entity.getBody() - .get(0)).get("beans"); - List beanNamesList = allBeans.stream() - .map(x -> (String) x.get("bean")) - .collect(Collectors.toList()); + List> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans"); + List beanNamesList = allBeans.stream().map(x -> (String) x.get("bean")).collect(Collectors.toList()); assertThat(beanNamesList, hasItem("fooController")); assertThat(beanNamesList, hasItem("fooService")); diff --git a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java index 4856c17c7d..2c0152b97f 100644 --- a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -26,18 +26,12 @@ public class AppLiveTest { @Test public void getIndex() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("Index Page"))); + mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Index Page"))); } @Test public void getLocal() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/local") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("/local"))); + mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("/local"))); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java b/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java index f399806a65..5cf19dd1db 100644 --- a/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java @@ -39,7 +39,8 @@ public class KongAdminAPILiveTest { System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); } - @Autowired TestRestTemplate restTemplate; + @Autowired + TestRestTemplate restTemplate; @Test public void givenEndpoint_whenQueryStockPrice_thenPriceCorrect() { diff --git a/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java b/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java index f8090e4c86..abc7151720 100644 --- a/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java @@ -30,7 +30,8 @@ public class KongLoadBalanceLiveTest { System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); } - @Autowired TestRestTemplate restTemplate; + @Autowired + TestRestTemplate restTemplate; @Test public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception { diff --git a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java index 5b70fa3cbe..ca6230e8f5 100644 --- a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java @@ -35,8 +35,7 @@ public class ToggleIntegrationTest { @Before public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) - .build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test @@ -46,8 +45,7 @@ public class ToggleIntegrationTest { System.setProperty("employee.feature", "false"); - mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")) - .andExpect(status().is(200)); + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); emp = employeeRepository.findOne(1L); assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); @@ -60,8 +58,7 @@ public class ToggleIntegrationTest { System.setProperty("employee.feature", "true"); - mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")) - .andExpect(status().is(200)); + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); emp = employeeRepository.findOne(1L); assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5); diff --git a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java index 5a80e13791..080f660c40 100644 --- a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java @@ -21,17 +21,14 @@ public class UtilsControllerIntegrationTest { @Before public void setup() { MockitoAnnotations.initMocks(this); - this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController) - .build(); + this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController).build(); } @Test public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception { String param = "testparam"; - this.mockMvc.perform(post("/setParam").param("param", param) - .sessionAttr("parameter", param)) - .andExpect(status().isOk()); + this.mockMvc.perform(post("/setParam").param("param", param).sessionAttr("parameter", param)).andExpect(status().isOk()); } } diff --git a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java index 4dc4793ce2..bb1b5e254e 100644 --- a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java @@ -14,9 +14,7 @@ public class MyStompSessionHandlerIntegrationTest { StompHeaders mockHeader = Mockito.mock(StompHeaders.class); MyStompSessionHandler sessionHandler = new MyStompSessionHandler(); sessionHandler.afterConnected(mockSession, mockHeader); - Mockito.verify(mockSession) - .subscribe("/topic/messages", sessionHandler); - Mockito.verify(mockSession) - .send(Mockito.anyString(), Mockito.anyObject()); + Mockito.verify(mockSession).subscribe("/topic/messages", sessionHandler); + Mockito.verify(mockSession).send(Mockito.anyString(), Mockito.anyObject()); } } diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java index 823625f811..5627543b62 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java @@ -34,56 +34,36 @@ public class SpringBootApplicationIntegrationTest { @Before public void setupMockMvc() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) - .build(); + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")) - .andExpect(MockMvcResultMatchers.status() - .isOk()) - .andExpect(MockMvcResultMatchers.content() - .contentType(contentType)) - .andExpect(jsonPath("$", hasSize(4))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4))); } @Test public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")) - .andExpect(MockMvcResultMatchers.status() - .isOk()) - .andExpect(MockMvcResultMatchers.content() - .contentType(contentType)) - .andExpect(jsonPath("$.id", equalTo(1))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); } @Test public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())) - .andExpect(MockMvcResultMatchers.status() - .isOk()) - .andExpect(MockMvcResultMatchers.content() - .contentType(contentType)) - .andExpect(jsonPath("$.id", equalTo(1))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$.id", equalTo(1))); } @Test public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion") - .header("Version", "1.0.0")) - .andExpect(MockMvcResultMatchers.status() - .isOk()) - .andExpect(MockMvcResultMatchers.content() - .contentType(contentType)) - .andExpect(jsonPath("$.id", equalTo(1))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java index 5dd6ab8e17..a6a84184fa 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java @@ -61,15 +61,11 @@ public class SpringBootMailIntegrationTest { } private String getMessage(WiserMessage wiserMessage) throws MessagingException, IOException { - return wiserMessage.getMimeMessage() - .getContent() - .toString() - .trim(); + return wiserMessage.getMimeMessage().getContent().toString().trim(); } private String getSubject(WiserMessage wiserMessage) throws MessagingException { - return wiserMessage.getMimeMessage() - .getSubject(); + return wiserMessage.getMimeMessage().getSubject(); } private SimpleMailMessage composeEmailMessage() { diff --git a/spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java index 6f1cc66979..37fc202e8a 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java @@ -33,8 +33,7 @@ public class DetailsServiceClientIntegrationTest { @Before public void setUp() throws Exception { String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john")); - this.server.expect(requestTo("/john/details")) - .andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); + this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); } @Test diff --git a/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java b/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java index 499a755ae7..d0b92a7a93 100644 --- a/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java +++ b/spring-boot/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java @@ -41,7 +41,7 @@ public class H2TestProfileJPAConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.domain", "org.baeldung.boot.boottest","org.baeldung.model" }); + em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.domain", "org.baeldung.boot.boottest", "org.baeldung.model" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java index fc94fe7d7d..bd1ae2c8fa 100644 --- a/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java @@ -33,8 +33,7 @@ public class CustomConverterIntegrationTest { public void whenConvertStringToEmployee_thenSuccess() { Employee employee = conversionService.convert("1,50000.00", Employee.class); Employee actualEmployee = new Employee(1, 50000.00); - assertThat(conversionService.convert("1,50000.00", Employee.class)) - .isEqualToComparingFieldByField(actualEmployee); + assertThat(conversionService.convert("1,50000.00", Employee.class)).isEqualToComparingFieldByField(actualEmployee); } @Test @@ -44,11 +43,8 @@ public class CustomConverterIntegrationTest { @Test public void whenConvertingToBigDecimalUsingGenericConverter_thenSuccess() { - assertThat(conversionService.convert(Integer.valueOf(11), BigDecimal.class)) - .isEqualTo(BigDecimal.valueOf(11.00).setScale(2, BigDecimal.ROUND_HALF_EVEN)); - assertThat(conversionService.convert(Double.valueOf(25.23), BigDecimal.class)) - .isEqualByComparingTo(BigDecimal.valueOf(Double.valueOf(25.23))); - assertThat(conversionService.convert("2.32", BigDecimal.class)) - .isEqualTo(BigDecimal.valueOf(2.32)); + assertThat(conversionService.convert(Integer.valueOf(11), BigDecimal.class)).isEqualTo(BigDecimal.valueOf(11.00).setScale(2, BigDecimal.ROUND_HALF_EVEN)); + assertThat(conversionService.convert(Double.valueOf(25.23), BigDecimal.class)).isEqualByComparingTo(BigDecimal.valueOf(Double.valueOf(25.23))); + assertThat(conversionService.convert("2.32", BigDecimal.class)).isEqualTo(BigDecimal.valueOf(2.32)); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java index 3310eb9984..466d81e658 100644 --- a/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java @@ -26,10 +26,6 @@ public class StringToEmployeeConverterControllerIntegrationTest { @Test public void getStringToEmployeeTest() throws Exception { - mockMvc.perform(get("/string-to-employee?employee=1,2000")) - .andDo(print()) - .andExpect(jsonPath("$.id", is(1))) - .andExpect(jsonPath("$.salary", is(2000.0))) - .andExpect(status().isOk()); + mockMvc.perform(get("/string-to-employee?employee=1,2000")).andDo(print()).andExpect(jsonPath("$.id", is(1))).andExpect(jsonPath("$.salary", is(2000.0))).andExpect(status().isOk()); } } diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java index f06c144908..640a8b322a 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java @@ -47,10 +47,7 @@ public class EmployeeControllerIntegrationTest { Employee alex = new Employee("alex"); given(service.save(Mockito.anyObject())).willReturn(alex); - mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON) - .content(JsonUtil.toJson(alex))) - .andExpect(status().isCreated()) - .andExpect(jsonPath("$.name", is("alex"))); + mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(alex))).andExpect(status().isCreated()).andExpect(jsonPath("$.name", is("alex"))); verify(service, VerificationModeFactory.times(1)).save(Mockito.anyObject()); reset(service); } @@ -65,12 +62,8 @@ public class EmployeeControllerIntegrationTest { given(service.getAllEmployees()).willReturn(allEmployees); - mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$", hasSize(3))) - .andExpect(jsonPath("$[0].name", is(alex.getName()))) - .andExpect(jsonPath("$[1].name", is(john.getName()))) - .andExpect(jsonPath("$[2].name", is(bob.getName()))); + mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(3))).andExpect(jsonPath("$[0].name", is(alex.getName()))).andExpect(jsonPath("$[1].name", is(john.getName()))) + .andExpect(jsonPath("$[2].name", is(bob.getName()))); verify(service, VerificationModeFactory.times(1)).getAllEmployees(); reset(service); } diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java index 221beda900..f581052596 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java @@ -66,8 +66,6 @@ public class EmployeeRepositoryIntegrationTest { List allEmployees = employeeRepository.findAll(); - assertThat(allEmployees).hasSize(3) - .extracting(Employee::getName) - .containsOnly(alex.getName(), ron.getName(), bob.getName()); + assertThat(allEmployees).hasSize(3).extracting(Employee::getName).containsOnly(alex.getName(), ron.getName(), bob.getName()); } } diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java index e6f2203476..da9df4db7d 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java @@ -50,12 +50,10 @@ public class EmployeeRestControllerIntegrationTest { @Test public void whenValidInput_thenCreateEmployee() throws IOException, Exception { Employee bob = new Employee("bob"); - mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON) - .content(JsonUtil.toJson(bob))); + mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(bob))); List found = repository.findAll(); - assertThat(found).extracting(Employee::getName) - .containsOnly("bob"); + assertThat(found).extracting(Employee::getName).containsOnly("bob"); } @Test @@ -64,13 +62,8 @@ public class EmployeeRestControllerIntegrationTest { createTestEmployee("bob"); createTestEmployee("alex"); - mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2)))) - .andExpect(jsonPath("$[0].name", is("bob"))) - .andExpect(jsonPath("$[1].name", is("alex"))); + mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2)))) + .andExpect(jsonPath("$[0].name", is("bob"))).andExpect(jsonPath("$[1].name", is("alex"))); } private void createTestEmployee(String name) { diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java index 58ef3d4081..f004536c49 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java @@ -47,18 +47,12 @@ public class EmployeeServiceImplIntegrationTest { List allEmployees = Arrays.asList(john, bob, alex); - Mockito.when(employeeRepository.findByName(john.getName())) - .thenReturn(john); - Mockito.when(employeeRepository.findByName(alex.getName())) - .thenReturn(alex); - Mockito.when(employeeRepository.findByName("wrong_name")) - .thenReturn(null); - Mockito.when(employeeRepository.findById(john.getId())) - .thenReturn(john); - Mockito.when(employeeRepository.findAll()) - .thenReturn(allEmployees); - Mockito.when(employeeRepository.findById(-99L)) - .thenReturn(null); + Mockito.when(employeeRepository.findByName(john.getName())).thenReturn(john); + Mockito.when(employeeRepository.findByName(alex.getName())).thenReturn(alex); + Mockito.when(employeeRepository.findByName("wrong_name")).thenReturn(null); + Mockito.when(employeeRepository.findById(john.getId())).thenReturn(john); + Mockito.when(employeeRepository.findAll()).thenReturn(allEmployees); + Mockito.when(employeeRepository.findById(-99L)).thenReturn(null); } @Test @@ -116,26 +110,21 @@ public class EmployeeServiceImplIntegrationTest { List allEmployees = employeeService.getAllEmployees(); verifyFindAllEmployeesIsCalledOnce(); - assertThat(allEmployees).hasSize(3) - .extracting(Employee::getName) - .contains(alex.getName(), john.getName(), bob.getName()); + assertThat(allEmployees).hasSize(3).extracting(Employee::getName).contains(alex.getName(), john.getName(), bob.getName()); } private void verifyFindByNameIsCalledOnce(String name) { - Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findByName(name); + Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findByName(name); Mockito.reset(employeeRepository); } private void verifyFindByIdIsCalledOnce() { - Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findById(Mockito.anyLong()); + Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findById(Mockito.anyLong()); Mockito.reset(employeeRepository); } private void verifyFindAllEmployeesIsCalledOnce() { - Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findAll(); + Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findAll(); Mockito.reset(employeeRepository); } } diff --git a/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java index ffd5bf55d6..3f3b558db9 100644 --- a/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java @@ -23,30 +23,21 @@ public class ConfigPropertiesIntegrationTest { @Test public void whenListPropertyQueriedthenReturnsProperty() throws Exception { - Assert.assertTrue("Couldn't bind list property!", properties.getDefaultRecipients() - .size() == 2); - Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", properties.getDefaultRecipients() - .size() == 2); + Assert.assertTrue("Couldn't bind list property!", properties.getDefaultRecipients().size() == 2); + Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", properties.getDefaultRecipients().size() == 2); } @Test public void whenMapPropertyQueriedthenReturnsProperty() throws Exception { Assert.assertTrue("Couldn't bind map property!", properties.getAdditionalHeaders() != null); - Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", properties.getAdditionalHeaders() - .size() == 3); + Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", properties.getAdditionalHeaders().size() == 3); } @Test public void whenObjectPropertyQueriedthenReturnsProperty() throws Exception { Assert.assertTrue("Couldn't bind map property!", properties.getCredentials() != null); - Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials() - .getAuthMethod() - .equals("SHA1")); - Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials() - .getUsername() - .equals("john")); - Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials() - .getPassword() - .equals("password")); + Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getAuthMethod().equals("SHA1")); + Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getUsername().equals("john")); + Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getPassword().equals("password")); } } diff --git a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java index 6dfcb78327..2b61aa6252 100644 --- a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java @@ -47,8 +47,7 @@ public class UserRepositoryIntegrationTest { Optional foundUser = userRepository.findOneByName(USER_NAME_ADAM); assertThat(foundUser.isPresent(), equalTo(true)); - assertThat(foundUser.get() - .getName(), equalTo(USER_NAME_ADAM)); + assertThat(foundUser.get().getName(), equalTo(USER_NAME_ADAM)); } @Test @@ -84,8 +83,7 @@ public class UserRepositoryIntegrationTest { CompletableFuture userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS); - assertThat(userByStatus.get() - .getName(), equalTo(USER_NAME_ADAM)); + assertThat(userByStatus.get().getName(), equalTo(USER_NAME_ADAM)); } From 698e78150cb1fd73d411cdc759b22e173e4a2c23 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 4 Mar 2018 18:05:37 +0200 Subject: [PATCH 48/91] testing cleanup --- libraries/helloWorld.docx | Bin 76890 -> 76885 bytes libraries/pom.xml | 266 +++++++++--------- ... => HelloWorldServiceIntegrationTest.java} | 6 +- ... TransactionalServiceIntegrationTest.java} | 2 +- ...ava => EntryProcessorIntegrationTest.java} | 2 +- ...derClassDirtiesContextIntegrationTest.java | 6 +- ...=> ProgrammaticTomcatIntegrationTest.java} | 2 +- 7 files changed, 139 insertions(+), 145 deletions(-) rename libraries/src/test/java/com/baeldung/infinispan/service/{HelloWorldServiceUnitTest.java => HelloWorldServiceIntegrationTest.java} (96%) rename libraries/src/test/java/com/baeldung/infinispan/service/{TransactionalServiceUnitTest.java => TransactionalServiceIntegrationTest.java} (90%) rename libraries/src/test/java/com/baeldung/jcache/{EntryProcessorTest.java => EntryProcessorIntegrationTest.java} (96%) rename libraries/src/test/java/com/baeldung/tomcat/{ProgrammaticTomcatTest.java => ProgrammaticTomcatIntegrationTest.java} (97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X4dWhnOY?CG0)k1%Ouov#pOke zX1mpSw>#pfQ+qB$0=)cnXvzZWWqKG~+k6>Dy~aY36(JLjp-_g_-_6E0Z^h!)`v|J7 zNaGMQGE4hS8v|b7jxSl-kn*qhtY#6Y4{vcuMVEPgZ)2lbn_gvgGT$+nUFxz!Spi6o z8p1}m(wqd}a=%oR7|(4sv(|Wf0FcBuV`E9l@ufv{K&$%dWj?8nA27)U3tPkcKn%E- z2E>QlI+%nS^}*DNvpzTxLw(hxKGCvbGAV!+2f)@pr3;%i zU&DJOq(4*x>vMRqvZK6jU#pva^I=I!-nBxGlxxN(5SNUj#zx{@iJ>{yAD?N=yH%L8 zTjkPP6uA-Q6_^C|?6z#1j6^;Y8#>j`F)u)Zn~w#5qqZn+hL9G6v?OZJ&zllAXs~X~ zW0YH;7THF00EaXV;*K;kucm9Xyf2s4Hh@!jPU)InjM+=y>C~B)$B7-KKD2C%##ivHX1Xqb2)P`lNc(eyXebF@mXsCQNRBUWqD-;ixv(|Z@}^q_}LL$cxI z?j;{+mPRqQl63|54Trze#wZxc4P3S?x<%i|mC!P@S-&_bR)A&M>VG&jT zL>|fc^?cquIX;r_9#zJHScPvj--$>tJZxbDp3G3VSqHBC2?#b|%~p(C`P78g2vA?};^eP@UepkTA%BG*`-Kzbs?a9e!s_osh zR#p2073&TIr3N3jb`pD&rJ&4F@270FpfGZ!Ho6-Lfy<;qM)htNb-jda=E3M1OBflm z%O?tD(8!UxzqUw^+*4NBa1<+!%XRIurEM->ifCodjB%saB`BJSDrwJapIAe8xFJG$f`q}}WGa48CNOImEXYylJdhVKr4MyYBFMGQCzZwq1+uXIE%)y`QT - + + 4.0.0 + libraries + libraries + parent-modules com.baeldung 1.0.0-SNAPSHOT - 4.0.0 - libraries - libraries - - - - org.apache.maven.plugins - maven-dependency-plugin - - - org.apache.felix - maven-bundle-plugin - 3.3.0 - maven-plugin - - - true - - - maven-failsafe-plugin - 2.20 - - - chromedriver - - - - - net.serenity-bdd.maven.plugins - serenity-maven-plugin - ${serenity.plugin.version} - - - serenity-reports - post-integration-test - - aggregate - - - - - - - org.datanucleus - datanucleus-maven-plugin - 5.0.2 - - JDO - ${basedir}/datanucleus.properties - ${basedir}/log4j.properties - true - false - - - - - process-classes - - enhance - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 3.0.2 - - - **/log4j.properties - - - - com.baeldung.neuroph.NeurophXOR - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.18.1 - - - test - test - - test - - - - test/java/com/baeldung/neuroph/XORTest.java - - - - - - - - maven-compiler-plugin - 3.7.0 - - 1.8 - 1.8 - - - - + - + org.asynchttpclient async-http-client @@ -200,11 +95,11 @@ jetty-servlet ${jetty.version} - - org.eclipse.jetty - jetty-webapp - ${jetty.version} - + + org.eclipse.jetty + jetty-webapp + ${jetty.version} + rome rome @@ -640,14 +535,14 @@ ${googleclient.version} - com.google.http-client - google-http-client-jackson2 - ${googleclient.version} + com.google.http-client + google-http-client-jackson2 + ${googleclient.version} - com.google.http-client - google-http-client-gson - ${googleclient.version} + com.google.http-client + google-http-client-gson + ${googleclient.version} org.infinispan @@ -655,7 +550,7 @@ ${infinispan.version} - + com.github.docker-java docker-java @@ -680,23 +575,23 @@ jersey-client 1.19.4 - + - com.google.api-client - google-api-client - ${google-api.version} + com.google.api-client + google-api-client + ${google-api.version} - com.google.oauth-client - google-oauth-client-jetty - ${google-api.version} + com.google.oauth-client + google-oauth-client-jetty + ${google-api.version} - com.google.apis - google-api-services-sheets - ${google-sheets.version} + com.google.apis + google-api-services-sheets + ${google-sheets.version} org.apache.kafka @@ -753,6 +648,108 @@ https://repository.apache.org/content/groups/staging + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + org.apache.felix + maven-bundle-plugin + 3.3.0 + maven-plugin + + + true + + + maven-failsafe-plugin + 2.20 + + + chromedriver + + + + + net.serenity-bdd.maven.plugins + serenity-maven-plugin + ${serenity.plugin.version} + + + serenity-reports + post-integration-test + + aggregate + + + + + + + org.datanucleus + datanucleus-maven-plugin + 5.0.2 + + JDO + ${basedir}/datanucleus.properties + ${basedir}/log4j.properties + true + false + + + + + process-classes + + enhance + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.0.2 + + + **/log4j.properties + + + + com.baeldung.neuroph.NeurophXOR + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.18.1 + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + + 1.23.0 0.1.0 @@ -818,4 +815,5 @@ 2.2.0 9.1.5.Final + diff --git a/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java b/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceIntegrationTest.java similarity index 96% rename from libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java rename to libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceIntegrationTest.java index 9b977358bb..0a2ace9ca0 100644 --- a/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceUnitTest.java +++ b/libraries/src/test/java/com/baeldung/infinispan/service/HelloWorldServiceIntegrationTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import static org.assertj.core.api.Java6Assertions.assertThat; -public class HelloWorldServiceUnitTest extends ConfigurationTest { +public class HelloWorldServiceIntegrationTest extends ConfigurationTest { @Test public void whenGetIsCalledTwoTimes_thenTheSecondShouldHitTheCache() { @@ -23,7 +23,6 @@ public class HelloWorldServiceUnitTest extends ConfigurationTest { @Test public void whenGetIsCalledTwoTimesSparsely_thenNeitherShouldHitTheCache() throws InterruptedException { - assertThat(timeThis(() -> helloWorldService.findExpiringHelloWorld())).isGreaterThanOrEqualTo(1000); Thread.sleep(1100); @@ -33,7 +32,6 @@ public class HelloWorldServiceUnitTest extends ConfigurationTest { @Test public void givenOneEntryIsConfigured_whenTwoAreAdded_thenFirstShouldntBeAvailable() { - assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); assertThat(timeThis(() -> helloWorldService.findEvictingHelloWorld("key 2"))).isGreaterThanOrEqualTo(1000); @@ -43,13 +41,11 @@ public class HelloWorldServiceUnitTest extends ConfigurationTest { @Test public void givenOneEntryIsConfigured_whenTwoAreAdded_thenTheFirstShouldBeAvailable() { - assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))).isGreaterThanOrEqualTo(1000); assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 2"))).isGreaterThanOrEqualTo(1000); assertThat(timeThis(() -> helloWorldService.findPassivatingHelloWorld("key 1"))).isLessThan(100); - } } diff --git a/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceUnitTest.java b/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceIntegrationTest.java similarity index 90% rename from libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceUnitTest.java rename to libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceIntegrationTest.java index 49681dd893..ace99eef36 100644 --- a/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceUnitTest.java +++ b/libraries/src/test/java/com/baeldung/infinispan/service/TransactionalServiceIntegrationTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import static org.assertj.core.api.Java6Assertions.assertThat; -public class TransactionalServiceUnitTest extends ConfigurationTest { +public class TransactionalServiceIntegrationTest extends ConfigurationTest { @Test public void whenLockingAnEntry_thenItShouldBeInaccessible() throws InterruptedException { diff --git a/libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java b/libraries/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java similarity index 96% rename from libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java rename to libraries/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java index ab35d23768..61c98d0126 100644 --- a/libraries/src/test/java/com/baeldung/jcache/EntryProcessorTest.java +++ b/libraries/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java @@ -12,7 +12,7 @@ import javax.cache.spi.CachingProvider; import static org.junit.Assert.assertEquals; -public class EntryProcessorTest { +public class EntryProcessorIntegrationTest { private static final String CACHE_NAME = "MyCache"; diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderClassDirtiesContextIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderClassDirtiesContextIntegrationTest.java index 7eb658ca23..07b60df264 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderClassDirtiesContextIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderClassDirtiesContextIntegrationTest.java @@ -15,7 +15,7 @@ import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt; import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS; @RunWith(Suite.class) -@Suite.SuiteClasses({ AdderClassDirtiesContextIntegrationTest.DirtiesContextTest.class, AdderClassDirtiesContextIntegrationTest.AnotherDirtiesContextTest.class }) +@Suite.SuiteClasses({ AdderClassDirtiesContextIntegrationTest.DirtiesContextIntegrationTest.class, AdderClassDirtiesContextIntegrationTest.AnotherDirtiesContextIntegrationTest.class }) public class AdderClassDirtiesContextIntegrationTest { @RunWith(SerenityRunner.class) @@ -46,7 +46,7 @@ public class AdderClassDirtiesContextIntegrationTest { } @DirtiesContext(classMode = AFTER_CLASS) - public static class AnotherDirtiesContextTest extends Base { + public static class AnotherDirtiesContextIntegrationTest extends Base { @Test public void givenNumber_whenAdd_thenSumWrong() { @@ -58,7 +58,7 @@ public class AdderClassDirtiesContextIntegrationTest { } @DirtiesContext(classMode = AFTER_CLASS) - public static class DirtiesContextTest extends Base { + public static class DirtiesContextIntegrationTest extends Base { @Test public void givenNumber_whenAdd_thenSumWrong() { diff --git a/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatTest.java b/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java similarity index 97% rename from libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatTest.java rename to libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java index 6ce11d1895..9224561341 100644 --- a/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatTest.java +++ b/libraries/src/test/java/com/baeldung/tomcat/ProgrammaticTomcatIntegrationTest.java @@ -20,7 +20,7 @@ import static org.junit.Assert.assertNotNull; * Created by adi on 1/14/18. */ @RunWith(BlockJUnit4ClassRunner.class) -public class ProgrammaticTomcatTest { +public class ProgrammaticTomcatIntegrationTest { private ProgrammaticTomcat tomcat = new ProgrammaticTomcat(); From b97310a15b72f6b13ebd96bed2adb2e205eb4f35 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 4 Mar 2018 18:06:53 +0200 Subject: [PATCH 49/91] minior rename --- libraries/helloWorld.docx | Bin 76885 -> 76893 bytes ...dUtilsTest.java => WordUtilsUnitTest.java} | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename libraries/src/test/java/com/baeldung/text/{WordUtilsTest.java => WordUtilsUnitTest.java} (94%) diff --git a/libraries/helloWorld.docx b/libraries/helloWorld.docx index 23c8b2c7376ee7007a79c39c5fc94b7082adcc00..12eba0a6c80c422be6a174dc2fcf7ae242f1ad2c 100644 GIT binary patch delta 4156 zcmY*cWmuHa)@2AuksRsH8A@_!hDK@#K|(@0B?N|i=|*CtVHk&&kOt{gX%s;kR9Xb2 zL6oca`+j)OpY^Q0*R#+0vE%HSIsD~0d{Trq9zG2Y5fKqiYdxtO2-Mmb0OI-ss9H)o zR1+=(C=)e_%LF(SwtQK}ee^L9fgB4d$bAAUS^svYDq30_D^44-d&NuriJd7a{s_7I z`}BI};)7okTuxcXOVsa^Y6q+5v)XAkDr7o^CzH~ejAr@%5*a%T8~qY|ITd;pjDSdSMKU=_(1K$>GumYg%r#{-zHwnHhDdph%;HxZy z-q~;2b*NNoLS}nRnvCL$I=(<6l$cB@Bu68eIM|>%5dR^fm}~3G`lYh^YFZLN6nAmc zd}s{zvs5!7Bl1W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?dxmaxxUY~uS=X8etqHdI7 zbopY^>>*iP(Q3msT?W>UmAyMdWc;1z`ZN2^v(Cpq5JB|vDR6A&lsLKifaI$=R!j{~ zgGfb-U@_b|7BNMp*oL1$E8S-u{v@E4N2(?|&rzeUsnnvkee$us3Oi>0*QNB-pRii@ zUaNJ&1GU;5hfmimdvVA3DA`jR)j7)<&Quv}qn2;E9Ce{@dDmZ~P3f8y#m*W-f3FaL zr1Y8IK7HOFwqV?uuX#zBxgB!LOL&)oVdOB?@j>3g8C2~fCJV_;`SJAM{+%}#;B4MG zaNTsb!424ywQ`)@0AOY|kmr!dgS-2d3c^2AOfeV42LM(c|6hx}|D@2Tj#7{!K6_(? z$&trlZ(>5A@0(0sXPHi$P9J%YrGE`W_T=GI{3>lCaLR{A1HviWI5(44gSH+29{&Dh ziePEoh8S$5N9*={ zv+7cF=sD8JsUW;1{+?wQIG?{c%HGD0`y&ycP=*{Nk7zkNEKXodYC%@v&a1>{Y*4sg zFF6qLx?XR_tE~#E$(@en!Uo(>j1B|sOu?o{4@`8tO_taN6JyFp))^@rhfgwWIVJlidFh+u6;N0J01M&& zC2vF=b#ojwu!9PSLTmB>H|~L-7r1Z_AU>edKO`SengEsLr1S3s6CKM3l)PuV`G71y z67&im5W@D);(xCO8Q{M|8qEU%vi`fnzehmpLx40u4B8n2WM}_JYQ7B>^P~a-im8DB zuKy|lLDZ=^)L`@o1W0^uISaYBlt5qH>;AQT-C!@3eINh#ev<#6jsY#s59Go-;|1Q+ F{{w-A$fW=P diff --git a/libraries/src/test/java/com/baeldung/text/WordUtilsTest.java b/libraries/src/test/java/com/baeldung/text/WordUtilsUnitTest.java similarity index 94% rename from libraries/src/test/java/com/baeldung/text/WordUtilsTest.java rename to libraries/src/test/java/com/baeldung/text/WordUtilsUnitTest.java index fafba2fbb5..23712a2a3d 100644 --- a/libraries/src/test/java/com/baeldung/text/WordUtilsTest.java +++ b/libraries/src/test/java/com/baeldung/text/WordUtilsUnitTest.java @@ -4,7 +4,7 @@ import org.apache.commons.text.WordUtils; import org.junit.Assert; import org.junit.Test; -public class WordUtilsTest { +public class WordUtilsUnitTest { @Test public void whenCapitalized_thenCorrect() { From 2028662cd3e39b2d66d3cc17ac50727afdc19af6 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 4 Mar 2018 18:23:38 +0200 Subject: [PATCH 50/91] cleanup work --- .../{CourseServiceTest.java => CourseServiceUnitTest.java} | 2 +- .../src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java | 2 ++ .../retrofit/rx/{GitHubRxApiTest.java => GitHubRxLiveTest.java} | 2 +- .../spring/{AdderTest.java => AdderIntegrationTest.java} | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) rename libraries/src/test/java/com/baeldung/commons/beanutils/{CourseServiceTest.java => CourseServiceUnitTest.java} (98%) rename libraries/src/test/java/com/baeldung/retrofit/rx/{GitHubRxApiTest.java => GitHubRxLiveTest.java} (97%) rename libraries/src/test/java/com/baeldung/serenity/spring/{AdderTest.java => AdderIntegrationTest.java} (90%) diff --git a/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java b/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java similarity index 98% rename from libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java rename to libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java index fd09f4d9f6..833d91b2c4 100644 --- a/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java +++ b/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java @@ -7,7 +7,7 @@ import java.util.List; import org.junit.Assert; import org.junit.Test; -public class CourseServiceTest { +public class CourseServiceUnitTest { @Test public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { diff --git a/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java index 1acbf00e3c..d3abbe2e7e 100644 --- a/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java +++ b/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java @@ -6,6 +6,7 @@ import com.github.dockerjava.api.model.Network; import com.github.dockerjava.api.model.Network.Ipam; import com.github.dockerjava.core.DockerClientBuilder; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; import java.util.List; @@ -25,6 +26,7 @@ public class NetworkLiveTest { } @Test + @Ignore("temporarily") public void whenListingNetworks_thenSizeMustBeGreaterThanZero() { // when diff --git a/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java b/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxLiveTest.java similarity index 97% rename from libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java rename to libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxLiveTest.java index 48161fa3ee..7ab4af3af2 100644 --- a/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxApiTest.java +++ b/libraries/src/test/java/com/baeldung/retrofit/rx/GitHubRxLiveTest.java @@ -13,7 +13,7 @@ import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; -public class GitHubRxApiTest { +public class GitHubRxLiveTest { GitHubRxApi gitHub; diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderIntegrationTest.java similarity index 90% rename from libraries/src/test/java/com/baeldung/serenity/spring/AdderTest.java rename to libraries/src/test/java/com/baeldung/serenity/spring/AdderIntegrationTest.java index 3144771e70..b30496462e 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; @ContextConfiguration(classes = { AdderController.class, AdderService.class }) -public class AdderTest extends SerenityStory { +public class AdderIntegrationTest extends SerenityStory { @Autowired private AdderService adderService; From c1cde1752e8cc60de80618790836d7b14ed719ba Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Sun, 4 Mar 2018 19:55:08 +0100 Subject: [PATCH 51/91] added link to article --- algorithms/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/algorithms/README.md b/algorithms/README.md index 3401b6d935..31cb8076d9 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -16,3 +16,4 @@ - [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm) - [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance) - [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element) +- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm) From 029e160156d0f987e523b569db8da0eb06152d02 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Sun, 4 Mar 2018 20:34:17 +0100 Subject: [PATCH 52/91] added link to article (#3768) --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index 8bb114b95f..b7482b09cc 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -135,4 +135,5 @@ - [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator) - [The Trie Data Structure in Java](http://www.baeldung.com/trie-java) - [Introduction to Javadoc](http://www.baeldung.com/javadoc) +- [How to TDD a List Implementation](http://jira.baeldung.com/browse/BAEL-1537) From 103e6b69fa0abff855094c69a6c50e3da01595a0 Mon Sep 17 00:00:00 2001 From: myluckagain Date: Mon, 5 Mar 2018 16:21:48 +0300 Subject: [PATCH 53/91] Bael-1604 (#3765) * BAEL-1604 * BAEL-1604 --- .../baeldung/casting/AnimalFeederGeneric.java | 24 +++++++++++++++++++ .../com/baeldung/casting/CastingTest.java | 22 +++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java diff --git a/core-java/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java b/core-java/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java new file mode 100644 index 0000000000..5fbd2415c7 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java @@ -0,0 +1,24 @@ +package com.baeldung.casting; + +import java.util.ArrayList; +import java.util.List; + +public class AnimalFeederGeneric { + private Class type; + + public AnimalFeederGeneric(Class type) { + this.type = type; + } + + public List feed(List animals) { + List list = new ArrayList(); + animals.forEach(animal -> { + if (type.isInstance(animal)) { + T objAsType = type.cast(animal); + list.add(objAsType); + } + }); + return list; + } + +} diff --git a/core-java/src/test/java/com/baeldung/casting/CastingTest.java b/core-java/src/test/java/com/baeldung/casting/CastingTest.java index 0ca1ce88dc..dd95e0dd80 100644 --- a/core-java/src/test/java/com/baeldung/casting/CastingTest.java +++ b/core-java/src/test/java/com/baeldung/casting/CastingTest.java @@ -11,6 +11,7 @@ public class CastingTest { public void whenPrimitiveConverted_thenValueChanged() { double myDouble = 1.1; int myInt = (int) myDouble; + assertNotEquals(myDouble, myInt); } @@ -55,4 +56,25 @@ public class CastingTest { animals.add(new Dog()); new AnimalFeeder().uncheckedFeed(animals); } + + @Test + public void whenDowncastToCatWithCastMethod_thenMeowIsCalled() { + Animal animal = new Cat(); + if (Cat.class.isInstance(animal)) { + Cat cat = Cat.class.cast(animal); + cat.meow(); + } + } + + @Test + public void whenParameterCat_thenOnlyCatsFed() { + List animals = new ArrayList<>(); + animals.add(new Cat()); + animals.add(new Dog()); + AnimalFeederGeneric catFeeder = new AnimalFeederGeneric(Cat.class); + List fedAnimals = catFeeder.feed(animals); + + assertTrue(fedAnimals.size() == 1); + assertTrue(fedAnimals.get(0) instanceof Cat); + } } From a674acacb98f71e9769e81e80635f776f041eee8 Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 5 Mar 2018 17:17:25 +0200 Subject: [PATCH 54/91] move hamcrest text and file matchers --- guava/pom.xml | 8 +------- testing-modules/mockito/pom.xml | 9 ++++++++- .../java/org/baeldung/hamcrest/HamcrestFileUnitTest.java | 0 .../java/org/baeldung/hamcrest/HamcrestTextUnitTest.java | 0 testing-modules/mockito/src/test/resources/test1.in | 1 + 5 files changed, 10 insertions(+), 8 deletions(-) rename {guava => testing-modules/mockito}/src/test/java/org/baeldung/hamcrest/HamcrestFileUnitTest.java (100%) rename {guava => testing-modules/mockito}/src/test/java/org/baeldung/hamcrest/HamcrestTextUnitTest.java (100%) create mode 100644 testing-modules/mockito/src/test/resources/test1.in diff --git a/guava/pom.xml b/guava/pom.xml index aa162b7d1b..ca9e1e528e 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -43,13 +43,7 @@ ${assertj.version} test - - - org.hamcrest - java-hamcrest - 2.0.0.0 - test - + diff --git a/testing-modules/mockito/pom.xml b/testing-modules/mockito/pom.xml index 0e83c46926..1ec1ffe7bd 100644 --- a/testing-modules/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -46,7 +46,14 @@ ${powermock.version} test - + + + org.hamcrest + java-hamcrest + 2.0.0.0 + test + + diff --git a/guava/src/test/java/org/baeldung/hamcrest/HamcrestFileUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestFileUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/hamcrest/HamcrestFileUnitTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestFileUnitTest.java diff --git a/guava/src/test/java/org/baeldung/hamcrest/HamcrestTextUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestTextUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/hamcrest/HamcrestTextUnitTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestTextUnitTest.java diff --git a/testing-modules/mockito/src/test/resources/test1.in b/testing-modules/mockito/src/test/resources/test1.in new file mode 100644 index 0000000000..70c379b63f --- /dev/null +++ b/testing-modules/mockito/src/test/resources/test1.in @@ -0,0 +1 @@ +Hello world \ No newline at end of file From 48e5d41bc10b8b9aac8938ac334daca815ff21a7 Mon Sep 17 00:00:00 2001 From: orrym Date: Mon, 5 Mar 2018 20:01:00 +0200 Subject: [PATCH 55/91] BAEL-1572: use yourInstanceId variable --- aws/src/main/java/com/baeldung/ec2/EC2Application.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aws/src/main/java/com/baeldung/ec2/EC2Application.java b/aws/src/main/java/com/baeldung/ec2/EC2Application.java index bb7d8ca1d7..4d22c91924 100644 --- a/aws/src/main/java/com/baeldung/ec2/EC2Application.java +++ b/aws/src/main/java/com/baeldung/ec2/EC2Application.java @@ -123,7 +123,7 @@ public class EC2Application { // 9) - Start an Instance StartInstancesRequest startInstancesRequest = new StartInstancesRequest() - .withInstanceIds("instance-id"); + .withInstanceIds("yourInstanceId"); ec2Client.startInstances(startInstancesRequest); From 92bf89787439019c6a7673611e49184b1cfa738a Mon Sep 17 00:00:00 2001 From: orrym Date: Mon, 5 Mar 2018 20:05:48 +0200 Subject: [PATCH 56/91] BAEL-1572: remove quotes --- aws/src/main/java/com/baeldung/ec2/EC2Application.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aws/src/main/java/com/baeldung/ec2/EC2Application.java b/aws/src/main/java/com/baeldung/ec2/EC2Application.java index 4d22c91924..62179145f9 100644 --- a/aws/src/main/java/com/baeldung/ec2/EC2Application.java +++ b/aws/src/main/java/com/baeldung/ec2/EC2Application.java @@ -123,7 +123,7 @@ public class EC2Application { // 9) - Start an Instance StartInstancesRequest startInstancesRequest = new StartInstancesRequest() - .withInstanceIds("yourInstanceId"); + .withInstanceIds(yourInstanceId); ec2Client.startInstances(startInstancesRequest); From f4a7946634dc70faa2d5d8c2ad52f22bc88947e1 Mon Sep 17 00:00:00 2001 From: orrym Date: Mon, 5 Mar 2018 20:48:37 +0200 Subject: [PATCH 57/91] BAEL-1572: Use instance ID of newly created instance for the rest of the examples --- aws/src/main/java/com/baeldung/ec2/EC2Application.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/aws/src/main/java/com/baeldung/ec2/EC2Application.java b/aws/src/main/java/com/baeldung/ec2/EC2Application.java index 62179145f9..6876eb7369 100644 --- a/aws/src/main/java/com/baeldung/ec2/EC2Application.java +++ b/aws/src/main/java/com/baeldung/ec2/EC2Application.java @@ -38,9 +38,7 @@ public class EC2Application { } public static void main(String[] args) { - - String yourInstanceId = ""; - + // 0) - Set up the client AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) @@ -91,7 +89,7 @@ public class EC2Application { .withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance .withSecurityGroups("BaeldungSecurityGroup"); - ec2Client.runInstances(runInstancesRequest); + String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId(); // 6) Monitor Instances MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest() From 572509f5ca66c15d4863a5f8f46323d9bb22d241 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 6 Mar 2018 00:25:11 +0200 Subject: [PATCH 58/91] move start instance --- .../java/com/baeldung/ec2/EC2Application.java | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/aws/src/main/java/com/baeldung/ec2/EC2Application.java b/aws/src/main/java/com/baeldung/ec2/EC2Application.java index 6876eb7369..6755188fcd 100644 --- a/aws/src/main/java/com/baeldung/ec2/EC2Application.java +++ b/aws/src/main/java/com/baeldung/ec2/EC2Application.java @@ -39,18 +39,18 @@ public class EC2Application { public static void main(String[] args) { - // 0) - Set up the client + // Set up the client AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withRegion(Regions.US_EAST_1) .build(); - // 1) - Create a security group + // Create a security group CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup") .withDescription("Baeldung Security Group"); ec2Client.createSecurityGroup(createSecurityGroupRequest); - // 2) - Allow HTTP and SSH traffic + // Allow HTTP and SSH traffic IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0"); IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 })) @@ -69,7 +69,7 @@ public class EC2Application { ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); - // 3) - Create KeyPair + // Create KeyPair CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest() .withKeyName("baeldung-key-pair"); CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest); @@ -77,11 +77,11 @@ public class EC2Application { .getKeyPair() .getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key - // 4) - See what key-pairs you've got + // See what key-pairs you've got DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest(); DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest); - // 5) - Launch an Amazon Instance + // Launch an Amazon Instance RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html .withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html .withMinCount(1) @@ -91,7 +91,13 @@ public class EC2Application { String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId(); - // 6) Monitor Instances + // Start an Instance + StartInstancesRequest startInstancesRequest = new StartInstancesRequest() + .withInstanceIds(yourInstanceId); + + ec2Client.startInstances(startInstancesRequest); + + // Monitor Instances MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest() .withInstanceIds(yourInstanceId); @@ -102,14 +108,14 @@ public class EC2Application { ec2Client.unmonitorInstances(unmonitorInstancesRequest); - // 7) - Reboot an Instance + // Reboot an Instance RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest() .withInstanceIds(yourInstanceId); ec2Client.rebootInstances(rebootInstancesRequest); - // 8) - Stop an Instance + // Stop an Instance StopInstancesRequest stopInstancesRequest = new StopInstancesRequest() .withInstanceIds(yourInstanceId); @@ -119,13 +125,7 @@ public class EC2Application { .getPreviousState() .getName(); - // 9) - Start an Instance - StartInstancesRequest startInstancesRequest = new StartInstancesRequest() - .withInstanceIds(yourInstanceId); - - ec2Client.startInstances(startInstancesRequest); - - // 10) - Describe an Instance + // Describe an Instance DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest); System.out.println(response.getReservations() From 3364e1ccad8e0247f8cf1f3fed7f3673a431c10a Mon Sep 17 00:00:00 2001 From: Nguyen Nam Thai Date: Tue, 6 Mar 2018 15:37:37 +0700 Subject: [PATCH 59/91] Initial commit for Apache Tika --- apache-tika/.gitignore | 3 + apache-tika/pom.xml | 25 ++++++ .../java/com/baeldung/tika/TikaAnalysis.java | 67 +++++++++++++++ .../java/com/baeldung/tika/TikaUnitTest.java | 81 ++++++++++++++++++ apache-tika/src/test/resources/tika.txt | Bin 0 -> 36305 bytes apache-tika/src/test/resources/tika.xlsx | Bin 0 -> 8348 bytes pom.xml | 3 +- 7 files changed, 178 insertions(+), 1 deletion(-) create mode 100644 apache-tika/.gitignore create mode 100644 apache-tika/pom.xml create mode 100644 apache-tika/src/main/java/com/baeldung/tika/TikaAnalysis.java create mode 100644 apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java create mode 100644 apache-tika/src/test/resources/tika.txt create mode 100644 apache-tika/src/test/resources/tika.xlsx diff --git a/apache-tika/.gitignore b/apache-tika/.gitignore new file mode 100644 index 0000000000..5f88621edc --- /dev/null +++ b/apache-tika/.gitignore @@ -0,0 +1,3 @@ +*.docx +temp.xls +temp.xlsx \ No newline at end of file diff --git a/apache-tika/pom.xml b/apache-tika/pom.xml new file mode 100644 index 0000000000..34013dee89 --- /dev/null +++ b/apache-tika/pom.xml @@ -0,0 +1,25 @@ + + 4.0.0 + com.baeldung + apache-tika + 0.0.1-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 1.17 + + + + + org.apache.tika + tika-parsers + ${tika.version} + + + \ No newline at end of file diff --git a/apache-tika/src/main/java/com/baeldung/tika/TikaAnalysis.java b/apache-tika/src/main/java/com/baeldung/tika/TikaAnalysis.java new file mode 100644 index 0000000000..85eafc7c08 --- /dev/null +++ b/apache-tika/src/main/java/com/baeldung/tika/TikaAnalysis.java @@ -0,0 +1,67 @@ +package com.baeldung.tika; + +import java.io.IOException; +import java.io.InputStream; + +import org.apache.tika.Tika; +import org.apache.tika.detect.DefaultDetector; +import org.apache.tika.detect.Detector; +import org.apache.tika.exception.TikaException; +import org.apache.tika.metadata.Metadata; +import org.apache.tika.mime.MediaType; +import org.apache.tika.parser.AutoDetectParser; +import org.apache.tika.parser.ParseContext; +import org.apache.tika.parser.Parser; +import org.apache.tika.sax.BodyContentHandler; +import org.xml.sax.ContentHandler; +import org.xml.sax.SAXException; + +public class TikaAnalysis { + public static String detectDocTypeUsingDetector(InputStream stream) throws IOException { + Detector detector = new DefaultDetector(); + Metadata metadata = new Metadata(); + + MediaType mediaType = detector.detect(stream, metadata); + return mediaType.toString(); + } + + public static String detectDocTypeUsingFacade(InputStream stream) throws IOException { + Tika tika = new Tika(); + String mediaType = tika.detect(stream); + return mediaType; + } + + public static String extractContentUsingParser(InputStream stream) throws IOException, TikaException, SAXException { + Parser parser = new AutoDetectParser(); + ContentHandler handler = new BodyContentHandler(); + Metadata metadata = new Metadata(); + ParseContext context = new ParseContext(); + + parser.parse(stream, handler, metadata, context); + return handler.toString(); + } + + public static String extractContentUsingFacade(InputStream stream) throws IOException, TikaException { + Tika tika = new Tika(); + String content = tika.parseToString(stream); + return content; + } + + public static Metadata extractMetadatatUsingParser(InputStream stream) throws IOException, SAXException, TikaException { + Parser parser = new AutoDetectParser(); + ContentHandler handler = new BodyContentHandler(); + Metadata metadata = new Metadata(); + ParseContext context = new ParseContext(); + + parser.parse(stream, handler, metadata, context); + return metadata; + } + + public static Metadata extractMetadatatUsingFacade(InputStream stream) throws IOException, TikaException { + Tika tika = new Tika(); + Metadata metadata = new Metadata(); + + tika.parse(stream, metadata); + return metadata; + } +} diff --git a/apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java b/apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java new file mode 100644 index 0000000000..555a796d59 --- /dev/null +++ b/apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java @@ -0,0 +1,81 @@ +package com.baeldung.tika; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.io.InputStream; + +import org.apache.tika.exception.TikaException; +import org.apache.tika.metadata.Metadata; +import org.junit.Test; +import org.xml.sax.SAXException; + +public class TikaUnitTest { + private ClassLoader loader = this.getClass().getClassLoader(); + + @Test + public void whenUsingDetector_thenDocumentTypeIsReturned() throws IOException { + InputStream stream = loader.getResourceAsStream("tika.txt"); + String mediaType = TikaAnalysis.detectDocTypeUsingDetector(stream); + + assertEquals("application/pdf", mediaType); + + stream.close(); + } + + @Test + public void whenUsingFacade_thenDocumentTypeIsReturned() throws IOException { + InputStream stream = loader.getResourceAsStream("tika.txt"); + String mediaType = TikaAnalysis.detectDocTypeUsingFacade(stream); + + assertEquals("application/pdf", mediaType); + + stream.close(); + } + + @Test + public void whenUsingParser_thenContentIsReturned() throws IOException, TikaException, SAXException { + InputStream stream = loader.getResourceAsStream("tika.docx"); + String content = TikaAnalysis.extractContentUsingParser(stream); + + assertThat(content, containsString("Apache Tika - a content analysis toolkit")); + assertThat(content, containsString("detects and extracts metadata and text")); + + stream.close(); + } + + @Test + public void whenUsingFacade_thenContentIsReturned() throws IOException, TikaException { + InputStream stream = loader.getResourceAsStream("tika.docx"); + String content = TikaAnalysis.extractContentUsingFacade(stream); + + assertThat(content, containsString("Apache Tika - a content analysis toolkit")); + assertThat(content, containsString("detects and extracts metadata and text")); + + stream.close(); + } + + @Test + public void whenUsingParser_thenMetadataIsReturned() throws IOException, TikaException, SAXException { + InputStream stream = loader.getResourceAsStream("tika.xlsx"); + Metadata metadata = TikaAnalysis.extractMetadatatUsingParser(stream); + + assertEquals("org.apache.tika.parser.DefaultParser", metadata.get("X-Parsed-By")); + assertEquals("Microsoft Office User", metadata.get("Author")); + + stream.close(); + } + + @Test + public void whenUsingFacade_thenMetadataIsReturned() throws IOException, TikaException { + InputStream stream = loader.getResourceAsStream("tika.xlsx"); + Metadata metadata = TikaAnalysis.extractMetadatatUsingFacade(stream); + + assertEquals("org.apache.tika.parser.DefaultParser", metadata.get("X-Parsed-By")); + assertEquals("Microsoft Office User", metadata.get("Author")); + + stream.close(); + } +} diff --git a/apache-tika/src/test/resources/tika.txt b/apache-tika/src/test/resources/tika.txt new file mode 100644 index 0000000000000000000000000000000000000000..26923836de7d3e313047abfc892d503246616188 GIT binary patch literal 36305 zcma&N1y~%**0xQM;1=8+g1fuBySux)26uONcMC8`fM7{*cXxOHAlduubN<)9cSP?2)kvbn9uC65 zo+P)#nxsU$qfdD8_0M|8679_$eZ!U<(^6SX)`AKO*;UWO{h^2tf_eh!DK>jmW+lPp>DOX;Q=(m@5RH4S)D zFXOs2Kg#Lvk-VHpU)j98K7HhcU46mqd`{I(?b+hh39QKp67QlPsoNoIxDUCv*mU>4 z3-GA2;g+gNvewCXvPCnwJp5Ydp-CJ24Io3ZT{t6EG&37jkXEF?7`uQJTh-BMXZAAX ztA5|rALP%(E8V46WnDKAWqhAtx^8Knh0ovjQA3|d>}!)hp^CvvLn|D#OspL$e(tAc zZEcxt;Gb9}v~dw@4tO!j>QkVFVED7@d`97-;CqH{Rv;?p>vD5SemmA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a literal 0 HcmV?d00001 diff --git a/pom.xml b/pom.xml index 75cf4b84b8..1731e1661c 100644 --- a/pom.xml +++ b/pom.xml @@ -38,6 +38,7 @@ apache-cxf apache-fop apache-poi + apache-tika apache-thrift autovalue axon @@ -383,4 +384,4 @@ - \ No newline at end of file + From a079f521ebb977ae078e9136387c68a7ebd3391e Mon Sep 17 00:00:00 2001 From: Nguyen Nam Thai Date: Tue, 6 Mar 2018 15:40:01 +0700 Subject: [PATCH 60/91] Add a test resource for Apache Tika --- apache-tika/.gitignore | 3 --- apache-tika/src/test/resources/tika.docx | Bin 0 -> 12811 bytes 2 files changed, 3 deletions(-) delete mode 100644 apache-tika/.gitignore create mode 100644 apache-tika/src/test/resources/tika.docx diff --git a/apache-tika/.gitignore b/apache-tika/.gitignore deleted file mode 100644 index 5f88621edc..0000000000 --- a/apache-tika/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -*.docx -temp.xls -temp.xlsx \ No newline at end of file diff --git a/apache-tika/src/test/resources/tika.docx b/apache-tika/src/test/resources/tika.docx new file mode 100644 index 0000000000000000000000000000000000000000..0a01ccef55dfdff806e5ad9ef8b1174d2f001d16 GIT binary patch literal 12811 zcmeHt1y@|l()K`tOOW6e++BkPw?G(zyIXK~cXxMp*WeJ`-7UDgL-;1=-g8e*?pfa- zc<)|o*P7|wPj%0ps;=&*N=EY4>$d<%05kvqAOx)CPMWHK0RZnH002|~G`Omug}JT1 zxvi$0lcm0mI-R4L>AURL;1rnva8UpMUH^yQKyB=hc^3nc@NL|~o2UkPoxSX0D)12A zcv{(gC`=b{h3DwLmLF}X;6Qn>C|FY>Qs&!LW`$m#iN$17800z!(nAcMc&``@V|MC= zxh+}`JuI?~ScX;p0X9!lmX=nmk8EHJ#C6@#BcEYErRJpipefw}!l~jS6iA%InDKp| z(3#h7TUTEttdd$%eyW4QLDa}Zfs3i0V|6nZBf`{Mu$fXajQi-TRr@yRz;%B*Bi1!R zCenJz#|G~#92=7_QARNw>d2PBmIX-N-%FJ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KRF_aTm~Je}JLzaAtJudjJ}}c?7BNm6tRtN5m-30F6+ta`6>gk=E`%;$A(h zBz{rt4}q7S`t18oakDs2`cFaHUSc&PoAQf*LhRT0*!Z)d03@QF)qew)M!1uFj;Y@v8>Fcqw$=JLr@Z$Q=+;xPN%^i5p$zJm|fn+uZb zW+3gjsbg9x?|N>Soej|=kh*!kc2T3h^wtQz;m8D{K@oTh=KefFRue$^S@c@i0cO7G zB-+5qr#ZDITcg=tp(YHW&n_iHIz(2!-~QUM#lz}qqf5d9=wVb^nt>|6^zpi+W_sf& zY=l_kdhAl4^q8#vcE0p`j|uhV;fx3*{b2%@+m9%=W{W2ShvkQ?nwp8$en+g8i-Nt9 z;l!ZI>xLc`h2)CVy7C~&#>SKLhqa-}r}iIv3tq=qw>gH_OuI|^>6n3Ws!FD7N82#$ zkN&GO#0ERhEfqQ4m)M#SeP)Igte-6!vJyw<%WOIKjB3O&(m0ElgV{;UKAL~YG8tnj zBNlkJN;}MSt0wqdqMFQIgPk|4dBM`EeLZWvvBt7pQ>@X<&PH$RSm&%49?=`-^U;#0pA%Cg({T=xC;>TZsHJ}oS|6eKO@0xxui2F;|K8Wf5 zukyIx;lEd9`~}ZJ{5Smf8jaso{GOHjOT`X|>ilB{zvk$EhyPB@{{<()`ZxSKEV@R>OO#{WjN{;uKgblzWh0Kgm%0QjBU`yKsve&ts*&bwdGf3hvV!+$^P{-t1) e=+C$JpOdeQBm~Gje%6!20XjkCBMbe{Z~qT8WCim8 literal 0 HcmV?d00001 From bbe6f609167dfb6862ebec174a68beff727a1f91 Mon Sep 17 00:00:00 2001 From: Nguyen Nam Thai Date: Tue, 6 Mar 2018 15:53:17 +0700 Subject: [PATCH 61/91] Remove the ending line of the pom.xml file --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1731e1661c..10abee4016 100644 --- a/pom.xml +++ b/pom.xml @@ -384,4 +384,4 @@ - + \ No newline at end of file From 734ace918d9e22422261f4a4e1fa22893e3f4b7c Mon Sep 17 00:00:00 2001 From: Nguyen Nam Thai Date: Tue, 6 Mar 2018 17:58:13 +0700 Subject: [PATCH 62/91] Refactor the tests --- .../test/java/com/baeldung/tika/TikaUnitTest.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java b/apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java index 555a796d59..f8c2372d1f 100644 --- a/apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java +++ b/apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java @@ -13,11 +13,9 @@ import org.junit.Test; import org.xml.sax.SAXException; public class TikaUnitTest { - private ClassLoader loader = this.getClass().getClassLoader(); - @Test public void whenUsingDetector_thenDocumentTypeIsReturned() throws IOException { - InputStream stream = loader.getResourceAsStream("tika.txt"); + InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.txt"); String mediaType = TikaAnalysis.detectDocTypeUsingDetector(stream); assertEquals("application/pdf", mediaType); @@ -27,7 +25,7 @@ public class TikaUnitTest { @Test public void whenUsingFacade_thenDocumentTypeIsReturned() throws IOException { - InputStream stream = loader.getResourceAsStream("tika.txt"); + InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.txt"); String mediaType = TikaAnalysis.detectDocTypeUsingFacade(stream); assertEquals("application/pdf", mediaType); @@ -37,7 +35,7 @@ public class TikaUnitTest { @Test public void whenUsingParser_thenContentIsReturned() throws IOException, TikaException, SAXException { - InputStream stream = loader.getResourceAsStream("tika.docx"); + InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.docx"); String content = TikaAnalysis.extractContentUsingParser(stream); assertThat(content, containsString("Apache Tika - a content analysis toolkit")); @@ -48,7 +46,7 @@ public class TikaUnitTest { @Test public void whenUsingFacade_thenContentIsReturned() throws IOException, TikaException { - InputStream stream = loader.getResourceAsStream("tika.docx"); + InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.docx"); String content = TikaAnalysis.extractContentUsingFacade(stream); assertThat(content, containsString("Apache Tika - a content analysis toolkit")); @@ -59,7 +57,7 @@ public class TikaUnitTest { @Test public void whenUsingParser_thenMetadataIsReturned() throws IOException, TikaException, SAXException { - InputStream stream = loader.getResourceAsStream("tika.xlsx"); + InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.xlsx"); Metadata metadata = TikaAnalysis.extractMetadatatUsingParser(stream); assertEquals("org.apache.tika.parser.DefaultParser", metadata.get("X-Parsed-By")); @@ -70,7 +68,7 @@ public class TikaUnitTest { @Test public void whenUsingFacade_thenMetadataIsReturned() throws IOException, TikaException { - InputStream stream = loader.getResourceAsStream("tika.xlsx"); + InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.xlsx"); Metadata metadata = TikaAnalysis.extractMetadatatUsingFacade(stream); assertEquals("org.apache.tika.parser.DefaultParser", metadata.get("X-Parsed-By")); From 1bb98e491df6b00e167483bc68d3b355b3c65592 Mon Sep 17 00:00:00 2001 From: Magdalena Krause Date: Tue, 6 Mar 2018 12:46:35 -0300 Subject: [PATCH 63/91] BAEL-1580: Hamcrest number matchers. (#3749) * BAEL-1580: Hamcrest number matchers. * BAEL-1580: Moving hamcrest test to module mockito. --- .../hamcrest/HamcrestNumberUnitTest.java | 152 ++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestNumberUnitTest.java diff --git a/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestNumberUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestNumberUnitTest.java new file mode 100644 index 0000000000..21606afd79 --- /dev/null +++ b/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestNumberUnitTest.java @@ -0,0 +1,152 @@ +package org.baeldung.hamcrest; + +import org.junit.Test; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.closeTo; + +public class HamcrestNumberUnitTest { + + @Test + public void givenADouble_whenCloseTo_thenCorrect() { + double actual = 1.3; + double operand = 1; + double error = 0.5; + assertThat(actual, is(closeTo(operand, error))); + } + + @Test + public void givenADouble_whenNotCloseTo_thenCorrect() { + double actual = 1.6; + double operand = 1; + double error = 0.5; + assertThat(actual, is(not(closeTo(operand, error)))); + } + + @Test + public void givenABigDecimal_whenCloseTo_thenCorrect() { + BigDecimal actual = new BigDecimal("1.0003"); + BigDecimal operand = new BigDecimal("1"); + BigDecimal error = new BigDecimal("0.0005"); + assertThat(actual, is(closeTo(operand, error))); + } + + @Test + public void givenABigDecimal_whenNotCloseTo_thenCorrect() { + BigDecimal actual = new BigDecimal("1.0006"); + BigDecimal operand = new BigDecimal("1"); + BigDecimal error = new BigDecimal("0.0005"); + assertThat(actual, is(not(closeTo(operand, error)))); + } + + @Test + public void given7_whenGreaterThan5_thenCorrect() { + Integer seven = 7; + Integer five = 5; + assertThat(seven, is(greaterThan(five))); + } + + @Test + public void given7_whenGreaterThanOrEqualTo5_thenCorrect() { + Integer seven = 7; + Integer five = 5; + assertThat(seven, is(greaterThanOrEqualTo(five))); + } + + @Test + public void given5_whenGreaterThanOrEqualTo5_thenCorrect() { + Integer five = 5; + assertThat(five, is(greaterThanOrEqualTo(five))); + } + + @Test + public void given3_whenLessThan5_thenCorrect() { + Integer three = 3; + Integer five = 5; + assertThat(three, is(lessThan(five))); + } + + @Test + public void given3_whenLessThanOrEqualTo5_thenCorrect() { + Integer three = 3; + Integer five = 5; + assertThat(three, is(lessThanOrEqualTo(five))); + } + + @Test + public void given5_whenLessThanOrEqualTo5_thenCorrect() { + Integer five = 5; + assertThat(five, is(lessThanOrEqualTo(five))); + } + + @Test + public void givenBenjamin_whenGreaterThanAmanda_thenCorrect() { + String amanda = "Amanda"; + String benjamin = "Benjamin"; + assertThat(benjamin, is(greaterThan(amanda))); + } + + @Test + public void givenAmanda_whenLessThanBenajmin_thenCorrect() { + String amanda = "Amanda"; + String benjamin = "Benjamin"; + assertThat(amanda, is(lessThan(benjamin))); + } + + @Test + public void givenToday_whenGreaterThanYesterday_thenCorrect() { + LocalDate today = LocalDate.now(); + LocalDate yesterday = today.minusDays(1); + assertThat(today, is(greaterThan(yesterday))); + } + + @Test + public void givenToday_whenLessThanTomorrow_thenCorrect() { + LocalDate today = LocalDate.now(); + LocalDate tomorrow = today.plusDays(1); + assertThat(today, is(lessThan(tomorrow))); + } + + @Test + public void givenAmanda_whenOlderThanBenjamin_thenCorrect() { + Person amanda = new Person("Amanda", 20); + Person benjamin = new Person("Benjamin", 18); + assertThat(amanda, is(greaterThan(benjamin))); + } + + @Test + public void givenBenjamin_whenYoungerThanAmanda_thenCorrect() { + Person amanda = new Person("Amanda", 20); + Person benjamin = new Person("Benjamin", 18); + assertThat(benjamin, is(lessThan(amanda))); + } + + class Person implements Comparable { + String name; + int age; + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + @Override + public int compareTo(Person o) { + if (this.age == o.getAge()) return 0; + if (this.age > o.age) return 1; + else return -1; + } + } +} From c7f9792d54ddd7f29c12458db8b0d0ae65031675 Mon Sep 17 00:00:00 2001 From: Jose Carvajal Date: Wed, 7 Mar 2018 04:16:38 +0100 Subject: [PATCH 64/91] BAEL-1108 (#3766) * BAEL-399: A Guide to Multitenancy in Hibernate 5 * Removed unused properties in profile 2 * Changes after code review * Add XML, JavaConfig and Autowired examples. * BAEL-1517: Added Java7 style assertions * BAEL-1517: Upgrade AssertJ to 3.9.0; add Java 8 style assertion tests * Revert "Add XML, JavaConfig and Autowired examples." This reverts commit 8f4df6b903866dac1725832d06ee7382fc89d0ce. * BAEL-1517: Editor Review changes * BAEL-1517: Formatting... * BAEL-1572: AWS EC2 examples * BAEL-1108 * BAEL-1570 (#3762) * Create pom.xml * Update pom.xml * Create pom.xml * Update pom.xml * add impl * add app * minor cleanup * testing work * testing work * testing work * testing work * cleanup work * unused import cleanup * cleanup work for tests * formatting work * testing cleanup * minior rename * cleanup work * added link to article (#3768) * Fixed tests and renamed test names * BAEL-1108 Formatting --- apache-curator/pom.xml | 68 +++++++++++++ .../apache/curator/modeled/HostConfig.java | 31 ++++++ .../com/baeldung/apache/curator/BaseTest.java | 22 +++++ .../ConfigurationManagementManualTest.java | 98 +++++++++++++++++++ .../ConnectionManagementManualTest.java | 69 +++++++++++++ .../modeled/ModelTypedExamplesManualTest.java | 47 +++++++++ .../curator/recipes/RecipesManualTest.java | 74 ++++++++++++++ pom.xml | 1 + 8 files changed, 410 insertions(+) create mode 100644 apache-curator/pom.xml create mode 100644 apache-curator/src/main/java/com/baeldung/apache/curator/modeled/HostConfig.java create mode 100644 apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java create mode 100644 apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java create mode 100644 apache-curator/src/test/java/com/baeldung/apache/curator/connection/ConnectionManagementManualTest.java create mode 100644 apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java create mode 100644 apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java diff --git a/apache-curator/pom.xml b/apache-curator/pom.xml new file mode 100644 index 0000000000..36c3949b1a --- /dev/null +++ b/apache-curator/pom.xml @@ -0,0 +1,68 @@ + + 4.0.0 + apache-curator + 0.0.1-SNAPSHOT + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 4.0.1 + 3.4.11 + 2.9.4 + + + 3.6.1 + + + + + + + + + org.apache.curator + curator-x-async + ${curator.version} + + + org.apache.zookeeper + zookeeper + + + + + + org.apache.curator + curator-recipes + ${curator.version} + + + + org.apache.zookeeper + zookeeper + ${zookeeper.version} + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind.version} + + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + diff --git a/apache-curator/src/main/java/com/baeldung/apache/curator/modeled/HostConfig.java b/apache-curator/src/main/java/com/baeldung/apache/curator/modeled/HostConfig.java new file mode 100644 index 0000000000..bab7133742 --- /dev/null +++ b/apache-curator/src/main/java/com/baeldung/apache/curator/modeled/HostConfig.java @@ -0,0 +1,31 @@ +package com.baeldung.apache.curator.modeled; + +public class HostConfig { + private String hostname; + private int port; + + public HostConfig() { + + } + + public HostConfig(String hostname, int port) { + this.hostname = hostname; + this.port = port; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getHostname() { + return hostname; + } + + public void setHostname(String hostname) { + this.hostname = hostname; + } +} diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java new file mode 100644 index 0000000000..cfac3ee3f2 --- /dev/null +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java @@ -0,0 +1,22 @@ +package com.baeldung.apache.curator; + +import org.apache.curator.RetryPolicy; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.RetryNTimes; +import org.junit.Before; + +public abstract class BaseTest { + + @Before + public void setup() { + org.apache.log4j.BasicConfigurator.configure(); + } + + protected CuratorFramework newClient() { + int sleepMsBetweenRetries = 100; + int maxRetries = 3; + RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries); + return CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy); + } +} diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java new file mode 100644 index 0000000000..0475f9c237 --- /dev/null +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java @@ -0,0 +1,98 @@ +package com.baeldung.apache.curator.configuration; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.x.async.AsyncCuratorFramework; +import org.junit.Test; + +import com.baeldung.apache.curator.BaseTest; + +public class ConfigurationManagementManualTest extends BaseTest { + + private static final String KEY_FORMAT = "/%s"; + + @Test + public void givenPath_whenCreateKey_thenValueIsStored() throws Exception { + try (CuratorFramework client = newClient()) { + client.start(); + AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); + String key = getKey(); + String expected = "my_value"; + + // Create key nodes structure + client + .create() + .forPath(key); + + // Set data value for our key + async + .setData() + .forPath(key, expected.getBytes()); + + // Get data value + AtomicBoolean isEquals = new AtomicBoolean(); + async + .getData() + .forPath(key) + .thenAccept(data -> isEquals.set(new String(data).equals(expected))); + + Thread.sleep(1000); + + assertThat(isEquals.get()).isTrue(); + } + } + + @Test + public void givenPath_whenWatchAKeyAndStoreAValue_thenWatcherIsTriggered() throws Exception { + try (CuratorFramework client = newClient()) { + client.start(); + AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); + String key = getKey(); + String expected = "my_value"; + + // Create key structure + async + .create() + .forPath(key); + + List changes = new ArrayList<>(); + + // Watch data value + async + .watched() + .getData() + .forPath(key) + .event() + .thenAccept(watchedEvent -> { + try { + changes.add(new String(client + .getData() + .forPath(watchedEvent.getPath()))); + } catch (Exception e) { + // fail ... + } + }); + + // Set data value for our key + async + .setData() + .forPath(key, expected.getBytes()); + + Thread.sleep(1000); + + assertThat(changes.size() > 0).isTrue(); + } + } + + private String getKey() { + return String.format(KEY_FORMAT, UUID + .randomUUID() + .toString()); + } +} diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/connection/ConnectionManagementManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/connection/ConnectionManagementManualTest.java new file mode 100644 index 0000000000..931a977900 --- /dev/null +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/connection/ConnectionManagementManualTest.java @@ -0,0 +1,69 @@ +package com.baeldung.apache.curator.connection; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.curator.RetryPolicy; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.RetryNTimes; +import org.apache.curator.x.async.AsyncCuratorFramework; +import org.junit.Test; + +public class ConnectionManagementManualTest { + + @Test + public void givenRunningZookeeper_whenOpenConnection_thenClientIsOpened() throws Exception { + int sleepMsBetweenRetries = 100; + int maxRetries = 3; + RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries); + + try (CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy)) { + client.start(); + assertThat(client + .checkExists() + .forPath("/")).isNotNull(); + } + } + + @Test + public void givenRunningZookeeper_whenOpenConnectionUsingAsyncNotBlocking_thenClientIsOpened() throws InterruptedException { + int sleepMsBetweenRetries = 100; + int maxRetries = 3; + RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries); + + try (CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy)) { + client.start(); + AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); + + AtomicBoolean exists = new AtomicBoolean(false); + async + .checkExists() + .forPath("/") + .thenAcceptAsync(s -> exists.set(s != null)); + Thread.sleep(100); + assertThat(exists.get()).isTrue(); + } + } + + @Test + public void givenRunningZookeeper_whenOpenConnectionUsingAsyncBlocking_thenClientIsOpened() throws InterruptedException { + int sleepMsBetweenRetries = 100; + int maxRetries = 3; + RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries); + + try (CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy)) { + client.start(); + AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); + + AtomicBoolean exists = new AtomicBoolean(false); + async + .checkExists() + .forPath("/") + .thenAccept(s -> exists.set(s != null)); + Thread.sleep(100); + assertThat(exists.get()).isTrue(); + } + } +} diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java new file mode 100644 index 0000000000..9d00c0a4c2 --- /dev/null +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java @@ -0,0 +1,47 @@ +package com.baeldung.apache.curator.modeled; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.x.async.AsyncCuratorFramework; +import org.apache.curator.x.async.modeled.JacksonModelSerializer; +import org.apache.curator.x.async.modeled.ModelSpec; +import org.apache.curator.x.async.modeled.ModeledFramework; +import org.apache.curator.x.async.modeled.ZPath; +import org.junit.Test; + +import com.baeldung.apache.curator.BaseTest; + +public class ModelTypedExamplesManualTest extends BaseTest { + + @Test + public void givenPath_whenStoreAModel_thenNodesAreCreated() throws InterruptedException { + + ModelSpec mySpec = ModelSpec + .builder(ZPath.parseWithIds("/config/dev"), JacksonModelSerializer.build(HostConfig.class)) + .build(); + + try (CuratorFramework client = newClient()) { + client.start(); + AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); + ModeledFramework modeledClient = ModeledFramework.wrap(async, mySpec); + + modeledClient.set(new HostConfig("host-name", 8080)); + + modeledClient + .read() + .whenComplete((value, e) -> { + if (e != null) { + fail("Cannot read host config", e); + } else { + assertThat(value).isNotNull(); + assertThat(value.getHostname()).isEqualTo("host-name"); + assertThat(value.getPort()).isEqualTo(8080); + } + + }); + } + + } +} diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java new file mode 100644 index 0000000000..04f4104e6b --- /dev/null +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java @@ -0,0 +1,74 @@ +package com.baeldung.apache.curator.recipes; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.recipes.leader.LeaderSelector; +import org.apache.curator.framework.recipes.leader.LeaderSelectorListener; +import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex; +import org.apache.curator.framework.recipes.shared.SharedCount; +import org.apache.curator.framework.state.ConnectionState; +import org.junit.Test; + +import com.baeldung.apache.curator.BaseTest; + +public class RecipesManualTest extends BaseTest { + + @Test + public void givenRunningZookeeper_whenUsingLeaderElection_thenNoErrors() { + try (CuratorFramework client = newClient()) { + client.start(); + LeaderSelector leaderSelector = new LeaderSelector(client, "/mutex/select/leader/for/job/A", new LeaderSelectorListener() { + + @Override + public void stateChanged(CuratorFramework client, ConnectionState newState) { + + } + + @Override + public void takeLeadership(CuratorFramework client) throws Exception { + // I'm the leader of the job A ! + } + + }); + + leaderSelector.start(); + + // Wait until the job A is done among all the members + + leaderSelector.close(); + } + } + + @Test + public void givenRunningZookeeper_whenUsingSharedLock_thenNoErrors() throws Exception { + try (CuratorFramework client = newClient()) { + client.start(); + InterProcessSemaphoreMutex sharedLock = new InterProcessSemaphoreMutex(client, "/mutex/process/A"); + + sharedLock.acquire(); + + // Do process A + + sharedLock.release(); + } + } + + @Test + public void givenRunningZookeeper_whenUsingSharedCounter_thenCounterIsIncrement() throws Exception { + try (CuratorFramework client = newClient()) { + client.start(); + + try (SharedCount counter = new SharedCount(client, "/counters/A", 0)) { + counter.start(); + + counter.setCount(0); + counter.setCount(counter.getCount() + 1); + + assertThat(counter.getCount()).isEqualTo(1); + } + + } + } + +} diff --git a/pom.xml b/pom.xml index 75cf4b84b8..23f14a56a4 100644 --- a/pom.xml +++ b/pom.xml @@ -39,6 +39,7 @@ apache-fop apache-poi apache-thrift + apache-curator autovalue axon bootique From 89c4933a2b08a1d00e5817ad1eb2cdec0688edae Mon Sep 17 00:00:00 2001 From: Nikhil Khatwani Date: Wed, 7 Mar 2018 16:10:10 +0530 Subject: [PATCH 65/91] Bael 1532 (#3767) * Changes for BAEL1532 * Changes for BAEL_1532 * BAEL-1532-Added as module to parent project --- apache-zookeeper/pom.xml | 6 ++++++ pom.xml | 1 + 2 files changed, 7 insertions(+) diff --git a/apache-zookeeper/pom.xml b/apache-zookeeper/pom.xml index 6d49d74ade..3a6fc1787b 100644 --- a/apache-zookeeper/pom.xml +++ b/apache-zookeeper/pom.xml @@ -6,6 +6,12 @@ 0.0.1-SNAPSHOT jar + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + org.apache.zookeeper diff --git a/pom.xml b/pom.xml index 23f14a56a4..463f060240 100644 --- a/pom.xml +++ b/pom.xml @@ -40,6 +40,7 @@ apache-poi apache-thrift apache-curator + apache-zookeeper autovalue axon bootique From 52d257a5458a5b36c4ee984c3c64fc80b3af1bb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Mattos=20Torr=C3=A3o?= Date: Wed, 7 Mar 2018 09:13:24 -0300 Subject: [PATCH 66/91] fix: groovy dependency version (#3776) --- core-groovy/build.gradle | 2 +- core-groovy/pom.xml | 6 +++--- .../groovy/com/baeldung/json/JsonParser.groovy | 9 --------- .../groovy/com/baeldung/json/JsonParserTest.groovy | 14 -------------- 4 files changed, 4 insertions(+), 27 deletions(-) diff --git a/core-groovy/build.gradle b/core-groovy/build.gradle index b3f33836da..300827ee7c 100644 --- a/core-groovy/build.gradle +++ b/core-groovy/build.gradle @@ -8,6 +8,6 @@ repositories { } dependencies { - compile 'org.codehaus.groovy:groovy-all:2.5.0-alpha-1' + compile 'org.codehaus.groovy:groovy-all:2.4.13' testCompile 'org.spockframework:spock-core:1.1-groovy-2.4' } diff --git a/core-groovy/pom.xml b/core-groovy/pom.xml index 961a4ba125..91cbe66e35 100644 --- a/core-groovy/pom.xml +++ b/core-groovy/pom.xml @@ -23,17 +23,17 @@ org.codehaus.groovy groovy - 2.5.0-alpha-1 + 2.4.13 org.codehaus.groovy groovy-all - 2.5.0-alpha-1 + 2.4.13 org.codehaus.groovy groovy-sql - 2.5.0-alpha-1 + 2.4.13 org.junit.jupiter diff --git a/core-groovy/src/main/groovy/com/baeldung/json/JsonParser.groovy b/core-groovy/src/main/groovy/com/baeldung/json/JsonParser.groovy index 0d7c451972..6cda7c6fbd 100644 --- a/core-groovy/src/main/groovy/com/baeldung/json/JsonParser.groovy +++ b/core-groovy/src/main/groovy/com/baeldung/json/JsonParser.groovy @@ -1,6 +1,5 @@ package com.baeldung.json -import groovy.json.JsonGenerator import groovy.json.JsonOutput import groovy.json.JsonParserType import groovy.json.JsonSlurper @@ -21,14 +20,6 @@ class JsonParser { JsonOutput.toJson(account) } - String toJson(Account account, String dateFormat, String... fieldsToExclude) { - JsonGenerator generator = new JsonGenerator.Options() - .dateFormat(dateFormat) - .excludeFieldsByName(fieldsToExclude) - .build() - generator.toJson(account) - } - String prettyfy(String json) { JsonOutput.prettyPrint(json) } diff --git a/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy b/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy index fcd51d58bc..c3842340a5 100644 --- a/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy @@ -52,20 +52,6 @@ class JsonParserTest extends Specification { json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}' } - def 'Should parse to Json given an Account object, a date format and fields to exclude' () { - given: - Account account = new Account( - id: '123', - value: 15.6, - createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('01/01/2018') - ) - when: - def json = jsonParser.toJson(account, 'MM/dd/yyyy', 'value') - then: - json - json == '{"createdAt":"01/01/2018","id":"123"}' - } - def 'Should prettify given a json string' () { given: String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}' From 201092c2632c626e4c8655fc8da4ad1a949ba1f9 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 7 Mar 2018 14:59:06 +0200 Subject: [PATCH 67/91] advanced rest assured --- .../RestAssuredAdvancedLiveTest.java | 139 ++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredAdvancedLiveTest.java diff --git a/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredAdvancedLiveTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredAdvancedLiveTest.java new file mode 100644 index 0000000000..23fff6a129 --- /dev/null +++ b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredAdvancedLiveTest.java @@ -0,0 +1,139 @@ +package com.baeldung.restassured; + +import static io.restassured.RestAssured.given; +import static io.restassured.RestAssured.when; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.lessThan; +import static org.junit.Assert.assertEquals; +import io.restassured.RestAssured; +import io.restassured.http.Cookie; +import io.restassured.response.Response; + +import java.util.concurrent.TimeUnit; + +import org.junit.Before; +import org.junit.Test; + +public class RestAssuredAdvancedLiveTest { + + @Before + public void setup(){ + RestAssured.baseURI = "https://api.github.com"; + RestAssured.port = 443; + } + + @Test + public void whenMeasureResponseTime_thenOK(){ + Response response = RestAssured.get("/users/eugenp"); + long timeInMS = response.time(); + long timeInS = response.timeIn(TimeUnit.SECONDS); + + assertEquals(timeInS, timeInMS/1000); + } + + @Test + public void whenValidateResponseTime_thenSuccess(){ + when().get("/users/eugenp").then().time(lessThan(5000L)); + } + + @Test + public void whenValidateResponseTimeInSeconds_thenSuccess(){ + when().get("/users/eugenp").then().time(lessThan(5L),TimeUnit.SECONDS); + } + + //===== parameter + + @Test + public void whenUseQueryParam_thenOK(){ + given().queryParam("q", "john").when().get("/search/users").then().statusCode(200); + given().param("q", "john").when().get("/search/users").then().statusCode(200); + } + + @Test + public void whenUseMultipleQueryParam_thenOK(){ + int perPage = 20; + given().queryParam("q", "john").queryParam("per_page",perPage).when().get("/search/users").then().body("items.size()", is(perPage)); + given().queryParams("q", "john","per_page",perPage).when().get("/search/users").then().body("items.size()", is(perPage)); + } + + @Test + public void whenUseFormParam_thenSuccess(){ + given().log().all().formParams("username", "john","password","1234").post("/"); + given().log().all().params("username", "john","password","1234").post("/"); + } + + @Test + public void whenUsePathParam_thenOK(){ + given().pathParam("user", "eugenp").when().get("/users/{user}/repos").then().log().all().statusCode(200); + } + + @Test + public void whenUseMultiplePathParam_thenOK(){ + given().log().all().pathParams("owner", "eugenp","repo","tutorials").when().get("/repos/{owner}/{repo}").then().statusCode(200); + given().log().all().pathParams("owner", "eugenp").when().get("/repos/{owner}/{repo}","tutorials").then().statusCode(200); + } + + //===== header + + @Test + public void whenUseCustomHeader_thenOK(){ + given().header("User-Agent", "MyAppName").when().get("/users/eugenp").then().statusCode(200); + } + + @Test + public void whenUseMultipleHeaders_thenOK(){ + given().header("User-Agent", "MyAppName","Accept-Charset","utf-8").when().get("/users/eugenp").then().statusCode(200); + } + + //======= cookie + + @Test + public void whenUseCookie_thenOK(){ + given().cookie("session_id", "1234").when().get("/users/eugenp").then().statusCode(200); + } + + @Test + public void whenUseCookieBuilder_thenOK(){ + Cookie myCookie = new Cookie.Builder("session_id", "1234").setSecured(true).setComment("session id cookie").build(); + given().cookie(myCookie).when().get("/users/eugenp").then().statusCode(200); + } + + // ====== request + + @Test + public void whenRequestGet_thenOK(){ + when().request("GET", "/users/eugenp").then().statusCode(200); + } + + @Test + public void whenRequestHead_thenOK(){ + when().request("HEAD", "/users/eugenp").then().statusCode(200); + } + + //======= log + + @Test + public void whenLogRequest_thenOK(){ + given().log().all().when().get("/users/eugenp").then().statusCode(200); + } + + @Test + public void whenLogResponse_thenOK(){ + when().get("/repos/eugenp/tutorials").then().log().body().statusCode(200); + } + + @Test + public void whenLogResponseIfErrorOccurred_thenSuccess(){ + when().get("/users/eugenp").then().log().ifError(); + when().get("/users/eugenp").then().log().ifStatusCodeIsEqualTo(500); + when().get("/users/eugenp").then().log().ifStatusCodeMatches(greaterThan(200)); + } + + @Test + public void whenLogOnlyIfValidationFailed_thenSuccess(){ + when().get("/users/eugenp").then().log().ifValidationFails().statusCode(200); + given().log().ifValidationFails().when().get("/users/eugenp").then().statusCode(200); + } + +} From 4526bb6addba3a4c957dd9a027ca6e6f78440cd7 Mon Sep 17 00:00:00 2001 From: raghav-jha Date: Wed, 7 Mar 2018 21:29:50 +0530 Subject: [PATCH 68/91] BAEL-1586 Sum and Average in Java Array (#3718) * Evaluation Article * CR comments resolved * BAEL-1586 Find Sum and Average in Java Array * Revert "CR comments resolved" This reverts commit c9bf88fcd58773d3df34e2a6cb4db44c3b54777d. * Revert "Evaluation Article" This reverts commit 41ad30313ab2c454350b5accdee531dba80e7ea9. * BAEL-1586 Removed Author Description * BAEL-1586 Find Sum And Avergae In Array * remove excess whitespace --- .../baeldung/array/Find2ndLargestInArray.java | 20 +++++++++ .../baeldung/array/FindElementInArray.java | 22 ++++++++++ .../baeldung/array/SumAndAverageInArray.java | 27 ++++++++++++ .../array/Find2ndLargestInArrayTest.java | 16 ++++++++ .../array/FindElementInArrayTest.java | 35 ++++++++++++++++ .../array/SumAndAverageInArrayTest.java | 41 +++++++++++++++++++ 6 files changed, 161 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/array/Find2ndLargestInArray.java create mode 100644 core-java/src/main/java/com/baeldung/array/FindElementInArray.java create mode 100644 core-java/src/main/java/com/baeldung/array/SumAndAverageInArray.java create mode 100644 core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java create mode 100644 core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java create mode 100644 core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java diff --git a/core-java/src/main/java/com/baeldung/array/Find2ndLargestInArray.java b/core-java/src/main/java/com/baeldung/array/Find2ndLargestInArray.java new file mode 100644 index 0000000000..d424bd429f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/array/Find2ndLargestInArray.java @@ -0,0 +1,20 @@ +package com.baeldung.array; + +public class Find2ndLargestInArray { + + public static int find2ndLargestElement(int[] array) { + int maxElement = array[0]; + int secondLargestElement = -1; + + for (int index = 0; index < array.length; index++) { + if (maxElement <= array[index]) { + secondLargestElement = maxElement; + maxElement = array[index]; + } else if (secondLargestElement < array[index]) { + secondLargestElement = array[index]; + } + } + return secondLargestElement; + } + +} diff --git a/core-java/src/main/java/com/baeldung/array/FindElementInArray.java b/core-java/src/main/java/com/baeldung/array/FindElementInArray.java new file mode 100644 index 0000000000..6da889fe91 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/array/FindElementInArray.java @@ -0,0 +1,22 @@ +package com.baeldung.array; + +import java.util.Arrays; + +public class FindElementInArray { + + public static boolean findGivenElementInArrayWithoutUsingStream(int[] array, int element) { + boolean actualResult = false; + + for (int index = 0; index < array.length; index++) { + if (element == array[index]) { + actualResult = true; + break; + } + } + return actualResult; + } + + public static boolean findGivenElementInArrayUsingStream(int[] array, int element) { + return Arrays.stream(array).filter(x -> element == x).findFirst().isPresent(); + } +} diff --git a/core-java/src/main/java/com/baeldung/array/SumAndAverageInArray.java b/core-java/src/main/java/com/baeldung/array/SumAndAverageInArray.java new file mode 100644 index 0000000000..e7d7172fdb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/array/SumAndAverageInArray.java @@ -0,0 +1,27 @@ +package com.baeldung.array; + +import java.util.Arrays; + +public class SumAndAverageInArray { + + public static int findSumWithoutUsingStream(int[] array) { + int sum = 0; + for (int index = 0; index < array.length; index++) { + sum += array[index]; + } + return sum; + } + + public static int findSumUsingStream(int[] array) { + return Arrays.stream(array).sum(); + } + + public static double findAverageWithoutUsingStream(int[] array) { + int sum = findSumWithoutUsingStream(array); + return (double) sum / array.length; + } + + public static double findAverageUsingStream(int[] array) { + return Arrays.stream(array).average().getAsDouble(); + } +} diff --git a/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java b/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java new file mode 100644 index 0000000000..ec916af092 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java @@ -0,0 +1,16 @@ +package com.baeldung.array; + +import org.junit.Assert; +import org.junit.Test; + +public class Find2ndLargestInArrayTest { + @Test + public void givenAnIntArray_thenFind2ndLargestElement() { + int[] array = { 1, 3, 24, 16, 87, 20 }; + int expected2ndLargest = 24; + + int actualSecondLargestElement = Find2ndLargestInArray.find2ndLargestElement(array); + + Assert.assertEquals(expected2ndLargest, actualSecondLargestElement); + } +} diff --git a/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java b/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java new file mode 100644 index 0000000000..ba9188fa7b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java @@ -0,0 +1,35 @@ +package com.baeldung.array; + +import org.junit.Assert; +import org.junit.Test; + +public class FindElementInArrayTest { + @Test + public void givenAnIntArray_whenNotUsingStream_thenFindAnElement() { + int[] array = { 1, 3, 4, 8, 19, 20 }; + int element = 19; + boolean expectedResult = true; + boolean actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element); + Assert.assertEquals(expectedResult, actualResult); + + element = 78; + expectedResult = false; + actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element); + Assert.assertEquals(expectedResult, actualResult); + } + + @Test + public void givenAnIntArray_whenUsingStream_thenFindAnElement() { + int[] array = { 15, 16, 12, 18 }; + int element = 16; + boolean expectedResult = true; + boolean actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element); + Assert.assertEquals(expectedResult, actualResult); + + element = 20; + expectedResult = false; + actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element); + Assert.assertEquals(expectedResult, actualResult); + } + +} diff --git a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java new file mode 100644 index 0000000000..3385ed690f --- /dev/null +++ b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java @@ -0,0 +1,41 @@ +package com.baeldung.array; + +import org.junit.Assert; +import org.junit.Test; + +public class SumAndAverageInArrayTest { + @Test + public void givenAnIntArray_whenNotUsingStream_thenFindSum() { + int[] array = { 1, 3, 4, 8, 19, 20 }; + int expectedSumOfArray = 55; + int actualSumOfArray = SumAndAverageInArray.findSumWithoutUsingStream(array); + Assert.assertEquals(expectedSumOfArray, actualSumOfArray); + } + + @Test + public void givenAnIntArray_whenUsingStream_thenFindSum() { + int[] array = { 1, 3, 4, 8, 19, 20 }; + int expectedSumOfArray = 55; + int actualSumOfArray = SumAndAverageInArray.findSumUsingStream(array); + + Assert.assertEquals(expectedSumOfArray, actualSumOfArray); + } + + @Test + public void givenAnIntArray_whenNotUsingStream_thenFindAverage() { + int[] array = { 1, 3, 4, 8, 19, 20 }; + double expectedAvgOfArray = 9.17; + double actualAvgOfArray = SumAndAverageInArray.findAverageWithoutUsingStream(array); + + Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034); + } + + @Test + public void givenAnIntArray_whenUsingStream_thenFindAverage() { + int[] array = { 1, 3, 4, 8, 19, 20 }; + double expectedAvgOfArray = 9.17; + double actualAvgOfArray = SumAndAverageInArray.findAverageUsingStream(array); + + Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034); + } +} From 67092ccc494ce985e78f047a2ca8af133255e282 Mon Sep 17 00:00:00 2001 From: Juan Moreno Date: Thu, 8 Mar 2018 08:31:06 -0300 Subject: [PATCH 69/91] BAEL-1159 - Added sample with null fields (#3756) * Squashed commit of the following: commit b31955df9638a6217a804e61faa230d8eacb293b Author: Juan Moreno Date: Wed Feb 21 22:45:52 2018 -0300 Sample code for BAEL-1159 - Working with Kotlin and JPA - earth001@gmail.com * Squashed commit of the following: commit 4e6e27c914a401ee6bc599c7ffe913384137646a Author: Juan Moreno Date: Wed Feb 21 23:26:20 2018 -0300 Fix package names commit b31955df9638a6217a804e61faa230d8eacb293b Author: Juan Moreno Date: Wed Feb 21 22:45:52 2018 -0300 Sample code for BAEL-1159 - Working with Kotlin and JPA - earth001@gmail.com * Added sample with null fields * Removed unused dependency --- spring-mvc-kotlin/pom.xml | 2 +- .../kotlin/com/baeldung/kotlin/jpa/Person.kt | 13 ++++++++++-- .../com/baeldung/kotlin/jpa/PhoneNumber.kt | 17 ++++++++++++++++ .../jpa/HibernateKotlinIntegrationTest.kt | 20 ++++++++++++++----- 4 files changed, 44 insertions(+), 8 deletions(-) create mode 100644 spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/PhoneNumber.kt diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml index 28a5681c03..8f9c58854d 100644 --- a/spring-mvc-kotlin/pom.xml +++ b/spring-mvc-kotlin/pom.xml @@ -20,7 +20,7 @@ UTF-8 5.2.13.Final - 1.2.21 + 1.2.30 4.3.10.RELEASE 3.0.7.RELEASE 1.4.196 diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/Person.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/Person.kt index 801bd1b0a5..076dcdac46 100644 --- a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/Person.kt +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/Person.kt @@ -1,15 +1,24 @@ package com.baeldung.jpa +import javax.persistence.CascadeType +import javax.persistence.Column import javax.persistence.Entity +import javax.persistence.FetchType import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id +import javax.persistence.OneToMany import javax.persistence.Table @Entity @Table(name = "person") data class Person( @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Int, - val name: String) \ No newline at end of file + @Column(nullable = false) + val name: String, + @Column(nullable = true) + val email: String?, + @Column(nullable = true) + @OneToMany(fetch = FetchType.LAZY, cascade = [CascadeType.ALL]) val phoneNumbers: List?) \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/PhoneNumber.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/PhoneNumber.kt new file mode 100644 index 0000000000..25894275f6 --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/PhoneNumber.kt @@ -0,0 +1,17 @@ +package com.baeldung.jpa + +import javax.persistence.Column +import javax.persistence.Entity +import javax.persistence.GeneratedValue +import javax.persistence.GenerationType +import javax.persistence.Id +import javax.persistence.Table + +@Entity +@Table(name = "phone_number") +data class PhoneNumber( + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + val id: Int, + @Column(nullable = false) + val number: String) \ No newline at end of file diff --git a/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/jpa/HibernateKotlinIntegrationTest.kt b/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/jpa/HibernateKotlinIntegrationTest.kt index 8f54373406..94559812fa 100644 --- a/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/jpa/HibernateKotlinIntegrationTest.kt +++ b/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/jpa/HibernateKotlinIntegrationTest.kt @@ -1,6 +1,7 @@ package com.baeldung.kotlin.jpa import com.baeldung.jpa.Person +import com.baeldung.jpa.PhoneNumber import org.hibernate.cfg.Configuration import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase import org.hibernate.testing.transaction.TransactionUtil.doInHibernate @@ -21,7 +22,7 @@ class HibernateKotlinIntegrationTest : BaseCoreFunctionalTestCase() { } override fun getAnnotatedClasses(): Array> { - return arrayOf(Person::class.java) + return arrayOf(Person::class.java, PhoneNumber::class.java) } override fun configure(configuration: Configuration) { @@ -31,13 +32,22 @@ class HibernateKotlinIntegrationTest : BaseCoreFunctionalTestCase() { @Test fun givenPerson_whenSaved_thenFound() { - val personToSave = Person(0, "John") doInHibernate(({ this.sessionFactory() }), { session -> + val personToSave = Person(0, "John", "jhon@test.com", Arrays.asList(PhoneNumber(0, "202-555-0171"), PhoneNumber(0, "202-555-0102"))) session.persist(personToSave) - assertTrue(session.contains(personToSave)) - }) - doInHibernate(({ this.sessionFactory() }), { session -> val personFound = session.find(Person::class.java, personToSave.id) + session.refresh(personFound) + assertTrue(personToSave == personFound) + }) + } + + @Test + fun givenPersonWithNullFields_whenSaved_thenFound() { + doInHibernate(({ this.sessionFactory() }), { session -> + val personToSave = Person(0, "John", null, null) + session.persist(personToSave) + val personFound = session.find(Person::class.java, personToSave.id) + session.refresh(personFound) assertTrue(personToSave == personFound) }) } From 00c022388fcc884c18cf068e17afdbaaf1d9c757 Mon Sep 17 00:00:00 2001 From: Tarang Bhalodia Date: Thu, 8 Mar 2018 20:15:48 +0530 Subject: [PATCH 70/91] BAEL-1524: Chain of Responsibility Design Pattern in Java (#3780) * BAEL-1422: measure performance of Random and ThreadLocalRandom using JMH * BAEL-1422: updated benchmarking examples of Random and ThreadLocalRandom to use newWorkStealingPool that leverages ForkJoinPool * BAEL-1422: refactored benchmarking examples for comparing performance of ThreadLocalRandom and Random - initialised the collection of Callable before running benchmarking - removed for loop for submitting task and instead used executor.invokeAll(collection_of_callable) * BAEL-1282: added TDD type junit tests for geospatial queries elasticsearch * BAEL-1524: added example for chain of responsibility design pattern * BAEL-1524: added BDD style jUnit test to test unknown handler in ChainOfResponsibility design pattern * BAEL-1524: refactored ChainOfResponsibility design pattern example * BAEL-1524: refactored ChainOfResponsibility design pattern example * BAEL-1524: updated ChainOfResponsibility design pattern example * BAEL-1524: updated ChainOfResponsibility design pattern example * BAEL-1524: moved chain of responsibility example from core-java module to patterns module --- .../chainofresponsibility/AuthenticationProvider.java | 5 ----- .../chainofresponsibility/AuthenticationProcessor.java | 2 +- .../chainofresponsibility/AuthenticationProvider.java | 5 +++++ .../chainofresponsibility/OAuthAuthenticationProcessor.java | 2 +- .../pattern}/chainofresponsibility/OAuthTokenProvider.java | 2 +- .../chainofresponsibility/SamlAuthenticationProvider.java | 2 +- .../UsernamePasswordAuthenticationProcessor.java | 2 +- .../chainofresponsibility/UsernamePasswordProvider.java | 2 +- .../chainofresponsibility/ChainOfResponsibilityTest.java | 2 +- 9 files changed, 12 insertions(+), 12 deletions(-) delete mode 100644 core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/AuthenticationProvider.java rename {core-java/src/main/java/com/baeldung/designpatterns => patterns/behavioral-patterns/src/main/java/com/baeldung/pattern}/chainofresponsibility/AuthenticationProcessor.java (85%) create mode 100644 patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/AuthenticationProvider.java rename {core-java/src/main/java/com/baeldung/designpatterns => patterns/behavioral-patterns/src/main/java/com/baeldung/pattern}/chainofresponsibility/OAuthAuthenticationProcessor.java (90%) rename {core-java/src/main/java/com/baeldung/designpatterns => patterns/behavioral-patterns/src/main/java/com/baeldung/pattern}/chainofresponsibility/OAuthTokenProvider.java (54%) rename {core-java/src/main/java/com/baeldung/designpatterns => patterns/behavioral-patterns/src/main/java/com/baeldung/pattern}/chainofresponsibility/SamlAuthenticationProvider.java (57%) rename {core-java/src/main/java/com/baeldung/designpatterns => patterns/behavioral-patterns/src/main/java/com/baeldung/pattern}/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java (90%) rename {core-java/src/main/java/com/baeldung/designpatterns => patterns/behavioral-patterns/src/main/java/com/baeldung/pattern}/chainofresponsibility/UsernamePasswordProvider.java (56%) rename {core-java/src/test/java/com/baeldung/designpatterns => patterns/behavioral-patterns/src/test/java/com/baeldung/pattern}/chainofresponsibility/ChainOfResponsibilityTest.java (95%) diff --git a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/AuthenticationProvider.java b/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/AuthenticationProvider.java deleted file mode 100644 index 552a7ff6d9..0000000000 --- a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/AuthenticationProvider.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.designpatterns.chainofresponsibility; - -public interface AuthenticationProvider { - -} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/AuthenticationProcessor.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/AuthenticationProcessor.java similarity index 85% rename from core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/AuthenticationProcessor.java rename to patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/AuthenticationProcessor.java index b86a572393..374de31ba9 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/AuthenticationProcessor.java +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/AuthenticationProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.designpatterns.chainofresponsibility; +package com.baeldung.pattern.chainofresponsibility; public abstract class AuthenticationProcessor { diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/AuthenticationProvider.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/AuthenticationProvider.java new file mode 100644 index 0000000000..7b8771ca41 --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/AuthenticationProvider.java @@ -0,0 +1,5 @@ +package com.baeldung.pattern.chainofresponsibility; + +public interface AuthenticationProvider { + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/OAuthAuthenticationProcessor.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/OAuthAuthenticationProcessor.java similarity index 90% rename from core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/OAuthAuthenticationProcessor.java rename to patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/OAuthAuthenticationProcessor.java index 2e2e51fed2..3bf20cfc85 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/OAuthAuthenticationProcessor.java +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/OAuthAuthenticationProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.designpatterns.chainofresponsibility; +package com.baeldung.pattern.chainofresponsibility; public class OAuthAuthenticationProcessor extends AuthenticationProcessor { diff --git a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/OAuthTokenProvider.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/OAuthTokenProvider.java similarity index 54% rename from core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/OAuthTokenProvider.java rename to patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/OAuthTokenProvider.java index d4e516053b..92d5f94245 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/OAuthTokenProvider.java +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/OAuthTokenProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.designpatterns.chainofresponsibility; +package com.baeldung.pattern.chainofresponsibility; public class OAuthTokenProvider implements AuthenticationProvider { diff --git a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/SamlAuthenticationProvider.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/SamlAuthenticationProvider.java similarity index 57% rename from core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/SamlAuthenticationProvider.java rename to patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/SamlAuthenticationProvider.java index 533b2b4a2d..cd927932ad 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/SamlAuthenticationProvider.java +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/SamlAuthenticationProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.designpatterns.chainofresponsibility; +package com.baeldung.pattern.chainofresponsibility; public class SamlAuthenticationProvider implements AuthenticationProvider { diff --git a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java similarity index 90% rename from core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java rename to patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java index df600c35db..3885b2b79b 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.designpatterns.chainofresponsibility; +package com.baeldung.pattern.chainofresponsibility; public class UsernamePasswordAuthenticationProcessor extends AuthenticationProcessor { diff --git a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/UsernamePasswordProvider.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/UsernamePasswordProvider.java similarity index 56% rename from core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/UsernamePasswordProvider.java rename to patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/UsernamePasswordProvider.java index 9fbfa7554d..9877039446 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/UsernamePasswordProvider.java +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/chainofresponsibility/UsernamePasswordProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.designpatterns.chainofresponsibility; +package com.baeldung.pattern.chainofresponsibility; public class UsernamePasswordProvider implements AuthenticationProvider { diff --git a/core-java/src/test/java/com/baeldung/designpatterns/chainofresponsibility/ChainOfResponsibilityTest.java b/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/chainofresponsibility/ChainOfResponsibilityTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/designpatterns/chainofresponsibility/ChainOfResponsibilityTest.java rename to patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/chainofresponsibility/ChainOfResponsibilityTest.java index a28577efb1..a84f9dd8e5 100644 --- a/core-java/src/test/java/com/baeldung/designpatterns/chainofresponsibility/ChainOfResponsibilityTest.java +++ b/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/chainofresponsibility/ChainOfResponsibilityTest.java @@ -1,4 +1,4 @@ -package com.baeldung.designpatterns.chainofresponsibility; +package com.baeldung.pattern.chainofresponsibility; import org.junit.Test; From 36a7ed48af932270f820049aca5b5ba8a6b9cfdb Mon Sep 17 00:00:00 2001 From: Alessio Stalla Date: Thu, 8 Mar 2018 18:57:30 +0100 Subject: [PATCH 71/91] BAEL-1573 Code for the article: a guide to Jdbi (#3785) --- persistence-modules/java-jdbi/README.md | 2 + persistence-modules/java-jdbi/pom.xml | 40 +++ .../baeldung/persistence/jdbi/JdbiTest.java | 338 ++++++++++++++++++ pom.xml | 1 + 4 files changed, 381 insertions(+) create mode 100644 persistence-modules/java-jdbi/README.md create mode 100644 persistence-modules/java-jdbi/pom.xml create mode 100644 persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiTest.java diff --git a/persistence-modules/java-jdbi/README.md b/persistence-modules/java-jdbi/README.md new file mode 100644 index 0000000000..3bab6faa29 --- /dev/null +++ b/persistence-modules/java-jdbi/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Guide to CockroachDB in Java](http://www.baeldung.com/cockroachdb-java) diff --git a/persistence-modules/java-jdbi/pom.xml b/persistence-modules/java-jdbi/pom.xml new file mode 100644 index 0000000000..392f0bdcbf --- /dev/null +++ b/persistence-modules/java-jdbi/pom.xml @@ -0,0 +1,40 @@ + + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + ../../ + + + 4.0.0 + + java-jdbi + 1.0-SNAPSHOT + + + + org.jdbi + jdbi3-core + 3.1.0 + + + org.hsqldb + hsqldb + 2.4.0 + test + + + + + + Central + Central + http://repo1.maven.org/maven2/ + default + + + \ No newline at end of file diff --git a/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiTest.java b/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiTest.java new file mode 100644 index 0000000000..503bf90fdb --- /dev/null +++ b/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiTest.java @@ -0,0 +1,338 @@ +package com.baeldung.persistence.jdbi; + +import org.jdbi.v3.core.Handle; +import org.jdbi.v3.core.Jdbi; +import org.jdbi.v3.core.result.ResultBearing; +import org.jdbi.v3.core.result.ResultProducer; +import org.jdbi.v3.core.statement.Query; +import org.jdbi.v3.core.statement.StatementContext; +import org.jdbi.v3.core.statement.Update; +import org.junit.Test; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.*; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import static org.junit.Assert.*; + +public class JdbiTest { + + @Test + public void whenJdbiCreated_thenSuccess() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + + Jdbi.create("WRONG"); + } + + @Test + public void whenJdbiWithProperties_thenSuccess() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.open().close(); + Properties properties = new Properties(); + properties.setProperty("username", "sa"); + properties.setProperty("password", ""); + jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", properties); + jdbi.open().close(); + } + + @Test + public void whenHandle_thenBoh() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + final Handle[] handleRef = new Handle[1]; + boolean closed = jdbi.withHandle(handle -> { + handleRef[0] = handle; + return handle.isClosed(); + }); + + assertFalse(closed); + assertTrue(handleRef[0].isClosed()); + } + + @Test + public void whenTableCreated_thenInsertIsPossible() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + int updateCount = handle.execute("create table PROJECT_1 (id integer identity, name varchar(50), url varchar(100))"); + + assertEquals(0, updateCount); + + updateCount = handle.execute("INSERT INTO PROJECT_1 VALUES (1, 'tutorials', 'github.com/eugenp/tutorials')"); + + assertEquals(1, updateCount); + }); + } + + @Test + public void whenIdentityColumn_thenInsertReturnsNewId() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + Update update = handle.createUpdate( + "INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); + ResultBearing generatedKeys = update.executeAndReturnGeneratedKeys(); + + assertEquals(0, generatedKeys.mapToMap().findOnly().get("id")); + + update = handle.createUpdate( + "INSERT INTO PROJECT_2 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); + + assertEquals(1, generatedKeys.mapToMap().findOnly().get("id")); + }); + } + + @Test + public void whenSelectMapToMap_thenResultsAreMapEntries() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); + Query query = handle.createQuery("select * from PROJECT_3 order by id"); + List> list = query.mapToMap().list(); + + assertEquals("tutorials", list.get(0).get("name")); + assertEquals("REST with Spring", list.get(1).get("name")); + }); + } + + @Test + public void whenSelectMapToString_thenResultIsString() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); + Query query = handle.createQuery("select name, url from PROJECT_4 order by id"); + List list = query.mapTo(String.class).list(); + + assertEquals("tutorials", list.get(0)); + assertEquals("REST with Spring", list.get(1)); + }); + } + + @Test + public void whenSelectMapToString_thenStream() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); + Query query = handle.createQuery("select name, url from PROJECT_5 order by id"); + query.mapTo(String.class).useStream((Stream stream) -> assertEquals("tutorials", stream.findFirst().get())); + }); + } + + @Test + public void whenNoResults_thenFindFirstReturnsNone() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + + assertFalse(handle.createQuery("select * from project_6").mapToMap().findFirst().isPresent()); + }); + } + + @Test + public void whenMultipleResults_thenFindFirstReturnsFirst() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_7 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_7 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_7 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); + + Query query = handle.createQuery("select * from project_7 order by id"); + Optional> first = query.mapToMap().findFirst(); + + assertTrue(first.isPresent()); + assertEquals("tutorials", first.get().get("name")); + }); + } + + @Test + public void whenNoResults_thenFindOnlyThrows() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_8 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + + try { + handle.createQuery("select * from project_8").mapToMap().findOnly(); + + fail("Exception expected"); + } catch (Exception e) { + e.printStackTrace(); + } + }); + } + + @Test + public void whenMultipleResults_thenFindOnlyThrows() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_9 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')"); + + try { + Query query = handle.createQuery("select * from project_9"); + Map onlyResult = query.mapToMap().findOnly(); + + fail("Exception expected"); + } catch (Exception e) { + e.printStackTrace(); + } + }); + } + + @Test + public void whenParameters_thenReplacement() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + Update update1 = handle.createUpdate("INSERT INTO PROJECT_10 (NAME, URL) VALUES (?, ?)"); + update1.bind(0, "tutorials"); + update1.bind(1, "github.com/eugenp/tutorials"); + int rows = update1.execute(); + + assertEquals(1, rows); + + Update update2 = handle.createUpdate("INSERT INTO PROJECT_10 (NAME, URL) VALUES (:name, :url)"); + update2.bind("name", "REST with Spring"); + update2.bind("url", "github.com/eugenp/REST-With-Spring"); + rows = update2.execute(); + + assertEquals(1, rows); + + List> list = + handle.select("SELECT * FROM PROJECT_10 WHERE NAME = 'tutorials'").mapToMap().list(); + + assertEquals(1, list.size()); + + list = handle.select("SELECT * FROM PROJECT_10 WHERE NAME = 'REST with Spring'").mapToMap().list(); + + assertEquals(1, list.size()); + }); + } + + @Test + public void whenMultipleParameters_thenReplacement() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.execute("create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + Update update = handle.createUpdate("INSERT INTO PROJECT_11 (NAME, URL) VALUES (:name, :url)"); + Map params = new HashMap<>(); + params.put("name", "REST with Spring"); + params.put("url", "github.com/eugenp/REST-With-Spring"); + update.bindMap(params); + int rows = update.execute(); + + assertEquals(1, rows); + + List> list = + handle.select("SELECT * FROM PROJECT_11").mapToMap().list(); + + assertEquals(1, list.size()); + + class Params { + private String name; + private String url; + + public Params(String name, String url) { + this.name = name; + this.url = url; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + } + + update.bindBean(new Params("tutorials", "github.com/eugenp/tutorials")); + rows = update.execute(); + + assertEquals(1, rows); + + list = handle.select("SELECT * FROM PROJECT_11").mapToMap().list(); + + assertEquals(2, list.size()); + }); + } + + @Test + public void whenTransactionRollback_thenNoDataInserted() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.useTransaction(h -> { + handle.execute("create table PROJECT_12 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')"); + handle.rollback(); + List> list = handle.select("SELECT * FROM PROJECT_12").mapToMap().list(); + + assertEquals(0, list.size()); + }); + }); + } + + @Test + public void whenTransactionRollbackThenCommit_thenOnlyLastInserted() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + handle.useTransaction((Handle h) -> { + assertEquals(handle, h); + + handle.execute("create table PROJECT_13 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + handle.execute("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')"); + handle.rollback(); + handle.begin(); + handle.execute("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')"); + handle.rollback(); + handle.begin(); + handle.execute("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')"); + handle.execute("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')"); + handle.commit(); + }); + List> list = handle.select("SELECT * FROM PROJECT_13").mapToMap().list(); + + assertEquals(2, list.size()); + }); + } + + + @Test + public void whenException_thenTransactionIsRolledBack() { + Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", ""); + jdbi.useHandle(handle -> { + try { + handle.useTransaction(h -> { + h.execute("create table PROJECT_14 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))"); + h.execute("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')"); + List> list = handle.select("SELECT * FROM PROJECT_14").mapToMap().list(); + + assertTrue(h.isInTransaction()); + assertEquals(1, list.size()); + + throw new Exception("rollback"); + }); + } catch (Exception ignored) {} + List> list = handle.select("SELECT * FROM PROJECT_14").mapToMap().list(); + + assertFalse(handle.isInTransaction()); + assertEquals(0, list.size()); + }); + } + +} diff --git a/pom.xml b/pom.xml index 463f060240..70a3bbc5b4 100644 --- a/pom.xml +++ b/pom.xml @@ -280,6 +280,7 @@ lucene vraptor persistence-modules/java-cockroachdb + persistence-modules/java-jdbi jersey java-spi From 71ec77b6d50cb14189a03269f2e880b3b1853c1f Mon Sep 17 00:00:00 2001 From: Jose Carvajal Date: Fri, 9 Mar 2018 00:31:49 +0100 Subject: [PATCH 72/91] BAEL-1108 Added awailability (#3788) * BAEL-399: A Guide to Multitenancy in Hibernate 5 * Removed unused properties in profile 2 * Changes after code review * BAEL-1108 * Fixed tests and renamed test names * BAEL-1108 Formatting * Added awailability --- apache-curator/pom.xml | 8 +++ .../ConfigurationManagementManualTest.java | 71 ++++++++----------- .../ConnectionManagementManualTest.java | 58 ++++++++------- .../modeled/ModelTypedExamplesManualTest.java | 32 +++++---- 4 files changed, 90 insertions(+), 79 deletions(-) diff --git a/apache-curator/pom.xml b/apache-curator/pom.xml index 36c3949b1a..35549861c8 100644 --- a/apache-curator/pom.xml +++ b/apache-curator/pom.xml @@ -18,6 +18,7 @@ 3.6.1 + 1.7.0 @@ -64,5 +65,12 @@ ${assertj.version} test + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java index 0475f9c237..d02ef8131d 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java @@ -1,5 +1,6 @@ package com.baeldung.apache.curator.configuration; +import static com.jayway.awaitility.Awaitility.await; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; @@ -26,30 +27,27 @@ public class ConfigurationManagementManualTest extends BaseTest { String expected = "my_value"; // Create key nodes structure - client - .create() - .forPath(key); + client.create() + .forPath(key); // Set data value for our key - async - .setData() - .forPath(key, expected.getBytes()); + async.setData() + .forPath(key, expected.getBytes()); // Get data value AtomicBoolean isEquals = new AtomicBoolean(); - async - .getData() - .forPath(key) - .thenAccept(data -> isEquals.set(new String(data).equals(expected))); + async.getData() + .forPath(key) + .thenAccept( + data -> isEquals.set(new String(data).equals(expected))); - Thread.sleep(1000); - - assertThat(isEquals.get()).isTrue(); + await().until(() -> assertThat(isEquals.get()).isTrue()); } } @Test - public void givenPath_whenWatchAKeyAndStoreAValue_thenWatcherIsTriggered() throws Exception { + public void givenPath_whenWatchAKeyAndStoreAValue_thenWatcherIsTriggered() + throws Exception { try (CuratorFramework client = newClient()) { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); @@ -57,42 +55,35 @@ public class ConfigurationManagementManualTest extends BaseTest { String expected = "my_value"; // Create key structure - async - .create() - .forPath(key); + async.create() + .forPath(key); List changes = new ArrayList<>(); // Watch data value - async - .watched() - .getData() - .forPath(key) - .event() - .thenAccept(watchedEvent -> { - try { - changes.add(new String(client - .getData() - .forPath(watchedEvent.getPath()))); - } catch (Exception e) { - // fail ... - } - }); + async.watched() + .getData() + .forPath(key) + .event() + .thenAccept(watchedEvent -> { + try { + changes.add(new String(client.getData() + .forPath(watchedEvent.getPath()))); + } catch (Exception e) { + // fail ... + } + }); // Set data value for our key - async - .setData() - .forPath(key, expected.getBytes()); + async.setData() + .forPath(key, expected.getBytes()); - Thread.sleep(1000); - - assertThat(changes.size() > 0).isTrue(); + await().until(() -> assertThat(changes.size() > 0).isTrue()); } } private String getKey() { - return String.format(KEY_FORMAT, UUID - .randomUUID() - .toString()); + return String.format(KEY_FORMAT, UUID.randomUUID() + .toString()); } } diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/connection/ConnectionManagementManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/connection/ConnectionManagementManualTest.java index 931a977900..61fa1c7c2c 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/connection/ConnectionManagementManualTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/connection/ConnectionManagementManualTest.java @@ -1,5 +1,6 @@ package com.baeldung.apache.curator.connection; +import static com.jayway.awaitility.Awaitility.await; import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.atomic.AtomicBoolean; @@ -14,56 +15,65 @@ import org.junit.Test; public class ConnectionManagementManualTest { @Test - public void givenRunningZookeeper_whenOpenConnection_thenClientIsOpened() throws Exception { + public void givenRunningZookeeper_whenOpenConnection_thenClientIsOpened() + throws Exception { int sleepMsBetweenRetries = 100; int maxRetries = 3; - RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries); + RetryPolicy retryPolicy = new RetryNTimes(maxRetries, + sleepMsBetweenRetries); - try (CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy)) { + try (CuratorFramework client = CuratorFrameworkFactory + .newClient("127.0.0.1:2181", retryPolicy)) { client.start(); - assertThat(client - .checkExists() - .forPath("/")).isNotNull(); + + assertThat(client.checkExists() + .forPath("/")).isNotNull(); } } @Test - public void givenRunningZookeeper_whenOpenConnectionUsingAsyncNotBlocking_thenClientIsOpened() throws InterruptedException { + public void givenRunningZookeeper_whenOpenConnectionUsingAsyncNotBlocking_thenClientIsOpened() + throws InterruptedException { int sleepMsBetweenRetries = 100; int maxRetries = 3; - RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries); + RetryPolicy retryPolicy = new RetryNTimes(maxRetries, + sleepMsBetweenRetries); - try (CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy)) { + try (CuratorFramework client = CuratorFrameworkFactory + .newClient("127.0.0.1:2181", retryPolicy)) { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); AtomicBoolean exists = new AtomicBoolean(false); - async - .checkExists() - .forPath("/") - .thenAcceptAsync(s -> exists.set(s != null)); - Thread.sleep(100); - assertThat(exists.get()).isTrue(); + + async.checkExists() + .forPath("/") + .thenAcceptAsync(s -> exists.set(s != null)); + + await().until(() -> assertThat(exists.get()).isTrue()); } } @Test - public void givenRunningZookeeper_whenOpenConnectionUsingAsyncBlocking_thenClientIsOpened() throws InterruptedException { + public void givenRunningZookeeper_whenOpenConnectionUsingAsyncBlocking_thenClientIsOpened() + throws InterruptedException { int sleepMsBetweenRetries = 100; int maxRetries = 3; - RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries); + RetryPolicy retryPolicy = new RetryNTimes(maxRetries, + sleepMsBetweenRetries); - try (CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy)) { + try (CuratorFramework client = CuratorFrameworkFactory + .newClient("127.0.0.1:2181", retryPolicy)) { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); AtomicBoolean exists = new AtomicBoolean(false); - async - .checkExists() - .forPath("/") - .thenAccept(s -> exists.set(s != null)); - Thread.sleep(100); - assertThat(exists.get()).isTrue(); + + async.checkExists() + .forPath("/") + .thenAccept(s -> exists.set(s != null)); + + await().until(() -> assertThat(exists.get()).isTrue()); } } } diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java index 9d00c0a4c2..4400c1d1aa 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java @@ -16,31 +16,33 @@ import com.baeldung.apache.curator.BaseTest; public class ModelTypedExamplesManualTest extends BaseTest { @Test - public void givenPath_whenStoreAModel_thenNodesAreCreated() throws InterruptedException { + public void givenPath_whenStoreAModel_thenNodesAreCreated() + throws InterruptedException { ModelSpec mySpec = ModelSpec - .builder(ZPath.parseWithIds("/config/dev"), JacksonModelSerializer.build(HostConfig.class)) - .build(); + .builder(ZPath.parseWithIds("/config/dev"), + JacksonModelSerializer.build(HostConfig.class)) + .build(); try (CuratorFramework client = newClient()) { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - ModeledFramework modeledClient = ModeledFramework.wrap(async, mySpec); + ModeledFramework modeledClient = ModeledFramework + .wrap(async, mySpec); modeledClient.set(new HostConfig("host-name", 8080)); - modeledClient - .read() - .whenComplete((value, e) -> { - if (e != null) { - fail("Cannot read host config", e); - } else { - assertThat(value).isNotNull(); - assertThat(value.getHostname()).isEqualTo("host-name"); - assertThat(value.getPort()).isEqualTo(8080); - } + modeledClient.read() + .whenComplete((value, e) -> { + if (e != null) { + fail("Cannot read host config", e); + } else { + assertThat(value).isNotNull(); + assertThat(value.getHostname()).isEqualTo("host-name"); + assertThat(value.getPort()).isEqualTo(8080); + } - }); + }); } } From 00b3a5148e7194a2d02bb3fe3866e76125a63162 Mon Sep 17 00:00:00 2001 From: felipeazv Date: Fri, 9 Mar 2018 13:46:02 +0100 Subject: [PATCH 73/91] [BAEL-1449] Combining Publishers: increase delay time (#3795) --- .../reactor/core/CombiningPublishersTest.java | 56 +++++++++---------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersTest.java b/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersTest.java index 81dfda3bb3..41769b1b35 100644 --- a/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersTest.java +++ b/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersTest.java @@ -15,28 +15,28 @@ public class CombiningPublishersTest { private static Flux evenNumbers = Flux.range(min, max).filter(x -> x % 2 == 0); private static Flux oddNumbers = Flux.range(min, max).filter(x -> x % 2 > 0); - @Test - public void givenFluxes_whenMergeIsInvoked_thenMerge() { - Flux fluxOfIntegers = Flux.merge( - evenNumbers, - oddNumbers); + public void givenFluxes_whenMergeDelayErrorIsInvoked_thenMergeDelayError() { + Flux fluxOfIntegers = Flux.mergeDelayError(1, + evenNumbers.delayElements(Duration.ofMillis(2000L)), + oddNumbers.delayElements(Duration.ofMillis(1000L))); StepVerifier.create(fluxOfIntegers) - .expectNext(2) - .expectNext(4) .expectNext(1) + .expectNext(2) .expectNext(3) .expectNext(5) + .expectNext(4) .expectComplete() .verify(); } + @Test public void givenFluxes_whenMergeWithDelayedElementsIsInvoked_thenMergeWithDelayedElements() { Flux fluxOfIntegers = Flux.merge( - evenNumbers.delayElements(Duration.ofMillis(500L)), - oddNumbers.delayElements(Duration.ofMillis(300L))); + evenNumbers.delayElements(Duration.ofMillis(2000L)), + oddNumbers.delayElements(Duration.ofMillis(1000L))); StepVerifier.create(fluxOfIntegers) .expectNext(1) @@ -51,8 +51,24 @@ public class CombiningPublishersTest { @Test public void givenFluxes_whenConcatIsInvoked_thenConcat() { Flux fluxOfIntegers = Flux.concat( - evenNumbers.delayElements(Duration.ofMillis(500L)), - oddNumbers.delayElements(Duration.ofMillis(300L))); + evenNumbers.delayElements(Duration.ofMillis(2000L)), + oddNumbers.delayElements(Duration.ofMillis(1000L))); + + StepVerifier.create(fluxOfIntegers) + .expectNext(2) + .expectNext(4) + .expectNext(1) + .expectNext(3) + .expectNext(5) + .expectComplete() + .verify(); + } + + @Test + public void givenFluxes_whenMergeIsInvoked_thenMerge() { + Flux fluxOfIntegers = Flux.merge( + evenNumbers, + oddNumbers); StepVerifier.create(fluxOfIntegers) .expectNext(2) @@ -121,22 +137,6 @@ public class CombiningPublishersTest { } - @Test - public void givenFluxes_whenMergeDelayErrorIsInvoked_thenMergeDelayError() { - Flux fluxOfIntegers = Flux.mergeDelayError(1, - evenNumbers.delayElements(Duration.ofMillis(500L)), - oddNumbers.delayElements(Duration.ofMillis(300L))); - - StepVerifier.create(fluxOfIntegers) - .expectNext(1) - .expectNext(2) - .expectNext(3) - .expectNext(5) - .expectNext(4) - .expectComplete() - .verify(); - } - @Test public void givenFluxes_whenMergeWithIsInvoked_thenMergeWith() { Flux fluxOfIntegers = evenNumbers.mergeWith(oddNumbers); @@ -177,4 +177,4 @@ public class CombiningPublishersTest { .expectComplete() .verify(); } -} +} \ No newline at end of file From 42d3de85ba0eeb70465f1a5e95eae9ea4234dd3b Mon Sep 17 00:00:00 2001 From: Dassi orleando Date: Sat, 10 Mar 2018 01:48:11 +0100 Subject: [PATCH 74/91] BAEL-1273: add two test of the articles feed controller (#3794) * BAEL-1216: improve tests * BAEL-1448: Update Spring 5 articles to use the release version * Setting up the Maven Wrapper on a maven project * Add Maven Wrapper on spring-boot module * simple add * BAEL-976: Update spring version * BAEL-1273: Display RSS feed with spring mvc (AbstractRssFeedView) * Move RSS feed with Spring MVC from spring-boot to spring-mvc-simple * BAEL-1285: Update Jackson articles * BAEL-1273: implement both MVC and Rest approach to serve RSS content * RSS(XML & Json) with a custom model * BAEL-1273: remove a resource * BAEL-1519: Guide to scribejava * BAEL-1273: improve xml representation * Fix pom * BAEL-1587: JUnit 5 upgrade * BAEL-1519: add GitHub implementation and improve article * BAEL-1273: build a custom message converter to serve Rome Rss feed as json * BAEL-1273: add two test of the articles feed controller * Revert "BAEL-1273: add two test of the articles feed controller" This reverts commit 3e4ced8a16e495971c05bccd5c507c4d68039ea0. * BAEL-1273: add two test of the articles feed controller * Remove some others article files --- jsonld/.gitignore | 24 -- jsonld/.mvn/wrapper/maven-wrapper.jar | Bin 49502 -> 0 bytes jsonld/.mvn/wrapper/maven-wrapper.properties | 1 - jsonld/README.md | 22 -- jsonld/mvnw | 233 ------------------ jsonld/mvnw.cmd | 145 ----------- jsonld/pom.xml | 53 ---- .../java/com/baeldung/JsonLdApplication.java | 11 - .../src/main/resources/application.properties | 14 -- .../com/baeldung/JsonLdSerializatorTest.java | 33 --- spring-mvc-simple/pom.xml | 18 +- .../ApplicationConfiguration.java | 17 +- .../rss/{RssData.java => Article.java} | 23 +- .../spring/controller/rss/ArticleFeed.java | 29 --- .../spring/controller/rss/ArticleItem.java | 22 -- .../controller/rss/ArticleRssController.java | 51 +++- .../rss/JsonChannelHttpMessageConverter.java | 47 ++++ .../controller/scribe/GithubController.java | 58 +++++ ...Controller.java => TwitterController.java} | 14 +- .../rss/ArticleRssIntegrationTest.java | 45 ++++ 20 files changed, 219 insertions(+), 641 deletions(-) delete mode 100644 jsonld/.gitignore delete mode 100644 jsonld/.mvn/wrapper/maven-wrapper.jar delete mode 100644 jsonld/.mvn/wrapper/maven-wrapper.properties delete mode 100644 jsonld/README.md delete mode 100755 jsonld/mvnw delete mode 100644 jsonld/mvnw.cmd delete mode 100644 jsonld/pom.xml delete mode 100644 jsonld/src/main/java/com/baeldung/JsonLdApplication.java delete mode 100644 jsonld/src/main/resources/application.properties delete mode 100644 jsonld/src/test/java/com/baeldung/JsonLdSerializatorTest.java rename spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/{RssData.java => Article.java} (70%) delete mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleFeed.java delete mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleItem.java create mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/JsonChannelHttpMessageConverter.java create mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/GithubController.java rename spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/{ScribeController.java => TwitterController.java} (83%) create mode 100644 spring-mvc-simple/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java diff --git a/jsonld/.gitignore b/jsonld/.gitignore deleted file mode 100644 index 2af7cefb0a..0000000000 --- a/jsonld/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -nbproject/private/ -build/ -nbbuild/ -dist/ -nbdist/ -.nb-gradle/ \ No newline at end of file diff --git a/jsonld/.mvn/wrapper/maven-wrapper.jar b/jsonld/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 5fd4d5023f1463b5ba3970e33c460c1eb26d748d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 49502 zcmb@tV|1n6wzeBvGe*U>ZQHh;%-Bg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yN% z_g90{z|?BLiTfv@hp{u@$1u7B_-1N#iJ#RBzM2BR!2c8QKQ->n9NpJB+kXlz_@(`y zApg-W%GVs=-$=u6Jp_Mfr34rf;5=qxnT`lG`0>Z&B#n)_ODW`1+jPPicN} zhgOBZJau)7R=(j9e&@_!Y{d>iX#+|6|i>`&Q={(}Kji+O zpFcjFOMd9Ss|3O?C362PVeDvZY6)PztKhZE=cg?HTJXn${I25H4xgVwR(eM*+@Z8Irh^0H1^@(vM%fLB8x9<0IcS*cf20Th OJOEd-=rxTO#Qy`$*1Hh^ diff --git a/jsonld/.mvn/wrapper/maven-wrapper.properties b/jsonld/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index c954cec91c..0000000000 --- a/jsonld/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip diff --git a/jsonld/README.md b/jsonld/README.md deleted file mode 100644 index 51ca961bea..0000000000 --- a/jsonld/README.md +++ /dev/null @@ -1,22 +0,0 @@ -JSON-LD -======= - -Hypermedia serialization with JSON-LD. - -### Requirements - -- Maven -- JDK 8 -- JSON-LD - -### Running -To build and start the server simply type - -```bash -$ mvn clean install -$ mvn spring-boot:run -``` - -Now with default configurations it will be available at: [http://localhost:8080](http://localhost:8080) - -Enjoy it :) \ No newline at end of file diff --git a/jsonld/mvnw b/jsonld/mvnw deleted file mode 100755 index a1ba1bf554..0000000000 --- a/jsonld/mvnw +++ /dev/null @@ -1,233 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - wdir=$(cd "$wdir/.."; pwd) - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} "$@" diff --git a/jsonld/mvnw.cmd b/jsonld/mvnw.cmd deleted file mode 100644 index 2b934e89dd..0000000000 --- a/jsonld/mvnw.cmd +++ /dev/null @@ -1,145 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -set MAVEN_CMD_LINE_ARGS=%* - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% \ No newline at end of file diff --git a/jsonld/pom.xml b/jsonld/pom.xml deleted file mode 100644 index 1574878667..0000000000 --- a/jsonld/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - 4.0.0 - - jsonld - 0.0.1-SNAPSHOT - jar - - jsonld - Hypermedia serialization with JSON-LD - - - parent-boot-5 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-5 - - - - UTF-8 - UTF-8 - 1.8 - 0.11.1 - - - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.github.jsonld-java - jsonld-java - ${jsonld.version} - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - diff --git a/jsonld/src/main/java/com/baeldung/JsonLdApplication.java b/jsonld/src/main/java/com/baeldung/JsonLdApplication.java deleted file mode 100644 index 0b8f338127..0000000000 --- a/jsonld/src/main/java/com/baeldung/JsonLdApplication.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class JsonLdApplication { - public static void main(String[] args) { - SpringApplication.run(JsonLdApplication.class, args); - } -} diff --git a/jsonld/src/main/resources/application.properties b/jsonld/src/main/resources/application.properties deleted file mode 100644 index b6bfd8f6f3..0000000000 --- a/jsonld/src/main/resources/application.properties +++ /dev/null @@ -1,14 +0,0 @@ -# the db host -spring.data.mongodb.host=localhost -# the connection port (defaults to 27107) -spring.data.mongodb.port=27017 -# The database's name -spring.data.mongodb.database=Jenkins-Pipeline - -# Or this -# spring.data.mongodb.uri=mongodb://localhost/Jenkins-Pipeline - -# spring.data.mongodb.username= -# spring.data.mongodb.password= - -spring.data.mongodb.repositories.enabled=true \ No newline at end of file diff --git a/jsonld/src/test/java/com/baeldung/JsonLdSerializatorTest.java b/jsonld/src/test/java/com/baeldung/JsonLdSerializatorTest.java deleted file mode 100644 index 762a4254dc..0000000000 --- a/jsonld/src/test/java/com/baeldung/JsonLdSerializatorTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung; - -import com.github.jsonldjava.core.JsonLdError; -import com.github.jsonldjava.core.JsonLdOptions; -import com.github.jsonldjava.core.JsonLdProcessor; -import com.github.jsonldjava.utils.JsonUtils; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertNotEquals; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest -public class JsonLdSerializatorTest { - - @Test - public void whenInserting_andCount_thenWeDontGetZero() throws JsonLdError { - String inputStream = "{name:}"; - Object jsonObject = JsonUtils.fromInputStream(inputStream); - - Map context = new HashMap(); - JsonLdOptions options = new JsonLdOptions(); - Object compact = JsonLdProcessor.compact(jsonObject, context, options); - - assertNotEquals(0, 0); - } - -} diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index c0e4b63897..a2ba2188d6 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -34,6 +34,7 @@ 2.9.4 1.4.9 5.1.0 + 20180130 @@ -129,18 +130,6 @@ rome ${rome.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${jackson.version} - - com.thoughtworks.xstream xstream @@ -151,6 +140,11 @@ scribejava-apis ${scribejava.version} + + org.json + json + ${json.version} + diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java index 3275d919ea..c4c6791f9a 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java @@ -1,17 +1,13 @@ package com.baeldung.spring.configuration; import com.baeldung.spring.controller.rss.ArticleRssFeedViewResolver; -import com.fasterxml.jackson.dataformat.xml.XmlMapper; -import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator; +import com.baeldung.spring.controller.rss.JsonChannelHttpMessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.feed.RssChannelHttpMessageConverter; -import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.commons.CommonsMultipartResolver; @@ -28,7 +24,7 @@ import java.util.List; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) -class ApplicationConfiguration extends WebMvcConfigurerAdapter { +public class ApplicationConfiguration extends WebMvcConfigurerAdapter { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { @@ -60,16 +56,9 @@ class ApplicationConfiguration extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List> converters) { - Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.xml(); - builder.indentOutput(true); - - XmlMapper xmlMapper = builder.createXmlMapper(true).build(); - xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true); - converters.add(new StringHttpMessageConverter()); converters.add(new RssChannelHttpMessageConverter()); - converters.add(new MappingJackson2HttpMessageConverter()); - converters.add(new MappingJackson2XmlHttpMessageConverter(xmlMapper)); + converters.add(new JsonChannelHttpMessageConverter()); super.configureMessageConverters(converters); } diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/RssData.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/Article.java similarity index 70% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/RssData.java rename to spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/Article.java index 258712eb2d..e6e83f95ff 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/RssData.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/Article.java @@ -1,15 +1,14 @@ package com.baeldung.spring.controller.rss; import java.io.Serializable; -import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.Date; -public class RssData implements Serializable { +public class Article implements Serializable { private String link; private String title; private String description; - private String publishedDate; + private Date publishedDate; + private String author; public String getLink() { return link; @@ -35,22 +34,30 @@ public class RssData implements Serializable { this.description = description; } - public String getPublishedDate() { + public Date getPublishedDate() { return publishedDate; } public void setPublishedDate(Date publishedDate) { - DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); - this.publishedDate = df.format(publishedDate); + this.publishedDate = publishedDate; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; } @Override public String toString() { - return "RssData{" + + return "Article{" + "link='" + link + '\'' + ", title='" + title + '\'' + ", description='" + description + '\'' + ", publishedDate=" + publishedDate + + ", author='" + author + '\'' + '}'; } } diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleFeed.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleFeed.java deleted file mode 100644 index 71b225bf3f..0000000000 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleFeed.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.spring.controller.rss; - -import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; -import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; -import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -@JacksonXmlRootElement(localName="articles") -public class ArticleFeed extends RssData implements Serializable { - - @JacksonXmlProperty(localName = "item") - @JacksonXmlElementWrapper(useWrapping = false) - private List items = new ArrayList(); - - public void addItem(ArticleItem articleItem) { - this.items.add(articleItem); - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } -} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleItem.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleItem.java deleted file mode 100644 index 6c91819676..0000000000 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleItem.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.spring.controller.rss; - -import java.io.Serializable; - -public class ArticleItem extends RssData implements Serializable { - private String author; - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - - @Override - public String toString() { - return "ArticleItem{" + - "author='" + author + '\'' + - '}'; - } -} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleRssController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleRssController.java index b0cce99d33..23a6b8700e 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleRssController.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/ArticleRssController.java @@ -1,10 +1,15 @@ package com.baeldung.spring.controller.rss; +import com.rometools.rome.feed.rss.Channel; +import com.rometools.rome.feed.rss.Description; +import com.rometools.rome.feed.rss.Item; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; +import java.util.ArrayList; import java.util.Date; +import java.util.List; @Controller public class ArticleRssController { @@ -14,33 +19,53 @@ public class ArticleRssController { return "articleFeedView"; } - @GetMapping(value = "/rss2") + @GetMapping(value = "/rss2", produces = {"application/rss+xml", "application/rss+json"}) @ResponseBody - public ArticleFeed articleRestFeed2() { - ArticleFeed feed = new ArticleFeed(); - feed.setLink("http://localhost:8080/spring-mvc-simple/rss"); - feed.setTitle("Article Feed"); - feed.setDescription("Article Feed Description"); - feed.setPublishedDate(new Date()); - - ArticleItem item1 = new ArticleItem(); + public Channel articleHttpFeed() { + List
items = new ArrayList<>(); + Article item1 = new Article(); item1.setLink("http://www.baeldung.com/netty-exception-handling"); item1.setTitle("Exceptions in Netty"); item1.setDescription("In this quick article, we’ll be looking at exception handling in Netty."); item1.setPublishedDate(new Date()); item1.setAuthor("Carlos"); - ArticleItem item2 = new ArticleItem(); + Article item2 = new Article(); item2.setLink("http://www.baeldung.com/cockroachdb-java"); item2.setTitle("Guide to CockroachDB in Java"); item2.setDescription("This tutorial is an introductory guide to using CockroachDB with Java."); item2.setPublishedDate(new Date()); item2.setAuthor("Baeldung"); - feed.addItem(item1); - feed.addItem(item2); + items.add(item1); + items.add(item2); + Channel channelData = buildChannel(items); - return feed; + return channelData; + } + + private Channel buildChannel(List
articles){ + Channel channel = new Channel("rss_2.0"); + channel.setLink("http://localhost:8080/spring-mvc-simple/rss"); + channel.setTitle("Article Feed"); + channel.setDescription("Article Feed Description"); + channel.setPubDate(new Date()); + + List items = new ArrayList<>(); + for (Article article : articles) { + Item item = new Item(); + item.setLink(article.getLink()); + item.setTitle(article.getTitle()); + Description description1 = new Description(); + description1.setValue(article.getDescription()); + item.setDescription(description1); + item.setPubDate(article.getPublishedDate()); + item.setAuthor(article.getAuthor()); + items.add(item); + } + + channel.setItems(items); + return channel; } } diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/JsonChannelHttpMessageConverter.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/JsonChannelHttpMessageConverter.java new file mode 100644 index 0000000000..a32cbbdb7f --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/rss/JsonChannelHttpMessageConverter.java @@ -0,0 +1,47 @@ +package com.baeldung.spring.controller.rss; + +import com.rometools.rome.feed.rss.Channel; +import com.rometools.rome.io.FeedException; +import com.rometools.rome.io.WireFeedOutput; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.XML; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.HttpOutputMessage; +import org.springframework.http.MediaType; +import org.springframework.http.converter.AbstractHttpMessageConverter; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.http.converter.HttpMessageNotWritableException; + +import java.io.IOException; + +public class JsonChannelHttpMessageConverter extends AbstractHttpMessageConverter { + public JsonChannelHttpMessageConverter(){ + super(new MediaType("application", "rss+json")); + } + + @Override + protected boolean supports(Class aClass) { + return Channel.class.isAssignableFrom(aClass); + } + + @Override + protected Channel readInternal(Class aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException { + return null; + } + + @Override + protected void writeInternal(Channel wireFeed, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { + WireFeedOutput feedOutput = new WireFeedOutput(); + + try { + String xmlStr = feedOutput.outputString(wireFeed, true); + JSONObject xmlJSONObj = XML.toJSONObject(xmlStr); + String jsonPrettyPrintString = xmlJSONObj.toString(4); + + outputMessage.getBody().write(jsonPrettyPrintString.getBytes()); + } catch (JSONException | FeedException e) { + e.printStackTrace(); + } + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/GithubController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/GithubController.java new file mode 100644 index 0000000000..61b91cbd4d --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/GithubController.java @@ -0,0 +1,58 @@ +package com.baeldung.spring.controller.scribe; + +import com.github.scribejava.apis.GitHubApi; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.model.*; +import com.github.scribejava.core.oauth.OAuth20Service; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.view.RedirectView; + +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.Random; +import java.util.concurrent.ExecutionException; + +@Controller +@RequestMapping("github") +public class GithubController { + private OAuth20Service createService(String state) { + return new ServiceBuilder("e1f8d4f1a5c71467a159") + .apiSecret("4851597541a8f33a4f1bf1c70f3cedcfefbeb13b") + .state(state) + .callback("http://localhost:8080/spring-mvc-simple/github/callback") + .build(GitHubApi.instance()); + } + + @GetMapping(value = "/authorization") + public RedirectView authorization(HttpServletRequest servletReq) throws InterruptedException, ExecutionException, IOException { + String state = String.valueOf(new Random().nextInt(999_999)); + OAuth20Service githubService = createService(state); + servletReq.getSession().setAttribute("state", state); + + String authorizationUrl = githubService.getAuthorizationUrl(); + RedirectView redirectView = new RedirectView(); + redirectView.setUrl(authorizationUrl); + return redirectView; + } + + @GetMapping(value = "/callback", produces = "text/plain") + @ResponseBody + public String callback(HttpServletRequest servletReq, @RequestParam("code") String code, @RequestParam("state") String state) throws InterruptedException, ExecutionException, IOException { + String initialState = (String) servletReq.getSession().getAttribute("state"); + if(initialState.equals(state)) { + OAuth20Service githubService = createService(initialState); + OAuth2AccessToken accessToken = githubService.getAccessToken(code); + + OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.github.com/user"); + githubService.signRequest(accessToken, request); + Response response = githubService.execute(request); + + return response.getBody(); + } + return "Error"; + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/ScribeController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/TwitterController.java similarity index 83% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/ScribeController.java rename to spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/TwitterController.java index c5c97ff009..af47797ac5 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/ScribeController.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/scribe/TwitterController.java @@ -17,18 +17,18 @@ import java.util.concurrent.ExecutionException; @Controller @RequestMapping("twitter") -public class ScribeController { +public class TwitterController { - private OAuth10aService createTwitterService() { + private OAuth10aService createService() { return new ServiceBuilder("PSRszoHhRDVhyo2RIkThEbWko") - .apiSecret("prpJbz03DcGRN46sb4ucdSYtVxG8unUKhcnu3an5ItXbEOuenL") - .callback("http://localhost:8080/spring-mvc-simple/twitter/callback") - .build(TwitterApi.instance()); + .apiSecret("prpJbz03DcGRN46sb4ucdSYtVxG8unUKhcnu3an5ItXbEOuenL") + .callback("http://localhost:8080/spring-mvc-simple/twitter/callback") + .build(TwitterApi.instance()); } @GetMapping(value = "/authorization") public RedirectView authorization(HttpServletRequest servletReq) throws InterruptedException, ExecutionException, IOException { - OAuth10aService twitterService = createTwitterService(); + OAuth10aService twitterService = createService(); OAuth1RequestToken requestToken = twitterService.getRequestToken(); String authorizationUrl = twitterService.getAuthorizationUrl(requestToken); @@ -42,7 +42,7 @@ public class ScribeController { @GetMapping(value = "/callback", produces = "text/plain") @ResponseBody public String callback(HttpServletRequest servletReq, @RequestParam("oauth_verifier") String oauthV) throws InterruptedException, ExecutionException, IOException { - OAuth10aService twitterService = createTwitterService(); + OAuth10aService twitterService = createService(); OAuth1RequestToken requestToken = (OAuth1RequestToken) servletReq.getSession().getAttribute("requestToken"); OAuth1AccessToken accessToken = twitterService.getAccessToken(requestToken, oauthV); diff --git a/spring-mvc-simple/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java b/spring-mvc-simple/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java new file mode 100644 index 0000000000..fe7aeeb570 --- /dev/null +++ b/spring-mvc-simple/src/test/java/com/baeldung/controller/rss/ArticleRssIntegrationTest.java @@ -0,0 +1,45 @@ +package com.baeldung.controller.rss; + +import com.baeldung.spring.configuration.ApplicationConfiguration; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringJUnitWebConfig(ApplicationConfiguration.class) +public class ArticleRssIntegrationTest { + public static final String APPLICATION_RSS_XML = "application/rss+xml"; + public static final String APPLICATION_RSS_JSON = "application/rss+json"; + public static final String APPLICATION_RSS_XML_CHARSET_UTF_8 = "application/rss+xml;charset=UTF-8"; + + @Autowired + private WebApplicationContext webAppContext; + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext) + .build(); + } + + @Test + public void whenRequestingXMLFeed_thenContentTypeIsOk() throws Exception { + mockMvc.perform(get("/rss2").accept(APPLICATION_RSS_XML)) + .andExpect(status().isOk()) + .andExpect(content().contentType(APPLICATION_RSS_XML_CHARSET_UTF_8)); + } + + @Test + public void whenRequestingJSONFeed_thenContentTypeIsOk() throws Exception { + mockMvc.perform(get("/rss2").accept(APPLICATION_RSS_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(APPLICATION_RSS_JSON)); + } +} \ No newline at end of file From 24cc2e05bfaa7b5b7ead7809b5b0a43f0ef8598f Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Fri, 9 Mar 2018 22:40:11 -0600 Subject: [PATCH 75/91] BAEL-1462 README update (#3793) * BAEL-973: updated README * BAEL-1069: Updated README * BAEL-817: add README file * BAEL-1084: README update * BAEL-960: Update README * BAEL-1155: updated README * BAEL-1041: updated README * BAEL-973: Updated README * BAEL-1187: updated README * BAEL-1183: Update README * BAEL-1133: Updated README * BAEL-1098: README update * BAEL-719: add README.md * BAEL-1272: README update * BAEL-1272: README update * BAEL-1196: Update README * BAEL-1328: Updated README * BAEL-1371: Update README.md * BAEL-1371: Update README.md * BAEL-1278: Update README * BAEL-1326: Update README * BAEL-399: Update README * BAEL-1297: Update README * BAEL-1218: README * BAEL-1148 README update * BAEL-113 README * BAEL-1158 README * BAEL-1539: Update README * BAEL-1507 README update * BAEL-1178 README updated * BAEL-1462 README --- core-kotlin/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 7f68648eba..b8cea19c58 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -20,3 +20,4 @@ - [Infix Functions in Kotlin](http://www.baeldung.com/kotlin-infix-functions) - [Try-with-resources in Kotlin](http://www.baeldung.com/kotlin-try-with-resources) - [HTTP Requests with Kotlin and khttp](http://www.baeldung.com/kotlin-khttp) +- [Kotlin Dependency Injection with Kodein](http://www.baeldung.com/kotlin-kodein-dependency-injection) From 84080c9e955fafc9b56ab8079a520995c669af44 Mon Sep 17 00:00:00 2001 From: Chris Oberle Date: Sat, 10 Mar 2018 07:06:26 -0500 Subject: [PATCH 76/91] BAEL-1533 - Making a Spring MVC Form Remember Values --- pom.xml | 3 +- spring-5/pom.xml | 437 +++++++++--------- .../README.md | 0 .../pom.xml | 4 +- .../ApplicationConfiguration.java | 0 .../configuration/WebInitializer.java | 0 .../controller/CustomerController.java | 0 .../controller/EmployeeController.java | 0 .../controller/FileUploadController.java | 0 .../controller/UserController.java | 0 .../springmvcforms/domain/Customer.java | 0 .../springmvcforms/domain/Employee.java | 0 .../baeldung/springmvcforms/domain/User.java | 0 .../FileUploadExceptionAdvice.java | 0 .../validator/CustomerValidator.java | 0 .../src/main/webapp/WEB-INF/html/user.html | 0 .../webapp/WEB-INF/views/customerHome.jsp | 0 .../webapp/WEB-INF/views/customerView.jsp | 0 .../webapp/WEB-INF/views/employeeHome.jsp | 0 .../webapp/WEB-INF/views/employeeView.jsp | 0 .../src/main/webapp/WEB-INF/views/error.jsp | 0 .../src/main/webapp/WEB-INF/views/file.jsp | 0 .../src/main/webapp/css/user.css | 0 .../src/main/webapp/js/app.js | 0 spring-mvc-forms-thymeleaf/pom.xml | 73 +++ .../com/baeldung/sessionattrs/Config.java | 88 ++-- .../sessionattrs/SessionAttrsApplication.java | 0 .../TodoControllerWithScopedProxy.java | 90 ++-- .../TodoControllerWithSessionAttributes.java | 110 ++--- .../com/baeldung/sessionattrs/TodoItem.java | 78 ++-- .../com/baeldung/sessionattrs/TodoList.java | 16 +- .../src/main/resources/application.properties | 3 + .../templates/sessionattrs/index.html | 52 +-- .../sessionattrs/scopedproxyform.html | 52 +-- .../sessionattrs/scopedproxytodos.html | 94 ++-- .../sessionattrs/sessionattributesform.html | 52 +-- .../sessionattrs/sessionattributestodos.html | 94 ++-- .../SessionAttrsApplicationTest.java | 2 +- .../com/baeldung/sessionattrs/TestConfig.java | 34 +- .../TodoControllerWithScopedProxyTest.java | 136 +++--- ...doControllerWithSessionAttributesTest.java | 136 +++--- 41 files changed, 819 insertions(+), 735 deletions(-) rename {spring-mvc-forms => spring-mvc-forms-jsp}/README.md (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/pom.xml (97%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/java/com/baeldung/springmvcforms/controller/FileUploadController.java (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/java/com/baeldung/springmvcforms/controller/UserController.java (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/java/com/baeldung/springmvcforms/domain/Customer.java (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/java/com/baeldung/springmvcforms/domain/Employee.java (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/java/com/baeldung/springmvcforms/domain/User.java (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/java/com/baeldung/springmvcforms/interceptor/FileUploadExceptionAdvice.java (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/java/com/baeldung/springmvcforms/validator/CustomerValidator.java (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/webapp/WEB-INF/html/user.html (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/webapp/WEB-INF/views/customerHome.jsp (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/webapp/WEB-INF/views/customerView.jsp (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/webapp/WEB-INF/views/employeeHome.jsp (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/webapp/WEB-INF/views/employeeView.jsp (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/webapp/WEB-INF/views/error.jsp (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/webapp/WEB-INF/views/file.jsp (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/webapp/css/user.css (100%) rename {spring-mvc-forms => spring-mvc-forms-jsp}/src/main/webapp/js/app.js (100%) create mode 100644 spring-mvc-forms-thymeleaf/pom.xml rename {spring-5 => spring-mvc-forms-thymeleaf}/src/main/java/com/baeldung/sessionattrs/Config.java (97%) rename {spring-5 => spring-mvc-forms-thymeleaf}/src/main/java/com/baeldung/sessionattrs/SessionAttrsApplication.java (100%) rename {spring-5 => spring-mvc-forms-thymeleaf}/src/main/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxy.java (96%) rename {spring-5 => spring-mvc-forms-thymeleaf}/src/main/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributes.java (97%) rename {spring-5 => spring-mvc-forms-thymeleaf}/src/main/java/com/baeldung/sessionattrs/TodoItem.java (95%) rename {spring-5 => spring-mvc-forms-thymeleaf}/src/main/java/com/baeldung/sessionattrs/TodoList.java (94%) create mode 100644 spring-mvc-forms-thymeleaf/src/main/resources/application.properties rename {spring-5 => spring-mvc-forms-thymeleaf}/src/main/resources/templates/sessionattrs/index.html (97%) rename {spring-5 => spring-mvc-forms-thymeleaf}/src/main/resources/templates/sessionattrs/scopedproxyform.html (97%) rename {spring-5 => spring-mvc-forms-thymeleaf}/src/main/resources/templates/sessionattrs/scopedproxytodos.html (96%) rename {spring-5 => spring-mvc-forms-thymeleaf}/src/main/resources/templates/sessionattrs/sessionattributesform.html (97%) rename {spring-5 => spring-mvc-forms-thymeleaf}/src/main/resources/templates/sessionattrs/sessionattributestodos.html (96%) rename spring-5/src/test/java/com/baeldung/sessionattrs/SessionAttrsApplicationIntegrationTest.java => spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/SessionAttrsApplicationTest.java (85%) rename {spring-5 => spring-mvc-forms-thymeleaf}/src/test/java/com/baeldung/sessionattrs/TestConfig.java (97%) rename spring-5/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyIntegrationTest.java => spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyTest.java (91%) rename spring-5/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesIntegrationTest.java => spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesTest.java (95%) diff --git a/pom.xml b/pom.xml index 70a3bbc5b4..205d42858a 100644 --- a/pom.xml +++ b/pom.xml @@ -199,7 +199,8 @@ spring-ldap spring-mockito spring-mvc-email - spring-mvc-forms + spring-mvc-forms-jsp + spring-mvc-forms-thymeleaf spring-mvc-java spring-mvc-tiles spring-mvc-velocity diff --git a/spring-5/pom.xml b/spring-5/pom.xml index b4e6e684ad..f8bad72c51 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -1,215 +1,222 @@ - - - 4.0.0 - - com.baeldung - spring-5 - 0.0.1-SNAPSHOT - jar - - spring-5 - spring 5 sample project about new features - - - org.springframework.boot - spring-boot-starter-parent - 2.0.0.RELEASE - - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-validation - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-webflux - - - org.springframework.boot - spring-boot-starter-hateoas - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.projectreactor - reactor-spring - ${reactor-spring.version} - - - javax.json.bind - javax.json.bind-api - - - org.apache.geronimo.specs - geronimo-json_1.1_spec - ${geronimo-json_1.1_spec.version} - - - org.apache.johnzon - johnzon-jsonb - ${johnzon.version} - - - - org.apache.commons - commons-lang3 - - - - - - org.springframework.boot - spring-boot-devtools - runtime - - - com.h2database - h2 - runtime - - - - org.springframework - spring-test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - - - - org.apache.commons - commons-collections4 - 4.1 - test - - - - org.junit.jupiter - junit-jupiter-api - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - - org.springframework.restdocs - spring-restdocs-mockmvc - test - - - org.springframework.restdocs - spring-restdocs-webtestclient - test - - - org.springframework.restdocs - spring-restdocs-restassured - test - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - com.baeldung.Spring5Application - JAR - - - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - methods - true - - **/*IntegrationTest.java - **/*LiveTest.java - - - - - org.asciidoctor - asciidoctor-maven-plugin - ${asciidoctor-plugin.version} - - - generate-docs - package - - process-asciidoc - - - html - book - - ${snippetsDirectory} - - src/docs/asciidocs - target/generated-docs - - - - - - - - - UTF-8 - UTF-8 - 1.8 - 1.0.0 - 2.20 - 1.0.1.RELEASE - 1.1.3 - 1.0 - 1.5.6 - ${project.build.directory}/generated-snippets - - - + + + 4.0.0 + + com.baeldung + spring-5 + 0.0.1-SNAPSHOT + jar + + spring-5 + spring 5 sample project about new features + + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-hateoas + + + org.projectreactor + reactor-spring + ${reactor-spring.version} + + + javax.json.bind + javax.json.bind-api + + + + + + + + + + + + + + + org.apache.geronimo.specs + geronimo-json_1.1_spec + ${geronimo-json_1.1_spec.version} + + + org.apache.johnzon + johnzon-jsonb + + + + org.apache.commons + commons-lang3 + + + + + + org.springframework.boot + spring-boot-devtools + runtime + + + com.h2database + h2 + runtime + + + + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + org.apache.commons + commons-collections4 + 4.1 + test + + + + org.junit.jupiter + junit-jupiter-api + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + org.springframework.restdocs + spring-restdocs-mockmvc + test + + + org.springframework.restdocs + spring-restdocs-webtestclient + test + + + org.springframework.restdocs + spring-restdocs-restassured + test + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.Spring5Application + JAR + + + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + methods + true + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + org.asciidoctor + asciidoctor-maven-plugin + ${asciidoctor-plugin.version} + + + generate-docs + package + + process-asciidoc + + + html + book + + ${snippetsDirectory} + + src/docs/asciidocs + target/generated-docs + + + + + + + + + UTF-8 + UTF-8 + 1.8 + 1.0.0 + 2.20 + 5.0.2.RELEASE + 1.0.1.RELEASE + 1.0 + 1.5.6 + ${project.build.directory}/generated-snippets + + + diff --git a/spring-mvc-forms/README.md b/spring-mvc-forms-jsp/README.md similarity index 100% rename from spring-mvc-forms/README.md rename to spring-mvc-forms-jsp/README.md diff --git a/spring-mvc-forms/pom.xml b/spring-mvc-forms-jsp/pom.xml similarity index 97% rename from spring-mvc-forms/pom.xml rename to spring-mvc-forms-jsp/pom.xml index e82a906112..bb666cff4f 100644 --- a/spring-mvc-forms/pom.xml +++ b/spring-mvc-forms-jsp/pom.xml @@ -6,9 +6,9 @@ 4.0.0 com.baeldung 0.1-SNAPSHOT - spring-mvc-forms + spring-mvc-forms-jsp - spring-mvc-forms + spring-mvc-forms-jsp war diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java similarity index 100% rename from spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java rename to spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java similarity index 100% rename from spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java rename to spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java similarity index 100% rename from spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java rename to spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/CustomerController.java diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java similarity index 100% rename from spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java rename to spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/FileUploadController.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/FileUploadController.java similarity index 100% rename from spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/FileUploadController.java rename to spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/FileUploadController.java diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/UserController.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/UserController.java similarity index 100% rename from spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/UserController.java rename to spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/UserController.java diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Customer.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/Customer.java similarity index 100% rename from spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Customer.java rename to spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/Customer.java diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Employee.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/Employee.java similarity index 100% rename from spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Employee.java rename to spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/Employee.java diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/User.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/User.java similarity index 100% rename from spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/User.java rename to spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/domain/User.java diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/interceptor/FileUploadExceptionAdvice.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/interceptor/FileUploadExceptionAdvice.java similarity index 100% rename from spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/interceptor/FileUploadExceptionAdvice.java rename to spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/interceptor/FileUploadExceptionAdvice.java diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/validator/CustomerValidator.java b/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/validator/CustomerValidator.java similarity index 100% rename from spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/validator/CustomerValidator.java rename to spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/validator/CustomerValidator.java diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/html/user.html b/spring-mvc-forms-jsp/src/main/webapp/WEB-INF/html/user.html similarity index 100% rename from spring-mvc-forms/src/main/webapp/WEB-INF/html/user.html rename to spring-mvc-forms-jsp/src/main/webapp/WEB-INF/html/user.html diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/customerHome.jsp b/spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/customerHome.jsp similarity index 100% rename from spring-mvc-forms/src/main/webapp/WEB-INF/views/customerHome.jsp rename to spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/customerHome.jsp diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/customerView.jsp b/spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/customerView.jsp similarity index 100% rename from spring-mvc-forms/src/main/webapp/WEB-INF/views/customerView.jsp rename to spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/customerView.jsp diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeHome.jsp b/spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/employeeHome.jsp similarity index 100% rename from spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeHome.jsp rename to spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/employeeHome.jsp diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeView.jsp b/spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/employeeView.jsp similarity index 100% rename from spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeView.jsp rename to spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/employeeView.jsp diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/error.jsp b/spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/error.jsp similarity index 100% rename from spring-mvc-forms/src/main/webapp/WEB-INF/views/error.jsp rename to spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/error.jsp diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/file.jsp b/spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/file.jsp similarity index 100% rename from spring-mvc-forms/src/main/webapp/WEB-INF/views/file.jsp rename to spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/file.jsp diff --git a/spring-mvc-forms/src/main/webapp/css/user.css b/spring-mvc-forms-jsp/src/main/webapp/css/user.css similarity index 100% rename from spring-mvc-forms/src/main/webapp/css/user.css rename to spring-mvc-forms-jsp/src/main/webapp/css/user.css diff --git a/spring-mvc-forms/src/main/webapp/js/app.js b/spring-mvc-forms-jsp/src/main/webapp/js/app.js similarity index 100% rename from spring-mvc-forms/src/main/webapp/js/app.js rename to spring-mvc-forms-jsp/src/main/webapp/js/app.js diff --git a/spring-mvc-forms-thymeleaf/pom.xml b/spring-mvc-forms-thymeleaf/pom.xml new file mode 100644 index 0000000000..9238153847 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + + com.baeldung + spring-mvc-forms-thymeleaf + 0.0.1-SNAPSHOT + jar + + spring-mvc-forms-thymeleaf + spring forms examples using thymeleaf + + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + org.springframework.boot + spring-boot-devtools + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + methods + true + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + UTF-8 + UTF-8 + + + diff --git a/spring-5/src/main/java/com/baeldung/sessionattrs/Config.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/Config.java similarity index 97% rename from spring-5/src/main/java/com/baeldung/sessionattrs/Config.java rename to spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/Config.java index 9d5c9d9f42..7c9f1bf00b 100644 --- a/spring-5/src/main/java/com/baeldung/sessionattrs/Config.java +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/Config.java @@ -1,44 +1,44 @@ -package com.baeldung.sessionattrs; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Scope; -import org.springframework.context.annotation.ScopedProxyMode; -import org.springframework.core.Ordered; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.thymeleaf.templatemode.TemplateMode; -import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; -import org.thymeleaf.templateresolver.ITemplateResolver; - -@EnableWebMvc -@Configuration -public class Config implements WebMvcConfigurer { - - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/").setViewName("index"); - registry.setOrder(Ordered.HIGHEST_PRECEDENCE); - } - - @Bean - @Scope( - value = WebApplicationContext.SCOPE_SESSION, - proxyMode = ScopedProxyMode.TARGET_CLASS) - public TodoList todos() { - return new TodoList(); - } - - @Bean - public ITemplateResolver templateResolver() { - ClassLoaderTemplateResolver resolver - = new ClassLoaderTemplateResolver(); - resolver.setPrefix("templates/sessionattrs/"); - resolver.setSuffix(".html"); - resolver.setTemplateMode(TemplateMode.HTML); - resolver.setCharacterEncoding("UTF-8"); - return resolver; - } -} +package com.baeldung.sessionattrs; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; +import org.springframework.context.annotation.ScopedProxyMode; +import org.springframework.core.Ordered; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +import org.thymeleaf.templateresolver.ITemplateResolver; + +@EnableWebMvc +@Configuration +public class Config implements WebMvcConfigurer { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("index"); + registry.setOrder(Ordered.HIGHEST_PRECEDENCE); + } + + @Bean + @Scope( + value = WebApplicationContext.SCOPE_SESSION, + proxyMode = ScopedProxyMode.TARGET_CLASS) + public TodoList todos() { + return new TodoList(); + } + + @Bean + public ITemplateResolver templateResolver() { + ClassLoaderTemplateResolver resolver + = new ClassLoaderTemplateResolver(); + resolver.setPrefix("templates/sessionattrs/"); + resolver.setSuffix(".html"); + resolver.setTemplateMode(TemplateMode.HTML); + resolver.setCharacterEncoding("UTF-8"); + return resolver; + } +} diff --git a/spring-5/src/main/java/com/baeldung/sessionattrs/SessionAttrsApplication.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/SessionAttrsApplication.java similarity index 100% rename from spring-5/src/main/java/com/baeldung/sessionattrs/SessionAttrsApplication.java rename to spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/SessionAttrsApplication.java diff --git a/spring-5/src/main/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxy.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxy.java similarity index 96% rename from spring-5/src/main/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxy.java rename to spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxy.java index 0c3bd6c8b6..feedecf844 100644 --- a/spring-5/src/main/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxy.java +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxy.java @@ -1,45 +1,45 @@ -package com.baeldung.sessionattrs; - -import java.time.LocalDateTime; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -@RequestMapping("/scopedproxy") -public class TodoControllerWithScopedProxy { - - private TodoList todos; - - public TodoControllerWithScopedProxy(TodoList todos) { - this.todos = todos; - } - - @GetMapping("/form") - public String showForm(Model model) { - if (!todos.isEmpty()) { - model.addAttribute("todo", todos.peekLast()); - } else { - model.addAttribute("todo", new TodoItem()); - } - - return "scopedproxyform"; - } - - @PostMapping("/form") - public String create(@ModelAttribute TodoItem todo) { - todo.setCreateDate(LocalDateTime.now()); - todos.add(todo); - return "redirect:/scopedproxy/todos.html"; - } - - @GetMapping("/todos.html") - public String list(Model model) { - model.addAttribute("todos", todos); - return "scopedproxytodos"; - } -} +package com.baeldung.sessionattrs; + +import java.time.LocalDateTime; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/scopedproxy") +public class TodoControllerWithScopedProxy { + + private TodoList todos; + + public TodoControllerWithScopedProxy(TodoList todos) { + this.todos = todos; + } + + @GetMapping("/form") + public String showForm(Model model) { + if (!todos.isEmpty()) { + model.addAttribute("todo", todos.peekLast()); + } else { + model.addAttribute("todo", new TodoItem()); + } + + return "scopedproxyform"; + } + + @PostMapping("/form") + public String create(@ModelAttribute TodoItem todo) { + todo.setCreateDate(LocalDateTime.now()); + todos.add(todo); + return "redirect:/scopedproxy/todos.html"; + } + + @GetMapping("/todos.html") + public String list(Model model) { + model.addAttribute("todos", todos); + return "scopedproxytodos"; + } +} diff --git a/spring-5/src/main/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributes.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributes.java similarity index 97% rename from spring-5/src/main/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributes.java rename to spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributes.java index fc7e57b1db..99e0b46fc2 100644 --- a/spring-5/src/main/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributes.java +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributes.java @@ -1,55 +1,55 @@ -package com.baeldung.sessionattrs; - -import java.time.LocalDateTime; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.SessionAttributes; -import org.springframework.web.servlet.mvc.support.RedirectAttributes; -import org.springframework.web.servlet.view.RedirectView; - -@Controller -@RequestMapping("/sessionattributes") -@SessionAttributes("todos") -public class TodoControllerWithSessionAttributes { - - @GetMapping("/form") - public String showForm( - Model model, - @ModelAttribute("todos") TodoList todos) { - if (!todos.isEmpty()) { - model.addAttribute("todo", todos.peekLast()); - } else { - model.addAttribute("todo", new TodoItem()); - } - return "sessionattributesform"; - } - - @PostMapping("/form") - public RedirectView create( - @ModelAttribute TodoItem todo, - @ModelAttribute("todos") TodoList todos, - RedirectAttributes attributes) { - todo.setCreateDate(LocalDateTime.now()); - todos.add(todo); - attributes.addFlashAttribute("todos", todos); - return new RedirectView("/sessionattributes/todos.html"); - } - - @GetMapping("/todos.html") - public String list( - Model model, - @ModelAttribute("todos") TodoList todos) { - model.addAttribute("todos", todos); - return "sessionattributestodos"; - } - - @ModelAttribute("todos") - public TodoList todos() { - return new TodoList(); - } -} +package com.baeldung.sessionattrs; + +import java.time.LocalDateTime; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.SessionAttributes; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; +import org.springframework.web.servlet.view.RedirectView; + +@Controller +@RequestMapping("/sessionattributes") +@SessionAttributes("todos") +public class TodoControllerWithSessionAttributes { + + @GetMapping("/form") + public String showForm( + Model model, + @ModelAttribute("todos") TodoList todos) { + if (!todos.isEmpty()) { + model.addAttribute("todo", todos.peekLast()); + } else { + model.addAttribute("todo", new TodoItem()); + } + return "sessionattributesform"; + } + + @PostMapping("/form") + public RedirectView create( + @ModelAttribute TodoItem todo, + @ModelAttribute("todos") TodoList todos, + RedirectAttributes attributes) { + todo.setCreateDate(LocalDateTime.now()); + todos.add(todo); + attributes.addFlashAttribute("todos", todos); + return new RedirectView("/sessionattributes/todos.html"); + } + + @GetMapping("/todos.html") + public String list( + Model model, + @ModelAttribute("todos") TodoList todos) { + model.addAttribute("todos", todos); + return "sessionattributestodos"; + } + + @ModelAttribute("todos") + public TodoList todos() { + return new TodoList(); + } +} diff --git a/spring-5/src/main/java/com/baeldung/sessionattrs/TodoItem.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/TodoItem.java similarity index 95% rename from spring-5/src/main/java/com/baeldung/sessionattrs/TodoItem.java rename to spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/TodoItem.java index 619d61d5f0..b8b24bc04d 100644 --- a/spring-5/src/main/java/com/baeldung/sessionattrs/TodoItem.java +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/TodoItem.java @@ -1,39 +1,39 @@ -package com.baeldung.sessionattrs; - -import java.time.LocalDateTime; - -public class TodoItem { - - private String description; - private LocalDateTime createDate; - - public TodoItem(String description, LocalDateTime createDate) { - this.description = description; - this.createDate = createDate; - } - - public TodoItem() { - // default no arg constructor - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public LocalDateTime getCreateDate() { - return createDate; - } - - public void setCreateDate(LocalDateTime createDate) { - this.createDate = createDate; - } - - @Override - public String toString() { - return "TodoItem [description=" + description + ", createDate=" + createDate + "]"; - } -} +package com.baeldung.sessionattrs; + +import java.time.LocalDateTime; + +public class TodoItem { + + private String description; + private LocalDateTime createDate; + + public TodoItem(String description, LocalDateTime createDate) { + this.description = description; + this.createDate = createDate; + } + + public TodoItem() { + // default no arg constructor + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public LocalDateTime getCreateDate() { + return createDate; + } + + public void setCreateDate(LocalDateTime createDate) { + this.createDate = createDate; + } + + @Override + public String toString() { + return "TodoItem [description=" + description + ", createDate=" + createDate + "]"; + } +} diff --git a/spring-5/src/main/java/com/baeldung/sessionattrs/TodoList.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/TodoList.java similarity index 94% rename from spring-5/src/main/java/com/baeldung/sessionattrs/TodoList.java rename to spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/TodoList.java index cad7811da4..02c05f4282 100644 --- a/spring-5/src/main/java/com/baeldung/sessionattrs/TodoList.java +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/sessionattrs/TodoList.java @@ -1,8 +1,8 @@ -package com.baeldung.sessionattrs; - -import java.util.ArrayDeque; - -@SuppressWarnings("serial") -public class TodoList extends ArrayDeque{ - -} +package com.baeldung.sessionattrs; + +import java.util.ArrayDeque; + +@SuppressWarnings("serial") +public class TodoList extends ArrayDeque{ + +} diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/application.properties b/spring-mvc-forms-thymeleaf/src/main/resources/application.properties new file mode 100644 index 0000000000..ccec014c2b --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8081 + +logging.level.root=INFO \ No newline at end of file diff --git a/spring-5/src/main/resources/templates/sessionattrs/index.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/index.html similarity index 97% rename from spring-5/src/main/resources/templates/sessionattrs/index.html rename to spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/index.html index 72427cd62b..f9df863e45 100644 --- a/spring-5/src/main/resources/templates/sessionattrs/index.html +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/index.html @@ -1,27 +1,27 @@ - - - - Session Scope in Spring MVC - - - - - - - -
-

-

Session Scope in Spring MVC - Example

-

-
- - + + + + Session Scope in Spring MVC + + + + + + + +
+

+

Session Scope in Spring MVC - Example

+

+
+ + \ No newline at end of file diff --git a/spring-5/src/main/resources/templates/sessionattrs/scopedproxyform.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxyform.html similarity index 97% rename from spring-5/src/main/resources/templates/sessionattrs/scopedproxyform.html rename to spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxyform.html index e72651556b..604c60dfbb 100644 --- a/spring-5/src/main/resources/templates/sessionattrs/scopedproxyform.html +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxyform.html @@ -1,27 +1,27 @@ - - - - Session Scope in Spring MVC - - - - - - - -
-

-

Scoped Proxy Example

-

-
-
-
Enter a TODO
-
-
- - -
-
-
- + + + + Session Scope in Spring MVC + + + + + + + +
+

+

Scoped Proxy Example

+

+
+
+
Enter a TODO
+
+
+ + +
+
+
+ \ No newline at end of file diff --git a/spring-5/src/main/resources/templates/sessionattrs/scopedproxytodos.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxytodos.html similarity index 96% rename from spring-5/src/main/resources/templates/sessionattrs/scopedproxytodos.html rename to spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxytodos.html index 5493b5cf64..743cd76b5d 100644 --- a/spring-5/src/main/resources/templates/sessionattrs/scopedproxytodos.html +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxytodos.html @@ -1,48 +1,48 @@ - - - - Session Scope in Spring MVC - - - - - - - -
-

-

Scoped Proxy Example

-

-
-
-
-
- Add New -
-
-
-
-
-
TODO List
- - - - - - - - - - - -
DescriptionCreate Date
DescriptionCreate Date
-
-
-
-
- + + + + Session Scope in Spring MVC + + + + + + + +
+

+

Scoped Proxy Example

+

+
+
+
+
+ Add New +
+
+
+
+
+
TODO List
+ + + + + + + + + + + +
DescriptionCreate Date
DescriptionCreate Date
+
+
+
+
+ \ No newline at end of file diff --git a/spring-5/src/main/resources/templates/sessionattrs/sessionattributesform.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributesform.html similarity index 97% rename from spring-5/src/main/resources/templates/sessionattrs/sessionattributesform.html rename to spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributesform.html index 28e1d5d2c1..93e052d6b5 100644 --- a/spring-5/src/main/resources/templates/sessionattrs/sessionattributesform.html +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributesform.html @@ -1,27 +1,27 @@ - - - - Session Scope in Spring MVC - - - - - - - -
-

-

Session Attributes Example

-

-
-
-
Enter a TODO
-
-
- - -
-
-
- + + + + Session Scope in Spring MVC + + + + + + + +
+

+

Session Attributes Example

+

+
+
+
Enter a TODO
+
+
+ + +
+
+
+ \ No newline at end of file diff --git a/spring-5/src/main/resources/templates/sessionattrs/sessionattributestodos.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributestodos.html similarity index 96% rename from spring-5/src/main/resources/templates/sessionattrs/sessionattributestodos.html rename to spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributestodos.html index 4bae12ffb9..7525604298 100644 --- a/spring-5/src/main/resources/templates/sessionattrs/sessionattributestodos.html +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributestodos.html @@ -1,48 +1,48 @@ - - - - Session Scope in Spring MVC - - - - - - - -
-

-

Session Attributes Example

-

-
-
-
-
- Add New -
-
-
-
-
-
TODO List
- - - - - - - - - - - -
DescriptionCreate Date
DescriptionCreate Date
-
-
-
-
- + + + + Session Scope in Spring MVC + + + + + + + +
+

+

Session Attributes Example

+

+
+
+
+
+ Add New +
+
+
+
+
+
TODO List
+ + + + + + + + + + + +
DescriptionCreate Date
DescriptionCreate Date
+
+
+
+
+ \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/sessionattrs/SessionAttrsApplicationIntegrationTest.java b/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/SessionAttrsApplicationTest.java similarity index 85% rename from spring-5/src/test/java/com/baeldung/sessionattrs/SessionAttrsApplicationIntegrationTest.java rename to spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/SessionAttrsApplicationTest.java index 05e9cdd21e..2fc27841da 100644 --- a/spring-5/src/test/java/com/baeldung/sessionattrs/SessionAttrsApplicationIntegrationTest.java +++ b/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/SessionAttrsApplicationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class SessionAttrsApplicationIntegrationTest { +public class SessionAttrsApplicationTest { @Test public void contextLoads() { diff --git a/spring-5/src/test/java/com/baeldung/sessionattrs/TestConfig.java b/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TestConfig.java similarity index 97% rename from spring-5/src/test/java/com/baeldung/sessionattrs/TestConfig.java rename to spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TestConfig.java index 07d65dd7c2..cf38463c0f 100644 --- a/spring-5/src/test/java/com/baeldung/sessionattrs/TestConfig.java +++ b/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TestConfig.java @@ -1,17 +1,17 @@ -package com.baeldung.sessionattrs; - -import org.springframework.beans.factory.config.CustomScopeConfigurer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.SimpleThreadScope; - -@Configuration -public class TestConfig { - - @Bean - public CustomScopeConfigurer customScopeConfigurer() { - CustomScopeConfigurer configurer = new CustomScopeConfigurer(); - configurer.addScope("session", new SimpleThreadScope()); - return configurer; - } -} +package com.baeldung.sessionattrs; + +import org.springframework.beans.factory.config.CustomScopeConfigurer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.SimpleThreadScope; + +@Configuration +public class TestConfig { + + @Bean + public CustomScopeConfigurer customScopeConfigurer() { + CustomScopeConfigurer configurer = new CustomScopeConfigurer(); + configurer.addScope("session", new SimpleThreadScope()); + return configurer; + } +} diff --git a/spring-5/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyIntegrationTest.java b/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyTest.java similarity index 91% rename from spring-5/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyIntegrationTest.java rename to spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyTest.java index 5b2f653f8a..49be948a2a 100644 --- a/spring-5/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyIntegrationTest.java +++ b/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyTest.java @@ -1,68 +1,68 @@ -package com.baeldung.sessionattrs; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.util.StringUtils; -import org.springframework.web.context.WebApplicationContext; - -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -@Import(TestConfig.class) -public class TodoControllerWithScopedProxyIntegrationTest { - - @Autowired - private MockMvc mockMvc; - - @Autowired - private WebApplicationContext wac; - - @Before - public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) - .build(); - } - - @Test - public void whenFirstRequest_thenContainsAllCategoriesAndUnintializedTodo() throws Exception { - MvcResult result = mockMvc.perform(get("/scopedproxy/form")) - .andExpect(status().isOk()) - .andExpect(model().attributeExists("todo")) - .andReturn(); - - TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo"); - assertTrue(StringUtils.isEmpty(item.getDescription())); - } - - @Test - public void whenSubmit_thenSubsequentFormRequestContainsMostRecentTodo() throws Exception { - mockMvc.perform(post("/scopedproxy/form") - .param("description", "newtodo")) - .andExpect(status().is3xxRedirection()) - .andReturn(); - - MvcResult result = mockMvc.perform(get("/scopedproxy/form")) - .andExpect(status().isOk()) - .andExpect(model().attributeExists("todo")) - .andReturn(); - TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo"); - assertEquals("newtodo", item.getDescription()); - } - -} +package com.baeldung.sessionattrs; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.util.StringUtils; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +@Import(TestConfig.class) +public class TodoControllerWithScopedProxyTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext wac; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) + .build(); + } + + @Test + public void whenFirstRequest_thenContainsUnintializedTodo() throws Exception { + MvcResult result = mockMvc.perform(get("/scopedproxy/form")) + .andExpect(status().isOk()) + .andExpect(model().attributeExists("todo")) + .andReturn(); + + TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo"); + assertTrue(StringUtils.isEmpty(item.getDescription())); + } + + @Test + public void whenSubmit_thenSubsequentFormRequestContainsMostRecentTodo() throws Exception { + mockMvc.perform(post("/scopedproxy/form") + .param("description", "newtodo")) + .andExpect(status().is3xxRedirection()) + .andReturn(); + + MvcResult result = mockMvc.perform(get("/scopedproxy/form")) + .andExpect(status().isOk()) + .andExpect(model().attributeExists("todo")) + .andReturn(); + TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo"); + assertEquals("newtodo", item.getDescription()); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesIntegrationTest.java b/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesTest.java similarity index 95% rename from spring-5/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesIntegrationTest.java rename to spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesTest.java index c97fc79f29..e41de880d3 100644 --- a/spring-5/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesIntegrationTest.java +++ b/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesTest.java @@ -1,68 +1,68 @@ -package com.baeldung.sessionattrs; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.util.StringUtils; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.servlet.FlashMap; - -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -public class TodoControllerWithSessionAttributesIntegrationTest { - - @Autowired - private MockMvc mockMvc; - - @Autowired - private WebApplicationContext wac; - - @Before - public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) - .build(); - } - - @Test - public void whenFirstRequest_thenContainsUnintializedTodo() throws Exception { - MvcResult result = mockMvc.perform(get("/sessionattributes/form")) - .andExpect(status().isOk()) - .andExpect(model().attributeExists("todo")) - .andReturn(); - - TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo"); - assertTrue(StringUtils.isEmpty(item.getDescription())); - } - - @Test - public void whenSubmit_thenSubsequentFormRequestContainsMostRecentTodo() throws Exception { - FlashMap flashMap = mockMvc.perform(post("/sessionattributes/form") - .param("description", "newtodo")) - .andExpect(status().is3xxRedirection()) - .andReturn().getFlashMap(); - - MvcResult result = mockMvc.perform(get("/sessionattributes/form") - .sessionAttrs(flashMap)) - .andExpect(status().isOk()) - .andExpect(model().attributeExists("todo")) - .andReturn(); - TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo"); - assertEquals("newtodo", item.getDescription()); - } - -} +package com.baeldung.sessionattrs; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.util.StringUtils; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.FlashMap; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class TodoControllerWithSessionAttributesTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext wac; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) + .build(); + } + + @Test + public void whenFirstRequest_thenContainsUnintializedTodo() throws Exception { + MvcResult result = mockMvc.perform(get("/sessionattributes/form")) + .andExpect(status().isOk()) + .andExpect(model().attributeExists("todo")) + .andReturn(); + + TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo"); + assertTrue(StringUtils.isEmpty(item.getDescription())); + } + + @Test + public void whenSubmit_thenSubsequentFormRequestContainsMostRecentTodo() throws Exception { + FlashMap flashMap = mockMvc.perform(post("/sessionattributes/form") + .param("description", "newtodo")) + .andExpect(status().is3xxRedirection()) + .andReturn().getFlashMap(); + + MvcResult result = mockMvc.perform(get("/sessionattributes/form") + .sessionAttrs(flashMap)) + .andExpect(status().isOk()) + .andExpect(model().attributeExists("todo")) + .andReturn(); + TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo"); + assertEquals("newtodo", item.getDescription()); + } + +} From af7f39371641ff574c6e3193ad4ded31c831e74f Mon Sep 17 00:00:00 2001 From: Chris Oberle Date: Sat, 10 Mar 2018 07:19:57 -0500 Subject: [PATCH 77/91] update title of html pages --- .../src/main/resources/templates/sessionattrs/index.html | 2 +- .../main/resources/templates/sessionattrs/scopedproxyform.html | 2 +- .../main/resources/templates/sessionattrs/scopedproxytodos.html | 2 +- .../resources/templates/sessionattrs/sessionattributesform.html | 2 +- .../templates/sessionattrs/sessionattributestodos.html | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/index.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/index.html index f9df863e45..d0c4c7cd3a 100644 --- a/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/index.html +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/index.html @@ -1,7 +1,7 @@ - Session Scope in Spring MVC + Session Attributes in Spring MVC diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxyform.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxyform.html index 604c60dfbb..ebb3e16525 100644 --- a/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxyform.html +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxyform.html @@ -1,7 +1,7 @@ - Session Scope in Spring MVC + Session Attributes in Spring MVC diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxytodos.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxytodos.html index 743cd76b5d..f7916b0f8a 100644 --- a/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxytodos.html +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/scopedproxytodos.html @@ -1,7 +1,7 @@ - Session Scope in Spring MVC + Session Attributes in Spring MVC diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributesform.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributesform.html index 93e052d6b5..73233c12f3 100644 --- a/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributesform.html +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributesform.html @@ -1,7 +1,7 @@ - Session Scope in Spring MVC + Session Attributes in Spring MVC diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributestodos.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributestodos.html index 7525604298..753ee133e9 100644 --- a/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributestodos.html +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/sessionattrs/sessionattributestodos.html @@ -1,7 +1,7 @@ - Session Scope in Spring MVC + Session Attributes in Spring MVC From 9667f061abd89f880f6b7e9dca4142394c3c63d2 Mon Sep 17 00:00:00 2001 From: Arjay Nacion Date: Sat, 10 Mar 2018 22:52:35 +0800 Subject: [PATCH 78/91] BAEL-1510 - RxJava - Combining Observables (#3605) * BAEL-1510 - RxJava - Combining Observables Signed-off-by: Arjay Nacion * BAEL-1510 - RxJava - Combining Observables * BAEL-1510 - RxJava - Combining Observables * Fixed indentations, used assertJ assertions, renamed test class to end in UnitTest * BAEL-1510 - RxJava - Combining Observables * Amendments based on PR review --- .../combine/ObservableCombineUnitTest.java | 121 ++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 rxjava/src/test/java/com/baeldung/rxjava/combine/ObservableCombineUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/combine/ObservableCombineUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/combine/ObservableCombineUnitTest.java new file mode 100644 index 0000000000..693608d116 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/combine/ObservableCombineUnitTest.java @@ -0,0 +1,121 @@ +package com.baeldung.rxjava.combine; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import rx.Observable; +import rx.observers.TestSubscriber; + +public class ObservableCombineUnitTest { + + private static ExecutorService executor; + + @BeforeClass + public static void setupClass() { + executor = Executors.newFixedThreadPool(10); + } + + @AfterClass + public static void tearDownClass() { + executor.shutdown(); + } + + @Test + public void givenTwoObservables_whenMerged_shouldEmitCombinedResults() { + List results = new ArrayList<>(); + + //@formatter:off + Observable.merge( + Observable.from(new String[] {"Hello", "World"}), + Observable.from(new String[]{ "I love", "RxJava"}) + ).subscribe(data -> { + results.add(data); + }); + //@formatter:on + + assertThat(results).isNotEmpty(); + assertThat(results.size()).isEqualTo(4); + assertThat(results).contains("Hello", "World", "I love", "RxJava"); + } + + @Test + public void givenAnObservable_whenStartWith_thenPrependEmittedResults() { + StringBuffer buffer = new StringBuffer(); + + //@formatter:off + Observable + .from(new String[] { "RxJava", "Observables" }) + .startWith("Buzzwords of Reactive Programming") + .subscribe(data -> { + buffer.append(data).append(" "); + }); + //@formatter:on + + assertThat(buffer.toString().trim()).isEqualTo("Buzzwords of Reactive Programming RxJava Observables"); + } + + @Test + public void givenTwoObservables_whenZipped_thenReturnCombinedResults() { + List zippedStrings = new ArrayList<>(); + + //@formatter:off + Observable.zip( + Observable.from(new String[] { "Simple", "Moderate", "Complex" }), + Observable.from(new String[] { "Solutions", "Success", "Heirarchy"}), + (str1, str2) -> { + return str1 + " " + str2; + }).subscribe(zipped -> { + zippedStrings.add(zipped); + }); + //formatter:on + + assertThat(zippedStrings).isNotEmpty(); + assertThat(zippedStrings.size()).isEqualTo(3); + assertThat(zippedStrings).contains("Simple Solutions", "Moderate Success", "Complex Heirarchy"); + } + + @Test + public void givenMutipleObservablesOneThrows_whenMerged_thenCombineBeforePropagatingError() { + Future f1 = executor.submit(createCallable("Hello")); + Future f2 = executor.submit(createCallable("World")); + Future f3 = executor.submit(createCallable(null)); + Future f4 = executor.submit(createCallable("RxJava")); + + TestSubscriber testSubscriber = new TestSubscriber<>(); + + //@formatter:off + Observable.mergeDelayError( + Observable.from(f1), + Observable.from(f2), + Observable.from(f3), + Observable.from(f4) + ).subscribe(testSubscriber); + //@formatter:on + + testSubscriber.assertValues("hello", "world", "rxjava"); + testSubscriber.assertError(ExecutionException.class); + } + + private Callable createCallable(final String data) { + return new Callable() { + @Override + public String call() throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data should not be null."); + } + return data.toLowerCase(); + } + }; + } +} From bce01cfff54e2e081d90277c30db6945585b6dd7 Mon Sep 17 00:00:00 2001 From: Magdalena Krause Date: Sat, 10 Mar 2018 12:51:37 -0300 Subject: [PATCH 79/91] Bael 1580 2 (#3787) * BAEL-1580: Changing hamcrest dependency. * BAEL-1580: Adding test scope. * BAEL-1580: Adding comparesEqualTo and notANumber matchers. --- testing-modules/mockito/pom.xml | 7 +++-- .../hamcrest/HamcrestNumberUnitTest.java | 28 ++++++++++++++++++- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/testing-modules/mockito/pom.xml b/testing-modules/mockito/pom.xml index 1ec1ffe7bd..cdd73e6efe 100644 --- a/testing-modules/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -46,14 +46,14 @@ ${powermock.version} test - + org.hamcrest java-hamcrest - 2.0.0.0 + ${hamcrest.version} test - + @@ -74,6 +74,7 @@ 1.7.0 + 2.0.0.0 diff --git a/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestNumberUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestNumberUnitTest.java index 21606afd79..fbba6b94d2 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestNumberUnitTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestNumberUnitTest.java @@ -6,8 +6,15 @@ import java.math.BigDecimal; import java.time.LocalDate; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.closeTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.hamcrest.Matchers.comparesEqualTo; +import static org.hamcrest.Matchers.notANumber; public class HamcrestNumberUnitTest { @@ -43,6 +50,19 @@ public class HamcrestNumberUnitTest { assertThat(actual, is(not(closeTo(operand, error)))); } + @Test + public void given5_whenComparesEqualTo5_thenCorrect() { + Integer five = 5; + assertThat(five, comparesEqualTo(five)); + } + + @Test + public void given5_whenNotComparesEqualTo7_thenCorrect() { + Integer seven = 7; + Integer five = 5; + assertThat(five, not(comparesEqualTo(seven))); + } + @Test public void given7_whenGreaterThan5_thenCorrect() { Integer seven = 7; @@ -149,4 +169,10 @@ public class HamcrestNumberUnitTest { else return -1; } } + + @Test + public void givenNaN_whenIsNotANumber_thenCorrect() { + double zero = 0d; + assertThat(zero / zero, is(notANumber())); + } } From c5fadb51916d2890ad6fd5d25a0ddbd4484f2f42 Mon Sep 17 00:00:00 2001 From: bahti Date: Sat, 10 Mar 2018 19:00:14 +0300 Subject: [PATCH 80/91] RxJava Maybe samples added. (#3646) * RxJava Maybe samples added. * update rxjava maybe test * Update rxjava maybe tests --- .../java/com/baeldung/rxjava/MaybeTest.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 rxjava/src/test/java/com/baeldung/rxjava/MaybeTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/MaybeTest.java b/rxjava/src/test/java/com/baeldung/rxjava/MaybeTest.java new file mode 100644 index 0000000000..501ee1f196 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/MaybeTest.java @@ -0,0 +1,40 @@ +package com.baeldung.rxjava; + +import org.junit.Test; + +import io.reactivex.Flowable; +import io.reactivex.Maybe; + +public class MaybeTest { + @Test + public void whenEmitsSingleValue_thenItIsObserved() { + Maybe maybe = Flowable.just(1, 2, 3, 4, 5) + .firstElement(); + + maybe.map(x -> x + 7) + .filter(x -> x > 0) + .test() + .assertResult(8) + .assertComplete(); + } + + @Test + public void whenEmitsNoValue_thenSignalsCompletionAndNoValueObserved() { + Maybe maybe = Flowable.just(1, 2, 3, 4, 5) + .skip(5) + .firstElement(); + + maybe.test() + .assertComplete() + .assertNoValues(); + } + + @Test + public void whenThrowsError_thenErrorIsRaised() { + Maybe maybe = Flowable. error(new Exception("msg")) + .firstElement(); + + maybe.test() + .assertErrorMessage("msg"); + } +} From 89f1c2721ee847b3d9c581082a91c7068922a916 Mon Sep 17 00:00:00 2001 From: Predrag Maric Date: Sat, 10 Mar 2018 20:20:04 +0100 Subject: [PATCH 81/91] BAEL-1498 Money into words (#3797) * Add tradukisto library * Implement MoneyIntoWords * Update the version of tradukisto library * Refactor MoneyIntoWords * Refactor * Refactor pom.xml * Refactor pom.xml * Refactor NumberWordConverter * BAEL-1498 Small refactoring * Test edge cases * BAEL-1498 Additional tests --- algorithms/pom.xml | 9 +- .../NumberWordConverter.java | 75 +++++++++++++++++ .../moneywords/NumberWordConverterTest.java | 84 +++++++++++++++++++ 3 files changed, 166 insertions(+), 2 deletions(-) create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/numberwordconverter/NumberWordConverter.java create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java diff --git a/algorithms/pom.xml b/algorithms/pom.xml index 2eb8cd42b6..8751cf45c0 100644 --- a/algorithms/pom.xml +++ b/algorithms/pom.xml @@ -9,6 +9,7 @@ 1.5.0 1.16.12 3.6.1 + 1.0.1 @@ -39,6 +40,11 @@ jgrapht-core 1.0.1 + + pl.allegro.finance + tradukisto + ${tradukisto.version} + org.assertj assertj-core @@ -46,7 +52,6 @@ test - @@ -77,4 +82,4 @@ - + \ No newline at end of file diff --git a/algorithms/src/main/java/com/baeldung/algorithms/numberwordconverter/NumberWordConverter.java b/algorithms/src/main/java/com/baeldung/algorithms/numberwordconverter/NumberWordConverter.java new file mode 100644 index 0000000000..0fe2960f96 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/numberwordconverter/NumberWordConverter.java @@ -0,0 +1,75 @@ +package com.baeldung.algorithms.numberwordconverter; + +import java.math.BigDecimal; + +import pl.allegro.finance.tradukisto.MoneyConverters; + +public class NumberWordConverter { + + public static final String INVALID_INPUT_GIVEN = "Invalid input given"; + + public static final String[] ones = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; + + public static final String[] tens = { + "", // 0 + "", // 1 + "twenty", // 2 + "thirty", // 3 + "forty", // 4 + "fifty", // 5 + "sixty", // 6 + "seventy", // 7 + "eighty", // 8 + "ninety" // 9 + }; + + public static String getMoneyIntoWords(String input) { + MoneyConverters converter = MoneyConverters.ENGLISH_BANKING_MONEY_VALUE; + return converter.asWords(new BigDecimal(input)); + } + + public static String getMoneyIntoWords(final double money) { + long dollar = (long) money; + long cents = Math.round((money - dollar) * 100); + if (money == 0D) { + return ""; + } + if (money < 0) { + return INVALID_INPUT_GIVEN; + } + String dollarPart = ""; + if (dollar > 0) { + dollarPart = convert(dollar) + " dollar" + (dollar == 1 ? "" : "s"); + } + String centsPart = ""; + if (cents > 0) { + if (dollarPart.length() > 0) { + centsPart = " and "; + } + centsPart += convert(cents) + " cent" + (cents == 1 ? "" : "s"); + } + return dollarPart + centsPart; + } + + private static String convert(final long n) { + if (n < 0) { + return INVALID_INPUT_GIVEN; + } + if (n < 20) { + return ones[(int) n]; + } + if (n < 100) { + return tens[(int) n / 10] + ((n % 10 != 0) ? " " : "") + ones[(int) n % 10]; + } + if (n < 1000) { + return ones[(int) n / 100] + " hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100); + } + if (n < 1_000_000) { + return convert(n / 1000) + " thousand" + ((n % 1000 != 0) ? " " : "") + convert(n % 1000); + } + if (n < 1_000_000_000) { + return convert(n / 1_000_000) + " million" + ((n % 1_000_000 != 0) ? " " : "") + convert(n % 1_000_000); + } + return convert(n / 1_000_000_000) + " billion" + ((n % 1_000_000_000 != 0) ? " " : "") + convert(n % 1_000_000_000); + } +} \ No newline at end of file diff --git a/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java b/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java new file mode 100644 index 0000000000..a4a169f158 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java @@ -0,0 +1,84 @@ +package com.baeldung.algorithms.moneywords; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.algorithms.numberwordconverter.NumberWordConverter; + +public class NumberWordConverterTest { + + @Test + public void whenMoneyNegative_thenReturnInvalidInput() { + assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13)); + } + + @Test + public void whenZeroDollarsGiven_thenReturnEmptyString() { + assertEquals("", NumberWordConverter.getMoneyIntoWords(0)); + } + + @Test + public void whenOnlyDollarsGiven_thenReturnWords() { + assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1)); + } + + @Test + public void whenOnlyCentsGiven_thenReturnWords() { + assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6)); + } + + @Test + public void whenAlmostAMillioDollarsGiven_thenReturnWords() { + String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars"; + assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999)); + } + + @Test + public void whenThirtyMillionDollarsGiven_thenReturnWords() { + String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars"; + assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978)); + } + + @Test + public void whenTwoBillionDollarsGiven_thenReturnWords() { + String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars"; + assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810)); + } + + @Test + public void whenGivenDollarsAndCents_thenReturnWords() { + String expectedResult = "nine hundred twenty four dollars and sixty cents"; + assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6)); + } + + @Test + public void whenOneDollarAndNoCents_thenReturnDollarSingular() { + assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1)); + } + + @Test + public void whenNoDollarsAndOneCent_thenReturnCentSingular() { + assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01)); + } + + @Test + public void whenNoDollarsAndTwoCents_thenReturnCentsPlural() { + assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02)); + } + + @Test + public void whenNoDollarsAndNinetyNineCents_thenReturnWords() { + assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99)); + } + + @Test + public void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() { + assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959)); + } + + @Test + public void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() { + assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310")); + } +} From 41a377a456b289721a5d90e83a2321c1dc5ab79b Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sat, 10 Mar 2018 21:33:31 +0200 Subject: [PATCH 82/91] removing unused imports --- .../baeldung/dsrouting/DataSourceRoutingTestConfiguration.java | 1 - .../deletion/config/PersistenceJPAConfigDeletion.java | 2 -- .../test/java/org/baeldung/persistence/deletion/model/Baz.java | 1 - 3 files changed, 4 deletions(-) diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java index dee9d58722..abda9d3ee3 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java @@ -7,7 +7,6 @@ import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java index 37388d1c51..09d118fedc 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java @@ -2,8 +2,6 @@ package org.baeldung.persistence.deletion.config; import org.baeldung.config.PersistenceJPAConfigL2Cache; -import java.util.Properties; - public class PersistenceJPAConfigDeletion extends PersistenceJPAConfigL2Cache { public PersistenceJPAConfigDeletion() { diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java index 2dad3e6654..4fb3f8965e 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java @@ -1,7 +1,6 @@ package org.baeldung.persistence.deletion.model; import javax.persistence.*; -import java.util.List; @Entity @Table(name = "BAZ") From 3380dba316dc4b2a66796a7be7d98cc7686f12ad Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 10 Mar 2018 21:56:29 +0100 Subject: [PATCH 83/91] Delete README.md (#3796) --- intelliJ/README.md | 1 - 1 file changed, 1 deletion(-) delete mode 100644 intelliJ/README.md diff --git a/intelliJ/README.md b/intelliJ/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/intelliJ/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: From dffd5fd9035b9a3a2fceccd5a4da1e336960794a Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sun, 11 Mar 2018 00:07:32 +0200 Subject: [PATCH 84/91] minor formatting work --- .../org/baeldung/config/StudentJpaConfig.java | 12 +++++------ .../org/baeldung/dsrouting/ClientDao.java | 3 +-- .../dao/ExtendedRepositoryImpl.java | 3 +-- .../inmemory/persistence/model/KVTag.java | 3 ++- .../persistence/model/LocationTag.java | 3 ++- .../persistence/model/ManyStudent.java | 7 +++---- .../inmemory/persistence/model/ManyTag.java | 3 ++- .../inmemory/persistence/model/SkillTag.java | 3 ++- .../java/org/baeldung/sqlfiles/Country.java | 9 ++++++--- .../DataSourceRoutingTestConfiguration.java | 10 ++-------- .../AdvancedTaggingIntegrationTest.java | 2 +- ...endedStudentRepositoryIntegrationTest.java | 12 +++++------ .../repository/InMemoryDBIntegrationTest.java | 20 +++++++++---------- .../service/DeletionIntegrationTest.java | 8 ++------ 14 files changed, 46 insertions(+), 52 deletions(-) diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJpaConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJpaConfig.java index 8021691716..17047cbab2 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJpaConfig.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJpaConfig.java @@ -25,7 +25,7 @@ public class StudentJpaConfig { @Autowired private Environment env; - + @Bean public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); @@ -36,7 +36,7 @@ public class StudentJpaConfig { return dataSource; } - + @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); @@ -46,23 +46,23 @@ public class StudentJpaConfig { em.setJpaProperties(additionalProperties()); return em; } - + @Bean JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory); return transactionManager; } - + final Properties additionalProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); - hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); - + return hibernateProperties; } } diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDao.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDao.java index 180f54326e..9e19cf4ed9 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDao.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDao.java @@ -19,8 +19,7 @@ public class ClientDao { } public String getClientName() { - return this.jdbcTemplate.query(SQL_GET_CLIENT_NAME, rowMapper) - .get(0); + return this.jdbcTemplate.query(SQL_GET_CLIENT_NAME, rowMapper).get(0); } private static RowMapper rowMapper = (rs, rowNum) -> { diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java index 0dd32757d7..7ed652dc4d 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java @@ -27,8 +27,7 @@ public class ExtendedRepositoryImpl extends SimpleJp CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery query = builder.createQuery(getDomainClass()); Root root = query.from(getDomainClass()); - query.select(root) - .where(builder.like(root. get(attributeName), "%" + text + "%")); + query.select(root).where(builder.like(root. get(attributeName), "%" + text + "%")); TypedQuery q = entityManager.createQuery(query); return q.getResultList(); } diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/KVTag.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/KVTag.java index ba0071e37b..1522744116 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/KVTag.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/KVTag.java @@ -7,7 +7,8 @@ public class KVTag { private String key; private String value; - public KVTag(){} + public KVTag() { + } public KVTag(String key, String value) { super(); diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/LocationTag.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/LocationTag.java index 071dc24806..3acdbbe6fe 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/LocationTag.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/LocationTag.java @@ -8,7 +8,8 @@ public class LocationTag { private int xPos; private int yPos; - public LocationTag(){} + public LocationTag() { + } public LocationTag(String name, int xPos, int yPos) { super(); diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyStudent.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyStudent.java index 98778b8f75..8343edc9cd 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyStudent.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyStudent.java @@ -13,12 +13,11 @@ public class ManyStudent { private String name; @ManyToMany(cascade = CascadeType.ALL) - @JoinTable(name = "manystudent_manytags", - joinColumns = @JoinColumn(name = "manystudent_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "manytag_id", referencedColumnName = "id")) + @JoinTable(name = "manystudent_manytags", joinColumns = @JoinColumn(name = "manystudent_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "manytag_id", referencedColumnName = "id")) private Set manyTags = new HashSet<>(); - public ManyStudent() {} + public ManyStudent() { + } public ManyStudent(String name) { this.name = name; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyTag.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyTag.java index 96f9534d43..e820506544 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyTag.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/ManyTag.java @@ -15,7 +15,8 @@ public class ManyTag { @ManyToMany(mappedBy = "manyTags") private Set students = new HashSet<>(); - public ManyTag() {} + public ManyTag() { + } public ManyTag(String name) { this.name = name; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/SkillTag.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/SkillTag.java index 0300d83d50..490ee0a18e 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/SkillTag.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/SkillTag.java @@ -7,7 +7,8 @@ public class SkillTag { private String name; private int value; - public SkillTag(){} + public SkillTag() { + } public SkillTag(String name, int value) { super(); diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/sqlfiles/Country.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/sqlfiles/Country.java index 0555c8186c..922f55cbf6 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/sqlfiles/Country.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/sqlfiles/Country.java @@ -13,21 +13,24 @@ public class Country { @Id @GeneratedValue(strategy = IDENTITY) private Integer id; - + @Column(nullable = false) private String name; - + public Integer getId() { return id; } + public void setId(Integer id) { this.id = id; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } - + } diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java index abda9d3ee3..faad1695f4 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java @@ -34,17 +34,11 @@ public class DataSourceRoutingTestConfiguration { private DataSource clientADatasource() { EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); - return dbBuilder.setType(EmbeddedDatabaseType.H2) - .setName("CLIENT_A") - .addScript("classpath:dsrouting-db.sql") - .build(); + return dbBuilder.setType(EmbeddedDatabaseType.H2).setName("CLIENT_A").addScript("classpath:dsrouting-db.sql").build(); } private DataSource clientBDatasource() { EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); - return dbBuilder.setType(EmbeddedDatabaseType.H2) - .setName("CLIENT_B") - .addScript("classpath:dsrouting-db.sql") - .build(); + return dbBuilder.setType(EmbeddedDatabaseType.H2).setName("CLIENT_B").addScript("classpath:dsrouting-db.sql").build(); } } diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java index 2e4f1a0e23..9432420878 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java @@ -53,7 +53,7 @@ public class AdvancedTaggingIntegrationTest { } @Test - public void givenStudentWithKVTags_whenSave_thenGetByTagOk(){ + public void givenStudentWithKVTags_whenSave_thenGetByTagOk() { Student student = new Student(0, "John"); student.setKVTags(Arrays.asList(new KVTag("department", "computer science"))); studentRepository.save(student); diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java index 0970daa0ee..7c6ec9b6da 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java @@ -16,13 +16,13 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { StudentJPAH2Config.class}) +@ContextConfiguration(classes = { StudentJPAH2Config.class }) public class ExtendedStudentRepositoryIntegrationTest { @Resource private ExtendedStudentRepository extendedStudentRepository; - + @Before - public void setup(){ + public void setup() { Student student = new Student(1, "john"); extendedStudentRepository.save(student); Student student2 = new Student(2, "johnson"); @@ -30,10 +30,10 @@ public class ExtendedStudentRepositoryIntegrationTest { Student student3 = new Student(3, "tom"); extendedStudentRepository.save(student3); } - + @Test - public void givenStudents_whenFindByName_thenGetOk(){ + public void givenStudents_whenFindByName_thenGetOk() { List students = extendedStudentRepository.findByAttributeContainsText("name", "john"); - assertThat(students.size()).isEqualTo(2); + assertThat(students.size()).isEqualTo(2); } } diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java index 28d7e3772c..3d9e376e81 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java @@ -21,24 +21,24 @@ import static org.junit.Assert.assertEquals; @ContextConfiguration(classes = { StudentJpaConfig.class }, loader = AnnotationConfigContextLoader.class) @Transactional public class InMemoryDBIntegrationTest { - + @Resource private StudentRepository studentRepository; - + private static final long ID = 1; - private static final String NAME="john"; - + private static final String NAME = "john"; + @Test - public void givenStudent_whenSave_thenGetOk(){ + public void givenStudent_whenSave_thenGetOk() { Student student = new Student(ID, NAME); studentRepository.save(student); - + Student student2 = studentRepository.findOne(ID); - assertEquals("name incorrect", NAME, student2.getName()); + assertEquals("name incorrect", NAME, student2.getName()); } @Test - public void givenStudentWithTags_whenSave_thenGetByTagOk(){ + public void givenStudentWithTags_whenSave_thenGetByTagOk() { Student student = new Student(ID, NAME); student.setTags(Arrays.asList("full time", "computer science")); studentRepository.save(student); @@ -48,7 +48,7 @@ public class InMemoryDBIntegrationTest { } @Test - public void givenMultipleStudentsWithTags_whenSave_thenGetByTagReturnsCorrectCount(){ + public void givenMultipleStudentsWithTags_whenSave_thenGetByTagReturnsCorrectCount() { Student student = new Student(0, "Larry"); student.setTags(Arrays.asList("full time", "computer science")); studentRepository.save(student); @@ -70,7 +70,7 @@ public class InMemoryDBIntegrationTest { } @Test - public void givenStudentWithTags_whenSave_thenGetByNameAndTagOk(){ + public void givenStudentWithTags_whenSave_thenGetByNameAndTagOk() { Student student = new Student(ID, NAME); student.setTags(Arrays.asList("full time", "computer science")); studentRepository.save(student); diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java index 9e5c5fa07a..f42a4e9be1 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java @@ -117,9 +117,7 @@ public class DeletionIntegrationTest { entityManager.persist(foo); flushAndClear(); - entityManager.createQuery("delete from Foo where id = :id") - .setParameter("id", foo.getId()) - .executeUpdate(); + entityManager.createQuery("delete from Foo where id = :id").setParameter("id", foo.getId()).executeUpdate(); assertThat(entityManager.find(Foo.class, foo.getId()), nullValue()); } @@ -131,9 +129,7 @@ public class DeletionIntegrationTest { entityManager.persist(foo); flushAndClear(); - entityManager.createNativeQuery("delete from FOO where ID = :id") - .setParameter("id", foo.getId()) - .executeUpdate(); + entityManager.createNativeQuery("delete from FOO where ID = :id").setParameter("id", foo.getId()).executeUpdate(); assertThat(entityManager.find(Foo.class, foo.getId()), nullValue()); } From f50d111c5e5d4fbb4e0a85ae8c621d46e0b8403f Mon Sep 17 00:00:00 2001 From: Jonathan Date: Sun, 11 Mar 2018 13:18:35 -0500 Subject: [PATCH 85/91] BAEL-1068 (#3456) * BAEL-1068 - Javadoc example classes * BAEL-1068 - Formatting change for pom.xml * Updated javadoc comments to reflect article example * Added javadoc tags for throws, deprecated, and version and a clause to throw an exception --- .../src/main/java/com/baeldung/javadoc/SuperHero.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java b/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java index 029a779cdb..561430f66f 100644 --- a/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java +++ b/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java @@ -23,9 +23,15 @@ public class SuperHero extends Person { * @return the amount of health hero has after attack * @see HERO-402 * @since 1.0 + * @deprecated As of version 1.1, use . . . instead + * @version 1.2 + * @throws IllegalArgumentException if incomingDamage is negative */ - public int successfullyAttacked(int incomingDamage, String damageType) { + public int successfullyAttacked(int incomingDamage, String damageType) throws Exception { // do things + if (incomingDamage < 0) { + throw new IllegalArgumentException ("Cannot cause negative damage"); + } return 0; } From e6360db343e3362f4ff1d9a84d7bdb6e3b301cf1 Mon Sep 17 00:00:00 2001 From: sasdroid <35628411+sasdroid@users.noreply.github.com> Date: Mon, 12 Mar 2018 18:18:55 +0100 Subject: [PATCH 86/91] Add code for article "Mapping LOB Data in Hibernate" (#3778) * Add lob example * Migrate the XML Based Configuration to Java Based Configuration --- .../hibernate/lob/HibernateSessionUtil.java | 61 ++++++++++++++++++ .../baeldung/hibernate/lob/model/User.java | 46 +++++++++++++ .../com/baeldung/hibernate/lob/LobTest.java | 61 ++++++++++++++++++ hibernate5/src/test/resources/profile.png | Bin 0 -> 1117 bytes 4 files changed, 168 insertions(+) create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java create mode 100644 hibernate5/src/test/java/com/baeldung/hibernate/lob/LobTest.java create mode 100644 hibernate5/src/test/resources/profile.png diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java new file mode 100644 index 0000000000..dc5242ee7c --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.lob; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.lob.model.User; + +public class HibernateSessionUtil { + + private static SessionFactory sessionFactory; + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = makeSessionFactory(serviceRegistry); + } + return sessionFactory; + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(User.class); + + Metadata metadata = metadataSources.buildMetadata(); + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java new file mode 100644 index 0000000000..21f725b388 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java @@ -0,0 +1,46 @@ +package com.baeldung.hibernate.lob.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.Table; + +@Entity +@Table(name="user") +public class User { + + @Id + private String id; + + @Column(name = "name", columnDefinition="VARCHAR(128)") + private String name; + + @Lob + @Column(name = "photo", columnDefinition="BLOB") + private byte[] photo; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public byte[] getPhoto() { + return photo; + } + + public void setPhoto(byte[] photo) { + this.photo = photo; + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobTest.java new file mode 100644 index 0000000000..74a94d544b --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobTest.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.lob; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; + +import org.apache.commons.io.IOUtils; +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.lob.model.User; + +public class LobTest { + + private Session session; + + @Before + public void init(){ + try { + session = HibernateSessionUtil.getSessionFactory("hibernate.properties") + .openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + } + + @After + public void close(){ + if(session != null) session.close(); + } + + @Test + public void givenValidInsertLobObject_whenQueried_returnSameDataAsInserted(){ + User user = new User(); + try(InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("profile.png");) { + // Get Image file from the resource + if(inputStream == null) fail("Unable to get resources"); + user.setId("1"); + user.setName("User"); + user.setPhoto(IOUtils.toByteArray(inputStream)); + + session.persist(user); + } catch (IOException e) { + fail("Unable to read input stream"); + } + + User result = session.find(User.class, "1"); + + assertNotNull("Query result is null", result); + assertEquals("User's name is invalid", user.getName(), result.getName() ); + assertTrue("User's photo is corrupted", Arrays.equals(user.getPhoto(), result.getPhoto()) ); + } +} diff --git a/hibernate5/src/test/resources/profile.png b/hibernate5/src/test/resources/profile.png new file mode 100644 index 0000000000000000000000000000000000000000..1cd4e978b96d0f59a6e48692fcb68d1c6c565a20 GIT binary patch literal 1117 zcmV-j1fu(iP)%yyh@V&OYl(_AFwE`D&8)` zPnvkdvc#Z>pRh2kBHk{=qaGfCG;?<;rVe;D+%LyZS~!K}c+|op81YK@rzPHU@Th|m z4Dk`HcojTY;+}_-W%HGqKH@C!LiH8Tp>1lC@aTqoy zBU~QK<}hs@q|M8($ee`o<9#`B3-PL4Y7d9kW#<;n>t}6VNpYCswLrJTtEa_lFwgN$52-_vxvvfJs@B6-OYs%-@M_JTx*UfozG6(Bhs)>w z!pG%vU$b%f++EGa<#Tu1FZ^c#{;G|y5=kM3Y#X^mtSrFA_-o-vX7e_$5-udx(>S4U)i|4)(UJ~zR(vwE+6VTAzoo7wIS|c zh*yt`3wK%<+yX~Z9G1z2GQgf3~qx jc9u$WjpqGof00000NkvXXu0mjfJX<<= literal 0 HcmV?d00001 From d0b42d10f22054ada505596d0f687e13c167e563 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Mon, 12 Mar 2018 22:21:45 +0200 Subject: [PATCH 87/91] modify tomcat dependency (#3806) --- guest/remote-debugging/pom.xml | 1 - hystrix/pom.xml | 1 - spring-boot/pom.xml | 1 - spring-custom-aop/spring-custom-aop/pom.xml | 1 - spring-mvc-email/pom.xml | 1 - spring-rest-angular/pom.xml | 1 - spring-rest-full/pom.xml | 1 - spring-rest-query-language/pom.xml | 1 - .../spring-security-jsp-authentication/pom.xml | 1 - spring-security-client/spring-security-jsp-authorize/pom.xml | 1 - spring-security-client/spring-security-jsp-config/pom.xml | 1 - .../spring-security-thymeleaf-authentication/pom.xml | 1 - .../spring-security-thymeleaf-authorize/pom.xml | 1 - spring-security-client/spring-security-thymeleaf-config/pom.xml | 1 - spring-security-mvc-boot/pom.xml | 1 - spring-security-openid/pom.xml | 1 - 16 files changed, 16 deletions(-) diff --git a/guest/remote-debugging/pom.xml b/guest/remote-debugging/pom.xml index d958d4c681..8540347e40 100644 --- a/guest/remote-debugging/pom.xml +++ b/guest/remote-debugging/pom.xml @@ -31,7 +31,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 9e4b2bb082..19da678eb7 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -34,7 +34,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided org.springframework.boot diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index a557604bf3..84dc43a605 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -58,7 +58,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided diff --git a/spring-custom-aop/spring-custom-aop/pom.xml b/spring-custom-aop/spring-custom-aop/pom.xml index 0bab7a4057..95c1b7419f 100644 --- a/spring-custom-aop/spring-custom-aop/pom.xml +++ b/spring-custom-aop/spring-custom-aop/pom.xml @@ -43,7 +43,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided diff --git a/spring-mvc-email/pom.xml b/spring-mvc-email/pom.xml index ddb1765af0..5f08b710ec 100644 --- a/spring-mvc-email/pom.xml +++ b/spring-mvc-email/pom.xml @@ -24,7 +24,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 3fc429f626..255aa840e7 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -19,7 +19,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided org.springframework.boot diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index c00387e7de..3bd7ec07f6 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -94,7 +94,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index 6826634bc9..b329bec07e 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -94,7 +94,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided diff --git a/spring-security-client/spring-security-jsp-authentication/pom.xml b/spring-security-client/spring-security-jsp-authentication/pom.xml index b29ce90aa4..2509b26293 100644 --- a/spring-security-client/spring-security-jsp-authentication/pom.xml +++ b/spring-security-client/spring-security-jsp-authentication/pom.xml @@ -31,7 +31,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided diff --git a/spring-security-client/spring-security-jsp-authorize/pom.xml b/spring-security-client/spring-security-jsp-authorize/pom.xml index 6fd89933bb..bd13520948 100644 --- a/spring-security-client/spring-security-jsp-authorize/pom.xml +++ b/spring-security-client/spring-security-jsp-authorize/pom.xml @@ -31,7 +31,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided diff --git a/spring-security-client/spring-security-jsp-config/pom.xml b/spring-security-client/spring-security-jsp-config/pom.xml index f533410acc..0a4c8fb5be 100644 --- a/spring-security-client/spring-security-jsp-config/pom.xml +++ b/spring-security-client/spring-security-jsp-config/pom.xml @@ -31,7 +31,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided diff --git a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml index 941cbb8a76..e42d499b64 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml @@ -31,7 +31,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided diff --git a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml index c70a099e68..5fa2016be8 100644 --- a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml @@ -31,7 +31,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided diff --git a/spring-security-client/spring-security-thymeleaf-config/pom.xml b/spring-security-client/spring-security-thymeleaf-config/pom.xml index 9ef2444d6c..9a00ad0080 100644 --- a/spring-security-client/spring-security-thymeleaf-config/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-config/pom.xml @@ -31,7 +31,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index 6566c0eea6..b717a1366d 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -31,7 +31,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided diff --git a/spring-security-openid/pom.xml b/spring-security-openid/pom.xml index aeabb161c9..a3942a8423 100644 --- a/spring-security-openid/pom.xml +++ b/spring-security-openid/pom.xml @@ -31,7 +31,6 @@ org.springframework.boot spring-boot-starter-tomcat - provided From ade15ea80a84a21b17b52bf817b35437bf18b666 Mon Sep 17 00:00:00 2001 From: Dhrubajyoti Bhattacharjee Date: Tue, 13 Mar 2018 02:37:03 +0530 Subject: [PATCH 88/91] BAEL-1576 Guide to unirest (#3779) --- libraries/pom.xml | 6 + .../java/com/baeldung/unirest/Article.java | 39 ++++ .../com/baeldung/unirest/HttpClientTest.java | 172 ++++++++++++++++++ pom.xml | 2 +- 4 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 libraries/src/test/java/com/baeldung/unirest/Article.java create mode 100644 libraries/src/test/java/com/baeldung/unirest/HttpClientTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index beeba88ff1..e9bfecf527 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -627,6 +627,11 @@ org.milyn milyn-smooks-all ${smooks.version} + + + com.mashape.unirest + unirest-java + ${unirest.version} @@ -814,6 +819,7 @@ 8.5.24 2.2.0 9.1.5.Final + 1.4.9 diff --git a/libraries/src/test/java/com/baeldung/unirest/Article.java b/libraries/src/test/java/com/baeldung/unirest/Article.java new file mode 100644 index 0000000000..03fd4959b2 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/unirest/Article.java @@ -0,0 +1,39 @@ +package com.baeldung.unirest; + +public class Article { + + private String id; + private String title; + private String author; + + public Article(String id, String title, String author) { + super(); + this.id = id; + this.title = title; + this.author = author; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/unirest/HttpClientTest.java b/libraries/src/test/java/com/baeldung/unirest/HttpClientTest.java new file mode 100644 index 0000000000..3e919f031c --- /dev/null +++ b/libraries/src/test/java/com/baeldung/unirest/HttpClientTest.java @@ -0,0 +1,172 @@ +package com.baeldung.unirest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import org.apache.http.entity.ContentType; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.unirest.Article; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.mashape.unirest.http.HttpResponse; +import com.mashape.unirest.http.JsonNode; +import com.mashape.unirest.http.ObjectMapper; +import com.mashape.unirest.http.Unirest; +import com.mashape.unirest.http.async.Callback; +import com.mashape.unirest.http.exceptions.UnirestException; + +public class HttpClientTest { + + @BeforeClass + public static void setup() { + // Unirest.setProxy(new HttpHost("localhost", 8080)); + Unirest.setTimeouts(20000, 15000); + Unirest.setDefaultHeader("X-app-name", "baeldung-unirest"); + Unirest.setDefaultHeader("X-request-id", "100004f00ab5"); + Unirest.setConcurrency(20, 5); + Unirest.setObjectMapper(new ObjectMapper() { + com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); + + public String writeValue(Object value) { + try { + return mapper.writeValueAsString(value); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + + } + + public T readValue(String value, Class valueType) { + + try { + return mapper.readValue(value, valueType); + } catch (Exception e) { + throw new RuntimeException(e); + } + + } + }); + } + + @AfterClass + public static void tearDown() throws IOException { + Unirest.clearDefaultHeaders(); + Unirest.shutdown(); + } + + @Test + public void shouldReturnStatusOkay() throws UnirestException { + HttpResponse jsonResponse = Unirest.get("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154") + .header("accept", "application/json") + .queryString("apiKey", "123") + .asJson(); + assertNotNull(jsonResponse.getBody()); + assertEquals(200, jsonResponse.getStatus()); + } + + @Test + public void shouldReturnStatusAccepted() throws UnirestException { + + Map headers = new HashMap(); + headers.put("accept", "application/json"); + headers.put("Authorization", "Bearer 5a9ce37b3100004f00ab5154"); + + Map fields = new HashMap(); + fields.put("name", "Sam Baeldung"); + fields.put("id", "PSP123"); + + HttpResponse jsonResponse = Unirest.put("http://www.mocky.io/v2/5a9ce7853100002a00ab515e") + .headers(headers) + .fields(fields) + .asJson(); + assertNotNull(jsonResponse.getBody()); + assertEquals(202, jsonResponse.getStatus()); + } + + @Test + public void givenRequestBodyWhenCreatedThenCorrect() throws UnirestException { + + HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") + .body("{\"name\":\"Sam Baeldung\", \"city\":\"viena\"}") + .asJson(); + assertEquals(201, jsonResponse.getStatus()); + } + + @Test + public void whenAysncRequestShouldReturnOk() throws InterruptedException, ExecutionException { + Future> future = Unirest.post("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154?mocky-delay=10000ms") + .header("accept", "application/json") + .asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + // Do something if the request failed + } + + public void completed(HttpResponse response) { + // Do something if the request is successful + } + + public void cancelled() { + // Do something if the request is cancelled + } + + }); + assertEquals(200, future.get() + .getStatus()); + + } + + @Test + public void givenArticleWhenCreatedThenCorrect() throws UnirestException { + Article article = new Article("ID1213", "Guide to Rest", "baeldung"); + HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") + .body(article) + .asJson(); + assertEquals(201, jsonResponse.getStatus()); + } + + // @Test + public void givenFileWhenUploadedThenCorrect() throws UnirestException { + + HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") + .field("file", new File("/path/to/file")) + .asJson(); + assertEquals(201, jsonResponse.getStatus()); + } + + // @Test + public void givenByteStreamWhenUploadedThenCorrect() throws IOException, UnirestException { + try (InputStream inputStream = new FileInputStream(new File("/path/to/file/artcile.txt"))) { + byte[] bytes = new byte[inputStream.available()]; + inputStream.read(bytes); + HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") + .field("file", bytes, "article.txt") + .asJson(); + assertEquals(201, jsonResponse.getStatus()); + } + + } + + // @Test + public void givenInputStreamWhenUploadedThenCorrect() throws UnirestException, IOException { + try (InputStream inputStream = new FileInputStream(new File("/path/to/file/artcile.txt"))) { + + HttpResponse jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d") + .field("file", inputStream, ContentType.APPLICATION_OCTET_STREAM, "article.txt") + .asJson(); + assertEquals(201, jsonResponse.getStatus()); + + } + } +} diff --git a/pom.xml b/pom.xml index 9b76ffd26d..6118e81288 100644 --- a/pom.xml +++ b/pom.xml @@ -388,4 +388,4 @@ - \ No newline at end of file + From 6fdfc3c48a5ba44890e8aa4ba477ccce03a93fa6 Mon Sep 17 00:00:00 2001 From: Miguel Rivero Date: Tue, 13 Mar 2018 07:30:19 +0100 Subject: [PATCH 89/91] BAEL-1546: Java 8 Math additions (#3805) * BAEL-1546: Java 8 Math additions * Applied feedback to Unit Tests * BAEL-1546 Added missing test annotations --- .../baeldung/math/MathNewMethodsUnitTest.java | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/math/MathNewMethodsUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/math/MathNewMethodsUnitTest.java b/core-java-8/src/test/java/com/baeldung/math/MathNewMethodsUnitTest.java new file mode 100644 index 0000000000..da96376009 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/math/MathNewMethodsUnitTest.java @@ -0,0 +1,89 @@ +package com.baeldung.math; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MathNewMethodsUnitTest { + + @Test + public void whenAddExactToInteger_thenExpectCorrectArithmeticResult() { + assertEquals(150, Math.addExact(100, 50)); // Returns 150 + } + + @Test + public void whenSubstractExactFromInteger_thenExpectCorrectArithmeticResult() { + assertEquals(50, Math.subtractExact(100, 50)); // Returns 50 + } + + @Test + public void whenDecrementExactInteger_thenExpectCorrectArithmeticResult() { + assertEquals(99, Math.decrementExact(100)); // Returns 99 + } + + @Test + public void whenIncrementExactToInteger_thenExpectCorrectArithmeticResult() { + assertEquals(101, Math.incrementExact(100)); // Returns 101 + } + + @Test + public void whenMultiplyExactTwoIntegers_thenExpectCorrectArithmeticResult() { + assertEquals(500, Math.multiplyExact(100, 5)); // Returns 500 + } + + @Test + public void whenNegateExactInteger_thenExpectCorrectArithmeticResult() { + assertEquals(-100, Math.negateExact(100)); // Returns -100 + } + + @Test(expected = ArithmeticException.class) + public void whenAddToMaxInteger_thenThrowsArithmeticException() { + Math.addExact(Integer.MAX_VALUE, 1); // Throws ArithmeticException + } + + @Test(expected = ArithmeticException.class) + public void whenDecrementMinInteger_thenThrowsArithmeticException() { + Math.decrementExact(Integer.MIN_VALUE); // Throws ArithmeticException + } + + @Test(expected = ArithmeticException.class) + public void whenIncrementMaxLong_thenThrowsArithmeticException() { + Math.incrementExact(Long.MAX_VALUE); // Throws ArithmeticException + } + + @Test(expected = ArithmeticException.class) + public void whenMultiplyMaxLong_thenThrowsArithmeticException() { + Math.multiplyExact(Long.MAX_VALUE, 2); // Throws ArithmeticException + } + + @Test(expected = ArithmeticException.class) + public void whenNegateMinInteger_thenThrowsArithmeticException() { + Math.negateExact(Integer.MIN_VALUE); // MinInt value: −2.147.483.648, but MaxInt Value: 2.147.483.647 => Throws ArithmeticException + } + + @Test(expected = ArithmeticException.class) + public void whenSubstractFromMinInteger_thenThrowsArithmeticException() { + Math.subtractExact(Integer.MIN_VALUE, 1); + } + + @Test + public void whenFloorDivTwoIntegers_thenExpectCorrectArithmeticResult() { + assertEquals(3, Math.floorDiv(7, 2)); // Exact quotient is 3.5 so floor(3.5) == 3 + assertEquals(-4, Math.floorDiv(-7, 2)); // Exact quotient is -3.5 so floor(-3.5) == -4 + } + + @Test + public void whenModDivTwoIntegers_thenExpectCorrectArithmeticResult() { + assertEquals(2, Math.floorMod(5, 3)); // Returns 2: floorMod for positive numbers returns the same as % operator + assertEquals(1, Math.floorMod(-5, 3)); // Returns 1 and not 2 because floorDiv(-5, 3) is -2 and not -1 and (-2*3) + (1) = -5 + } + + @Test + public void whenNextDownOfDouble_thenExpectCorrectNumber() { + double number = 3.0; + double expected = 2.999999999999; + double delta = 0.00000001; + assertEquals(expected, Math.nextDown(number), delta); // The delta defines the accepted error range + } + +} From 3ad0cb693cf0212f8f0b6f761c25b2ae3567fd44 Mon Sep 17 00:00:00 2001 From: ankishagarwal <34980371+ankishagarwal@users.noreply.github.com> Date: Wed, 14 Mar 2018 00:18:11 +0530 Subject: [PATCH 90/91] Request for BAEL-1584 (#3740) * Added for BAEL-1584 * updated for BAEL-1584 * Updated as per Suggestions from Josh, for BAEL-1584 * Removed wrapper class and updated few methods to return boolean instead of Integer --- .../findanelement/FindElementInAList.java | 71 +++++++++++ .../findanelement/FindAnElementTest.java | 116 ++++++++++++++++++ 2 files changed, 187 insertions(+) create mode 100644 core-java-8/src/main/java/com/baeldung/findanelement/FindElementInAList.java create mode 100644 core-java-8/src/test/java/com/baeldung/findanelement/FindAnElementTest.java diff --git a/core-java-8/src/main/java/com/baeldung/findanelement/FindElementInAList.java b/core-java-8/src/main/java/com/baeldung/findanelement/FindElementInAList.java new file mode 100644 index 0000000000..2f402ee72b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/findanelement/FindElementInAList.java @@ -0,0 +1,71 @@ +package com.baeldung.findanelement; + +import java.util.List; +import java.util.ListIterator; +import org.apache.commons.collections4.IterableUtils; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; + +public class FindElementInAList { + + public T findUsingIndexOf(T element, List list) { + int index = list.indexOf(element); + if (index >= 0) { + return element; + } + return null; + } + + public boolean findUsingListIterator(T element, List list) { + ListIterator listIterator = list.listIterator(); + while (listIterator.hasNext()) { + T elementFromList = listIterator.next(); + if (elementFromList.equals(element)) { + return true; + } + } + return false; + } + + public boolean findUsingEnhancedForLoop(T element, List list) { + for (T elementFromList : list) { + if (element.equals(elementFromList)) { + return true; + } + } + return false; + } + + public T findUsingStream(T element, List list) { + return list.stream() + .filter(integer -> integer.equals(element)) + .findFirst() + .orElse(null); + } + + public T findUsingParallelStream(T element, List list) { + return list.parallelStream() + .filter(integer -> integer.equals(element)) + .findAny() + .orElse(null); + } + + public T findUsingGuava(T element, List list) { + T foundElement = Iterables.tryFind(list, new Predicate() { + public boolean apply(T input) { + return element.equals(input); + } + }).orNull(); + return foundElement; + } + + public T findUsingApacheCommon(T element, List list) { + T foundElement = IterableUtils.find(list, new org.apache.commons.collections4.Predicate() { + public boolean evaluate(T input) { + return element.equals(input); + } + }); + return foundElement; + } + +} \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/findanelement/FindAnElementTest.java b/core-java-8/src/test/java/com/baeldung/findanelement/FindAnElementTest.java new file mode 100644 index 0000000000..1fef2d98e7 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/findanelement/FindAnElementTest.java @@ -0,0 +1,116 @@ +package com.baeldung.findanelement; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; + +public class FindAnElementTest { + + private static List scores = new ArrayList<>(); + static { + scores.add(0); + scores.add(1); + scores.add(2); + } + + private static FindElementInAList findElementInAList = new FindElementInAList<>(); + + @Test + public void givenElement_whenFoundUsingIndexOf_thenReturnElement() { + Integer scoreToFind = 1; + Integer score = findElementInAList.findUsingIndexOf(scoreToFind, scores); + assertTrue(score.equals(scoreToFind)); + } + + @Test + public void givenElement_whenNotFoundUsingListIterator_thenReturnNull() { + boolean found = findElementInAList.findUsingListIterator(5, scores); + assertTrue(!found); + } + + @Test + public void givenElement_whenFoundListIterator_thenReturnElement() { + Integer scoreToFind = 1; + boolean found = findElementInAList.findUsingListIterator(scoreToFind, scores); + assertTrue(found); + } + + @Test + public void givenElement_whenNotFoundUsingIndexOf_thenReturnNull() { + Integer score = findElementInAList.findUsingIndexOf(5, scores); + assertNull(score); + } + + @Test + public void givenElement_whenFoundUsingEnhancedForLoop_thenReturnElement() { + Integer scoreToFind = 1; + boolean found = findElementInAList.findUsingEnhancedForLoop(scoreToFind, scores); + assertTrue(found); + } + + @Test + public void givenElement_whenNotFoundUsingEnhancedForLoop_thenReturnNull() { + Integer scoreToFind = 5; + boolean found = findElementInAList.findUsingEnhancedForLoop(scoreToFind, scores); + assertTrue(!found); + } + + @Test + public void givenElement_whenFoundUsingStream_thenReturnElement() { + Integer scoreToFind = 1; + Integer score = findElementInAList.findUsingStream(scoreToFind, scores); + assertTrue(score.equals(scoreToFind)); + } + + @Test + public void givenElement_whenNotFoundUsingStream_thenReturnNull() { + Integer scoreToFind = 5; + Integer score = findElementInAList.findUsingStream(scoreToFind, scores); + assertNull(score); + } + + @Test + public void givenElement_whenFoundUsingParallelStream_thenReturnElement() { + Integer scoreToFind = 1; + Integer score = findElementInAList.findUsingParallelStream(scoreToFind, scores); + assertTrue(score.equals(scoreToFind)); + } + + @Test + public void givenElement_whenNotFoundUsingParallelStream_thenReturnNull() { + Integer scoreToFind = 5; + Integer score = findElementInAList.findUsingParallelStream(scoreToFind, scores); + assertNull(score); + } + + @Test + public void givenElement_whenFoundUsingGuava_thenReturnElement() { + Integer scoreToFind = 1; + Integer score = findElementInAList.findUsingGuava(scoreToFind, scores); + assertTrue(score.equals(scoreToFind)); + } + + @Test + public void givenElement_whenNotFoundUsingGuava_thenReturnNull() { + Integer scoreToFind = 5; + Integer score = findElementInAList.findUsingGuava(scoreToFind, scores); + assertNull(score); + } + + @Test + public void givenElement_whenFoundUsingApacheCommons_thenReturnElement() { + Integer scoreToFind = 1; + Integer score = findElementInAList.findUsingApacheCommon(scoreToFind, scores); + assertTrue(score.equals(scoreToFind)); + } + + @Test + public void givenElement_whenNotFoundUsingApacheCommons_thenReturnNull() { + Integer scoreToFind = 5; + Integer score = findElementInAList.findUsingApacheCommon(scoreToFind, scores); + assertNull(score); + } + +} \ No newline at end of file From 510ad19f9048a0425376e7cfbb7568deb4df0245 Mon Sep 17 00:00:00 2001 From: Carlo Corti Date: Tue, 13 Mar 2018 22:34:40 +0100 Subject: [PATCH 91/91] BAEL-1588 Junit assertions (#3810) * Added JUnit Assertions code * Fix method spelling * Fix wrong assertion --- .../java/com/baeldung/AssertionUnitTest.java | 147 +++++++++++++++++- .../baeldung/junit/AssertionsUnitTest.java | 101 ++++++++++++ 2 files changed, 247 insertions(+), 1 deletion(-) create mode 100644 testing-modules/testing/src/test/java/com/baeldung/junit/AssertionsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java index 6fefd4e06d..79ba882205 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java @@ -1,11 +1,156 @@ package com.baeldung; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static java.time.Duration.ofSeconds; +import static java.util.Arrays.asList; +import static org.junit.jupiter.api.Assertions.*; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.function.BooleanSupplier; + +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +/** + * Unit test that demonstrate the different assertions available within JUnit 4 + */ public class AssertionUnitTest { + @Test + public void whenAssertingArraysEquality_thenEqual() { + char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'}; + char[] actual = "Jupiter".toCharArray(); + + assertArrayEquals(expected, actual, "Arrays should be equal"); + } + + @Test + public void whenAssertingEquality_thenEqual() { + float square = 2 * 2; + float rectangle = 2 * 2; + + assertEquals(square, rectangle); + } + + @Test + public void whenAssertingEqualityWithDelta_thenEqual() { + float square = 2 * 2; + float rectangle = 3 * 2; + float delta = 2; + + assertEquals(square, rectangle, delta); + } + + @Test + public void whenAssertingConditions_thenVerified() { + assertTrue(5 > 4, "5 is greater the 4"); + assertTrue(null == null, "null is equal to null"); + } + + @Test + public void whenAssertingNull_thenTrue() { + Object cat = null; + + assertNull(cat, () -> "The cat should be null"); + } + + @Test + public void whenAssertingNotNull_thenTrue() { + Object dog = new Object(); + + assertNotNull(dog, () -> "The dog should not be null"); + } + + @Test + public void whenAssertingSameObject_thenSuccessfull() { + String language = "Java"; + Optional optional = Optional.of(language); + + assertSame(language, optional.get()); + } + + @Test + public void givenBooleanSupplier_whenAssertingCondition_thenVerified() { + BooleanSupplier condition = () -> 5 > 6; + + assertFalse(condition, "5 is not greater then 6"); + } + + @Test + @Disabled + public void whenFailingATest_thenFailed() { + // Test not completed + fail("FAIL - test not completed"); + } + + @Test + public void givenMultipleAssertion_whenAssertingAll_thenOK() { + assertAll( + "heading", + () -> assertEquals(4, 2 * 2, "4 is 2 times 2"), + () -> assertEquals("java", "JAVA".toLowerCase()), + () -> assertEquals(null, null, "null is equal to null") + ); + } + + @Test + public void givenTwoLists_whenAssertingIterables_thenEquals() { + Iterable al = new ArrayList<>(asList("Java", "Junit", "Test")); + Iterable ll = new LinkedList<>(asList("Java", "Junit", "Test")); + + assertIterableEquals(al, ll); + } + + @Test + public void whenAssertingTimeout_thenNotExceeded() { + assertTimeout( + ofSeconds(2), + () -> { + // code that requires less then 2 minutes to execute + Thread.sleep(1000); + } + ); + } + + @Test + public void whenAssertingTimeoutPreemptively_thenNotExceeded() { + assertTimeoutPreemptively( + ofSeconds(2), + () -> { + // code that requires less then 2 minutes to execute + Thread.sleep(1000); + } + ); + } + + @Test + public void whenAssertingEquality_thenNotEqual() { + Integer value = 5; // result of an algorithm + + assertNotEquals(0, value, "The result cannot be 0"); + } + + @Test + public void whenAssertingEqualityListOfStrings_thenEqual() { + List expected = asList("Java", "\\d+", "JUnit"); + List actual = asList("Java", "11", "JUnit"); + + assertLinesMatch(expected, actual); + } + + @Test + void whenAssertingException_thenThrown() { + Throwable exception = assertThrows( + IllegalArgumentException.class, + () -> { + throw new IllegalArgumentException("Exception message"); + } + ); + assertEquals("Exception message", exception.getMessage()); + } + @Test public void testConvertToDoubleThrowException() { String age = "eighteen"; diff --git a/testing-modules/testing/src/test/java/com/baeldung/junit/AssertionsUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/AssertionsUnitTest.java new file mode 100644 index 0000000000..b0209b01aa --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/junit/AssertionsUnitTest.java @@ -0,0 +1,101 @@ +package com.baeldung.junit; + +import org.junit.Test; + +import java.util.Arrays; + +import static org.hamcrest.core.IsCollectionContaining.hasItems; +import static org.junit.Assert.*; + +/** + * Unit test that demonstrate the different assertions available within JUnit 4 + */ +public class AssertionsUnitTest { + + @Test + public void whenAssertingEquality_thenEqual() { + String expected = "Baeldung"; + String actual = "Baeldung"; + + assertEquals(expected, actual); + } + + @Test + public void whenAssertingEqualityWithMessage_thenEqual() { + String expected = "Baeldung"; + String actual = "Baeldung"; + + assertEquals("failure - strings are not equal", expected, actual); + } + + @Test + public void whenAssertingArraysEquality_thenEqual() { + char[] expected = { 'J', 'u', 'n', 'i', 't' }; + char[] actual = "Junit".toCharArray(); + + assertArrayEquals(expected, actual); + } + + @Test + public void givenNullArrays_whenAssertingArraysEquality_thenEqual() { + int[] expected = null; + int[] actual = null; + + assertArrayEquals(expected, actual); + } + + @Test + public void whenAssertingNull_thenTrue() { + Object car = null; + + assertNull("The car should be null", car); + } + + @Test + public void whenAssertingNotNull_thenTrue() { + Object car = new Object(); + + assertNotNull("The car should not be null", car); + } + + @Test + public void whenAssertingNotSameObject_thenDifferent() { + Object cat = new Object(); + Object dog = new Object(); + + assertNotSame(cat, dog); + } + + @Test + public void whenAssertingSameObject_thenSame() { + Object cat = new Object(); + + assertSame(cat, cat); + } + + @Test + public void whenAssertingConditions_thenVerified() { + assertTrue("5 is greater then 4", 5 > 4); + assertFalse("5 is not greater then 6", 5 > 6); + } + + @Test + public void when_thenNotFailed() { + try { + methodThatShouldThrowException(); + fail("Exception not thrown"); + } catch (UnsupportedOperationException e) { + assertEquals("Operation Not Supported", e.getMessage()); + } + } + + private void methodThatShouldThrowException() { + throw new UnsupportedOperationException("Operation Not Supported"); + } + + @Test + public void testAssertThatHasItems() { + assertThat(Arrays.asList("Java", "Kotlin", "Scala"), hasItems("Java", "Kotlin")); + } + +}