From 626360dedd1b36c5511e68b940340d631d1e15dc Mon Sep 17 00:00:00 2001 From: tschiman Date: Mon, 30 Jan 2017 23:07:09 -0700 Subject: [PATCH 01/58] BAEL-649 Making updates to add two service applications that are domain specific --- ...rce.properties => book-service.properties} | 2 +- .../application-config/gateway.properties | 10 ++- .../rating-service.properties | 17 ++++ .../bootstrap/gateway/SecurityConfig.java | 4 +- spring-cloud/spring-cloud-bootstrap/pom.xml | 3 +- .../resource/ResourceApplication.java | 41 --------- .../{resource => svc-book}/pom.xml | 3 +- .../spring/cloud/bootstrap/svcbook/Book.java | 40 +++++++++ .../svcbook/BookServiceApplication.java | 37 ++++++++ .../bootstrap/svcbook}/SecurityConfig.java | 7 +- .../bootstrap/svcbook}/SessionConfig.java | 2 +- .../src/main/resources/bootstrap.properties | 2 +- .../spring-cloud-bootstrap/svc-rating/pom.xml | 85 +++++++++++++++++++ .../cloud/bootstrap/svcrating/Rating.java | 40 +++++++++ .../svcrating/RatingServiceApplication.java | 41 +++++++++ .../bootstrap/svcrating/SecurityConfig.java | 32 +++++++ .../bootstrap/svcrating/SessionConfig.java | 10 +++ .../src/main/resources/bootstrap.properties | 7 ++ 18 files changed, 328 insertions(+), 55 deletions(-) rename spring-cloud/spring-cloud-bootstrap/application-config/{resource.properties => book-service.properties} (91%) create mode 100644 spring-cloud/spring-cloud-bootstrap/application-config/rating-service.properties delete mode 100644 spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/ResourceApplication.java rename spring-cloud/spring-cloud-bootstrap/{resource => svc-book}/pom.xml (96%) create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/Book.java create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java rename spring-cloud/spring-cloud-bootstrap/{resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource => svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook}/SecurityConfig.java (83%) rename spring-cloud/spring-cloud-bootstrap/{resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource => svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook}/SessionConfig.java (87%) rename spring-cloud/spring-cloud-bootstrap/{resource => svc-book}/src/main/resources/bootstrap.properties (87%) create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/Rating.java create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SessionConfig.java create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/resources/bootstrap.properties diff --git a/spring-cloud/spring-cloud-bootstrap/application-config/resource.properties b/spring-cloud/spring-cloud-bootstrap/application-config/book-service.properties similarity index 91% rename from spring-cloud/spring-cloud-bootstrap/application-config/resource.properties rename to spring-cloud/spring-cloud-bootstrap/application-config/book-service.properties index 9fb610d655..e1244a0cf0 100644 --- a/spring-cloud/spring-cloud-bootstrap/application-config/resource.properties +++ b/spring-cloud/spring-cloud-bootstrap/application-config/book-service.properties @@ -1,4 +1,4 @@ -spring.application.name=resource +spring.application.name=book-service server.port=8083 resource.returnString=hello cloud diff --git a/spring-cloud/spring-cloud-bootstrap/application-config/gateway.properties b/spring-cloud/spring-cloud-bootstrap/application-config/gateway.properties index 6f52a59db9..09f7f3bf4a 100644 --- a/spring-cloud/spring-cloud-bootstrap/application-config/gateway.properties +++ b/spring-cloud/spring-cloud-bootstrap/application-config/gateway.properties @@ -6,9 +6,13 @@ eureka.client.registryFetchIntervalSeconds = 5 management.security.sessions=always -zuul.routes.resource.path=/resource/** -zuul.routes.resource.sensitive-headers=Set-Cookie,Authorization -hystrix.command.resource.execution.isolation.thread.timeoutInMilliseconds=600000 +zuul.routes.book-service.path=/book-service/** +zuul.routes.book-service.sensitive-headers=Set-Cookie,Authorization +hystrix.command.book-service.execution.isolation.thread.timeoutInMilliseconds=600000 + +zuul.routes.rating-service.path=/rating-service/** +zuul.routes.rating-service.sensitive-headers=Set-Cookie,Authorization +hystrix.command.rating-service.execution.isolation.thread.timeoutInMilliseconds=600000 zuul.routes.discovery.path=/discovery/** zuul.routes.discovery.sensitive-headers=Set-Cookie,Authorization diff --git a/spring-cloud/spring-cloud-bootstrap/application-config/rating-service.properties b/spring-cloud/spring-cloud-bootstrap/application-config/rating-service.properties new file mode 100644 index 0000000000..4817d12c83 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/application-config/rating-service.properties @@ -0,0 +1,17 @@ +spring.application.name=rating-service +server.port=8084 + +resource.returnString=hello cloud +resource.user.returnString=hello cloud user +resource.admin.returnString=hello cloud admin + +eureka.client.region = default +eureka.client.registryFetchIntervalSeconds = 5 + +management.security.sessions=never + +logging.level.org.springframework.web.=debug +logging.level.org.springframework.security=debug + +spring.redis.host=localhost +spring.redis.port=6379 diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java index 60dccf9042..9e5c424403 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java @@ -22,14 +22,14 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() - .antMatchers("/resource/hello/cloud").permitAll() + .antMatchers("/book-service/books").permitAll() .antMatchers("/eureka/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .and() .logout().permitAll() - .logoutSuccessUrl("/resource/hello/cloud").permitAll() + .logoutSuccessUrl("/book-service/books").permitAll() .and() .csrf() .disable(); diff --git a/spring-cloud/spring-cloud-bootstrap/pom.xml b/spring-cloud/spring-cloud-bootstrap/pom.xml index 9a1b2e6d0e..ccfbdb9735 100644 --- a/spring-cloud/spring-cloud-bootstrap/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/pom.xml @@ -14,7 +14,8 @@ config discovery gateway - resource + svc-book + svc-rating diff --git a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/ResourceApplication.java b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/ResourceApplication.java deleted file mode 100644 index accef18a14..0000000000 --- a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/ResourceApplication.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.spring.cloud.bootstrap.resource; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@SpringBootApplication -@EnableEurekaClient -@RestController -public class ResourceApplication { - public static void main(String[] args) { - SpringApplication.run(ResourceApplication.class, args); - } - - @Value("${resource.returnString}") - private String returnString; - - @Value("${resource.user.returnString}") - private String userReturnString; - - @Value("${resource.admin.returnString}") - private String adminReturnString; - - @RequestMapping("/hello/cloud") - public String getString() { - return returnString; - } - - @RequestMapping("/hello/user") - public String getUserString() { - return userReturnString; - } - - @RequestMapping("/hello/admin") - public String getAdminString() { - return adminReturnString; - } -} diff --git a/spring-cloud/spring-cloud-bootstrap/resource/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml similarity index 96% rename from spring-cloud/spring-cloud-bootstrap/resource/pom.xml rename to spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml index 1472693de8..ac7cd30dbf 100644 --- a/spring-cloud/spring-cloud-bootstrap/resource/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml @@ -4,7 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - resource + com.baeldung.spring.cloud + svc-book 1.0.0-SNAPSHOT diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/Book.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/Book.java new file mode 100644 index 0000000000..e652437454 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/Book.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.cloud.bootstrap.svcbook; + +public class Book { + private Long id; + private String author; + private String title; + + public Book(Long id, String title, String author) { + this.id = id; + this.author = author; + this.title = title; + } + + public Book() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java new file mode 100644 index 0000000000..25ad2a83b2 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.cloud.bootstrap.svcbook; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Arrays; +import java.util.List; + +@SpringBootApplication +@EnableEurekaClient +@RestController +@RequestMapping("/books") +public class BookServiceApplication { + public static void main(String[] args) { + SpringApplication.run(BookServiceApplication.class, args); + } + + private List bookList = Arrays.asList( + new Book(1L, "Baeldung goes to the market", "Tim Schimandle"), + new Book(2L, "Baeldung goes to the park", "Slavisa") + ); + + @GetMapping("") + public List findAllBooks() { + return bookList; + } + + @GetMapping("/{bookId}") + public Book findBook(@PathVariable Long bookId) { + return bookList.stream().filter(b -> b.getId().equals(bookId)).findFirst().orElse(null); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java similarity index 83% rename from spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java rename to spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java index 0b0de6ec20..300b4d7c5a 100644 --- a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.cloud.bootstrap.resource; +package com.baeldung.spring.cloud.bootstrap.svcbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; @@ -22,9 +22,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { http.httpBasic() .disable() .authorizeRequests() - .antMatchers("/hello/cloud").permitAll() - .antMatchers("/hello/user").hasAnyRole("USER", "ADMIN") - .antMatchers("/hello/admin").hasRole("ADMIN") + .antMatchers("/books").permitAll() + .antMatchers("/books/*").hasAnyRole("USER", "ADMIN") .anyRequest().authenticated() .and() .csrf() diff --git a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SessionConfig.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SessionConfig.java similarity index 87% rename from spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SessionConfig.java rename to spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SessionConfig.java index f11f316826..dbde068069 100644 --- a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SessionConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SessionConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.cloud.bootstrap.resource; +package com.baeldung.spring.cloud.bootstrap.svcbook; import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; diff --git a/spring-cloud/spring-cloud-bootstrap/resource/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/resources/bootstrap.properties similarity index 87% rename from spring-cloud/spring-cloud-bootstrap/resource/src/main/resources/bootstrap.properties rename to spring-cloud/spring-cloud-bootstrap/svc-book/src/main/resources/bootstrap.properties index 9ecfb46125..8f3a3261ac 100644 --- a/spring-cloud/spring-cloud-bootstrap/resource/src/main/resources/bootstrap.properties +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/resources/bootstrap.properties @@ -1,4 +1,4 @@ -spring.cloud.config.name=resource +spring.cloud.config.name=book-service spring.cloud.config.discovery.service-id=config spring.cloud.config.discovery.enabled=true spring.cloud.config.username=configUser diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml new file mode 100644 index 0000000000..36a29708a6 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml @@ -0,0 +1,85 @@ + + + 4.0.0 + + com.baeldung.spring.cloud + svc-rating + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.2.RELEASE + + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-eureka + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-security + + + + org.springframework.session + spring-session + + + org.springframework.boot + spring-boot-starter-data-redis + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud-dependencies.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + Brixton.SR7 + 3.6.0 + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/Rating.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/Rating.java new file mode 100644 index 0000000000..5dd3572098 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/Rating.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.cloud.bootstrap.svcrating; + +public class Rating { + private Long id; + private Long bookId; + private int stars; + + public Rating() { + } + + public Rating(Long id, Long bookId, int stars) { + this.id = id; + this.bookId = bookId; + this.stars = stars; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getBookId() { + return bookId; + } + + public void setBookId(Long bookId) { + this.bookId = bookId; + } + + public int getStars() { + return stars; + } + + public void setStars(int stars) { + this.stars = stars; + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java new file mode 100644 index 0000000000..11fb5f06b6 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java @@ -0,0 +1,41 @@ +package com.baeldung.spring.cloud.bootstrap.svcrating; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +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.RestController; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +@SpringBootApplication +@EnableEurekaClient +@RestController +@RequestMapping("/ratings") +public class RatingServiceApplication { + public static void main(String[] args) { + SpringApplication.run(RatingServiceApplication.class, args); + } + + private List ratingList = Arrays.asList( + new Rating(1L, 1L, 2), + new Rating(2L, 1L, 3), + new Rating(3L, 2L, 4), + new Rating(4L, 2L, 5) + ); + + @GetMapping("") + public List findRatingsByBookId(@RequestParam Long bookId) { + return bookId == null || bookId.equals(0L) ? Collections.EMPTY_LIST : ratingList.stream().filter(r -> r.getBookId().equals(bookId)).collect(Collectors.toList()); + } + + @GetMapping("/all") + public List findAllRatings() { + return ratingList; + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java new file mode 100644 index 0000000000..66b714634c --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.cloud.bootstrap.svcrating; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@EnableWebSecurity +@Configuration +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + public void configureGlobal1(AuthenticationManagerBuilder auth) throws Exception { + //try in memory auth with no users to support the case that this will allow for users that are logged in to go anywhere + auth.inMemoryAuthentication(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.httpBasic() + .disable() + .authorizeRequests() + .antMatchers("/ratings").hasRole("USER") + .antMatchers("/ratings/all").hasAnyRole("USER", "ADMIN") + .anyRequest().authenticated() + .and() + .csrf() + .disable(); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SessionConfig.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SessionConfig.java new file mode 100644 index 0000000000..62bc701868 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SessionConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.cloud.bootstrap.svcrating; + +import org.springframework.context.annotation.Configuration; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; + +@Configuration +@EnableRedisHttpSession +public class SessionConfig extends AbstractHttpSessionApplicationInitializer { +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..be5cf7f1e1 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/resources/bootstrap.properties @@ -0,0 +1,7 @@ +spring.cloud.config.name=rating-service +spring.cloud.config.discovery.service-id=config +spring.cloud.config.discovery.enabled=true +spring.cloud.config.username=configUser +spring.cloud.config.password=configPassword + +eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/ From fb950e2dfa5883941620d8e9eaec6a484f2983a7 Mon Sep 17 00:00:00 2001 From: tschiman Date: Thu, 2 Feb 2017 21:18:06 -0700 Subject: [PATCH 02/58] BAEL-649 changing test content and some security changes to make all the tests work. --- .../gateway/GatewayApplicationLiveTest.java | 16 ++++++++-------- .../bootstrap/svcrating/SecurityConfig.java | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplicationLiveTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplicationLiveTest.java index cea431d461..aa39232bb2 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplicationLiveTest.java +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplicationLiveTest.java @@ -14,12 +14,12 @@ public class GatewayApplicationLiveTest { TestRestTemplate testRestTemplate = new TestRestTemplate(); String testUrl = "http://localhost:8080"; - ResponseEntity response = testRestTemplate.getForEntity(testUrl + "/resource/hello/cloud", String.class); + ResponseEntity response = testRestTemplate.getForEntity(testUrl + "/book-service/books", String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); - Assert.assertEquals("hello cloud", response.getBody()); + Assert.assertNotNull(response.getBody()); //try the protected resource and confirm the redirect to login - response = testRestTemplate.getForEntity(testUrl + "/resource/hello/user", String.class); + response = testRestTemplate.getForEntity(testUrl + "/book-service/books/1", String.class); Assert.assertEquals(HttpStatus.FOUND, response.getStatusCode()); Assert.assertEquals("http://localhost:8080/login", response.getHeaders().get("Location").get(0)); @@ -36,12 +36,12 @@ public class GatewayApplicationLiveTest { HttpEntity httpEntity = new HttpEntity<>(headers); //request the protected resource - response = testRestTemplate.exchange(testUrl + "/resource/hello/user", HttpMethod.GET, httpEntity, String.class); + response = testRestTemplate.exchange(testUrl + "/book-service/books/1", HttpMethod.GET, httpEntity, String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); - Assert.assertEquals("hello cloud user", response.getBody()); + Assert.assertNotNull(response.getBody()); //request the admin protected resource to determine it is still protected - response = testRestTemplate.exchange(testUrl + "/resource/hello/admin", HttpMethod.GET, httpEntity, String.class); + response = testRestTemplate.exchange(testUrl + "/rating-service/ratings/all", HttpMethod.GET, httpEntity, String.class); Assert.assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); //login as the admin @@ -57,9 +57,9 @@ public class GatewayApplicationLiveTest { httpEntity = new HttpEntity<>(headers); //request the protected resource - response = testRestTemplate.exchange(testUrl + "/resource/hello/admin", HttpMethod.GET, httpEntity, String.class); + response = testRestTemplate.exchange(testUrl + "/rating-service/ratings/all", HttpMethod.GET, httpEntity, String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); - Assert.assertEquals("hello cloud admin", response.getBody()); + Assert.assertNotNull(response.getBody()); //request the discovery resources as the admin response = testRestTemplate.exchange(testUrl + "/discovery", HttpMethod.GET, httpEntity, String.class); diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java index 66b714634c..371dc810d5 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java @@ -23,7 +23,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { .disable() .authorizeRequests() .antMatchers("/ratings").hasRole("USER") - .antMatchers("/ratings/all").hasAnyRole("USER", "ADMIN") + .antMatchers("/ratings/all").hasRole("ADMIN") .anyRequest().authenticated() .and() .csrf() From 80c07b0ab2d1c49e6b9c6fb39b4999262fca662e Mon Sep 17 00:00:00 2001 From: Stephen Braimah Date: Sat, 4 Feb 2017 14:07:16 +0000 Subject: [PATCH 03/58] BAEL-639: Guide to Guava's EventBus Tests - corrected formatting --- guava/pom.xml | 29 +++++++++++++++++++ .../java/org/baeldung/guava/CustomEvent.java | 1 - .../org/baeldung/guava/EventBusWrapper.java | 7 ++--- .../org/baeldung/guava/EventListener.java | 20 ++++++------- .../org/baeldung/guava/GuavaEventBusTest.java | 12 ++++---- 5 files changed, 47 insertions(+), 22 deletions(-) diff --git a/guava/pom.xml b/guava/pom.xml index a7b4e79e34..b40df178a6 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -57,6 +57,32 @@ test + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + @@ -105,6 +131,9 @@ 3.6.0 2.19.1 + + 1.7.21 + 1.1.7 \ No newline at end of file diff --git a/guava/src/test/java/org/baeldung/guava/CustomEvent.java b/guava/src/test/java/org/baeldung/guava/CustomEvent.java index 78348065b2..2d5c3382d4 100644 --- a/guava/src/test/java/org/baeldung/guava/CustomEvent.java +++ b/guava/src/test/java/org/baeldung/guava/CustomEvent.java @@ -1,6 +1,5 @@ package org.baeldung.guava; - public class CustomEvent { private String action; diff --git a/guava/src/test/java/org/baeldung/guava/EventBusWrapper.java b/guava/src/test/java/org/baeldung/guava/EventBusWrapper.java index eddaca0baf..243bc9e6ea 100644 --- a/guava/src/test/java/org/baeldung/guava/EventBusWrapper.java +++ b/guava/src/test/java/org/baeldung/guava/EventBusWrapper.java @@ -6,17 +6,16 @@ class EventBusWrapper { private static EventBus eventBus = new EventBus(); - static void register(Object object){ + static void register(Object object) { eventBus.register(object); } - static void unregister(Object object){ + static void unregister(Object object) { eventBus.unregister(object); } - static void post(Object object){ + static void post(Object object) { eventBus.post(object); } - } diff --git a/guava/src/test/java/org/baeldung/guava/EventListener.java b/guava/src/test/java/org/baeldung/guava/EventListener.java index 17a3ac093e..02f22ce6b9 100644 --- a/guava/src/test/java/org/baeldung/guava/EventListener.java +++ b/guava/src/test/java/org/baeldung/guava/EventListener.java @@ -1,25 +1,23 @@ package org.baeldung.guava; + import com.google.common.eventbus.Subscribe; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class EventListener { private static int eventsHandled; + private static final Logger LOG = LoggerFactory.getLogger(EventListener.class); - /** - * Handles events of type String * - */ @Subscribe - public void stringEvent(String event){ - System.out.println("do event ["+event+"]"); + public void stringEvent(String event) { + LOG.info("do event [" + event + "]"); eventsHandled++; } - /** - * Handles events of type CustomEvent - */ @Subscribe - public void someEvent(CustomEvent customEvent){ - System.out.println("do event ["+ customEvent.getAction()+"]"); + public void someCustomEvent(CustomEvent customEvent) { + LOG.info("do event [" + customEvent.getAction() + "]"); eventsHandled++; } @@ -27,7 +25,7 @@ public class EventListener { return eventsHandled; } - public void resetEventsHandled(){ + public void resetEventsHandled() { eventsHandled = 0; } } diff --git a/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java index 09f7eb775d..62e275fe92 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java @@ -10,32 +10,32 @@ public class GuavaEventBusTest { private EventListener listener; @Before - public void setUp() throws Exception { + public void setUp() { listener = new EventListener(); EventBusWrapper.register(listener); } @After - public void tearDown() throws Exception { + public void tearDown() { EventBusWrapper.unregister(listener); } @Test - public void givenStringEvent_whenEventHandled_thenSuccess() throws Exception { + public void givenStringEvent_whenEventHandled_thenSuccess() { listener.resetEventsHandled(); EventBusWrapper.post("String Event"); - assertEquals(1,listener.getEventsHandled()); + assertEquals(1, listener.getEventsHandled()); } @Test - public void givenCustomEvent_whenEventHandled_thenSuccess() throws Exception { + public void givenCustomEvent_whenEventHandled_thenSuccess() { listener.resetEventsHandled(); CustomEvent customEvent = new CustomEvent("Custom Event"); EventBusWrapper.post(customEvent); - assertEquals(1,listener.getEventsHandled()); + assertEquals(1, listener.getEventsHandled()); } } From 3bda12d20c9b820531e9feebb7bcd89a35421bf7 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sat, 4 Feb 2017 17:00:22 +0100 Subject: [PATCH 04/58] BEAL-572 use same chedulers to be consistent --- .../java/com/baelding/rxjava/ColdObservableBackpressure.java | 2 +- .../java/com/baelding/rxjava/HotObservableOnBackPressure.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java b/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java index cebc2d35f6..b0be29957d 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java +++ b/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java @@ -9,7 +9,7 @@ public class ColdObservableBackPressure { public static void main(String[] args) throws InterruptedException { Observable.range(1, 1_000_000) .observeOn(Schedulers.computation()) - .subscribe(v -> ComputeFunction.compute(v), Throwable::printStackTrace); + .subscribe(ComputeFunction::compute); Thread.sleep(10_000); diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackPressure.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackPressure.java index bf86312fff..124ee64d0b 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackPressure.java +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackPressure.java @@ -18,7 +18,7 @@ public class HotObservableOnBackPressure { Observable.range(1, 1_000_000) .onBackpressureDrop() - .observeOn(Schedulers.io()) + .observeOn(Schedulers.computation()) .doOnNext(ComputeFunction::compute) .subscribe(v -> { }, Throwable::printStackTrace); From 791142c67e2f38b4eade3f82a6442253365f6625 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 4 Feb 2017 21:56:11 +0200 Subject: [PATCH 05/58] cleanup and testing work --- .../com/baeldung/algorithms/RunAlgorithm.java | 47 +++-- .../algorithms/ga/binary/Individual.java | 60 +++--- .../algorithms/ga/binary/Population.java | 50 ++--- .../ga/binary/SimpleGeneticAlgorithm.java | 192 +++++++++--------- .../concurrent/future/SquareCalculator.java | 2 +- .../baeldung/CharArrayToStringUnitTest.java | 44 ++-- .../baeldung/StringToCharArrayUnitTest.java | 14 +- .../BinaryGeneticAlgorithmTest.java | 16 -- .../BinaryGeneticAlgorithmUnitTest.java | 15 ++ .../PriorityBlockingQueueUnitTest.java | 15 +- .../ConcurrentNavigableMapTests.java | 4 +- .../ThreadPoolInParallelStreamTest.java | 23 +-- log-mdc/pom.xml | 4 +- ... ExternalPropertiesWithXmlManualTest.java} | 2 +- ...t.java => SpringRetryIntegrationTest.java} | 2 +- ...readPoolTaskSchedulerIntegrationTest.java} | 3 +- .../baeldung/test/IntegrationTestSuite.java | 4 +- ...BeanNameMappingConfigIntegrationTest.java} | 2 +- ...assNameHandlerMappingIntegrationTest.java} | 2 +- ...rMappingDefaultConfigIntegrationTest.java} | 14 +- ...MappingPriorityConfigIntegrationTest.java} | 2 +- ...impleUrlMappingConfigIntegrationTest.java} | 2 +- 22 files changed, 256 insertions(+), 263 deletions(-) delete mode 100644 core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmTest.java create mode 100644 core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java rename spring-all/src/test/java/org/baeldung/properties/external/{ExternalPropertiesWithXmlIntegrationTest.java => ExternalPropertiesWithXmlManualTest.java} (95%) rename spring-all/src/test/java/org/baeldung/springretry/{SpringRetryTest.java => SpringRetryIntegrationTest.java} (96%) rename spring-all/src/test/java/org/baeldung/taskscheduler/{ThreadPoolTaskSchedulerTest.java => ThreadPoolTaskSchedulerIntegrationTest.java} (90%) rename spring-mvc-java/src/test/java/com/baeldung/handlermappings/{BeanNameMappingConfigTest.java => BeanNameMappingConfigIntegrationTest.java} (96%) rename spring-mvc-java/src/test/java/com/baeldung/handlermappings/{ControllerClassNameHandlerMappingTest.java => ControllerClassNameHandlerMappingIntegrationTest.java} (96%) rename spring-mvc-java/src/test/java/com/baeldung/handlermappings/{HandlerMappingDefaultConfigTest.java => HandlerMappingDefaultConfigIntegrationTest.java} (93%) rename spring-mvc-java/src/test/java/com/baeldung/handlermappings/{HandlerMappingPriorityConfigTest.java => HandlerMappingPriorityConfigIntegrationTest.java} (96%) rename spring-mvc-java/src/test/java/com/baeldung/handlermappings/{SimpleUrlMappingConfigTest.java => SimpleUrlMappingConfigIntegrationTest.java} (96%) diff --git a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java index 6d696dd272..476e873f90 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java +++ b/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java @@ -8,29 +8,28 @@ import com.baeldung.algorithms.slope_one.SlopeOne; public class RunAlgorithm { - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - System.out.println("Run algorithm:"); - System.out.println("1 - Simulated Annealing"); - System.out.println("2 - Slope One"); - System.out.println("3 - Simple Genetic Algorithm"); - int decision = in.nextInt(); - switch (decision) { - case 1: - System.out.println( - "Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995)); - break; - case 2: - SlopeOne.slopeOne(3); - break; - case 3: - SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"); - break; - default: - System.out.println("Unknown option"); - break; - } - in.close(); - } + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + System.out.println("Run algorithm:"); + System.out.println("1 - Simulated Annealing"); + System.out.println("2 - Slope One"); + System.out.println("3 - Simple Genetic Algorithm"); + int decision = in.nextInt(); + switch (decision) { + case 1: + System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995)); + break; + case 2: + SlopeOne.slopeOne(3); + break; + case 3: + SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"); + break; + default: + System.out.println("Unknown option"); + break; + } + in.close(); + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java index e9b6c8f66a..2a740777f3 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java @@ -5,40 +5,40 @@ import lombok.Data; @Data public class Individual { - protected int defaultGeneLength = 64; - private byte[] genes = new byte[defaultGeneLength]; - private int fitness = 0; + protected int defaultGeneLength = 64; + private byte[] genes = new byte[defaultGeneLength]; + private int fitness = 0; - public Individual() { - for (int i = 0; i < genes.length; i++) { - byte gene = (byte) Math.round(Math.random()); - genes[i] = gene; - } - } + public Individual() { + for (int i = 0; i < genes.length; i++) { + byte gene = (byte) Math.round(Math.random()); + genes[i] = gene; + } + } - protected byte getSingleGene(int index) { - return genes[index]; - } + protected byte getSingleGene(int index) { + return genes[index]; + } - protected void setSingleGene(int index, byte value) { - genes[index] = value; - fitness = 0; - } + protected void setSingleGene(int index, byte value) { + genes[index] = value; + fitness = 0; + } - public int getFitness() { - if (fitness == 0) { - fitness = SimpleGeneticAlgorithm.getFitness(this); - } - return fitness; - } + public int getFitness() { + if (fitness == 0) { + fitness = SimpleGeneticAlgorithm.getFitness(this); + } + return fitness; + } - @Override - public String toString() { - String geneString = ""; - for (int i = 0; i < genes.length; i++) { - geneString += getSingleGene(i); - } - return geneString; - } + @Override + public String toString() { + String geneString = ""; + for (int i = 0; i < genes.length; i++) { + geneString += getSingleGene(i); + } + return geneString; + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java index dbd1e04e0f..47677d7d88 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java @@ -8,33 +8,33 @@ import lombok.Data; @Data public class Population { - private List individuals; + private List individuals; - public Population(int size, boolean createNew) { - individuals = new ArrayList<>(); - if (createNew) { - createNewPopulation(size); - } - } + public Population(int size, boolean createNew) { + individuals = new ArrayList<>(); + if (createNew) { + createNewPopulation(size); + } + } - protected Individual getIndividual(int index) { - return individuals.get(index); - } + protected Individual getIndividual(int index) { + return individuals.get(index); + } - protected Individual getFittest() { - Individual fittest = individuals.get(0); - for (int i = 0; i < individuals.size(); i++) { - if (fittest.getFitness() <= getIndividual(i).getFitness()) { - fittest = getIndividual(i); - } - } - return fittest; - } + protected Individual getFittest() { + Individual fittest = individuals.get(0); + for (int i = 0; i < individuals.size(); i++) { + if (fittest.getFitness() <= getIndividual(i).getFitness()) { + fittest = getIndividual(i); + } + } + return fittest; + } - private void createNewPopulation(int size) { - for (int i = 0; i < size; i++) { - Individual newIndividual = new Individual(); - individuals.add(i, newIndividual); - } - } + private void createNewPopulation(int size) { + for (int i = 0; i < size; i++) { + Individual newIndividual = new Individual(); + individuals.add(i, newIndividual); + } + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java index 0f640e676a..c7e2a6b381 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java @@ -5,115 +5,113 @@ import lombok.Data; @Data public class SimpleGeneticAlgorithm { - private static final double uniformRate = 0.5; - private static final double mutationRate = 0.025; - private static final int tournamentSize = 5; - private static final boolean elitism = true; - private static byte[] solution = new byte[64]; + private static final double uniformRate = 0.5; + private static final double mutationRate = 0.025; + private static final int tournamentSize = 5; + private static final boolean elitism = true; + private static byte[] solution = new byte[64]; - public static boolean runAlgorithm(int populationSize, String solution) { - if (solution.length() != SimpleGeneticAlgorithm.solution.length) { - throw new RuntimeException( - "The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes"); - } - SimpleGeneticAlgorithm.setSolution(solution); - Population myPop = new Population(populationSize, true); + public static boolean runAlgorithm(int populationSize, String solution) { + if (solution.length() != SimpleGeneticAlgorithm.solution.length) { + throw new RuntimeException("The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes"); + } + SimpleGeneticAlgorithm.setSolution(solution); + Population myPop = new Population(populationSize, true); - int generationCount = 1; - while (myPop.getFittest().getFitness() < SimpleGeneticAlgorithm.getMaxFitness()) { - System.out.println( - "Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness()); - myPop = SimpleGeneticAlgorithm.evolvePopulation(myPop); - generationCount++; - } - System.out.println("Solution found!"); - System.out.println("Generation: " + generationCount); - System.out.println("Genes: "); - System.out.println(myPop.getFittest()); - return true; - } + int generationCount = 1; + while (myPop.getFittest().getFitness() < SimpleGeneticAlgorithm.getMaxFitness()) { + System.out.println("Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness()); + myPop = SimpleGeneticAlgorithm.evolvePopulation(myPop); + generationCount++; + } + System.out.println("Solution found!"); + System.out.println("Generation: " + generationCount); + System.out.println("Genes: "); + System.out.println(myPop.getFittest()); + return true; + } - public static Population evolvePopulation(Population pop) { - int elitismOffset; - Population newPopulation = new Population(pop.getIndividuals().size(), false); + public static Population evolvePopulation(Population pop) { + int elitismOffset; + Population newPopulation = new Population(pop.getIndividuals().size(), false); - if (elitism) { - newPopulation.getIndividuals().add(0, pop.getFittest()); - elitismOffset = 1; - } else { - elitismOffset = 0; - } + if (elitism) { + newPopulation.getIndividuals().add(0, pop.getFittest()); + elitismOffset = 1; + } else { + elitismOffset = 0; + } - for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) { - Individual indiv1 = tournamentSelection(pop); - Individual indiv2 = tournamentSelection(pop); - Individual newIndiv = crossover(indiv1, indiv2); - newPopulation.getIndividuals().add(i, newIndiv); - } + for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) { + Individual indiv1 = tournamentSelection(pop); + Individual indiv2 = tournamentSelection(pop); + Individual newIndiv = crossover(indiv1, indiv2); + newPopulation.getIndividuals().add(i, newIndiv); + } - for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) { - mutate(newPopulation.getIndividual(i)); - } + for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) { + mutate(newPopulation.getIndividual(i)); + } - return newPopulation; - } + return newPopulation; + } - private static Individual crossover(Individual indiv1, Individual indiv2) { - Individual newSol = new Individual(); - for (int i = 0; i < newSol.getDefaultGeneLength(); i++) { - if (Math.random() <= uniformRate) { - newSol.setSingleGene(i, indiv1.getSingleGene(i)); - } else { - newSol.setSingleGene(i, indiv2.getSingleGene(i)); - } - } - return newSol; - } + private static Individual crossover(Individual indiv1, Individual indiv2) { + Individual newSol = new Individual(); + for (int i = 0; i < newSol.getDefaultGeneLength(); i++) { + if (Math.random() <= uniformRate) { + newSol.setSingleGene(i, indiv1.getSingleGene(i)); + } else { + newSol.setSingleGene(i, indiv2.getSingleGene(i)); + } + } + return newSol; + } - private static void mutate(Individual indiv) { - for (int i = 0; i < indiv.getDefaultGeneLength(); i++) { - if (Math.random() <= mutationRate) { - byte gene = (byte) Math.round(Math.random()); - indiv.setSingleGene(i, gene); - } - } - } + private static void mutate(Individual indiv) { + for (int i = 0; i < indiv.getDefaultGeneLength(); i++) { + if (Math.random() <= mutationRate) { + byte gene = (byte) Math.round(Math.random()); + indiv.setSingleGene(i, gene); + } + } + } - private static Individual tournamentSelection(Population pop) { - Population tournament = new Population(tournamentSize, false); - for (int i = 0; i < tournamentSize; i++) { - int randomId = (int) (Math.random() * pop.getIndividuals().size()); - tournament.getIndividuals().add(i, pop.getIndividual(randomId)); - } - Individual fittest = tournament.getFittest(); - return fittest; - } + private static Individual tournamentSelection(Population pop) { + Population tournament = new Population(tournamentSize, false); + for (int i = 0; i < tournamentSize; i++) { + int randomId = (int) (Math.random() * pop.getIndividuals().size()); + tournament.getIndividuals().add(i, pop.getIndividual(randomId)); + } + Individual fittest = tournament.getFittest(); + return fittest; + } - protected static int getFitness(Individual individual) { - int fitness = 0; - for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) { - if (individual.getSingleGene(i) == solution[i]) { - fitness++; - } - } - return fitness; - } + protected static int getFitness(Individual individual) { + int fitness = 0; + for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) { + if (individual.getSingleGene(i) == solution[i]) { + fitness++; + } + } + return fitness; + } - protected static int getMaxFitness() { - int maxFitness = solution.length; - return maxFitness; - } + protected static int getMaxFitness() { + int maxFitness = solution.length; + return maxFitness; + } - protected static void setSolution(String newSolution) { - solution = new byte[newSolution.length()]; - for (int i = 0; i < newSolution.length(); i++) { - String character = newSolution.substring(i, i + 1); - if (character.contains("0") || character.contains("1")) { - solution[i] = Byte.parseByte(character); - } else { - solution[i] = 0; - } - } - } + protected static void setSolution(String newSolution) { + solution = new byte[newSolution.length()]; + for (int i = 0; i < newSolution.length(); i++) { + String character = newSolution.substring(i, i + 1); + if (character.contains("0") || character.contains("1")) { + solution[i] = Byte.parseByte(character); + } else { + solution[i] = 0; + } + } + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java index e53a2413d1..bcd559dd3b 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java +++ b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java @@ -15,6 +15,6 @@ public class SquareCalculator { return executor.submit(() -> { Thread.sleep(1000); return input * input; - }); + }); } } diff --git a/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java b/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java index 2f7830bbf4..3488f8b390 100644 --- a/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java +++ b/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java @@ -8,55 +8,55 @@ public class CharArrayToStringUnitTest { @Test public void givenCharArray_whenCallingStringConstructor_shouldConvertToString() { - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = new String(charArray); String expectedValue = "character"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = new String(charArray, 4, 3); String expectedValue = "act"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = String.copyValueOf(charArray); String expectedValue = "character"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = String.copyValueOf(charArray, 0, 4); String expectedValue = "char"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringValueOf_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringValueOf_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = String.valueOf(charArray); String expectedValue = "character"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = String.valueOf(charArray, 3, 4); String expectedValue = "ract"; - + assertEquals(expectedValue, result); } } diff --git a/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java b/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java index 2e7dc24a17..cd996e58e2 100644 --- a/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java +++ b/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java @@ -6,15 +6,15 @@ import org.junit.Test; public class StringToCharArrayUnitTest { -@Test -public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() { - String givenString = "characters"; + @Test + public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() { + String givenString = "characters"; - char[] result = givenString.toCharArray(); + char[] result = givenString.toCharArray(); - char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' }; + char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' }; - assertArrayEquals(expectedCharArray, result); -} + assertArrayEquals(expectedCharArray, result); + } } diff --git a/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmTest.java b/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmTest.java deleted file mode 100644 index 8a16311dfb..0000000000 --- a/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.algorithms; - -import org.junit.Assert; -import org.junit.Test; - -import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; - -public class BinaryGeneticAlgorithmTest { - - @Test - public void testGA() { - Assert.assertTrue(SimpleGeneticAlgorithm.runAlgorithm(50, - "1011000100000100010000100000100111001000000100000100000000001111")); - } - -} diff --git a/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java b/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java new file mode 100644 index 0000000000..6b720898eb --- /dev/null +++ b/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.algorithms; + +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; + +public class BinaryGeneticAlgorithmUnitTest { + + @Test + public void testGA() { + Assert.assertTrue(SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111")); + } + +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java index 5e6855e18a..0272726465 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java @@ -32,13 +32,14 @@ public class PriorityBlockingQueueUnitTest { PriorityBlockingQueue queue = new PriorityBlockingQueue<>(); final Thread thread = new Thread(() -> { - System.out.println("Polling..."); - while (true) { - try { - Integer poll = queue.take(); - System.out.println("Polled: " + poll); - } catch (InterruptedException e) {} - } + System.out.println("Polling..."); + while (true) { + try { + Integer poll = queue.take(); + System.out.println("Polled: " + poll); + } catch (InterruptedException e) { + } + } }); thread.start(); diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java index 93087626a4..96a8a6bac3 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java @@ -18,9 +18,7 @@ public class ConcurrentNavigableMapTests { updateMapConcurrently(skipListMap, 4); - Iterator skipListIter = skipListMap - .keySet() - .iterator(); + Iterator skipListIter = skipListMap.keySet().iterator(); int previous = skipListIter.next(); while (skipListIter.hasNext()) { int current = skipListIter.next(); diff --git a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java index 5fd3fa4cb0..c2eb1cff5d 100644 --- a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java +++ b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java @@ -1,5 +1,5 @@ package org.baeldung.java.streams; - + import org.junit.Test; import java.util.ArrayList; @@ -14,28 +14,25 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ThreadPoolInParallelStreamTest { - + @Test - public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() - throws InterruptedException, ExecutionException { + public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException { long firstNum = 1; long lastNum = 1_000_000; - List aList = LongStream.rangeClosed(firstNum, lastNum).boxed() - .collect(Collectors.toList()); + List aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList()); ForkJoinPool customThreadPool = new ForkJoinPool(4); - long actualTotal = customThreadPool.submit(() -> aList.parallelStream() - .reduce(0L, Long::sum)).get(); - - assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); + long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get(); + + assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); } - + @Test - public void givenList_whenCallingParallelStream_shouldBeParallelStream(){ + public void givenList_whenCallingParallelStream_shouldBeParallelStream() { List aList = new ArrayList<>(); Stream parallelStream = aList.parallelStream(); - + assertTrue(parallelStream.isParallel()); } } diff --git a/log-mdc/pom.xml b/log-mdc/pom.xml index 28c8bb820e..931e68a178 100644 --- a/log-mdc/pom.xml +++ b/log-mdc/pom.xml @@ -2,9 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - logmdc + log-mdc 0.0.1-SNAPSHOT - logmdc + log-mdc war tutorial on logging with MDC and NDC diff --git a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlManualTest.java similarity index 95% rename from spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java rename to spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlManualTest.java index 2ea2822b9a..a8a7bda91c 100644 --- a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlManualTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { ExternalPropertiesWithXmlConfig.class }, loader = AnnotationConfigContextLoader.class) @Ignore("manual only") -public class ExternalPropertiesWithXmlIntegrationTest { +public class ExternalPropertiesWithXmlManualTest { @Autowired private Environment env; diff --git a/spring-all/src/test/java/org/baeldung/springretry/SpringRetryTest.java b/spring-all/src/test/java/org/baeldung/springretry/SpringRetryIntegrationTest.java similarity index 96% rename from spring-all/src/test/java/org/baeldung/springretry/SpringRetryTest.java rename to spring-all/src/test/java/org/baeldung/springretry/SpringRetryIntegrationTest.java index 2f3411957e..d7d0943e6b 100644 --- a/spring-all/src/test/java/org/baeldung/springretry/SpringRetryTest.java +++ b/spring-all/src/test/java/org/baeldung/springretry/SpringRetryIntegrationTest.java @@ -12,7 +12,7 @@ import java.sql.SQLException; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class) -public class SpringRetryTest { +public class SpringRetryIntegrationTest { @Autowired private MyService myService; diff --git a/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerTest.java b/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerIntegrationTest.java similarity index 90% rename from spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerTest.java rename to spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerIntegrationTest.java index cc247cb384..d95857d384 100644 --- a/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerTest.java +++ b/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerIntegrationTest.java @@ -8,7 +8,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { ThreadPoolTaskSchedulerConfig.class }, loader = AnnotationConfigContextLoader.class) -public class ThreadPoolTaskSchedulerTest { +public class ThreadPoolTaskSchedulerIntegrationTest { + @Test public void testThreadPoolTaskSchedulerAnnotation() throws InterruptedException { Thread.sleep(2550); diff --git a/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java b/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java index f9845f42a7..470ae9e538 100644 --- a/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java +++ b/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java @@ -5,7 +5,7 @@ import org.baeldung.properties.basic.PropertiesWithMultipleXmlsIntegrationTest; import org.baeldung.properties.basic.PropertiesWithXmlIntegrationTest; import org.baeldung.properties.external.ExternalPropertiesWithJavaIntegrationTest; import org.baeldung.properties.external.ExternalPropertiesWithMultipleXmlsIntegrationTest; -import org.baeldung.properties.external.ExternalPropertiesWithXmlIntegrationTest; +import org.baeldung.properties.external.ExternalPropertiesWithXmlManualTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -15,7 +15,7 @@ import org.junit.runners.Suite.SuiteClasses; PropertiesWithXmlIntegrationTest.class, ExternalPropertiesWithJavaIntegrationTest.class, ExternalPropertiesWithMultipleXmlsIntegrationTest.class, - ExternalPropertiesWithXmlIntegrationTest.class, + ExternalPropertiesWithXmlManualTest.class, ExtendedPropertiesWithJavaIntegrationTest.class, PropertiesWithMultipleXmlsIntegrationTest.class, })// @formatter:on diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java similarity index 96% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java index f58e5cb0a1..f2c2c05f29 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java @@ -22,7 +22,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = BeanNameUrlHandlerMappingConfig.class) -public class BeanNameMappingConfigTest { +public class BeanNameMappingConfigIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java similarity index 96% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java index 6fdd168d0b..b84998470d 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java @@ -22,7 +22,7 @@ import com.baeldung.config.ControllerClassNameHandlerMappingConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = ControllerClassNameHandlerMappingConfig.class) -public class ControllerClassNameHandlerMappingTest { +public class ControllerClassNameHandlerMappingIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java similarity index 93% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java index 01be65b829..cb89c01fed 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java @@ -1,7 +1,10 @@ package com.baeldung.handlermappings; -import com.baeldung.config.HandlerMappingDefaultConfig; -import com.baeldung.config.HandlerMappingPrioritiesConfig; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -14,15 +17,12 @@ 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.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; +import com.baeldung.config.HandlerMappingDefaultConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = HandlerMappingDefaultConfig.class) -public class HandlerMappingDefaultConfigTest { +public class HandlerMappingDefaultConfigIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java similarity index 96% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java index d6329ca6c1..55007aec28 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java @@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = HandlerMappingPrioritiesConfig.class) -public class HandlerMappingPriorityConfigTest { +public class HandlerMappingPriorityConfigIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java similarity index 96% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java index 636339f152..ad35307330 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java @@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = SimpleUrlHandlerMappingConfig.class) -public class SimpleUrlMappingConfigTest { +public class SimpleUrlMappingConfigIntegrationTest { @Autowired private WebApplicationContext webAppContext; From b57cf0cf56b256f8fd27f009c50ace23082c0beb Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Sun, 5 Feb 2017 02:46:35 +0530 Subject: [PATCH 06/58] spring requestmapping shortcuts (#1096) * rest with spark java * 4 * Update Application.java * indentation changes * spring @requestmapping shortcuts * removing spring requestmapping and pushing spring-mvc-java --- .../main/java/com/baeldung/Application.java | 7 +- .../RequestMappingShortcutsController.java | 47 ++++++++++ .../RequestMapingShortcutsUnitTest.java | 92 +++++++++++++++++++ 3 files changed, 143 insertions(+), 3 deletions(-) create mode 100644 spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java create mode 100644 spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsUnitTest.java diff --git a/spring-mobile/src/main/java/com/baeldung/Application.java b/spring-mobile/src/main/java/com/baeldung/Application.java index d384ab09b3..7275477b8d 100644 --- a/spring-mobile/src/main/java/com/baeldung/Application.java +++ b/spring-mobile/src/main/java/com/baeldung/Application.java @@ -6,9 +6,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java new file mode 100644 index 0000000000..5d4cbe9d78 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java @@ -0,0 +1,47 @@ +package com.baeldung.web.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RequestMappingShortcutsController { + + @GetMapping("/get") + public @ResponseBody ResponseEntity get() { + return new ResponseEntity("GET Response", HttpStatus.OK); + } + + @GetMapping("/get/{id}") + public @ResponseBody ResponseEntity getById(@PathVariable String id) { + return new ResponseEntity("GET Response : " + id, HttpStatus.OK); + } + + @PostMapping("/post") + public @ResponseBody ResponseEntity post() { + return new ResponseEntity("POST Response", HttpStatus.OK); + } + + @PutMapping("/put") + public @ResponseBody ResponseEntity put() { + return new ResponseEntity("PUT Response", HttpStatus.OK); + } + + @DeleteMapping("/delete") + public @ResponseBody ResponseEntity delete() { + return new ResponseEntity("DELETE Response", HttpStatus.OK); + } + + @PatchMapping("/patch") + public @ResponseBody ResponseEntity patch() { + return new ResponseEntity("PATCH Response", HttpStatus.OK); + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsUnitTest.java new file mode 100644 index 0000000000..d02a7140b5 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.web.controller; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultMatcher; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.spring.web.config.WebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = WebConfig.class) +public class RequestMapingShortcutsUnitTest { + + @Autowired + private WebApplicationContext ctx; + + private MockMvc mockMvc; + + @Before + public void setup () { + DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.ctx); + this.mockMvc = builder.build(); + } + + @Test + public void giventUrl_whenGetRequest_thenFindGetResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/get"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("GET Response"); + + this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); + + } + + @Test + public void giventUrl_whenPostRequest_thenFindPostResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/post"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("POST Response"); + + this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); + + } + + @Test + public void giventUrl_whenPutRequest_thenFindPutResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put("/put"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PUT Response"); + + this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); + + } + + @Test + public void giventUrl_whenDeleteRequest_thenFindDeleteResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete("/delete"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("DELETE Response"); + + this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); + + } + + @Test + public void giventUrl_whenPatchRequest_thenFindPatchResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.patch("/patch"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PATCH Response"); + + this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); + + } + +} From c7203bd564f840f528d5146035f2877b613e742a Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Wed, 25 Jan 2017 23:06:22 +0100 Subject: [PATCH 07/58] BAEL-614 base module for cache-control --- spring-security-cache-control/pom.xml | 49 +++++++++++++++++++ .../cachecontrol/ResourceEndpoint.java | 35 +++++++++++++ .../baeldung/cachecontrol/app/AppRunner.java | 12 +++++ .../config/SpringSecurityConfig.java | 22 +++++++++ .../cachecontrol/config/WebConfiguration.java | 21 ++++++++ .../cachecontrol/model/TimestampDto.java | 10 ++++ .../baeldung/cachecontrol/model/UserDto.java | 11 +++++ 7 files changed, 160 insertions(+) create mode 100644 spring-security-cache-control/pom.xml create mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java create mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java create mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java create mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java create mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/TimestampDto.java create mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/UserDto.java diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml new file mode 100644 index 0000000000..787804e3fe --- /dev/null +++ b/spring-security-cache-control/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + com.baeldung + spring-security-cache-control + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.security + spring-security-core + + + org.springframework.security + spring-security-config + + + org.springframework.security + spring-security-web + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + + + 3.1.0 + + + \ No newline at end of file diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java new file mode 100644 index 0000000000..7a9860922c --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java @@ -0,0 +1,35 @@ +package com.baeldung.cachecontrol; + + +import com.baeldung.cachecontrol.model.TimestampDto; +import com.baeldung.cachecontrol.model.UserDto; +import org.springframework.http.CacheControl; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.concurrent.TimeUnit; + +@RestController +public class ResourceEndpoint { + + @RequestMapping(value = "/users/{name}", method = RequestMethod.GET) + public ResponseEntity getUser(@PathVariable(value = "name") String name) { + return ResponseEntity.ok() + .cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)) + .body(new UserDto(name)); + } + + + @RequestMapping(value = "/timestamp", method = RequestMethod.GET) + public ResponseEntity getServerTimestamp() { + return ResponseEntity.ok() + .cacheControl(CacheControl.noStore()) + .cacheControl(CacheControl.noCache()) + .body(new TimestampDto(LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli())); + } +} diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java new file mode 100644 index 0000000000..1da69f40ec --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java @@ -0,0 +1,12 @@ +package com.baeldung.cachecontrol.app; + + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AppRunner { + public static void main(String[] args) { + SpringApplication.run(AppRunner.class, args); + } +} \ No newline at end of file diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java new file mode 100644 index 0000000000..789d2132f3 --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java @@ -0,0 +1,22 @@ +package com.baeldung.cachecontrol.config; + + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .anyRequest().permitAll() + .and().headers() + .defaultsDisabled() + .cacheControl(); + } +} diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java new file mode 100644 index 0000000000..decc57ec8b --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java @@ -0,0 +1,21 @@ +package com.baeldung.cachecontrol.config; + +import org.springframework.http.CacheControl; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import java.util.concurrent.TimeUnit; + +@EnableWebMvc +public class WebConfiguration extends WebMvcConfigurerAdapter { + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry + .addResourceHandler("/resources/**") + .addResourceLocations("/resources/") + .setCacheControl(CacheControl.maxAge(24, TimeUnit.HOURS)); + + } +} + diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/TimestampDto.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/TimestampDto.java new file mode 100644 index 0000000000..cb3befacac --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/TimestampDto.java @@ -0,0 +1,10 @@ +package com.baeldung.cachecontrol.model; + + +public class TimestampDto { + public final Long timestamp; + + public TimestampDto(Long timestamp) { + this.timestamp = timestamp; + } +} diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/UserDto.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/UserDto.java new file mode 100644 index 0000000000..a41cb31d80 --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/UserDto.java @@ -0,0 +1,11 @@ +package com.baeldung.cachecontrol.model; + + +public class UserDto { + public final String name; + + public UserDto(String name) { + this.name = name; + } + +} From 3fa1b93f87ebf1fe0222aeb388e122ded13aad25 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Thu, 26 Jan 2017 18:56:42 +0100 Subject: [PATCH 08/58] BAEL-614 appRunner in proper place --- .../java/com/baeldung/cachecontrol/{app => }/AppRunner.java | 2 +- .../main/java/com/baeldung/cachecontrol/ResourceEndpoint.java | 4 ++-- .../baeldung/cachecontrol/config/SpringSecurityConfig.java | 2 ++ 3 files changed, 5 insertions(+), 3 deletions(-) rename spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/{app => }/AppRunner.java (87%) diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/AppRunner.java similarity index 87% rename from spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java rename to spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/AppRunner.java index 1da69f40ec..28ff90a570 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/AppRunner.java @@ -1,4 +1,4 @@ -package com.baeldung.cachecontrol.app; +package com.baeldung.cachecontrol; import org.springframework.boot.SpringApplication; diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java index 7a9860922c..34128e64fa 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java @@ -5,16 +5,16 @@ import com.baeldung.cachecontrol.model.TimestampDto; import com.baeldung.cachecontrol.model.UserDto; import org.springframework.http.CacheControl; import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.concurrent.TimeUnit; -@RestController +@Controller public class ResourceEndpoint { @RequestMapping(value = "/users/{name}", method = RequestMethod.GET) diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java index 789d2132f3..bd6d1a4aa1 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java @@ -2,12 +2,14 @@ package com.baeldung.cachecontrol.config; import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override From 4bac6e057165e891f2e9aad057d86f6e1aa72ca8 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Thu, 26 Jan 2017 20:16:31 +0100 Subject: [PATCH 09/58] BAEL-614 endpoint that has default cache-control headers --- .../cachecontrol/ResourceEndpoint.java | 6 ++++++ .../cachecontrol/config/WebConfiguration.java | 21 ------------------- 2 files changed, 6 insertions(+), 21 deletions(-) delete mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java index 34128e64fa..86f9747e1c 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java @@ -32,4 +32,10 @@ public class ResourceEndpoint { .cacheControl(CacheControl.noCache()) .body(new TimestampDto(LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli())); } + + @RequestMapping(value = "/private/users/{name}", method = RequestMethod.GET) + public ResponseEntity getUserNotCached(@PathVariable("name") String name) { + return ResponseEntity.ok() + .body(new UserDto(name)); + } } diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java deleted file mode 100644 index decc57ec8b..0000000000 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.cachecontrol.config; - -import org.springframework.http.CacheControl; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -import java.util.concurrent.TimeUnit; - -@EnableWebMvc -public class WebConfiguration extends WebMvcConfigurerAdapter { - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry - .addResourceHandler("/resources/**") - .addResourceLocations("/resources/") - .setCacheControl(CacheControl.maxAge(24, TimeUnit.HOURS)); - - } -} - From 25111c5b893090f65306af5797883c23ab206cef Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Thu, 26 Jan 2017 20:18:23 +0100 Subject: [PATCH 10/58] BAEL-542 use defaults --- .../baeldung/cachecontrol/config/SpringSecurityConfig.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java index bd6d1a4aa1..fbb6399c22 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java @@ -14,10 +14,7 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .anyRequest().permitAll() - .and().headers() + http.headers() .defaultsDisabled() .cacheControl(); } From c3cc42f458e92afcad3a906513a1358f5ca8fb32 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Thu, 26 Jan 2017 20:34:40 +0100 Subject: [PATCH 11/58] BAEL-542 wrote live tests --- spring-security-cache-control/pom.xml | 35 ++++++++++++++ .../cachecontrol/ResourceEndpointTest.java | 47 +++++++++++++++++++ .../com/baeldung/cachecontrol/TestConfig.java | 11 +++++ 3 files changed, 93 insertions(+) create mode 100644 spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java create mode 100644 spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml index 787804e3fe..1d154f333d 100644 --- a/spring-security-cache-control/pom.xml +++ b/spring-security-cache-control/pom.xml @@ -40,10 +40,45 @@ javax.servlet-api ${javax.servlet-api.version} + + + junit + junit + test + + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + + org.mockito + mockito-core + test + + + + org.springframework + spring-test + + + + com.jayway.restassured + rest-assured + ${rest-assured.version} + 3.1.0 + 2.9.0 \ No newline at end of file diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java new file mode 100644 index 0000000000..d0a15efb2b --- /dev/null +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java @@ -0,0 +1,47 @@ +package com.baeldung.cachecontrol; + +import com.jayway.restassured.http.ContentType; +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 static com.jayway.restassured.RestAssured.given; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +public class ResourceEndpointTest { + private static final String URL_PREFIX = "http://localhost:8080"; + + @Test + public void givenServiceEndpoint_whenGetRequestForUser_shouldResponseWithCacheControlMaxAge() { + given() + .when() + .get(URL_PREFIX + "/users/Michael") + .then() + .contentType(ContentType.JSON).and().statusCode(200).and() + .header("Cache-Control", "max-age=60"); + } + + @Test + public void givenServiceEndpoint_whenGetRequestForNotCacheableContent_shouldResponseWithCacheControlNoCache() { + given() + .when() + .get(URL_PREFIX + "/timestamp") + .then() + .contentType(ContentType.JSON).and().statusCode(200).and() + .header("Cache-Control", "no-cache"); + } + + @Test + public void givenServiceEndpoint_whenGetRequestForPrivateUser_shouldResponseWithSecurityDefaultCacheControl() { + given() + .when() + .get(URL_PREFIX + "/private/users/Michael") + .then() + .contentType(ContentType.JSON).and().statusCode(200).and() + .header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); + } + +} \ No newline at end of file diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java new file mode 100644 index 0000000000..af393f4b98 --- /dev/null +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java @@ -0,0 +1,11 @@ +package com.baeldung.cachecontrol; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + + +@Configuration +@ComponentScan({ "com.baeldung" }) +public class TestConfig { + +} From cc70eae896402d889040758824230e37e88bf5cb Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Thu, 26 Jan 2017 21:47:52 +0100 Subject: [PATCH 12/58] BAEL-542 test fix --- .../cachecontrol/ResourceEndpoint.java | 1 - .../cachecontrol/ResourceEndpointTest.java | 20 +++++++++---------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java index 86f9747e1c..f1c9786c68 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java @@ -29,7 +29,6 @@ public class ResourceEndpoint { public ResponseEntity getServerTimestamp() { return ResponseEntity.ok() .cacheControl(CacheControl.noStore()) - .cacheControl(CacheControl.noCache()) .body(new TimestampDto(LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli())); } diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java index d0a15efb2b..e85dd11667 100644 --- a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java @@ -14,15 +14,15 @@ import static com.jayway.restassured.RestAssured.given; public class ResourceEndpointTest { private static final String URL_PREFIX = "http://localhost:8080"; - @Test - public void givenServiceEndpoint_whenGetRequestForUser_shouldResponseWithCacheControlMaxAge() { - given() - .when() - .get(URL_PREFIX + "/users/Michael") - .then() - .contentType(ContentType.JSON).and().statusCode(200).and() - .header("Cache-Control", "max-age=60"); - } + @Test + public void givenServiceEndpoint_whenGetRequestForUser_shouldResponseWithCacheControlMaxAge() { + given() + .when() + .get(URL_PREFIX + "/users/Michael") + .then() + .contentType(ContentType.JSON).and().statusCode(200).and() + .header("Cache-Control", "max-age=60"); + } @Test public void givenServiceEndpoint_whenGetRequestForNotCacheableContent_shouldResponseWithCacheControlNoCache() { @@ -31,7 +31,7 @@ public class ResourceEndpointTest { .get(URL_PREFIX + "/timestamp") .then() .contentType(ContentType.JSON).and().statusCode(200).and() - .header("Cache-Control", "no-cache"); + .header("Cache-Control", "no-store"); } @Test From c8f6bed73d1eb778298f70bfb4e898e86056cc38 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sat, 4 Feb 2017 18:02:28 +0100 Subject: [PATCH 13/58] BAEL-542 rename test to LiveTest suffix --- ...{ResourceEndpointTest.java => ResourceEndpointLiveTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/{ResourceEndpointTest.java => ResourceEndpointLiveTest.java} (97%) diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java similarity index 97% rename from spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java rename to spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java index e85dd11667..f6e95779cb 100644 --- a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java @@ -11,7 +11,7 @@ import static com.jayway.restassured.RestAssured.given; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) -public class ResourceEndpointTest { +public class ResourceEndpointLiveTest { private static final String URL_PREFIX = "http://localhost:8080"; @Test From 652def889a147bbfe59d757fb13817d15d953ac0 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sat, 4 Feb 2017 20:44:16 +0100 Subject: [PATCH 14/58] BAEL-542 start application properly when integation test started --- pom.xml | 1 + spring-security-cache-control/pom.xml | 4 ++++ .../baeldung/cachecontrol/ResourceEndpointLiveTest.java | 9 ++++----- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index 41235dcc26..a24e3d4667 100644 --- a/pom.xml +++ b/pom.xml @@ -147,6 +147,7 @@ spring-rest-docs spring-rest spring-security-basic-auth + spring-security-cache-control spring-security-client/spring-security-jsp-authentication spring-security-client/spring-security-jsp-authorize spring-security-client/spring-security-jsp-config diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml index 1d154f333d..c30b0cd1aa 100644 --- a/spring-security-cache-control/pom.xml +++ b/spring-security-cache-control/pom.xml @@ -35,6 +35,10 @@ org.springframework.security spring-security-web + + org.springframework.boot + spring-boot-starter-test + javax.servlet javax.servlet-api diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java index f6e95779cb..0c23b1969d 100644 --- a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java @@ -3,14 +3,13 @@ package com.baeldung.cachecontrol; import com.jayway.restassured.http.ContentType; 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.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import static com.jayway.restassured.RestAssured.given; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = AppRunner.class) public class ResourceEndpointLiveTest { private static final String URL_PREFIX = "http://localhost:8080"; From c9394b216ae01d23917735a140c11226f43bcace Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sat, 4 Feb 2017 20:45:53 +0100 Subject: [PATCH 15/58] BAEL-542 do not need TestConfig class --- .../java/com/baeldung/cachecontrol/TestConfig.java | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java deleted file mode 100644 index af393f4b98..0000000000 --- a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.cachecontrol; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - - -@Configuration -@ComponentScan({ "com.baeldung" }) -public class TestConfig { - -} From 3f81460e90f0ec4408ca1e9beb4a9b54aea6d8e9 Mon Sep 17 00:00:00 2001 From: Andrew Morgan Date: Sat, 4 Feb 2017 23:46:53 +0000 Subject: [PATCH 16/58] Added extra endpoint for default caching --- .../cachecontrol/ResourceEndpoint.java | 6 +++- .../config/SpringSecurityConfig.java | 6 +--- .../ResourceEndpointLiveTest.java | 36 ++++++++++++++++--- 3 files changed, 37 insertions(+), 11 deletions(-) diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java index f1c9786c68..9f756b5ab4 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java @@ -17,6 +17,11 @@ import java.util.concurrent.TimeUnit; @Controller public class ResourceEndpoint { + @RequestMapping(value = "/default/users/{name}", method = RequestMethod.GET) + public ResponseEntity getUserWithDefaultCaching(@PathVariable(value = "name") String name) { + return ResponseEntity.ok(new UserDto(name)); + } + @RequestMapping(value = "/users/{name}", method = RequestMethod.GET) public ResponseEntity getUser(@PathVariable(value = "name") String name) { return ResponseEntity.ok() @@ -24,7 +29,6 @@ public class ResourceEndpoint { .body(new UserDto(name)); } - @RequestMapping(value = "/timestamp", method = RequestMethod.GET) public ResponseEntity getServerTimestamp() { return ResponseEntity.ok() diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java index fbb6399c22..b4127e9b71 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java @@ -13,9 +13,5 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override - protected void configure(HttpSecurity http) throws Exception { - http.headers() - .defaultsDisabled() - .cacheControl(); - } + protected void configure(HttpSecurity http) throws Exception {} } diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java index 0c23b1969d..94b6052ba4 100644 --- a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java @@ -3,21 +3,43 @@ package com.baeldung.cachecontrol; import com.jayway.restassured.http.ContentType; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static com.jayway.restassured.RestAssured.given; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = AppRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AppRunner.class) public class ResourceEndpointLiveTest { - private static final String URL_PREFIX = "http://localhost:8080"; + + @LocalServerPort + private int serverPort; + + @Test + public void whenGetRequestForUser_shouldRespondWithDefaultCacheHeaders() { + given() + .when() + .get(getBaseUrl() + "/default/users/Michael") + .then() + .headers("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate") + .header("Pragma", "no-cache"); + } + + @Test + public void whenGetRequestForUser_shouldRespondMaxAgeCacheControl() { + given() + .when() + .get(getBaseUrl() + "/users/Michael") + .then() + .header("Cache-Control", "max-age=60"); + } @Test public void givenServiceEndpoint_whenGetRequestForUser_shouldResponseWithCacheControlMaxAge() { given() .when() - .get(URL_PREFIX + "/users/Michael") + .get(getBaseUrl() + "/users/Michael") .then() .contentType(ContentType.JSON).and().statusCode(200).and() .header("Cache-Control", "max-age=60"); @@ -27,7 +49,7 @@ public class ResourceEndpointLiveTest { public void givenServiceEndpoint_whenGetRequestForNotCacheableContent_shouldResponseWithCacheControlNoCache() { given() .when() - .get(URL_PREFIX + "/timestamp") + .get(getBaseUrl() + "/timestamp") .then() .contentType(ContentType.JSON).and().statusCode(200).and() .header("Cache-Control", "no-store"); @@ -37,10 +59,14 @@ public class ResourceEndpointLiveTest { public void givenServiceEndpoint_whenGetRequestForPrivateUser_shouldResponseWithSecurityDefaultCacheControl() { given() .when() - .get(URL_PREFIX + "/private/users/Michael") + .get(getBaseUrl() + "/private/users/Michael") .then() .contentType(ContentType.JSON).and().statusCode(200).and() .header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); } + private String getBaseUrl() { + return "http://localhost:" + serverPort; + } + } \ No newline at end of file From 10eb6bfcc0ebaceae2b803bd6cbfc7ef77250fa1 Mon Sep 17 00:00:00 2001 From: lor6 Date: Sun, 5 Feb 2017 03:03:00 +0200 Subject: [PATCH 17/58] helper classes for excel processing, tests (#1093) * helper classes for excel processing, tests * fix imports * list declaration --- apache-poi/pom.xml | 16 ++ .../com/baeldung/jexcel/JExcelHelper.java | 79 ++++++++++ .../baeldung/poi/excel/ExcelPOIHelper.java | 137 ++++++++++++++++++ .../java/com/baeldung/jexcel/JExcelTest.java | 62 ++++++++ .../com/baeldung/poi/excel/ExcelTest.java | 59 ++++++++ 5 files changed, 353 insertions(+) create mode 100644 apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java create mode 100644 apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java create mode 100644 apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java create mode 100644 apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml index d94b2e2ad1..1b97248ab2 100644 --- a/apache-poi/pom.xml +++ b/apache-poi/pom.xml @@ -9,6 +9,7 @@ 3.6.0 4.12 3.15 + 1.0.6 @@ -37,5 +38,20 @@ poi-ooxml ${poi.version} + + org.apache.poi + poi + ${poi.version} + + + org.apache.poi + poi-ooxml-schemas + ${poi.version} + + + org.jxls + jxls-jexcel + ${jexcel.version} + diff --git a/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java b/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java new file mode 100644 index 0000000000..39076fd709 --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java @@ -0,0 +1,79 @@ +package com.baeldung.jexcel; + +import jxl.*; +import java.util.Map; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.List; +import jxl.read.biff.BiffException; +import java.io.File; +import java.io.IOException; +import jxl.write.*; +import jxl.write.Number; +import jxl.format.Colour; + +public class JExcelHelper { + + public Map> readJExcel(String fileLocation) throws IOException, BiffException { + Map> data = new HashMap<>(); + + Workbook workbook = Workbook.getWorkbook(new File(fileLocation)); + Sheet sheet = workbook.getSheet(0); + int rows = sheet.getRows(); + int columns = sheet.getColumns(); + + for (int i = 0; i < rows; i++) { + data.put(i, new ArrayList()); + for (int j = 0; j < columns; j++) { + data.get(i).add(sheet.getCell(j, i).getContents()); + } + } + return data; + } + + public void writeJExcel() throws IOException, WriteException { + WritableWorkbook workbook = null; + try { + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + String fileLocation = path.substring(0, path.length() - 1) + "temp.xls"; + + workbook = Workbook.createWorkbook(new File(fileLocation)); + + WritableSheet sheet = workbook.createSheet("Sheet 1", 0); + + WritableCellFormat headerFormat = new WritableCellFormat(); + WritableFont font = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD); + headerFormat.setFont(font); + headerFormat.setBackground(Colour.LIGHT_BLUE); + headerFormat.setWrap(true); + Label headerLabel = new Label(0, 0, "Name", headerFormat); + sheet.setColumnView(0, 60); + sheet.addCell(headerLabel); + + headerLabel = new Label(1, 0, "Age", headerFormat); + sheet.setColumnView(0, 40); + sheet.addCell(headerLabel); + + WritableCellFormat cellFormat = new WritableCellFormat(); + cellFormat.setWrap(true); + + Label cellLabel = new Label(0, 2, "John Smith", cellFormat); + sheet.addCell(cellLabel); + Number cellNumber = new Number(1, 2, 20, cellFormat); + sheet.addCell(cellNumber); + + cellLabel = new Label(0, 3, "Ana Johnson", cellFormat); + sheet.addCell(cellLabel); + cellNumber = new Number(1, 3, 30, cellFormat); + sheet.addCell(cellNumber); + + workbook.write(); + } finally { + if (workbook != null) { + workbook.close(); + } + } + + } +} \ No newline at end of file diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java new file mode 100644 index 0000000000..841be22d62 --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java @@ -0,0 +1,137 @@ +package com.baeldung.poi.excel; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFFont; +import org.apache.poi.ss.usermodel.DateUtil; +import org.apache.poi.ss.usermodel.FillPatternType; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.List; + +public class ExcelPOIHelper { + + public Map> readExcel(String fileLocation) throws IOException { + + Map> data = new HashMap<>(); + FileInputStream file = new FileInputStream(new File(fileLocation)); + Workbook workbook = new XSSFWorkbook(file); + Sheet sheet = workbook.getSheetAt(0); + int i = 0; + for (Row row : sheet) { + data.put(i, new ArrayList()); + for (Cell cell : row) { + switch (cell.getCellTypeEnum()) { + case STRING: + data.get(i) + .add(cell.getRichStringCellValue() + .getString()); + break; + case NUMERIC: + if (DateUtil.isCellDateFormatted(cell)) { + data.get(i) + .add(cell.getDateCellValue() + ""); + } else { + data.get(i) + .add((int)cell.getNumericCellValue() + ""); + } + break; + case BOOLEAN: + data.get(i) + .add(cell.getBooleanCellValue() + ""); + break; + case FORMULA: + data.get(i) + .add(cell.getCellFormula() + ""); + break; + default: + data.get(i) + .add(" "); + } + } + i++; + } + if (workbook != null){ + workbook.close(); + } + return data; + } + + public void writeExcel() throws IOException { + Workbook workbook = new XSSFWorkbook(); + + try { + Sheet sheet = workbook.createSheet("Persons"); + sheet.setColumnWidth(0, 6000); + sheet.setColumnWidth(1, 4000); + + Row header = sheet.createRow(0); + + CellStyle headerStyle = workbook.createCellStyle(); + + headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex()); + headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); + + XSSFFont font = ((XSSFWorkbook) workbook).createFont(); + font.setFontName("Arial"); + font.setFontHeightInPoints((short) 16); + font.setBold(true); + headerStyle.setFont(font); + + Cell headerCell = header.createCell(0); + headerCell.setCellValue("Name"); + headerCell.setCellStyle(headerStyle); + + headerCell = header.createCell(1); + headerCell.setCellValue("Age"); + headerCell.setCellStyle(headerStyle); + + CellStyle style = workbook.createCellStyle(); + style.setWrapText(true); + + Row row = sheet.createRow(2); + Cell cell = row.createCell(0); + cell.setCellValue("John Smith"); + cell.setCellStyle(style); + + cell = row.createCell(1); + cell.setCellValue(20); + cell.setCellStyle(style); + + row = sheet.createRow(3); + cell = row.createCell(0); + cell.setCellValue("Ana Johnson"); + cell.setCellStyle(style); + + cell = row.createCell(1); + cell.setCellValue(30); + cell.setCellStyle(style); + + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx"; + + FileOutputStream outputStream = new FileOutputStream(fileLocation); + workbook.write(outputStream); + } finally { + if (workbook != null) { + + workbook.close(); + + } + } + } + +} \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java new file mode 100644 index 0000000000..f0c129eb22 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java @@ -0,0 +1,62 @@ +package com.baeldung.jexcel; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import jxl.read.biff.BiffException; +import java.util.Map; +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.jexcel.JExcelHelper; + +import jxl.write.WriteException; +import jxl.read.biff.BiffException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.Before; + +public class JExcelTest { + + private JExcelHelper jExcelHelper; + private static String FILE_NAME = "temp.xls"; + private String fileLocation; + + @Before + public void generateExcelFile() throws IOException, WriteException { + + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; + + jExcelHelper = new JExcelHelper(); + jExcelHelper.writeJExcel(); + + } + + @Test + public void whenParsingJExcelFile_thenCorrect() throws IOException, BiffException { + Map> data = jExcelHelper.readJExcel(fileLocation); + + assertEquals("Name", data.get(0) + .get(0)); + assertEquals("Age", data.get(0) + .get(1)); + + assertEquals("John Smith", data.get(2) + .get(0)); + assertEquals("20", data.get(2) + .get(1)); + + assertEquals("Ana Johnson", data.get(3) + .get(0)); + assertEquals("30", data.get(3) + .get(1)); + + } + +} \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java new file mode 100644 index 0000000000..f58db241b2 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java @@ -0,0 +1,59 @@ +package com.baeldung.poi.excel; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import jxl.read.biff.BiffException; +import java.util.Map; +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.poi.excel.ExcelPOIHelper; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.Before; + +public class ExcelTest { + + private ExcelPOIHelper excelPOIHelper; + private static String FILE_NAME = "temp.xlsx"; + private String fileLocation; + + @Before + public void generateExcelFile() throws IOException { + + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; + + excelPOIHelper = new ExcelPOIHelper(); + excelPOIHelper.writeExcel(); + + } + + @Test + public void whenParsingPOIExcelFile_thenCorrect() throws IOException { + Map> data = excelPOIHelper.readExcel(fileLocation); + + assertEquals("Name", data.get(0) + .get(0)); + assertEquals("Age", data.get(0) + .get(1)); + + assertEquals("John Smith", data.get(1) + .get(0)); + assertEquals("20", data.get(1) + .get(1)); + + assertEquals("Ana Johnson", data.get(2) + .get(0)); + assertEquals("30", data.get(2) + .get(1)); + + } + +} \ No newline at end of file From 6d0dcd52fad370d25ea43f96efed043e5cb4be35 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Sun, 5 Feb 2017 08:30:32 +0100 Subject: [PATCH 18/58] Reformat Rxjava examples --- .../rxjava/ColdObservableBackpressure.java | 5 ++++- .../HotObservableBackpressureBatching.java | 7 +++++-- .../HotObservableBackpressureBuffering.java | 7 +++++-- .../HotObservableBackpressureSkipping.java | 7 ++++--- .../rxjava/HotObservableOnBackpressure.java | 19 ++++++++++++++----- .../HotObservableWithoutBackpressure.java | 9 ++++----- 6 files changed, 36 insertions(+), 18 deletions(-) diff --git a/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java b/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java index 9855123a3b..4d3d09da7e 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java +++ b/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java @@ -5,7 +5,10 @@ import rx.schedulers.Schedulers; public class ColdObservableBackpressure { public static void main(String[] args) throws InterruptedException { - Observable.range(1, 1_000_000).observeOn(Schedulers.computation()).subscribe(v -> ComputeFunction.compute(v), Throwable::printStackTrace); + Observable + .range(1, 1_000_000) + .observeOn(Schedulers.computation()) + .subscribe(ComputeFunction::compute, Throwable::printStackTrace); Thread.sleep(10_000); diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java index 6acda7eaad..9f7b8c107a 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java @@ -5,9 +5,12 @@ import rx.subjects.PublishSubject; public class HotObservableBackpressureBatching { public static void main(String[] args) throws InterruptedException { - PublishSubject source = PublishSubject.create(); + PublishSubject source = PublishSubject. create(); - source.window(500).observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace); + source + .window(500) + .observeOn(Schedulers.computation()) + .subscribe(ComputeFunction::compute, Throwable::printStackTrace); for (int i = 0; i < 1_000_000; i++) { source.onNext(i); diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java index 50638f4c8a..720918878f 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java @@ -5,9 +5,12 @@ import rx.subjects.PublishSubject; public class HotObservableBackpressureBuffering { public static void main(String[] args) throws InterruptedException { - PublishSubject source = PublishSubject.create(); + PublishSubject source = PublishSubject. create(); - source.buffer(1024).observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace); + source + .buffer(1024) + .observeOn(Schedulers.computation()) + .subscribe(ComputeFunction::compute, Throwable::printStackTrace); for (int i = 0; i < 1_000_000; i++) { source.onNext(i); diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java index f6f8b9f563..5b0a7f3a68 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java @@ -7,11 +7,12 @@ import java.util.concurrent.TimeUnit; public class HotObservableBackpressureSkipping { public static void main(String[] args) throws InterruptedException { - PublishSubject source = PublishSubject.create(); + PublishSubject source = PublishSubject. create(); source.sample(100, TimeUnit.MILLISECONDS) - // .throttleFirst(100, TimeUnit.MILLISECONDS) - .observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace); + //.throttleFirst(100, TimeUnit.MILLISECONDS) + .observeOn(Schedulers.computation()) + .subscribe(ComputeFunction::compute, Throwable::printStackTrace); for (int i = 0; i < 1_000_000; i++) { source.onNext(i); diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackpressure.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackpressure.java index afef8027bf..8ccd38beb6 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackpressure.java +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackpressure.java @@ -6,12 +6,21 @@ import rx.schedulers.Schedulers; public class HotObservableOnBackpressure { public static void main(String[] args) throws InterruptedException { - Observable.range(1, 1_000_000).onBackpressureBuffer(16, () -> { - }, BackpressureOverflow.ON_OVERFLOW_DROP_OLDEST).observeOn(Schedulers.computation()).subscribe(e -> { - }, Throwable::printStackTrace); + Observable + .range(1, 1_000_000) + .onBackpressureBuffer(16, () -> { + }, BackpressureOverflow.ON_OVERFLOW_DROP_OLDEST) + .observeOn(Schedulers.computation()) + .subscribe(e -> { + }, Throwable::printStackTrace); - Observable.range(1, 1_000_000).onBackpressureDrop().observeOn(Schedulers.io()).doOnNext(ComputeFunction::compute).subscribe(v -> { - }, Throwable::printStackTrace); + Observable + .range(1, 1_000_000) + .onBackpressureDrop() + .observeOn(Schedulers.io()) + .doOnNext(ComputeFunction::compute) + .subscribe(v -> { + }, Throwable::printStackTrace); Thread.sleep(10_000); } diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java index 7745dbe5c4..439db51695 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java @@ -1,16 +1,15 @@ package com.baelding.rxjava; - import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; public class HotObservableWithoutBackpressure { public static void main(String[] args) throws InterruptedException { - PublishSubject source = PublishSubject.create(); - - source.observeOn(Schedulers.computation()) - .subscribe(ComputeFunction::compute, Throwable::printStackTrace); + PublishSubject source = PublishSubject. create(); + source + .observeOn(Schedulers.computation()) + .subscribe(ComputeFunction::compute, Throwable::printStackTrace); for (int i = 0; i < 1_000_000; i++) { source.onNext(i); From 14bee159bdfa977e35e264268867d615cabdd081 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Sun, 5 Feb 2017 08:55:35 +0100 Subject: [PATCH 19/58] Fix JavaRandomUnitTest --- .../test/java/org/baeldung/java/JavaRandomUnitTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java index 4febe7c9fc..08f98025c3 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java @@ -1,12 +1,12 @@ package org.baeldung.java; -import java.nio.charset.Charset; -import java.util.Random; - import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.math3.random.RandomDataGenerator; import org.junit.Test; +import java.nio.charset.Charset; +import java.util.Random; + public class JavaRandomUnitTest { // tests - random long @@ -164,7 +164,7 @@ public class JavaRandomUnitTest { final int targetStringLength = 10; final StringBuilder buffer = new StringBuilder(targetStringLength); for (int i = 0; i < targetStringLength; i++) { - final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit)); + final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit + 1)); buffer.append((char) randomLimitedInt); } final String generatedString = buffer.toString(); From d4cb92250d036680bafa5a4ee322b7388d0c85b1 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Sun, 5 Feb 2017 10:20:12 +0100 Subject: [PATCH 20/58] LiveTest -> Test --- ...esourceEndpointLiveTest.java => ResourceEndpointTest.java} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/{ResourceEndpointLiveTest.java => ResourceEndpointTest.java} (95%) diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java similarity index 95% rename from spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java rename to spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java index 94b6052ba4..6d532f98fc 100644 --- a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java @@ -11,7 +11,7 @@ import static com.jayway.restassured.RestAssured.given; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AppRunner.class) -public class ResourceEndpointLiveTest { +public class ResourceEndpointTest { @LocalServerPort private int serverPort; @@ -66,7 +66,7 @@ public class ResourceEndpointLiveTest { } private String getBaseUrl() { - return "http://localhost:" + serverPort; + return String.format("http://localhost:%d", serverPort); } } \ No newline at end of file From 4b0249410c4334427e1bc6ba2a580b2dde9a05f3 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 5 Feb 2017 10:27:13 +0100 Subject: [PATCH 21/58] Update README.md --- spring-core/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-core/README.md b/spring-core/README.md index f6aaaf44a0..a32d30939f 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -3,4 +3,4 @@ - [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory) - [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) - [Constructor Dependency Injection in Spring](http://www.baeldung.com/constructor-injection-in-spring) -- [Constructor Injection in Spring with Lombok](http://inprogress.baeldung.com/constructor-injection-in-spring-with-lombok) +- [Constructor Injection in Spring with Lombok](http://www.baeldung.com/spring-injection-lombok) From 0e78d76f2291836c319f1b707e4ad553935fe501 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sun, 5 Feb 2017 10:27:44 +0100 Subject: [PATCH 22/58] BAEL-572 move code to tests --- rxjava/pom.xml | 6 + .../rxjava/ColdObservableBackpressure.java | 16 -- .../HotObservableBackpressureBatching.java | 18 -- .../HotObservableBackpressureBuffering.java | 17 -- .../HotObservableBackpressureSkipping.java | 21 --- .../HotObservableWithoutBackpressure.java | 20 --- .../rxjava/RxJavaBackpressureTest.java | 155 ++++++++++++++++++ 7 files changed, 161 insertions(+), 92 deletions(-) delete mode 100644 rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java delete mode 100644 rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java delete mode 100644 rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java delete mode 100644 rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java delete mode 100644 rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java create mode 100644 rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureTest.java diff --git a/rxjava/pom.xml b/rxjava/pom.xml index 63aa1f127e..6a351d98bd 100644 --- a/rxjava/pom.xml +++ b/rxjava/pom.xml @@ -26,9 +26,15 @@ rxjava ${rx.java.version} + + junit + junit + ${junit.version} + + 4.12 1.2.5 diff --git a/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java b/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java deleted file mode 100644 index abb0b99100..0000000000 --- a/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baelding.rxjava; - -import rx.Observable; -import rx.schedulers.Schedulers; - -public class ColdObservableBackpressure { - public static void main(String[] args) throws InterruptedException { - - Observable.range(1, 1_000_000) - .observeOn(Schedulers.computation()) - .subscribe(ComputeFunction::compute); - - Thread.sleep(10_000); - } - -} diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java deleted file mode 100644 index 6acda7eaad..0000000000 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baelding.rxjava; - -import rx.schedulers.Schedulers; -import rx.subjects.PublishSubject; - -public class HotObservableBackpressureBatching { - public static void main(String[] args) throws InterruptedException { - PublishSubject source = PublishSubject.create(); - - source.window(500).observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace); - - for (int i = 0; i < 1_000_000; i++) { - source.onNext(i); - } - Thread.sleep(10_000); - } - -} diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java deleted file mode 100644 index 50638f4c8a..0000000000 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baelding.rxjava; - -import rx.schedulers.Schedulers; -import rx.subjects.PublishSubject; - -public class HotObservableBackpressureBuffering { - public static void main(String[] args) throws InterruptedException { - PublishSubject source = PublishSubject.create(); - - source.buffer(1024).observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace); - - for (int i = 0; i < 1_000_000; i++) { - source.onNext(i); - } - Thread.sleep(10_000); - } -} diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java deleted file mode 100644 index f6f8b9f563..0000000000 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baelding.rxjava; - -import rx.schedulers.Schedulers; -import rx.subjects.PublishSubject; - -import java.util.concurrent.TimeUnit; - -public class HotObservableBackpressureSkipping { - public static void main(String[] args) throws InterruptedException { - PublishSubject source = PublishSubject.create(); - - source.sample(100, TimeUnit.MILLISECONDS) - // .throttleFirst(100, TimeUnit.MILLISECONDS) - .observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace); - - for (int i = 0; i < 1_000_000; i++) { - source.onNext(i); - } - Thread.sleep(10_000); - } -} diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java deleted file mode 100644 index 7745dbe5c4..0000000000 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baelding.rxjava; - - -import rx.schedulers.Schedulers; -import rx.subjects.PublishSubject; - -public class HotObservableWithoutBackpressure { - public static void main(String[] args) throws InterruptedException { - PublishSubject source = PublishSubject.create(); - - source.observeOn(Schedulers.computation()) - .subscribe(ComputeFunction::compute, Throwable::printStackTrace); - - - for (int i = 0; i < 1_000_000; i++) { - source.onNext(i); - } - Thread.sleep(10_000); - } -} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureTest.java new file mode 100644 index 0000000000..30357e7a27 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureTest.java @@ -0,0 +1,155 @@ +package com.baeldung.rxjava; + +import org.junit.Test; +import rx.BackpressureOverflow; +import rx.Observable; +import rx.exceptions.MissingBackpressureException; +import rx.observers.TestSubscriber; +import rx.schedulers.Schedulers; +import rx.subjects.PublishSubject; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertTrue; + +public class RxJavaBackpressureTest { + + @Test + public void givenColdObservable_shouldNotThrowException() { + //given + TestSubscriber testSubscriber = new TestSubscriber<>(); + + //when + Observable.range(1, 1_000_000) + .observeOn(Schedulers.computation()) + .subscribe(testSubscriber); + + //then + testSubscriber.awaitTerminalEvent(); + assertTrue(testSubscriber.getOnErrorEvents().size() == 0); + + } + + @Test + public void givenHotObservable_whenBackpressureNotDefined_shouldTrowException() { + //given + TestSubscriber testSubscriber = new TestSubscriber<>(); + PublishSubject source = PublishSubject.create(); + + source.observeOn(Schedulers.computation()) + .subscribe(testSubscriber); + + //when + for (int i = 0; i < 1_000_000; i++) { + source.onNext(i); + + } + + //then + testSubscriber.awaitTerminalEvent(); + testSubscriber.assertError(MissingBackpressureException.class); + } + + @Test + public void givenHotObservable_whenWindowIsDefined_shouldNotThrowException() { + //given + TestSubscriber> testSubscriber = new TestSubscriber<>(); + PublishSubject source = PublishSubject.create(); + + //when + source.window(500) + .observeOn(Schedulers.computation()) + .subscribe(testSubscriber); + + for (int i = 0; i < 1_000; i++) { + source.onNext(i); + } + + //then + testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); + assertTrue(testSubscriber.getOnErrorEvents().size() == 0); + + } + + @Test + public void givenHotObservable_whenBufferIsDefined_shouldNotThrowException() { + //given + TestSubscriber> testSubscriber = new TestSubscriber<>(); + PublishSubject source = PublishSubject.create(); + + //when + source.buffer(1024) + .observeOn(Schedulers.computation()) + .subscribe(testSubscriber); + + for (int i = 0; i < 1_000; i++) { + source.onNext(i); + } + + //then + testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); + assertTrue(testSubscriber.getOnErrorEvents().size() == 0); + + } + + + @Test + public void givenHotObservable_whenSkippingOperationIsDefined_shouldNotThrowException() { + //given + TestSubscriber testSubscriber = new TestSubscriber<>(); + PublishSubject source = PublishSubject.create(); + + //when + source.sample(100, TimeUnit.MILLISECONDS) +// .throttleFirst(100, TimeUnit.MILLISECONDS) + .observeOn(Schedulers.computation()) + .subscribe(testSubscriber); + + for (int i = 0; i < 1_000; i++) { + source.onNext(i); + } + + //then + testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); + assertTrue(testSubscriber.getOnErrorEvents().size() == 0); + + } + + @Test + public void givenHotObservable_whenOnBackpressureBufferDefined_shouldNotThrowException() { + //given + TestSubscriber testSubscriber = new TestSubscriber<>(); + + //when + Observable.range(1, 1_000_000) + .onBackpressureBuffer(16, () -> { + }, + BackpressureOverflow.ON_OVERFLOW_DROP_OLDEST) + .observeOn(Schedulers.computation()) + .subscribe(testSubscriber); + + //then + testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); + assertTrue(testSubscriber.getOnErrorEvents().size() == 0); + + } + + + @Test + public void givenHotObservable_whenOnBackpressureDropDefined_shouldNotThrowException() { + //given + TestSubscriber testSubscriber = new TestSubscriber<>(); + + //when + Observable.range(1, 1_000_000) + .onBackpressureDrop() + .observeOn(Schedulers.computation()) + .subscribe(testSubscriber); + + //then + testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); + assertTrue(testSubscriber.getOnErrorEvents().size() == 0); + + } +} From 99bb4104f86040ad22889dbb02055f33b228bf54 Mon Sep 17 00:00:00 2001 From: Nikhil Khatwani Date: Sun, 5 Feb 2017 16:02:59 +0530 Subject: [PATCH 23/58] BAEL-248_Update_deprecated_API Changes --- spring-security-rest-basic-auth/pom.xml | 6 +-- .../baeldung/client/RestTemplateFactory.java | 22 +++-------- ...entsClientHttpRequestFactoryBasicAuth.java | 39 +++++++++++++++++++ 3 files changed, 48 insertions(+), 19 deletions(-) create mode 100644 spring-security-rest-basic-auth/src/main/java/org/baeldung/http/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index 7987eebb66..953cfd6b6b 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -342,8 +342,8 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.3.6.RELEASE + 4.2.1.RELEASE 5.2.5.Final @@ -351,7 +351,7 @@ 4.4.5 - 4.5.2 + 4.5.3 1.7.21 diff --git a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java index 0cec0dc5c3..061f9b3022 100644 --- a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java @@ -1,15 +1,11 @@ package org.baeldung.client; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.HttpHost; +import org.baeldung.http.client.HttpComponentsClientHttpRequestFactoryBasicAuth; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.http.client.ClientHttpRequestFactory; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.http.client.support.BasicAuthorizationInterceptor; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; @@ -40,16 +36,10 @@ public class RestTemplateFactory implements FactoryBean, Initializ @Override public void afterPropertiesSet() { - final int timeout = 5; - - final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); - - final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(new AuthScope("localhost", 8082, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); - final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).setDefaultCredentialsProvider(credentialsProvider).build(); - - final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client); + HttpHost host = new HttpHost("localhost", 8082, "http"); + final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host); restTemplate = new RestTemplate(requestFactory); + restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user1", "user1Pass")); } } \ No newline at end of file diff --git a/spring-security-rest-basic-auth/src/main/java/org/baeldung/http/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/http/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java new file mode 100644 index 0000000000..4a7b4869bc --- /dev/null +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/http/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java @@ -0,0 +1,39 @@ +package org.baeldung.http.client; + +import java.net.URI; + +import org.apache.http.HttpHost; +import org.apache.http.client.AuthCache; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.BasicAuthCache; +import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; +import org.springframework.http.HttpMethod; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; + +public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpComponentsClientHttpRequestFactory { + + HttpHost host; + + public HttpComponentsClientHttpRequestFactoryBasicAuth(HttpHost host) { + super(); + this.host = host; + } + + protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { + return createHttpContext(); + } + + private HttpContext createHttpContext() { + + AuthCache authCache = new BasicAuthCache(); + + BasicScheme basicAuth = new BasicScheme(); + authCache.put(host, basicAuth); + + BasicHttpContext localcontext = new BasicHttpContext(); + localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); + return localcontext; + } +} \ No newline at end of file From c2ed9afc2dbcd178b9c1172ff4cd4401ccb37f6d Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sun, 5 Feb 2017 10:39:29 +0100 Subject: [PATCH 24/58] BAEL-542 use @GetMapping annotation --- .../baeldung/cachecontrol/ResourceEndpoint.java | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java index 9f756b5ab4..bd129cbdfa 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java @@ -6,9 +6,8 @@ import com.baeldung.cachecontrol.model.UserDto; import org.springframework.http.CacheControl; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import java.time.LocalDateTime; import java.time.ZoneOffset; @@ -17,27 +16,27 @@ import java.util.concurrent.TimeUnit; @Controller public class ResourceEndpoint { - @RequestMapping(value = "/default/users/{name}", method = RequestMethod.GET) - public ResponseEntity getUserWithDefaultCaching(@PathVariable(value = "name") String name) { + @GetMapping(value = "/default/users/{name}") + public ResponseEntity getUserWithDefaultCaching(@PathVariable String name) { return ResponseEntity.ok(new UserDto(name)); } - @RequestMapping(value = "/users/{name}", method = RequestMethod.GET) - public ResponseEntity getUser(@PathVariable(value = "name") String name) { + @GetMapping(value = "/users/{name}") + public ResponseEntity getUser(@PathVariable String name) { return ResponseEntity.ok() .cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)) .body(new UserDto(name)); } - @RequestMapping(value = "/timestamp", method = RequestMethod.GET) + @GetMapping(value = "/timestamp") public ResponseEntity getServerTimestamp() { return ResponseEntity.ok() .cacheControl(CacheControl.noStore()) .body(new TimestampDto(LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli())); } - @RequestMapping(value = "/private/users/{name}", method = RequestMethod.GET) - public ResponseEntity getUserNotCached(@PathVariable("name") String name) { + @GetMapping(value = "/private/users/{name}") + public ResponseEntity getUserNotCached(@PathVariable String name) { return ResponseEntity.ok() .body(new UserDto(name)); } From c791bdf1dca3a17ecee3872a4fa2c30762229ea6 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sun, 5 Feb 2017 12:56:09 +0100 Subject: [PATCH 25/58] BAEL-672 test for weakHashMap --- core-java/pom.xml | 7 +++ .../baeldung/weakhashmap/WeakHashMapTest.java | 48 +++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java diff --git a/core-java/pom.xml b/core-java/pom.xml index 85afee2968..5c91150941 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -154,6 +154,12 @@ ${mockito.version} test + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + commons-codec @@ -371,6 +377,7 @@ 1.10.19 6.10 3.6.1 + 1.7.0 3.6.0 diff --git a/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java b/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java new file mode 100644 index 0000000000..fbeb364ab6 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java @@ -0,0 +1,48 @@ +package com.baeldung.weakhashmap; + + +import org.junit.Test; + +import java.util.WeakHashMap; +import java.util.concurrent.TimeUnit; + +import static com.jayway.awaitility.Awaitility.await; +import static org.junit.Assert.assertTrue; + +public class WeakHashMapTest { + + @Test + public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObject() { + //given + WeakHashMap map = new WeakHashMap<>(); + BigImage bigImage = new BigImage("foo"); + UniqueImageName imageName = new UniqueImageName("name_of_big_image"); + + map.put(imageName, bigImage); + assertTrue(map.containsKey(imageName)); + + //when big image is not in use anymore + imageName = null; + System.gc(); + + //then GC will finally reclaim that object + await().atMost(10, TimeUnit.SECONDS).until(map::isEmpty); + } + + + class BigImage { + public final String imageId; + + BigImage(String imageId) { + this.imageId = imageId; + } + } + + class UniqueImageName { + public final String imageName; + + UniqueImageName(String imageName) { + this.imageName = imageName; + } + } +} From 0f59b0d5335bba974afb4915b961e859546b32c2 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sun, 5 Feb 2017 14:13:45 +0100 Subject: [PATCH 26/58] BAEL-672 proper image id --- .../test/java/com/baeldung/weakhashmap/WeakHashMapTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java b/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java index fbeb364ab6..7b34c6b316 100644 --- a/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java +++ b/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java @@ -15,13 +15,13 @@ public class WeakHashMapTest { public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObject() { //given WeakHashMap map = new WeakHashMap<>(); - BigImage bigImage = new BigImage("foo"); + BigImage bigImage = new BigImage("image_id"); UniqueImageName imageName = new UniqueImageName("name_of_big_image"); map.put(imageName, bigImage); assertTrue(map.containsKey(imageName)); - //when big image is not in use anymore + //when big image key is not reference anywhere imageName = null; System.gc(); From 5b79f605a4f85309970abd2fee67ed6d0b1cae20 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Sun, 5 Feb 2017 17:06:12 +0100 Subject: [PATCH 27/58] Refactor ResourceEndpoint --- spring-security-cache-control/pom.xml | 5 ++++ .../cachecontrol/ResourceEndpoint.java | 29 +++++++++++-------- 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml index c30b0cd1aa..da363a75af 100644 --- a/spring-security-cache-control/pom.xml +++ b/spring-security-cache-control/pom.xml @@ -14,6 +14,11 @@ 1.4.3.RELEASE + + 1.8 + + + org.springframework.boot diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java index bd129cbdfa..038df43165 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java @@ -1,6 +1,5 @@ package com.baeldung.cachecontrol; - import com.baeldung.cachecontrol.model.TimestampDto; import com.baeldung.cachecontrol.model.UserDto; import org.springframework.http.CacheControl; @@ -21,23 +20,29 @@ public class ResourceEndpoint { return ResponseEntity.ok(new UserDto(name)); } - @GetMapping(value = "/users/{name}") + @GetMapping("/users/{name}") public ResponseEntity getUser(@PathVariable String name) { - return ResponseEntity.ok() - .cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)) - .body(new UserDto(name)); + return ResponseEntity + .ok() + .cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)) + .body(new UserDto(name)); } - @GetMapping(value = "/timestamp") + @GetMapping("/timestamp") public ResponseEntity getServerTimestamp() { - return ResponseEntity.ok() - .cacheControl(CacheControl.noStore()) - .body(new TimestampDto(LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli())); + return ResponseEntity + .ok() + .cacheControl(CacheControl.noStore()) + .body(new TimestampDto(LocalDateTime + .now() + .toInstant(ZoneOffset.UTC) + .toEpochMilli())); } - @GetMapping(value = "/private/users/{name}") + @GetMapping("/private/users/{name}") public ResponseEntity getUserNotCached(@PathVariable String name) { - return ResponseEntity.ok() - .body(new UserDto(name)); + return ResponseEntity + .ok() + .body(new UserDto(name)); } } From 4e91a6388cce55ebe0274a48043895a971085ccc Mon Sep 17 00:00:00 2001 From: pivovarit Date: Sun, 5 Feb 2017 17:16:27 +0100 Subject: [PATCH 28/58] Refactor BackpressureTest --- .../rxjava/RxJavaBackpressureTest.java | 114 ++++++++++-------- 1 file changed, 65 insertions(+), 49 deletions(-) diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureTest.java index 30357e7a27..33f94a9c6f 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureTest.java @@ -10,6 +10,7 @@ import rx.subjects.PublishSubject; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; import static org.junit.Assert.assertTrue; @@ -21,13 +22,16 @@ public class RxJavaBackpressureTest { TestSubscriber testSubscriber = new TestSubscriber<>(); //when - Observable.range(1, 1_000_000) - .observeOn(Schedulers.computation()) - .subscribe(testSubscriber); + Observable + .range(1, 1_000_000) + .observeOn(Schedulers.computation()) + .subscribe(testSubscriber); //then testSubscriber.awaitTerminalEvent(); - assertTrue(testSubscriber.getOnErrorEvents().size() == 0); + assertTrue(testSubscriber + .getOnErrorEvents() + .size() == 0); } @@ -35,16 +39,16 @@ public class RxJavaBackpressureTest { public void givenHotObservable_whenBackpressureNotDefined_shouldTrowException() { //given TestSubscriber testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject.create(); + PublishSubject source = PublishSubject. create(); - source.observeOn(Schedulers.computation()) - .subscribe(testSubscriber); + source + .observeOn(Schedulers.computation()) + .subscribe(testSubscriber); //when - for (int i = 0; i < 1_000_000; i++) { - source.onNext(i); - - } + IntStream + .range(0, 1_000_000) + .forEach(source::onNext); //then testSubscriber.awaitTerminalEvent(); @@ -55,20 +59,23 @@ public class RxJavaBackpressureTest { public void givenHotObservable_whenWindowIsDefined_shouldNotThrowException() { //given TestSubscriber> testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject.create(); + PublishSubject source = PublishSubject. create(); //when - source.window(500) - .observeOn(Schedulers.computation()) - .subscribe(testSubscriber); + source + .window(500) + .observeOn(Schedulers.computation()) + .subscribe(testSubscriber); - for (int i = 0; i < 1_000; i++) { - source.onNext(i); - } + IntStream + .range(0, 1_000) + .forEach(source::onNext); //then testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); - assertTrue(testSubscriber.getOnErrorEvents().size() == 0); + assertTrue(testSubscriber + .getOnErrorEvents() + .size() == 0); } @@ -76,43 +83,49 @@ public class RxJavaBackpressureTest { public void givenHotObservable_whenBufferIsDefined_shouldNotThrowException() { //given TestSubscriber> testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject.create(); + PublishSubject source = PublishSubject. create(); //when - source.buffer(1024) - .observeOn(Schedulers.computation()) - .subscribe(testSubscriber); + source + .buffer(1024) + .observeOn(Schedulers.computation()) + .subscribe(testSubscriber); + + IntStream + .range(0, 1_000) + .forEach(source::onNext); - for (int i = 0; i < 1_000; i++) { - source.onNext(i); - } //then testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); - assertTrue(testSubscriber.getOnErrorEvents().size() == 0); + assertTrue(testSubscriber + .getOnErrorEvents() + .size() == 0); } - @Test public void givenHotObservable_whenSkippingOperationIsDefined_shouldNotThrowException() { //given TestSubscriber testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject.create(); + PublishSubject source = PublishSubject. create(); //when source.sample(100, TimeUnit.MILLISECONDS) -// .throttleFirst(100, TimeUnit.MILLISECONDS) - .observeOn(Schedulers.computation()) - .subscribe(testSubscriber); + // .throttleFirst(100, TimeUnit.MILLISECONDS) + .observeOn(Schedulers.computation()) + .subscribe(testSubscriber); + + IntStream + .range(0, 1_000) + .forEach(source::onNext); - for (int i = 0; i < 1_000; i++) { - source.onNext(i); - } //then testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); - assertTrue(testSubscriber.getOnErrorEvents().size() == 0); + assertTrue(testSubscriber + .getOnErrorEvents() + .size() == 0); } @@ -122,34 +135,37 @@ public class RxJavaBackpressureTest { TestSubscriber testSubscriber = new TestSubscriber<>(); //when - Observable.range(1, 1_000_000) - .onBackpressureBuffer(16, () -> { - }, - BackpressureOverflow.ON_OVERFLOW_DROP_OLDEST) - .observeOn(Schedulers.computation()) - .subscribe(testSubscriber); + Observable + .range(1, 1_000_000) + .onBackpressureBuffer(16, () -> {}, BackpressureOverflow.ON_OVERFLOW_DROP_OLDEST) + .observeOn(Schedulers.computation()) + .subscribe(testSubscriber); //then testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); - assertTrue(testSubscriber.getOnErrorEvents().size() == 0); + assertTrue(testSubscriber + .getOnErrorEvents() + .size() == 0); } - @Test public void givenHotObservable_whenOnBackpressureDropDefined_shouldNotThrowException() { //given TestSubscriber testSubscriber = new TestSubscriber<>(); //when - Observable.range(1, 1_000_000) - .onBackpressureDrop() - .observeOn(Schedulers.computation()) - .subscribe(testSubscriber); + Observable + .range(1, 1_000_000) + .onBackpressureDrop() + .observeOn(Schedulers.computation()) + .subscribe(testSubscriber); //then testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS); - assertTrue(testSubscriber.getOnErrorEvents().size() == 0); + assertTrue(testSubscriber + .getOnErrorEvents() + .size() == 0); } } From 4cbb0edafa6a9b5c0584a036d42b43e5e5880db7 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Sun, 5 Feb 2017 17:51:33 +0100 Subject: [PATCH 29/58] remove java.version from properties --- spring-security-cache-control/pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml index da363a75af..c30b0cd1aa 100644 --- a/spring-security-cache-control/pom.xml +++ b/spring-security-cache-control/pom.xml @@ -14,11 +14,6 @@ 1.4.3.RELEASE - - 1.8 - - - org.springframework.boot From 15659388032ded6c832a3c44a95560dcc78b0d53 Mon Sep 17 00:00:00 2001 From: Muhammed Almas Date: Mon, 6 Feb 2017 02:36:31 +0530 Subject: [PATCH 30/58] Pre conditions (#1116) * BAL-36 File size api in java and apache commons IO * BAEL-282 grep in java - fixes after code review * BAEL-519 Added support for disruptor library * BAEL-519 Added support for disruptor library * BAEL-519 Added support for disruptor library * BAEL-519 Added support for disruptor library * BAEL-519 Added support for disruptor library * BAEL-519 Added support for disruptor library * BAEL-519 Added support for disruptor * BAEL-519 Moved all supporting classes to main source * BAEL-519 Moved all supporting classes to main source * BAEL-519 Moved asserts and test classes in test folder. * BAEL-519 moved test related producer and consumer to src. * BAEL-586 Guide to Guava BiMap. * BAEL-587 formatted code. * BAEL-519 LMAX Disruptor * BAEL-587 resolved merge * BAEL-587 Resolved merge * BAEL-519 Removed disruptor link. * BAEL-519 Reverted Guava changes * RFQ-587 Added disruptor as a separate module. * BAEL-519 Disruptor changes. * BAEL-519 Removed disruptor from core-java module. * BAEL-637 Guide to PreConditions * BAEL-637 Used assertJ for exception assertion. * BAEL-637 updated tests to use assertJ. * BAEL-637 Removed redundant tests. --- .../guava/GuavaPreConditionsTest.java | 83 ++++--------------- 1 file changed, 15 insertions(+), 68 deletions(-) diff --git a/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java b/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java index 55e3c7db00..aff42ea6e2 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java @@ -3,7 +3,7 @@ package org.baeldung.guava; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Arrays; import org.junit.Test; -import static com.google.common.base.Preconditions.*; +import com.google.common.base.*; public class GuavaPreConditionsTest { @@ -11,10 +11,7 @@ public class GuavaPreConditionsTest { public void whenCheckArgumentEvaluatesFalse_throwsException() { int age = -18; - assertThatThrownBy(() -> checkArgument(age > 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage(null) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkArgument(age > 0)).isInstanceOf(IllegalArgumentException.class).hasMessage(null).hasNoCause(); } @Test @@ -22,10 +19,7 @@ public class GuavaPreConditionsTest { final int age = -18; final String message = "Age can't be zero or less than zero"; - assertThatThrownBy(() -> checkArgument(age > 0, message)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage(message) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message)).isInstanceOf(IllegalArgumentException.class).hasMessage(message).hasNoCause(); } @Test @@ -33,19 +27,14 @@ public class GuavaPreConditionsTest { final int age = -18; final String message = "Age can't be zero or less than zero, you supplied %s."; - assertThatThrownBy(() -> checkArgument(age > 0, message, age)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage(message, age) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message, age)).isInstanceOf(IllegalArgumentException.class).hasMessage(message, age).hasNoCause(); } @Test public void givenArrayOfIntegers_whenCheckElementIndexEvaluatesFalse_throwsException() { final int[] numbers = { 1, 2, 3, 4, 5 }; - assertThatThrownBy(() -> checkElementIndex(6, numbers.length - 1)) - .isInstanceOf(IndexOutOfBoundsException.class) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause(); } @Test @@ -53,20 +42,7 @@ public class GuavaPreConditionsTest { final int[] numbers = { 1, 2, 3, 4, 5 }; final String message = "Please check the bound of an array and retry"; - assertThatThrownBy(() -> checkElementIndex(6, numbers.length - 1, message)) - .isInstanceOf(IndexOutOfBoundsException.class) - .hasMessageStartingWith(message) - .hasNoCause(); - } - - @Test - public void givenNullString_whenCheckNotNullCalled_throwsException() { - final String nullObject = null; - - assertThatThrownBy(() -> checkNotNull(nullObject)) - .isInstanceOf(NullPointerException.class) - .hasMessage(null) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause(); } @Test @@ -74,10 +50,7 @@ public class GuavaPreConditionsTest { final String nullObject = null; final String message = "Please check the Object supplied, its null!"; - assertThatThrownBy(() -> checkNotNull(nullObject, message)) - .isInstanceOf(NullPointerException.class) - .hasMessage(message) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message)).isInstanceOf(NullPointerException.class).hasMessage(message).hasNoCause(); } @Test @@ -85,19 +58,14 @@ public class GuavaPreConditionsTest { final String nullObject = null; final String message = "Please check the Object supplied, its %s!"; - assertThatThrownBy(() -> checkNotNull(nullObject, message, nullObject)) - .isInstanceOf(NullPointerException.class) - .hasMessage(message, nullObject) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message, nullObject)).isInstanceOf(NullPointerException.class).hasMessage(message, nullObject).hasNoCause(); } @Test public void givenArrayOfIntegers_whenCheckPositionIndexEvaluatesFalse_throwsException() { final int[] numbers = { 1, 2, 3, 4, 5 }; - assertThatThrownBy(() -> checkPositionIndex(6, numbers.length - 1)) - .isInstanceOf(IndexOutOfBoundsException.class) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause(); } @Test @@ -105,30 +73,14 @@ public class GuavaPreConditionsTest { final int[] numbers = { 1, 2, 3, 4, 5 }; final String message = "Please check the bound of an array and retry"; - assertThatThrownBy(() -> checkPositionIndex(6, numbers.length - 1, message)) - .isInstanceOf(IndexOutOfBoundsException.class) - .hasMessageStartingWith(message) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause(); } @Test public void givenArrayOfIntegers_whenCheckPositionIndexesEvaluatesFalse_throwsException() { final int[] numbers = { 1, 2, 3, 4, 5 }; - assertThatThrownBy(() -> checkPositionIndexes(6, 0, numbers.length - 1)) - .isInstanceOf(IndexOutOfBoundsException.class) - .hasNoCause(); - } - - @Test - public void givenValidStates_whenCheckStateEvaluatesFalse_throwsException() { - final int[] validStates = { -1, 0, 1 }; - final int givenState = 10; - - assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0)) - .isInstanceOf(IllegalStateException.class) - .hasMessage(null) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkPositionIndexes(6, 0, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause(); } @Test @@ -137,10 +89,7 @@ public class GuavaPreConditionsTest { final int givenState = 10; final String message = "You have entered an invalid state"; - assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0, message)) - .isInstanceOf(IllegalStateException.class) - .hasMessageStartingWith(message) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message)).isInstanceOf(IllegalStateException.class).hasMessageStartingWith(message).hasNoCause(); } @Test @@ -149,9 +98,7 @@ public class GuavaPreConditionsTest { final int givenState = 10; final String message = "State can't be %s, It can be one of %s."; - assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0, message, givenState, Arrays.toString(validStates))) - .isInstanceOf(IllegalStateException.class) - .hasMessage(message, givenState, Arrays.toString(validStates)) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message, givenState, Arrays.toString(validStates))).isInstanceOf(IllegalStateException.class) + .hasMessage(message, givenState, Arrays.toString(validStates)).hasNoCause(); } -} +} \ No newline at end of file From 24ccec2a2080afb0a24da5f9564916594d7fe007 Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 6 Feb 2017 00:37:53 +0200 Subject: [PATCH 31/58] minof formatting work --- .../test/java/org/baeldung/guava/GuavaPreConditionsTest.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java b/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java index aff42ea6e2..f231fdda9d 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java @@ -1,9 +1,12 @@ package org.baeldung.guava; import static org.assertj.core.api.Assertions.assertThatThrownBy; + import java.util.Arrays; + import org.junit.Test; -import com.google.common.base.*; + +import com.google.common.base.Preconditions; public class GuavaPreConditionsTest { From 3b82dd6b3b1cb8c224fc5f1820cbcd3ccddf02dc Mon Sep 17 00:00:00 2001 From: Predrag Maric Date: Mon, 6 Feb 2017 04:59:03 +0100 Subject: [PATCH 32/58] BAEL-248 Moved HttpComponentsClientHttpRequestFactoryBasicAuth to an existing package --- .../client/HttpComponentsClientHttpRequestFactoryBasicAuth.java | 2 +- .../src/main/java/org/baeldung/client/RestTemplateFactory.java | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) rename spring-security-rest-basic-auth/src/main/java/org/baeldung/{http => }/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java (97%) diff --git a/spring-security-rest-basic-auth/src/main/java/org/baeldung/http/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java similarity index 97% rename from spring-security-rest-basic-auth/src/main/java/org/baeldung/http/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java rename to spring-security-rest-basic-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java index 4a7b4869bc..a2f51d343b 100644 --- a/spring-security-rest-basic-auth/src/main/java/org/baeldung/http/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java @@ -1,4 +1,4 @@ -package org.baeldung.http.client; +package org.baeldung.client; import java.net.URI; diff --git a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java index 061f9b3022..5e15648e9b 100644 --- a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java @@ -1,7 +1,6 @@ package org.baeldung.client; import org.apache.http.HttpHost; -import org.baeldung.http.client.HttpComponentsClientHttpRequestFactoryBasicAuth; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.http.client.ClientHttpRequestFactory; From daf7af813cfae915907e8a71d946445679f1018e Mon Sep 17 00:00:00 2001 From: Andrew Morgan Date: Mon, 6 Feb 2017 06:51:56 +0000 Subject: [PATCH 33/58] Implemented strategy pattern tutorial (#1110) --- .../strategy/ChristmasDiscounter.java | 10 ++++ .../com/baeldung/strategy/Discounter.java | 7 +++ .../baeldung/strategy/EasterDiscounter.java | 10 ++++ .../StrategyDesignPatternUnitTest.java | 58 +++++++++++++++++++ 4 files changed, 85 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java create mode 100644 core-java/src/main/java/com/baeldung/strategy/Discounter.java create mode 100644 core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java create mode 100644 core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java b/core-java/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java new file mode 100644 index 0000000000..644c57aa26 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java @@ -0,0 +1,10 @@ +package com.baeldung.strategy; + +import java.math.BigDecimal; + +public class ChristmasDiscounter implements Discounter { + @Override + public BigDecimal applyDiscount(final BigDecimal amount) { + return amount.multiply(BigDecimal.valueOf(0.9)); + } +} diff --git a/core-java/src/main/java/com/baeldung/strategy/Discounter.java b/core-java/src/main/java/com/baeldung/strategy/Discounter.java new file mode 100644 index 0000000000..ed6a00cba4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/strategy/Discounter.java @@ -0,0 +1,7 @@ +package com.baeldung.strategy; + +import java.math.BigDecimal; + +public interface Discounter { + BigDecimal applyDiscount(BigDecimal amount); +} diff --git a/core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java b/core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java new file mode 100644 index 0000000000..fd70255482 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java @@ -0,0 +1,10 @@ +package com.baeldung.strategy; + +import java.math.BigDecimal; + +public class EasterDiscounter implements Discounter { + @Override + public BigDecimal applyDiscount(final BigDecimal amount) { + return amount.multiply(BigDecimal.valueOf(0.5)); + } +} diff --git a/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java b/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java new file mode 100644 index 0000000000..b1881091d9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.strategy; + +import org.junit.Test; + +import java.math.BigDecimal; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.util.Lists.newArrayList; + +public class StrategyDesignPatternUnitTest { + @Test + public void shouldDivideByTwo_WhenApplyingStaffDiscounter() { + Discounter staffDiscounter = new EasterDiscounter(); + + final BigDecimal discountedValue = staffDiscounter + .applyDiscount(BigDecimal.valueOf(100)); + + assertThat(discountedValue) + .isEqualByComparingTo(BigDecimal.valueOf(50)); + } + + @Test + public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithAnonyousTypes() { + Discounter staffDiscounter = new Discounter() { + @Override + public BigDecimal applyDiscount(final BigDecimal amount) { + return amount.multiply(BigDecimal.valueOf(0.5)); + } + }; + + final BigDecimal discountedValue = staffDiscounter + .applyDiscount(BigDecimal.valueOf(100)); + + assertThat(discountedValue) + .isEqualByComparingTo(BigDecimal.valueOf(50)); + } + + @Test + public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithLamda() { + Discounter staffDiscounter = amount -> amount.multiply(BigDecimal.valueOf(0.5)); + + final BigDecimal discountedValue = staffDiscounter + .applyDiscount(BigDecimal.valueOf(100)); + + assertThat(discountedValue) + .isEqualByComparingTo(BigDecimal.valueOf(50)); + } + + @Test + public void shouldApplyListOfDiscounts() { + List discounters = newArrayList(); + + BigDecimal amount = BigDecimal.valueOf(100); + + discounters.forEach((d) -> d.applyDiscount(amount)); + } +} From 77f1a97e8fb3cbbbb10d2bf9bcbc12a957495cdc Mon Sep 17 00:00:00 2001 From: pivovarit Date: Mon, 6 Feb 2017 08:07:05 +0100 Subject: [PATCH 34/58] Refactor Discounter examples --- .../strategy/ChristmasDiscounter.java | 3 +- .../com/baeldung/strategy/Discounter.java | 16 ++++++++-- .../baeldung/strategy/EasterDiscounter.java | 3 +- .../StrategyDesignPatternUnitTest.java | 31 ++++++++++++++----- 4 files changed, 41 insertions(+), 12 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java b/core-java/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java index 644c57aa26..a0c36bb63e 100644 --- a/core-java/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java +++ b/core-java/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java @@ -3,8 +3,9 @@ package com.baeldung.strategy; import java.math.BigDecimal; public class ChristmasDiscounter implements Discounter { + @Override - public BigDecimal applyDiscount(final BigDecimal amount) { + public BigDecimal apply(BigDecimal amount) { return amount.multiply(BigDecimal.valueOf(0.9)); } } diff --git a/core-java/src/main/java/com/baeldung/strategy/Discounter.java b/core-java/src/main/java/com/baeldung/strategy/Discounter.java index ed6a00cba4..4701287946 100644 --- a/core-java/src/main/java/com/baeldung/strategy/Discounter.java +++ b/core-java/src/main/java/com/baeldung/strategy/Discounter.java @@ -1,7 +1,19 @@ package com.baeldung.strategy; import java.math.BigDecimal; +import java.util.function.UnaryOperator; -public interface Discounter { - BigDecimal applyDiscount(BigDecimal amount); +public interface Discounter extends UnaryOperator { + + static Discounter christmas() { + return (amount) -> amount.multiply(BigDecimal.valueOf(0.9)); + } + + static Discounter newYear() { + return (amount) -> amount.multiply(BigDecimal.valueOf(0.8)); + } + + static Discounter easter() { + return (amount) -> amount.multiply(BigDecimal.valueOf(0.5)); + } } diff --git a/core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java b/core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java index fd70255482..990d10073b 100644 --- a/core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java +++ b/core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java @@ -3,8 +3,9 @@ package com.baeldung.strategy; import java.math.BigDecimal; public class EasterDiscounter implements Discounter { + @Override - public BigDecimal applyDiscount(final BigDecimal amount) { + public BigDecimal apply(BigDecimal amount) { return amount.multiply(BigDecimal.valueOf(0.5)); } } diff --git a/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java b/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java index b1881091d9..2c1c166b9c 100644 --- a/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java +++ b/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java @@ -3,10 +3,12 @@ package com.baeldung.strategy; import org.junit.Test; import java.math.BigDecimal; +import java.util.Arrays; import java.util.List; +import java.util.function.Function; +import static com.baeldung.strategy.Discounter.*; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.util.Lists.newArrayList; public class StrategyDesignPatternUnitTest { @Test @@ -14,7 +16,7 @@ public class StrategyDesignPatternUnitTest { Discounter staffDiscounter = new EasterDiscounter(); final BigDecimal discountedValue = staffDiscounter - .applyDiscount(BigDecimal.valueOf(100)); + .apply(BigDecimal.valueOf(100)); assertThat(discountedValue) .isEqualByComparingTo(BigDecimal.valueOf(50)); @@ -24,13 +26,13 @@ public class StrategyDesignPatternUnitTest { public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithAnonyousTypes() { Discounter staffDiscounter = new Discounter() { @Override - public BigDecimal applyDiscount(final BigDecimal amount) { + public BigDecimal apply( BigDecimal amount) { return amount.multiply(BigDecimal.valueOf(0.5)); } }; final BigDecimal discountedValue = staffDiscounter - .applyDiscount(BigDecimal.valueOf(100)); + .apply(BigDecimal.valueOf(100)); assertThat(discountedValue) .isEqualByComparingTo(BigDecimal.valueOf(50)); @@ -41,18 +43,31 @@ public class StrategyDesignPatternUnitTest { Discounter staffDiscounter = amount -> amount.multiply(BigDecimal.valueOf(0.5)); final BigDecimal discountedValue = staffDiscounter - .applyDiscount(BigDecimal.valueOf(100)); + .apply(BigDecimal.valueOf(100)); assertThat(discountedValue) .isEqualByComparingTo(BigDecimal.valueOf(50)); } @Test - public void shouldApplyListOfDiscounts() { - List discounters = newArrayList(); + public void shouldApplyAllDiscounts() { + List discounters = Arrays.asList(christmas(), newYear(), easter()); BigDecimal amount = BigDecimal.valueOf(100); - discounters.forEach((d) -> d.applyDiscount(amount)); + final Discounter combinedDiscounter = discounters + .stream() + .reduce(v -> v, (d1, d2) -> (Discounter) d1.andThen(d2)); + + combinedDiscounter.apply(amount); + } + + @Test + public void shouldChainDiscounters() { + final Function combinedDiscounters = Discounter + .christmas() + .andThen(newYear()); + + combinedDiscounters.apply(BigDecimal.valueOf(100)); } } From 13f2eef879859dab437d6199ce717ecc75096536 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Mon, 6 Feb 2017 09:05:55 +0100 Subject: [PATCH 35/58] Fix Discounter examples --- core-java/src/main/java/com/baeldung/strategy/Discounter.java | 4 ++++ .../com/baeldung/strategy/StrategyDesignPatternUnitTest.java | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/core-java/src/main/java/com/baeldung/strategy/Discounter.java b/core-java/src/main/java/com/baeldung/strategy/Discounter.java index 4701287946..00bf4855d1 100644 --- a/core-java/src/main/java/com/baeldung/strategy/Discounter.java +++ b/core-java/src/main/java/com/baeldung/strategy/Discounter.java @@ -5,6 +5,10 @@ import java.util.function.UnaryOperator; public interface Discounter extends UnaryOperator { + default Discounter combine(Discounter after) { + return value -> after.apply(this.apply(value)); + } + static Discounter christmas() { return (amount) -> amount.multiply(BigDecimal.valueOf(0.9)); } diff --git a/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java b/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java index 2c1c166b9c..7ca1d000be 100644 --- a/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java +++ b/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java @@ -57,7 +57,7 @@ public class StrategyDesignPatternUnitTest { final Discounter combinedDiscounter = discounters .stream() - .reduce(v -> v, (d1, d2) -> (Discounter) d1.andThen(d2)); + .reduce(v -> v, Discounter::combine); combinedDiscounter.apply(amount); } From 9f77fecd1589c0a53281f8486847c9a092fcc247 Mon Sep 17 00:00:00 2001 From: Diane Duan Date: Mon, 6 Feb 2017 17:47:57 +0800 Subject: [PATCH 36/58] fix --- .../test/java/com/baeldung/metrics/core/MetricsTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java b/metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java index f670acfaef..e876de6e65 100644 --- a/metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java @@ -138,15 +138,15 @@ public class MetricsTest { long elapsed1 = context1.stop(); - assertEquals(5000000000L, elapsed1, 10000000); + assertEquals(5000000000L, elapsed1, 1000000000); assertThat(timer.getCount(), equalTo(1L)); - assertEquals(0.2, timer.getMeanRate(), 0.1); + assertEquals(0.2, timer.getMeanRate(), 0.2); Timer.Context context2 = timer.time(); TimeUnit.SECONDS.sleep(2); context2.close(); assertThat(timer.getCount(), equalTo(2L)); - assertEquals(0.3, timer.getMeanRate(), 0.1); + assertEquals(0.3, timer.getMeanRate(), 0.2); } } From 071790b1d8ad197c12cf80d17fdd90245ca49cb2 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Mon, 6 Feb 2017 14:05:00 +0100 Subject: [PATCH 37/58] Rename ConcurrentMap tests --- ...tusTest.java => ConcurrentMapAggregateStatusManualTest.java} | 2 +- ...yValueTest.java => ConcurrentMapNullKeyValueManualTest.java} | 2 +- ...ormanceTest.java => ConcurrentMapPerformanceManualTest.java} | 2 +- ...ableMapTests.java => ConcurrentNavigableMapManualTests.java} | 2 +- ...cyTest.java => ConcurretMapMemoryConsistencyManualTest.java} | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) rename core-java/src/test/java/com/baeldung/java/concurrentmap/{ConcurrentMapAggregateStatusTest.java => ConcurrentMapAggregateStatusManualTest.java} (97%) rename core-java/src/test/java/com/baeldung/java/concurrentmap/{ConcurrentMapNullKeyValueTest.java => ConcurrentMapNullKeyValueManualTest.java} (99%) rename core-java/src/test/java/com/baeldung/java/concurrentmap/{ConcurrentMapPerformanceTest.java => ConcurrentMapPerformanceManualTest.java} (98%) rename core-java/src/test/java/com/baeldung/java/concurrentmap/{ConcurrentNavigableMapTests.java => ConcurrentNavigableMapManualTests.java} (98%) rename core-java/src/test/java/com/baeldung/java/concurrentmap/{ConcurretMapMemoryConsistencyTest.java => ConcurretMapMemoryConsistencyManualTest.java} (97%) diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusTest.java rename to core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java index 73a4cdc0cd..ec865f71c4 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java @@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -public class ConcurrentMapAggregateStatusTest { +public class ConcurrentMapAggregateStatusManualTest { private ExecutorService executorService; private Map concurrentMap; diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueTest.java rename to core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java index 62a3d10add..33e3326427 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java @@ -10,7 +10,7 @@ import java.util.concurrent.ConcurrentMap; import static org.junit.Assert.assertNull; -public class ConcurrentMapNullKeyValueTest { +public class ConcurrentMapNullKeyValueManualTest { ConcurrentMap concurrentMap; diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceTest.java rename to core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java index a0efa89351..5c1612ca60 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java @@ -11,7 +11,7 @@ import java.util.concurrent.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class ConcurrentMapPerformanceTest { +public class ConcurrentMapPerformanceManualTest { @Test public void givenMaps_whenGetPut500KTimes_thenConcurrentMapFaster() throws Exception { diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTests.java similarity index 98% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java rename to core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTests.java index 96a8a6bac3..d102680aa4 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTests.java @@ -10,7 +10,7 @@ import java.util.concurrent.atomic.AtomicInteger; import static org.testng.Assert.*; -public class ConcurrentNavigableMapTests { +public class ConcurrentNavigableMapManualTests { @Test public void givenSkipListMap_whenAccessInMultiThreads_thenOrderingStable() throws InterruptedException { diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyTest.java rename to core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java index 63a96dd5ee..43cbb2d293 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java @@ -10,7 +10,7 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; -public class ConcurretMapMemoryConsistencyTest { +public class ConcurretMapMemoryConsistencyManualTest { @Test public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception { From c198a96ec51dd9fd1010f44f208bc93a4c035930 Mon Sep 17 00:00:00 2001 From: Muhammed Almas Date: Tue, 7 Feb 2017 02:33:47 +0530 Subject: [PATCH 38/58] Pre conditions (#1128) * BAL-36 File size api in java and apache commons IO * BAEL-282 grep in java - fixes after code review * BAEL-519 Added support for disruptor library * BAEL-519 Added support for disruptor library * BAEL-519 Added support for disruptor library * BAEL-519 Added support for disruptor library * BAEL-519 Added support for disruptor library * BAEL-519 Added support for disruptor library * BAEL-519 Added support for disruptor * BAEL-519 Moved all supporting classes to main source * BAEL-519 Moved all supporting classes to main source * BAEL-519 Moved asserts and test classes in test folder. * BAEL-519 moved test related producer and consumer to src. * BAEL-586 Guide to Guava BiMap. * BAEL-587 formatted code. * BAEL-519 LMAX Disruptor * BAEL-587 resolved merge * BAEL-587 Resolved merge * BAEL-519 Removed disruptor link. * BAEL-519 Reverted Guava changes * RFQ-587 Added disruptor as a separate module. * BAEL-519 Disruptor changes. * BAEL-519 Removed disruptor from core-java module. * BAEL-637 Guide to PreConditions * BAEL-637 Used assertJ for exception assertion. * BAEL-637 updated tests to use assertJ. * BAEL-637 Removed redundant tests. * BAEL-637 explicitely specify the null varargs. * BAEL-637 explicitely specify the null varargs. --- .../java/org/baeldung/guava/GuavaPreConditionsTest.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java b/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java index f231fdda9d..2d98418d48 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java @@ -1,12 +1,9 @@ package org.baeldung.guava; import static org.assertj.core.api.Assertions.assertThatThrownBy; - import java.util.Arrays; - import org.junit.Test; - -import com.google.common.base.Preconditions; +import com.google.common.base.*; public class GuavaPreConditionsTest { @@ -61,7 +58,7 @@ public class GuavaPreConditionsTest { final String nullObject = null; final String message = "Please check the Object supplied, its %s!"; - assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message, nullObject)).isInstanceOf(NullPointerException.class).hasMessage(message, nullObject).hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message, new Object[] { null })).isInstanceOf(NullPointerException.class).hasMessage(message, nullObject).hasNoCause(); } @Test From c40d6962dd5c630b7079297e7ba8ae90a55073e6 Mon Sep 17 00:00:00 2001 From: Andrew Morgan Date: Sat, 4 Feb 2017 13:45:39 +0000 Subject: [PATCH 39/58] Added ConcurrentModificationException test --- .../ConcurrentModificationUnitTest.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/java/concurrentmodificationexception/ConcurrentModificationUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmodificationexception/ConcurrentModificationUnitTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmodificationexception/ConcurrentModificationUnitTest.java new file mode 100644 index 0000000000..9db460abbd --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/concurrentmodificationexception/ConcurrentModificationUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.java.concurrentmodificationexception; + +import org.assertj.core.api.Assertions; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.ConcurrentModificationException; +import java.util.Iterator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.util.Lists.newArrayList; + +public class ConcurrentModificationUnitTest { + @Test(expected = ConcurrentModificationException.class) + public void whilstRemovingDuringIteration_shouldThrowException() throws InterruptedException { + + ArrayList integers = newArrayList(1, 2, 3); + + for (Integer integer : integers) { + integers.remove(1); + } + } + + @Test + public void whilstRemovingDuringIteration_shouldNotThrowException() throws InterruptedException { + + ArrayList integers = newArrayList(1, 2, 3); + + for (Iterator iterator = integers.iterator(); iterator.hasNext();) { + Integer integer = iterator.next(); + if(integer == 2) { + iterator.remove(); + } + } + + assertThat(integers).containsExactly(1, 3); + } + + @Test + public void whilstRemovingDuringForEach_shouldNotThrowException() throws InterruptedException { + + ArrayList integers = newArrayList(1, 2, 3); + ArrayList toRemove = newArrayList(); + + for (Integer integer : integers) { + if(integer == 2) { + toRemove.add(integer); + } + } + integers.removeAll(toRemove); + + assertThat(integers).containsExactly(1, 3); + } +} From 0a444d32cf1d9bb9225a0e28d54e2576fe718775 Mon Sep 17 00:00:00 2001 From: Andrew Morgan Date: Mon, 6 Feb 2017 21:55:24 +0000 Subject: [PATCH 40/58] Renamed unit tests for ConcurrentModificationUnit --- .../ConcurrentModificationUnitTest.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmodificationexception/ConcurrentModificationUnitTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmodificationexception/ConcurrentModificationUnitTest.java index 9db460abbd..11c6012ecd 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmodificationexception/ConcurrentModificationUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmodificationexception/ConcurrentModificationUnitTest.java @@ -12,7 +12,7 @@ import static org.assertj.core.util.Lists.newArrayList; public class ConcurrentModificationUnitTest { @Test(expected = ConcurrentModificationException.class) - public void whilstRemovingDuringIteration_shouldThrowException() throws InterruptedException { + public void givenIterating_whenRemoving_thenThrowException() throws InterruptedException { ArrayList integers = newArrayList(1, 2, 3); @@ -22,7 +22,7 @@ public class ConcurrentModificationUnitTest { } @Test - public void whilstRemovingDuringIteration_shouldNotThrowException() throws InterruptedException { + public void givenIterating_whenUsingIteratorRemove_thenDontError() throws InterruptedException { ArrayList integers = newArrayList(1, 2, 3); @@ -37,7 +37,7 @@ public class ConcurrentModificationUnitTest { } @Test - public void whilstRemovingDuringForEach_shouldNotThrowException() throws InterruptedException { + public void givenIterating_whenUsingRemovalList_thenDontError() throws InterruptedException { ArrayList integers = newArrayList(1, 2, 3); ArrayList toRemove = newArrayList(); @@ -51,4 +51,14 @@ public class ConcurrentModificationUnitTest { assertThat(integers).containsExactly(1, 3); } + + @Test + public void whenUsingRemoveIf_thenRemoveElements() throws InterruptedException { + + ArrayList integers = newArrayList(1, 2, 3); + + integers.removeIf((i) -> i == 2); + + assertThat(integers).containsExactly(1, 3); + } } From 47889bc227fda24d141a1b601377d8eed826e021 Mon Sep 17 00:00:00 2001 From: lor6 Date: Tue, 7 Feb 2017 01:03:00 +0200 Subject: [PATCH 41/58] Bael 623 v2 (#1119) * helper classes for excel processing, tests * fix imports * list declaration * shorten examples, add excel files --- apache-poi/pom.xml | 10 ---------- .../java/com/baeldung/jexcel/JExcelHelper.java | 7 +------ .../com/baeldung/poi/excel/ExcelPOIHelper.java | 9 --------- .../java/com/baeldung/jexcel/JExcelTest.java | 6 ------ .../java/com/baeldung/poi/excel/ExcelTest.java | 6 ------ apache-poi/temp.xls | Bin 0 -> 13824 bytes apache-poi/temp.xlsx | Bin 0 -> 3510 bytes 7 files changed, 1 insertion(+), 37 deletions(-) create mode 100644 apache-poi/temp.xls create mode 100644 apache-poi/temp.xlsx diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml index 1b97248ab2..d8a2cc72e0 100644 --- a/apache-poi/pom.xml +++ b/apache-poi/pom.xml @@ -37,16 +37,6 @@ org.apache.poi poi-ooxml ${poi.version} - - - org.apache.poi - poi - ${poi.version} - - - org.apache.poi - poi-ooxml-schemas - ${poi.version} org.jxls diff --git a/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java b/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java index 39076fd709..4ad3fc766c 100644 --- a/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java +++ b/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java @@ -62,12 +62,7 @@ public class JExcelHelper { sheet.addCell(cellLabel); Number cellNumber = new Number(1, 2, 20, cellFormat); sheet.addCell(cellNumber); - - cellLabel = new Label(0, 3, "Ana Johnson", cellFormat); - sheet.addCell(cellLabel); - cellNumber = new Number(1, 3, 30, cellFormat); - sheet.addCell(cellNumber); - + workbook.write(); } finally { if (workbook != null) { diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java index 841be22d62..b6b0cbef20 100644 --- a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java @@ -110,15 +110,6 @@ public class ExcelPOIHelper { cell.setCellValue(20); cell.setCellStyle(style); - row = sheet.createRow(3); - cell = row.createCell(0); - cell.setCellValue("Ana Johnson"); - cell.setCellStyle(style); - - cell = row.createCell(1); - cell.setCellValue(30); - cell.setCellStyle(style); - File currDir = new File("."); String path = currDir.getAbsolutePath(); String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx"; diff --git a/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java index f0c129eb22..8ee465be34 100644 --- a/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java +++ b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java @@ -51,12 +51,6 @@ public class JExcelTest { .get(0)); assertEquals("20", data.get(2) .get(1)); - - assertEquals("Ana Johnson", data.get(3) - .get(0)); - assertEquals("30", data.get(3) - .get(1)); - } } \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java index f58db241b2..34fa64dd94 100644 --- a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java @@ -48,12 +48,6 @@ public class ExcelTest { .get(0)); assertEquals("20", data.get(1) .get(1)); - - assertEquals("Ana Johnson", data.get(2) - .get(0)); - assertEquals("30", data.get(2) - .get(1)); - } } \ No newline at end of file diff --git a/apache-poi/temp.xls b/apache-poi/temp.xls new file mode 100644 index 0000000000000000000000000000000000000000..1fad76d88d4842cfa56a936fc6b33786ade3291f GIT binary patch literal 13824 zcmeHOOG{Nz6#n*o==F8IULTbdT#CR{M6*Jod_)cu3Q3{{Lis91%@DJK!rN)X+;>{y#nO@hC8;m1@{TC-}B@)&|BFiWMvaEP!Qun=0)+f@=d<1rL6Z7LUMc^D>W6b8@6 zc{U2+x-rS27dWh!eWQH92s|Dphgv?mn1lCIZ=r6bPEi-K`mdeDn%7QI$lvVjR)@`G z;3aE`9@b*YA(U#nOpj~=F)Tm&^8VOBPum&AYZb3kc~g-zZAy7LUb{&S4;pT;XCWfK zDp_x-^=*}N*ogvSehH)A)jPkv*cNDqleCTDy3UPgO{xEp48_$%=z=~i7UHW_+xnH1 zRfAx1;6jW;3$Ybt#E&MpbBs+~OP|uh?EPxebz!)$Fi~(c77%&Em0b{@zFb0ePW55_N28;n?z!)$Fi~(c7 z7%&Em0b{@zFb0ePW55_N28;n?z!)$Fi~(c77%&Emfz8Q)B$-NrsicTXdaPs}OAe|0 z3?Tn?NIIHPD NgSqGGUtRz7{{s%gg0TPq literal 0 HcmV?d00001 diff --git a/apache-poi/temp.xlsx b/apache-poi/temp.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..da67ca9e9e71409c744feca69821a8a39282d024 GIT binary patch literal 3510 zcmaJ@dpwhU8%LN^jCh@e`+tVcI5#P)2hor=c*XgeRgz%0qf6 zPYy{~2ZvA*5%!LS2=7+!``F`s>U)3gd-osr_1o|IUfuhuq7i9G+}QN2fO2i9mhvpzC;H-muWy$frQcG1Z1e-n zEzGRdn>@J&wSLfKXg6~SN0-}KMfsOF>{(CyXv_Hf;831QKFfq%R)>Jn=M1L&h5>oV z8GGrdeU%no+MvWzO!Z}X^)qPjv8v2eyjcZmKGed<3lT}Ze+_a0)uMf3t|0bd7zPRG zHc5(&=)aTSt~PnM;vFR1mO*ivhhV3#&f$yI)%w%iFS^$bMh$`QFXw*NEN6^CbOm8n z!Px;^D7xd-0!@3ca}UFy;v@Bw8Bv%AdJ~$(c<=|(h=#NU@O>~ZnVn*0e}apH1Nl>a zb}_$jIgAY^pn?e=ju9a!yqjitP+2s%)EcKv%8uJ@wO90lS&-i# zDW*&wxY11I@jhY=il-75MjtLi&{pHwb+5!6^ji%AI{;N&cZm8iuWOd4@zKvJuk>Tk zaS5caEl-!PN#2--Slsp>m?DKH((MzgAR&hqfvvmxNfRm#6klZ)+hGQsY&nLOqLvat=?;XP%b4zy-|iBze{wN%z$q}N4!>lMzP{TeD4A4yrRjC zW;qElIh1pvTIBp&a67ldlrTrZ$KNyg8M3O8P8YnZs#aiNjF{`N2}NBra^j&&aaVzE zOwp#F^@>Ayt;Uu!z2ghL4qDVviW|R!NV#*sdrqC87BwFA?{xl0LUzW57rxr z!-n9sJVQcQ?88%A1s;QdM`*-NAP)N=5}2V|rbtvf-z&m5{hBuqZhdlkijo#NI7TPuTf*<%d?td+dH5}dODA5Zpl)49{$Ae;5emB=5`yH_sZa4#@ zYpQs=1jbmGxQ&h8YjQDf&d=3J$i3rAdzl_ZTx{->D3Lbj_xJRm%b)QA3}nBRKt6zbg7Y<`hxPym{vRv!{-!nNuHD%Lj`gYJ_aE@!l!8 zy>rad%1%~{WhJ{g_zoCWZplgQk+R; zc%T;E-xG)OIZnW#gZ=O=uf9^z!H#V4J)||hHLYu+ zDtk;8YfdD~i1hUt@4Q&{)*&@jaMHdny|sRV6TB4Qd;%lkW`@?|xiwhm%3VDW@MSV> zIP}6yj&U+xX!Zgu`|{Fv<(Ic~E9Eoy-up|T?EG(bgor@Y_q58g;D~V$kVLay+kIe6 z@&S)hJXtZ`@t$8}zxzly`SgJIvvY&-9%)c98DYM2zqgGWESeVDsa6C7sylSRT0378 zq92uT*XUVzc~Hli=3ZbThrfYuMM+5*D{ycn2{ZIe;?H2E7Uwv1m#3a`JvAygo0rfK zYO?s6Q_?i|o)_iSOfp(CLtjGS%Siy@G`mQ zI-}{aln~6T9Ej2LF_j$0LF4qXo3|@Iv{P^J3QgP@KL>ci)lCYXu@4q9S_kHxVhNZd z5k^c)@?(|gk~ z<$cBP*h;!C!!WHrtCKOIT|I7nJ+QGu0iO{?M*CP$B1>igUyEO6GCpy=l?&KNvzmqY zebUQAAe6@Ja(KJTf@Vf?ir3Ni{XDgge<@MWBY;)72KA|vPx|!MiJ9X5wN1U8X)-U{ zI-&30M&v3NtLNQ&GDGjESy9&MQ) z%>1w>?EL(&DH$(pc9;t#Fl`EGV!kJsM|67NGGB8*^hHnAraFRwj@^f%N6p8~UGBcS z{#$x{)E^?XuFcOgBU-z>RRL~PqPc)!sxCNu=&grqoF`p;J&Ru+NqRN+b#Q@GO)K&V z`aqz##jIjdmMq3lCEvv0cg5-Q7okffLGpog&(DB+m+v>%h8A)DQQ<2u|1xy8B```J zDHpOJF@D3be%!LJaY*7DB4mC|`<nE82N9FL1l# zM{pKdBIgf|RJc9b@rW?n`X+Qin8nb|tG}fTG4qH1(wRtYX$S9*LJ{!HKFIvhW{D`2 z?1qQ~iIZsXZz6D7nb2EZUMF4OKEYk%Q=tHWzokq6IdA9~^$`DAI%z3uIpT#Cr8=#4 z4*+!1Kbr~@Kh9P8G8+lEheGvFJs`Nby8FcG8x3=Ti5F`Pg9<*=r0P(DcloLC&g743sqe2<{3Zq(7%W_Q=u#bK8h#s> z{KfE5bb_!AK+32NfT+`n+GP`=S4zyI87-G5r~%=hYo702N&CEXdPosMK3haH8H2}9j;rX$`U*m9lD0^dJHP$V} z0KSK^w~_6^>}QVEd$y3n_dWP0ooM?y?4n?u&@D9b|Fwz#JFiGv9$wa${LG7W>OH?} F=0A|CZn^*f literal 0 HcmV?d00001 From 24760595fac8755287f7f540e7a118294cadfb3d Mon Sep 17 00:00:00 2001 From: lor6 Date: Tue, 7 Feb 2017 06:13:18 +0200 Subject: [PATCH 42/58] 2 login pages config (#1081) * 2 login pages config * fix links * small fix * fix formatting --- spring-mvc-forms/pom.xml | 18 +++ .../configuration/SecurityConfig.java | 122 ++++++++++++++++++ .../configuration/WebInitializer.java | 4 + .../controller/UsersController.java | 38 ++++++ .../src/main/webapp/WEB-INF/views/403.jsp | 12 ++ .../main/webapp/WEB-INF/views/adminPage.jsp | 16 +++ .../main/webapp/WEB-INF/views/loginAdmin.jsp | 38 ++++++ .../main/webapp/WEB-INF/views/loginUser.jsp | 37 ++++++ .../webapp/WEB-INF/views/protectedLinks.jsp | 16 +++ .../main/webapp/WEB-INF/views/userPage.jsp | 15 +++ 10 files changed, 316 insertions(+) create mode 100644 spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/SecurityConfig.java create mode 100644 spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/UsersController.java create mode 100644 spring-mvc-forms/src/main/webapp/WEB-INF/views/403.jsp create mode 100644 spring-mvc-forms/src/main/webapp/WEB-INF/views/adminPage.jsp create mode 100644 spring-mvc-forms/src/main/webapp/WEB-INF/views/loginAdmin.jsp create mode 100644 spring-mvc-forms/src/main/webapp/WEB-INF/views/loginUser.jsp create mode 100644 spring-mvc-forms/src/main/webapp/WEB-INF/views/protectedLinks.jsp create mode 100644 spring-mvc-forms/src/main/webapp/WEB-INF/views/userPage.jsp diff --git a/spring-mvc-forms/pom.xml b/spring-mvc-forms/pom.xml index 31a0c38791..f17d695c35 100644 --- a/spring-mvc-forms/pom.xml +++ b/spring-mvc-forms/pom.xml @@ -46,6 +46,23 @@ commons-fileupload ${fileupload.version} + + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + org.springframework.security + spring-security-taglibs + ${org.springframework.security.version} + + @@ -98,6 +115,7 @@ 5.3.3.Final enter-location-of-server 1.3.2 + 4.2.1.RELEASE diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/SecurityConfig.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/SecurityConfig.java new file mode 100644 index 0000000000..e35844138d --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/SecurityConfig.java @@ -0,0 +1,122 @@ +package com.baeldung.springmvcforms.configuration; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.TestingAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; + +@Configuration +@EnableWebSecurity +public class SecurityConfig { + + @Bean + public UserDetailsService userDetailsService() throws Exception { + InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); + manager.createUser(User.withUsername("user") + .password("userPass") + .roles("USER") + .build()); + manager.createUser(User.withUsername("admin") + .password("adminPass") + .roles("ADMIN") + .build()); + return manager; + } + + @Configuration + @Order(1) + public static class App1ConfigurationAdapter extends WebSecurityConfigurerAdapter { + + public App1ConfigurationAdapter() { + super(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("admin") + .password("admin") + .roles("ADMIN"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/admin*") + .authorizeRequests() + .anyRequest() + .hasRole("ADMIN") + // log in + .and() + .formLogin() + .loginPage("/loginAdmin") + .loginProcessingUrl("/admin_login") + .failureUrl("/loginAdmin?error=loginError") + .defaultSuccessUrl("/adminPage") + // logout + .and() + .logout() + .logoutUrl("/admin_logout") + .logoutSuccessUrl("/protectedLinks") + .deleteCookies("JSESSIONID") + .and() + .exceptionHandling() + .accessDeniedPage("/403") + .and() + .csrf() + .disable(); + } + } + + @Configuration + @Order(2) + public static class App2ConfigurationAdapter extends WebSecurityConfigurerAdapter { + + public App2ConfigurationAdapter() { + super(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("user") + .password("user") + .roles("USER"); + } + + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/user*") + .authorizeRequests() + .anyRequest() + .hasRole("USER") + // log in + .and() + .formLogin() + .loginPage("/loginUser") + .loginProcessingUrl("/user_login") + .failureUrl("/loginUser?error=loginError") + .defaultSuccessUrl("/userPage") + // logout + .and() + .logout() + .logoutUrl("/user_logout") + .logoutSuccessUrl("/protectedLinks") + .deleteCookies("JSESSIONID") + .and() + .exceptionHandling() + .accessDeniedPage("/403") + .and() + .csrf() + .disable(); + } + } + +} diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java index c602ea6454..fdc155e101 100644 --- a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java @@ -3,6 +3,7 @@ package com.baeldung.springmvcforms.configuration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.ServletContext; @@ -24,6 +25,9 @@ public class WebInitializer implements WebApplicationInitializer { servlet.setLoadOnStartup(1); servlet.addMapping("/"); + + container.addFilter("springSecurityFilterChain", new DelegatingFilterProxy("springSecurityFilterChain")) + .addMappingForUrlPatterns(null, false, "/*"); } // @Override // public void onStartup(ServletContext container) { diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/UsersController.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/UsersController.java new file mode 100644 index 0000000000..c0858d427f --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/UsersController.java @@ -0,0 +1,38 @@ +package com.baeldung.springmvcforms.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class UsersController { + + @RequestMapping("/protectedLinks") + public String getAnonymousPage() { + return "protectedLinks"; + } + + @RequestMapping("/userPage") + public String getUserPage() { + return "userPage"; + } + + @RequestMapping("/adminPage") + public String getAdminPage() { + return "adminPage"; + } + + @RequestMapping("/loginAdmin") + public String getAdminLoginPage() { + return "loginAdmin"; + } + + @RequestMapping("/loginUser") + public String getUserLoginPage() { + return "loginUser"; + } + + @RequestMapping("/403") + public String getAccessDeniedPage() { + return "403"; + } +} diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/403.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/403.jsp new file mode 100644 index 0000000000..e665793e10 --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/403.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + + + + +Your do not have permission to view this page. + + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/adminPage.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/adminPage.jsp new file mode 100644 index 0000000000..a210b690b0 --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/adminPage.jsp @@ -0,0 +1,16 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + + + + +Insert title here + + +Welcome admin! Logout + +

+Back to links + + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/loginAdmin.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/loginAdmin.jsp new file mode 100644 index 0000000000..a6b2ee7914 --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/loginAdmin.jsp @@ -0,0 +1,38 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> + + + + +Insert title here + + + +

Admin login page

+
+ + + + + + + + + + + + + +
User:
Password:
+ +
+ + <% + if (request.getParameter("error") != null) { + out.println("Login failed!"); + } + %> + + + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/loginUser.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/loginUser.jsp new file mode 100644 index 0000000000..e65c11edaf --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/loginUser.jsp @@ -0,0 +1,37 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> + + + + +Login + + + +

User login page

+ +
+ + + + + + + + + + + + +
User:
Password:
+ +
+ <% + if (request.getParameter("error") != null) { + out.println("Login failed!"); + } + %> + + + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/protectedLinks.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/protectedLinks.jsp new file mode 100644 index 0000000000..b8453903ba --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/protectedLinks.jsp @@ -0,0 +1,16 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + + + + +Insert title here + + + +">User page +
+">Admin page + + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/userPage.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/userPage.jsp new file mode 100644 index 0000000000..4c1bd47502 --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/userPage.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + + + + +Insert title here + + +Welcome user! Logout +

+Back to links + + \ No newline at end of file From 4077ee29c50eebdecde96808ee97bbbdf8bd967e Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Tue, 7 Feb 2017 06:44:59 +0100 Subject: [PATCH 43/58] BAEL-639 - moving from test to main source tree --- guava/src/{test => main}/java/org/baeldung/guava/CustomEvent.java | 0 .../{test => main}/java/org/baeldung/guava/EventBusWrapper.java | 0 .../src/{test => main}/java/org/baeldung/guava/EventListener.java | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename guava/src/{test => main}/java/org/baeldung/guava/CustomEvent.java (100%) rename guava/src/{test => main}/java/org/baeldung/guava/EventBusWrapper.java (100%) rename guava/src/{test => main}/java/org/baeldung/guava/EventListener.java (100%) diff --git a/guava/src/test/java/org/baeldung/guava/CustomEvent.java b/guava/src/main/java/org/baeldung/guava/CustomEvent.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/CustomEvent.java rename to guava/src/main/java/org/baeldung/guava/CustomEvent.java diff --git a/guava/src/test/java/org/baeldung/guava/EventBusWrapper.java b/guava/src/main/java/org/baeldung/guava/EventBusWrapper.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/EventBusWrapper.java rename to guava/src/main/java/org/baeldung/guava/EventBusWrapper.java diff --git a/guava/src/test/java/org/baeldung/guava/EventListener.java b/guava/src/main/java/org/baeldung/guava/EventListener.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/EventListener.java rename to guava/src/main/java/org/baeldung/guava/EventListener.java From 178f49e4857a41f426330b29e155546904801852 Mon Sep 17 00:00:00 2001 From: Saptarshi Basu Date: Tue, 7 Feb 2017 15:27:52 +0530 Subject: [PATCH 44/58] BAEL-595 : Review comments incorporated (#1125) * WatchService vs. Apache Commons IO Mnitoring * Indentation fixed * Indentation fixed * JAX-RS API using Jersey [BAEL-558] * JAX-RS API using Jersey [BAEL-558] * Modifications made to remove xml * applicationContext.xml removed * All try catch moved to ExceptionMapper * fixes * review comments incorporated * module renamed * JAX-RS client [BAEL-595] * jersey-core dependency removed * assert changed to assertEquals * messagebody readers and writers removed * pom dependency corrected and other minor changes * Jersey version changed and toString() changed to valueOf() --- spring-jersey/pom.xml | 2 +- .../src/main/java/com/baeldung/client/rest/RestClient.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 293850d41e..41ebb9a6b5 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -9,7 +9,7 @@ war - 2.25 + 2.25.1 1.7.22 1.1.8 4.12 diff --git a/spring-jersey/src/main/java/com/baeldung/client/rest/RestClient.java b/spring-jersey/src/main/java/com/baeldung/client/rest/RestClient.java index 0e45b68b14..34f7d45601 100644 --- a/spring-jersey/src/main/java/com/baeldung/client/rest/RestClient.java +++ b/spring-jersey/src/main/java/com/baeldung/client/rest/RestClient.java @@ -18,7 +18,7 @@ public class RestClient { } public Employee getJsonEmployee(int id) { - return client.target(REST_URI).path(new Integer(id).toString()).request(MediaType.APPLICATION_JSON).get(Employee.class); + return client.target(REST_URI).path(String.valueOf(id)).request(MediaType.APPLICATION_JSON).get(Employee.class); } public Response createXmlEmployee(Employee emp) { @@ -26,6 +26,6 @@ public class RestClient { } public Employee getXmlEmployee(int id) { - return client.target(REST_URI).path(new Integer(id).toString()).request(MediaType.APPLICATION_XML).get(Employee.class); + return client.target(REST_URI).path(String.valueOf(id)).request(MediaType.APPLICATION_XML).get(Employee.class); } } From c13453d77229fb18475d591ead7fe03e4484f642 Mon Sep 17 00:00:00 2001 From: Tryfon Date: Tue, 7 Feb 2017 12:36:06 +0200 Subject: [PATCH 45/58] Java 8 grouping by collector pull request (#1102) * Char array to string and string to char array test cases added * Minor code renames * Added groupingBy collector unit tests * Added test case for int summary calculation on grouped results * Added the grouping by classes to the main source path * Reverting char array to string test class * Reverting char array to string test class * Reverting char array to string test class * Reverting char array to string test class --- .../java_8_features/groupingby/BlogPost.java | 36 +++++ .../groupingby/BlogPostType.java | 5 + .../Java8GroupingByCollectorUnitTest.java | 132 ++++++++++++++++++ 3 files changed, 173 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java create mode 100644 core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java create mode 100644 core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java b/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java new file mode 100644 index 0000000000..afc05e356a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java @@ -0,0 +1,36 @@ +package com.baeldung.java_8_features.groupingby; + +public class BlogPost { + private String title; + private String author; + private BlogPostType type; + private int likes; + + public BlogPost(String title, String author, BlogPostType type, int likes) { + this.title = title; + this.author = author; + this.type = type; + this.likes = likes; + } + + public String getTitle() { + return title; + } + + public String getAuthor() { + return author; + } + + public BlogPostType getType() { + return type; + } + + public int getLikes() { + return likes; + } + + @Override + public String toString() { + return "BlogPost{" + "title='" + title + '\'' + ", type=" + type + ", likes=" + likes + '}'; + } +} diff --git a/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java b/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java new file mode 100644 index 0000000000..2029784e91 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java @@ -0,0 +1,5 @@ +package com.baeldung.java_8_features.groupingby; + +public enum BlogPostType { + NEWS, REVIEW, GUIDE +} diff --git a/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java new file mode 100644 index 0000000000..544db90b73 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java @@ -0,0 +1,132 @@ +package com.baeldung.java8; + +import org.junit.Test; + +import com.baeldung.java_8_features.groupingby.BlogPost; +import com.baeldung.java_8_features.groupingby.BlogPostType; + +import java.util.*; +import java.util.concurrent.ConcurrentMap; + +import static java.util.Comparator.comparingInt; +import static java.util.stream.Collectors.*; +import static org.junit.Assert.*; + +public class Java8GroupingByCollectorUnitTest { + + private static final List POSTS = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), + new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15)); + + @Test + public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() { + Map> postsPerType = POSTS.stream().collect(groupingBy(BlogPost::getType)); + + assertEquals(2, postsPerType.get(BlogPostType.NEWS).size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE).size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW).size()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() { + Map postsPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]")))); + + assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS)); + assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE)); + assertEquals("Post titles: [Tech review 1, Tech review 2]", postsPerType.get(BlogPostType.REVIEW)); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() { + Map likesPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes))); + + assertEquals(50, likesPerType.get(BlogPostType.NEWS).intValue()); + assertEquals(20, likesPerType.get(BlogPostType.REVIEW).intValue()); + assertEquals(20, likesPerType.get(BlogPostType.GUIDE).intValue()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() { + EnumMap> postsPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList())); + + assertEquals(2, postsPerType.get(BlogPostType.NEWS).size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE).size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW).size()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() { + Map> postsPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, toSet())); + + assertEquals(2, postsPerType.get(BlogPostType.NEWS).size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE).size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW).size()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() { + ConcurrentMap> postsPerType = POSTS.parallelStream().collect(groupingByConcurrent(BlogPost::getType)); + + assertEquals(2, postsPerType.get(BlogPostType.NEWS).size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE).size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW).size()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() { + Map averageLikesPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes))); + + assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS).intValue()); + assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE).intValue()); + assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW).intValue()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() { + Map numberOfPostsPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, counting())); + + assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS).intValue()); + assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE).intValue()); + assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW).intValue()); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() { + Map> maxLikesPerPostType = POSTS.stream().collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes)))); + + assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS).isPresent()); + assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS).get().getLikes()); + + assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE).isPresent()); + assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE).get().getLikes()); + + assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW).isPresent()); + assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW).get().getLikes()); + } + + @Test + public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() { + Map>> map = POSTS.stream().collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType))); + + assertEquals(1, map.get("Author 1").get(BlogPostType.NEWS).size()); + assertEquals(1, map.get("Author 1").get(BlogPostType.GUIDE).size()); + assertEquals(1, map.get("Author 1").get(BlogPostType.REVIEW).size()); + + assertEquals(1, map.get("Author 2").get(BlogPostType.NEWS).size()); + assertEquals(1, map.get("Author 2").get(BlogPostType.REVIEW).size()); + assertNull(map.get("Author 2").get(BlogPostType.GUIDE)); + } + + @Test + public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() { + Map likeStatisticsPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes))); + + IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS); + + assertEquals(2, newsLikeStatistics.getCount()); + assertEquals(50, newsLikeStatistics.getSum()); + assertEquals(25.0, newsLikeStatistics.getAverage(), 0.001); + assertEquals(35, newsLikeStatistics.getMax()); + assertEquals(15, newsLikeStatistics.getMin()); + } + +} From fc233b4be7950b0df7f1a1dd88a515581519621f Mon Sep 17 00:00:00 2001 From: Sunil Mogadati Date: Tue, 7 Feb 2017 03:44:17 -0700 Subject: [PATCH 46/58] Formatting change using Baeldung formatter --- .../Java8GroupingByCollectorUnitTest.java | 36 ++++++++++++++----- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java index 544db90b73..178cd72542 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java @@ -1,17 +1,35 @@ package com.baeldung.java8; +import static java.util.Comparator.comparingInt; +import static java.util.stream.Collectors.averagingInt; +import static java.util.stream.Collectors.counting; +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.groupingByConcurrent; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.mapping; +import static java.util.stream.Collectors.maxBy; +import static java.util.stream.Collectors.summarizingInt; +import static java.util.stream.Collectors.summingInt; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toSet; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.EnumMap; +import java.util.IntSummaryStatistics; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentMap; + import org.junit.Test; import com.baeldung.java_8_features.groupingby.BlogPost; import com.baeldung.java_8_features.groupingby.BlogPostType; -import java.util.*; -import java.util.concurrent.ConcurrentMap; - -import static java.util.Comparator.comparingInt; -import static java.util.stream.Collectors.*; -import static org.junit.Assert.*; - public class Java8GroupingByCollectorUnitTest { private static final List POSTS = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), @@ -119,9 +137,9 @@ public class Java8GroupingByCollectorUnitTest { @Test public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() { Map likeStatisticsPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes))); - + IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS); - + assertEquals(2, newsLikeStatistics.getCount()); assertEquals(50, newsLikeStatistics.getSum()); assertEquals(25.0, newsLikeStatistics.getAverage(), 0.001); From 3559789573f612be3911eb983bf51abed125c5c0 Mon Sep 17 00:00:00 2001 From: Pedja Date: Tue, 7 Feb 2017 11:54:48 +0100 Subject: [PATCH 47/58] BAEL-677 Small refactoring --- .../ConcurrentModificationUnitTest.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) rename core-java/src/test/java/com/baeldung/java/{concurrentmodificationexception => concurrentmodification}/ConcurrentModificationUnitTest.java (81%) diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmodificationexception/ConcurrentModificationUnitTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java similarity index 81% rename from core-java/src/test/java/com/baeldung/java/concurrentmodificationexception/ConcurrentModificationUnitTest.java rename to core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java index 11c6012ecd..d16a1fcdf4 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmodificationexception/ConcurrentModificationUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java @@ -1,6 +1,5 @@ -package com.baeldung.java.concurrentmodificationexception; +package com.baeldung.java.concurrentmodification; -import org.assertj.core.api.Assertions; import org.junit.Test; import java.util.ArrayList; @@ -22,7 +21,7 @@ public class ConcurrentModificationUnitTest { } @Test - public void givenIterating_whenUsingIteratorRemove_thenDontError() throws InterruptedException { + public void givenIterating_whenUsingIteratorRemove_thenNoError() throws InterruptedException { ArrayList integers = newArrayList(1, 2, 3); @@ -37,7 +36,7 @@ public class ConcurrentModificationUnitTest { } @Test - public void givenIterating_whenUsingRemovalList_thenDontError() throws InterruptedException { + public void givenIterating_whenUsingRemovalList_thenNoError() throws InterruptedException { ArrayList integers = newArrayList(1, 2, 3); ArrayList toRemove = newArrayList(); @@ -57,7 +56,7 @@ public class ConcurrentModificationUnitTest { ArrayList integers = newArrayList(1, 2, 3); - integers.removeIf((i) -> i == 2); + integers.removeIf(i -> i == 2); assertThat(integers).containsExactly(1, 3); } From 69bfaa557a654c0c66391cd79a61e988fd9b5147 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Tue, 7 Feb 2017 17:50:11 +0100 Subject: [PATCH 48/58] BAEL-672 test case when one object is still referenced --- .../baeldung/weakhashmap/WeakHashMapTest.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java b/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java index 7b34c6b316..1c5a261eea 100644 --- a/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java +++ b/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java @@ -29,6 +29,30 @@ public class WeakHashMapTest { await().atMost(10, TimeUnit.SECONDS).until(map::isEmpty); } + @Test + public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObjectButLeaveReferencedObject() { + //given + WeakHashMap map = new WeakHashMap<>(); + BigImage bigImageFirst = new BigImage("foo"); + UniqueImageName imageNameFirst = new UniqueImageName("name_of_big_image"); + + BigImage bigImageSecond = new BigImage("foo_2"); + UniqueImageName imageNameSecond = new UniqueImageName("name_of_big_image_2"); + + map.put(imageNameFirst, bigImageFirst); + map.put(imageNameSecond, bigImageSecond); + assertTrue(map.containsKey(imageNameFirst)); + assertTrue(map.containsKey(imageNameSecond)); + + //when + imageNameFirst = null; + System.gc(); + + //then + await().atMost(10, TimeUnit.SECONDS).until(() -> map.size() == 1); + await().atMost(10, TimeUnit.SECONDS).until(() -> map.containsKey(imageNameSecond)); + } + class BigImage { public final String imageId; From 92ad8123f1288f051fe20b4cbd331a4a41867ba6 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Tue, 7 Feb 2017 19:32:09 +0100 Subject: [PATCH 49/58] Refactor Java8GroupingByCollectorUnitTest --- .../Java8GroupingByCollectorUnitTest.java | 227 ++++++++++++------ 1 file changed, 154 insertions(+), 73 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java index 178cd72542..4452b4db9a 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java @@ -1,52 +1,47 @@ package com.baeldung.java8; -import static java.util.Comparator.comparingInt; -import static java.util.stream.Collectors.averagingInt; -import static java.util.stream.Collectors.counting; -import static java.util.stream.Collectors.groupingBy; -import static java.util.stream.Collectors.groupingByConcurrent; -import static java.util.stream.Collectors.joining; -import static java.util.stream.Collectors.mapping; -import static java.util.stream.Collectors.maxBy; -import static java.util.stream.Collectors.summarizingInt; -import static java.util.stream.Collectors.summingInt; -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toSet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.EnumMap; -import java.util.IntSummaryStatistics; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import org.junit.Test; - import com.baeldung.java_8_features.groupingby.BlogPost; import com.baeldung.java_8_features.groupingby.BlogPostType; +import org.junit.Test; + +import java.util.*; +import java.util.concurrent.ConcurrentMap; + +import static java.util.Comparator.comparingInt; +import static java.util.stream.Collectors.*; +import static org.junit.Assert.*; public class Java8GroupingByCollectorUnitTest { - private static final List POSTS = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), - new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15)); + private static final List posts = Arrays.asList( + new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), + new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), + new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), + new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), + new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15)); @Test public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() { - Map> postsPerType = POSTS.stream().collect(groupingBy(BlogPost::getType)); + Map> postsPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType)); - assertEquals(2, postsPerType.get(BlogPostType.NEWS).size()); - assertEquals(1, postsPerType.get(BlogPostType.GUIDE).size()); - assertEquals(2, postsPerType.get(BlogPostType.REVIEW).size()); + assertEquals(2, postsPerType + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType + .get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType + .get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() { - Map postsPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]")))); + Map postsPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]")))); assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS)); assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE)); @@ -55,88 +50,174 @@ public class Java8GroupingByCollectorUnitTest { @Test public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() { - Map likesPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes))); + Map likesPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes))); - assertEquals(50, likesPerType.get(BlogPostType.NEWS).intValue()); - assertEquals(20, likesPerType.get(BlogPostType.REVIEW).intValue()); - assertEquals(20, likesPerType.get(BlogPostType.GUIDE).intValue()); + assertEquals(50, likesPerType + .get(BlogPostType.NEWS) + .intValue()); + assertEquals(20, likesPerType + .get(BlogPostType.REVIEW) + .intValue()); + assertEquals(20, likesPerType + .get(BlogPostType.GUIDE) + .intValue()); } @Test public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() { - EnumMap> postsPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList())); + EnumMap> postsPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList())); - assertEquals(2, postsPerType.get(BlogPostType.NEWS).size()); - assertEquals(1, postsPerType.get(BlogPostType.GUIDE).size()); - assertEquals(2, postsPerType.get(BlogPostType.REVIEW).size()); + assertEquals(2, postsPerType + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType + .get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType + .get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() { - Map> postsPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, toSet())); + Map> postsPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, toSet())); - assertEquals(2, postsPerType.get(BlogPostType.NEWS).size()); - assertEquals(1, postsPerType.get(BlogPostType.GUIDE).size()); - assertEquals(2, postsPerType.get(BlogPostType.REVIEW).size()); + assertEquals(2, postsPerType + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType + .get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType + .get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() { - ConcurrentMap> postsPerType = POSTS.parallelStream().collect(groupingByConcurrent(BlogPost::getType)); + ConcurrentMap> postsPerType = posts + .parallelStream() + .collect(groupingByConcurrent(BlogPost::getType)); - assertEquals(2, postsPerType.get(BlogPostType.NEWS).size()); - assertEquals(1, postsPerType.get(BlogPostType.GUIDE).size()); - assertEquals(2, postsPerType.get(BlogPostType.REVIEW).size()); + assertEquals(2, postsPerType + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType + .get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType + .get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() { - Map averageLikesPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes))); + Map averageLikesPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes))); - assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS).intValue()); - assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE).intValue()); - assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW).intValue()); + assertEquals(25, averageLikesPerType + .get(BlogPostType.NEWS) + .intValue()); + assertEquals(20, averageLikesPerType + .get(BlogPostType.GUIDE) + .intValue()); + assertEquals(10, averageLikesPerType + .get(BlogPostType.REVIEW) + .intValue()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() { - Map numberOfPostsPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, counting())); + Map numberOfPostsPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, counting())); - assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS).intValue()); - assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE).intValue()); - assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW).intValue()); + assertEquals(2, numberOfPostsPerType + .get(BlogPostType.NEWS) + .intValue()); + assertEquals(1, numberOfPostsPerType + .get(BlogPostType.GUIDE) + .intValue()); + assertEquals(2, numberOfPostsPerType + .get(BlogPostType.REVIEW) + .intValue()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() { - Map> maxLikesPerPostType = POSTS.stream().collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes)))); + Map> maxLikesPerPostType = posts + .stream() + .collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes)))); - assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS).isPresent()); - assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS).get().getLikes()); + assertTrue(maxLikesPerPostType + .get(BlogPostType.NEWS) + .isPresent()); + assertEquals(35, maxLikesPerPostType + .get(BlogPostType.NEWS) + .get() + .getLikes()); - assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE).isPresent()); - assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE).get().getLikes()); + assertTrue(maxLikesPerPostType + .get(BlogPostType.GUIDE) + .isPresent()); + assertEquals(20, maxLikesPerPostType + .get(BlogPostType.GUIDE) + .get() + .getLikes()); - assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW).isPresent()); - assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW).get().getLikes()); + assertTrue(maxLikesPerPostType + .get(BlogPostType.REVIEW) + .isPresent()); + assertEquals(15, maxLikesPerPostType + .get(BlogPostType.REVIEW) + .get() + .getLikes()); } @Test public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() { - Map>> map = POSTS.stream().collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType))); + Map>> map = posts + .stream() + .collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType))); - assertEquals(1, map.get("Author 1").get(BlogPostType.NEWS).size()); - assertEquals(1, map.get("Author 1").get(BlogPostType.GUIDE).size()); - assertEquals(1, map.get("Author 1").get(BlogPostType.REVIEW).size()); + assertEquals(1, map + .get("Author 1") + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, map + .get("Author 1") + .get(BlogPostType.GUIDE) + .size()); + assertEquals(1, map + .get("Author 1") + .get(BlogPostType.REVIEW) + .size()); - assertEquals(1, map.get("Author 2").get(BlogPostType.NEWS).size()); - assertEquals(1, map.get("Author 2").get(BlogPostType.REVIEW).size()); - assertNull(map.get("Author 2").get(BlogPostType.GUIDE)); + assertEquals(1, map + .get("Author 2") + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, map + .get("Author 2") + .get(BlogPostType.REVIEW) + .size()); + assertNull(map + .get("Author 2") + .get(BlogPostType.GUIDE)); } @Test public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() { - Map likeStatisticsPerType = POSTS.stream().collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes))); + Map likeStatisticsPerType = posts + .stream() + .collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes))); IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS); From a9d8c5f3a3154125cf90eef0541963a8ce0c2b4b Mon Sep 17 00:00:00 2001 From: Danil Kornishev Date: Tue, 7 Feb 2017 14:34:10 -0500 Subject: [PATCH 50/58] Introduction to Neo4j (#1098) * Nashorn * Nashorn x2 * Nashorn added trailing newlines * Cleanup * Formatted script lines * Change system outs to asserts * Change Nashorn to be Junit tests * Remove empty test * Added Neo4j section * Revert NashornTest --- core-java/pom.xml | 44 ++++- .../src/main/java/com/baeldung/graph/Car.java | 50 ++++++ .../main/java/com/baeldung/graph/Company.java | 45 +++++ .../com/baeldung/graph/Neo4JServerTest.java | 60 +++++++ .../java/com/baeldung/graph/Neo4jOgmTest.java | 46 +++++ .../java/com/baeldung/graph/Neo4jTest.java | 167 ++++++++++++++++++ 6 files changed, 409 insertions(+), 3 deletions(-) create mode 100644 core-java/src/main/java/com/baeldung/graph/Car.java create mode 100644 core-java/src/main/java/com/baeldung/graph/Company.java create mode 100644 core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java create mode 100644 core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java create mode 100644 core-java/src/test/java/com/baeldung/graph/Neo4jTest.java diff --git a/core-java/pom.xml b/core-java/pom.xml index 85afee2968..1a3034b860 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung core-java @@ -10,6 +10,44 @@ + + org.neo4j + neo4j + 3.1.0 + + + + org.neo4j.driver + neo4j-java-driver + 1.1.1 + + + + org.neo4j + neo4j-jdbc-driver + 3.0.1 + + + + org.neo4j + neo4j-ogm-core + 2.1.1 + + + + org.neo4j + neo4j-ogm-embedded-driver + 2.1.1 + + + + com.google.inject + guice + 4.1.0 + no_aop + test + + net.sourceforge.collections @@ -63,7 +101,6 @@ grep4j ${grep4j.version} - @@ -263,7 +300,8 @@ true - + org.baeldung.executable.ExecutableMavenJar diff --git a/core-java/src/main/java/com/baeldung/graph/Car.java b/core-java/src/main/java/com/baeldung/graph/Car.java new file mode 100644 index 0000000000..1dc65a0d4b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/graph/Car.java @@ -0,0 +1,50 @@ +package com.baeldung.graph; + +import org.neo4j.ogm.annotation.GraphId; +import org.neo4j.ogm.annotation.NodeEntity; +import org.neo4j.ogm.annotation.Relationship; + +/** + * @author Danil Kornishev (danil.kornishev@mastercard.com) + */ +@NodeEntity +public class Car { + @GraphId + private Long id; + + private String make; + + @Relationship(direction = "INCOMING") + private Company company; + + public Car(String make, String model) { + this.make = make; + this.model = model; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getMake() { + return make; + } + + public void setMake(String make) { + this.make = make; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + private String model; +} diff --git a/core-java/src/main/java/com/baeldung/graph/Company.java b/core-java/src/main/java/com/baeldung/graph/Company.java new file mode 100644 index 0000000000..1fe892b331 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/graph/Company.java @@ -0,0 +1,45 @@ +package com.baeldung.graph; + +import org.neo4j.ogm.annotation.NodeEntity; +import org.neo4j.ogm.annotation.Relationship; + +/** + * @author Danil Kornishev (danil.kornishev@mastercard.com) + */ +@NodeEntity +public class Company { + private Long id; + + private String name; + + @Relationship(type="owns") + private Car car; + + public Company(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Car getCar() { + return car; + } + + public void setCar(Car car) { + this.car = car; + } +} diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java b/core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java new file mode 100644 index 0000000000..b41588b71e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java @@ -0,0 +1,60 @@ +package com.baeldung.graph; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; + +import org.junit.Ignore; +import org.junit.Test; +import org.neo4j.driver.v1.AuthTokens; +import org.neo4j.driver.v1.Driver; +import org.neo4j.driver.v1.GraphDatabase; +import org.neo4j.driver.v1.Session; +import org.neo4j.driver.v1.StatementResult; +import org.testng.Assert; + +@Ignore +public class Neo4JServerTest { + + @Test + public void standAloneDriver() { + Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "12345")); + Session session = driver.session(); + + session.run("CREATE (baeldung:Company {name:\"Baeldung\"}) " + + "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + + "RETURN baeldung, tesla"); + + StatementResult result = session.run("MATCH (company:Company)-[:owns]-> (car:Car)" + + "WHERE car.make='tesla' and car.model='modelX'" + + "RETURN company.name"); + + Assert.assertTrue(result.hasNext()); + Assert.assertEquals(result.next().get("company.name").asString(), "Baeldung"); + + session.close(); + driver.close(); + } + + @Test + public void standAloneJdbc() throws Exception { + Connection con = DriverManager.getConnection("jdbc:neo4j:bolt://localhost/?user=neo4j,password=12345,scheme=basic"); + + // Querying + try (Statement stmt = con.createStatement()) { + stmt.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + + "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + + "RETURN baeldung, tesla"); + + ResultSet rs = stmt.executeQuery("MATCH (company:Company)-[:owns]-> (car:Car)" + + "WHERE car.make='tesla' and car.model='modelX'" + + "RETURN company.name"); + + while (rs.next()) { + Assert.assertEquals(rs.getString("company.name"), "Baeldung"); + } + } + con.close(); + } +} diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java b/core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java new file mode 100644 index 0000000000..00bd47d029 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java @@ -0,0 +1,46 @@ +package com.baeldung.graph; + +import org.junit.Test; +import org.neo4j.ogm.config.Configuration; +import org.neo4j.ogm.model.Result; +import org.neo4j.ogm.session.Session; +import org.neo4j.ogm.session.SessionFactory; +import org.testng.Assert; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Danil Kornishev (danil.kornishev@mastercard.com) + */ +public class Neo4jOgmTest { + + @Test + public void testOgm() { + Configuration conf = new Configuration(); + conf.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); + + SessionFactory factory = new SessionFactory(conf, "com.baeldung.graph"); + Session session = factory.openSession(); + + Car tesla = new Car("tesla", "modelS"); + Company baeldung = new Company("baeldung"); + + baeldung.setCar(tesla); + + session.save(baeldung); + + Map params = new HashMap<>(); + params.put("make", "tesla"); + Result result = session.query("MATCH (car:Car) <-[:owns]- (company:Company)" + + " WHERE car.make=$make" + + " RETURN company", params); + + Map firstResult = result.iterator().next(); + + Assert.assertEquals(firstResult.size(), 1); + + Company actual = (Company) firstResult.get("company"); + Assert.assertEquals(actual.getName(), baeldung.getName()); + } +} diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4jTest.java b/core-java/src/test/java/com/baeldung/graph/Neo4jTest.java new file mode 100644 index 0000000000..6956c2c39f --- /dev/null +++ b/core-java/src/test/java/com/baeldung/graph/Neo4jTest.java @@ -0,0 +1,167 @@ +package com.baeldung.graph; + + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.neo4j.graphdb.GraphDatabaseService; +import org.neo4j.graphdb.Label; +import org.neo4j.graphdb.Node; +import org.neo4j.graphdb.NotFoundException; +import org.neo4j.graphdb.RelationshipType; +import org.neo4j.graphdb.Result; +import org.neo4j.graphdb.factory.GraphDatabaseFactory; +import org.testng.Assert; + +public class Neo4jTest { + + private static GraphDatabaseService graphDb; + + @Before + public void setUp() { + GraphDatabaseFactory graphDbFactory = new GraphDatabaseFactory(); + graphDb = graphDbFactory.newEmbeddedDatabase(new File("data/cars")); + } + + @After + public void tearDown() { + graphDb.shutdown(); + } + + @Test + public void testPersonCar() { + graphDb.beginTx(); + Node car = graphDb.createNode(Label.label("Car")); + car.setProperty("make", "tesla"); + car.setProperty("model", "model3"); + + Node owner = graphDb.createNode(Label.label("Person")); + owner.setProperty("firstName", "baeldung"); + owner.setProperty("lastName", "baeldung"); + + owner.createRelationshipTo(car, RelationshipType.withName("owner")); + + Result result = graphDb.execute("MATCH (c:Car) <-[owner]- (p:Person) " + + "WHERE c.make = 'tesla'" + + "RETURN p.firstName, p.lastName"); + + Map firstResult = result.next(); + Assert.assertEquals("baeldung", firstResult.get("p.firstName")); + } + + @Test + public void testCreateNode() { + + graphDb.beginTx(); + + Result result = graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"})" + + "RETURN baeldung"); + + Map firstResult = result.next(); + Node firstNode = (Node) firstResult.get("baeldung"); + Assert.assertEquals(firstNode.getProperty("name"), "Baeldung"); + } + + @Test + public void testCreateNodeAndLink() { + graphDb.beginTx(); + + Result result = graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + + "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + + "RETURN baeldung, tesla"); + + Map firstResult = result.next(); + Assert.assertTrue(firstResult.containsKey("baeldung")); + Assert.assertTrue(firstResult.containsKey("tesla")); + } + + @Test + public void testFindAndReturn() { + graphDb.beginTx(); + + graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + + "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + + "RETURN baeldung, tesla"); + + Result result = graphDb.execute("MATCH (company:Company)-[:owns]-> (car:Car)" + + "WHERE car.make='tesla' and car.model='modelX'" + + "RETURN company.name"); + + Map firstResult = result.next(); + Assert.assertEquals(firstResult.get("company.name"), "Baeldung"); + } + + @Test + public void testUpdate() { + graphDb.beginTx(); + + graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + + "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + + "RETURN baeldung, tesla"); + + Result result = graphDb.execute("MATCH (car:Car)" + + "WHERE car.make='tesla'" + + " SET car.milage=120" + + " SET car :Car:Electro" + + " SET car.model=NULL" + + " RETURN car"); + + Map firstResult = result.next(); + Node car = (Node) firstResult.get("car"); + + Assert.assertEquals(car.getProperty("milage"), 120L); + Assert.assertEquals(car.getLabels(), Arrays.asList(Label.label("Car"), Label.label("Electro"))); + + try { + car.getProperty("model"); + Assert.fail(); + } catch (NotFoundException e) { + // expected + } + } + + @Test + public void testDelete() { + graphDb.beginTx(); + + graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " + + "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" + + "RETURN baeldung, tesla"); + + graphDb.execute("MATCH (company:Company)" + + " WHERE company.name='Baeldung'" + + " DELETE company"); + + Result result = graphDb.execute("MATCH (company:Company)" + + " WHERE company.name='Baeldung'" + + " RETURN company"); + + Assert.assertFalse(result.hasNext()); + } + + @Test + public void testBindings() { + graphDb.beginTx(); + + Map params = new HashMap<>(); + params.put("name", "baeldung"); + params.put("make", "tesla"); + params.put("model", "modelS"); + + Result result = graphDb.execute("CREATE (baeldung:Company {name:$name}) " + + "-[:owns]-> (tesla:Car {make: $make, model: $model})" + + "RETURN baeldung, tesla", params); + + Map firstResult = result.next(); + Assert.assertTrue(firstResult.containsKey("baeldung")); + Assert.assertTrue(firstResult.containsKey("tesla")); + + Node car = (Node) firstResult.get("tesla"); + Assert.assertEquals(car.getProperty("model"), "modelS"); + } +} From 5c8acbac57c08b2217d36c64abfea4cde4a8ac63 Mon Sep 17 00:00:00 2001 From: Andrew Morgan Date: Tue, 7 Feb 2017 21:12:14 +0000 Subject: [PATCH 51/58] Added stream removal from collection (#1131) --- .../ConcurrentModificationUnitTest.java | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java index d16a1fcdf4..f7a7bd5fe0 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java @@ -3,9 +3,12 @@ package com.baeldung.java.concurrentmodification; import org.junit.Test; import java.util.ArrayList; +import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; +import java.util.List; +import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.util.Lists.newArrayList; @@ -13,7 +16,7 @@ public class ConcurrentModificationUnitTest { @Test(expected = ConcurrentModificationException.class) public void givenIterating_whenRemoving_thenThrowException() throws InterruptedException { - ArrayList integers = newArrayList(1, 2, 3); + List integers = newArrayList(1, 2, 3); for (Integer integer : integers) { integers.remove(1); @@ -23,7 +26,7 @@ public class ConcurrentModificationUnitTest { @Test public void givenIterating_whenUsingIteratorRemove_thenNoError() throws InterruptedException { - ArrayList integers = newArrayList(1, 2, 3); + List integers = newArrayList(1, 2, 3); for (Iterator iterator = integers.iterator(); iterator.hasNext();) { Integer integer = iterator.next(); @@ -38,8 +41,8 @@ public class ConcurrentModificationUnitTest { @Test public void givenIterating_whenUsingRemovalList_thenNoError() throws InterruptedException { - ArrayList integers = newArrayList(1, 2, 3); - ArrayList toRemove = newArrayList(); + List integers = newArrayList(1, 2, 3); + List toRemove = newArrayList(); for (Integer integer : integers) { if(integer == 2) { @@ -54,10 +57,24 @@ public class ConcurrentModificationUnitTest { @Test public void whenUsingRemoveIf_thenRemoveElements() throws InterruptedException { - ArrayList integers = newArrayList(1, 2, 3); + Collection integers = newArrayList(1, 2, 3); integers.removeIf(i -> i == 2); assertThat(integers).containsExactly(1, 3); } + + @Test + public void whenUsingStream_thenRemoveElements() { + Collection integers = newArrayList(1, 2, 3); + + List collected = integers + .stream() + .filter(i -> i != 2) + .map(Object::toString) + .collect(toList()); + + assertThat(collected).containsExactly("1", "3"); + } + } From 40a22badfce648940016a90d6668fa2ee8458298 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Tue, 7 Feb 2017 19:39:27 -0600 Subject: [PATCH 52/58] Update README.md --- apache-poi/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/apache-poi/README.md b/apache-poi/README.md index cef6810c97..10fe8ba2e7 100644 --- a/apache-poi/README.md +++ b/apache-poi/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi) +- [Working with Microsoft Excel in Java](http://www.baeldung.com/java-microsoft-excel) From 9d46c8f3d1bece80f1292f4247d72863c1d74bf1 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Wed, 8 Feb 2017 12:05:02 +0100 Subject: [PATCH 53/58] BAEL-685 test for rx java --- rxjava/pom.xml | 17 +++ .../com/baeldung/rxjava/RxJavaTesting.java | 113 ++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 rxjava/src/test/java/com/baeldung/rxjava/RxJavaTesting.java diff --git a/rxjava/pom.xml b/rxjava/pom.xml index 6a351d98bd..f22e6a000a 100644 --- a/rxjava/pom.xml +++ b/rxjava/pom.xml @@ -31,11 +31,28 @@ junit ${junit.version}
+ + com.jayway.awaitility + awaitility + ${avaitility.version} + test + + + + org.hamcrest + hamcrest-all + ${hamcrest.version} + test + + +
4.12 1.2.5 + 1.7.0 + 1.3 \ No newline at end of file diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaTesting.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaTesting.java new file mode 100644 index 0000000000..67f6e1c2b8 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaTesting.java @@ -0,0 +1,113 @@ +package com.baeldung.rxjava; + +import org.junit.Test; +import rx.Observable; +import rx.observers.TestSubscriber; +import rx.schedulers.TestScheduler; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; + + +public class RxJavaTesting { + @Test + public void givenObservable_whenZip_shouldAssertBlockingInASameThread() { + //given + List letters = Arrays.asList("A", "B", "C", "D", "E"); + List results = new ArrayList<>(); + Observable observable = Observable + .from(letters) + .zipWith(Observable.range(1, Integer.MAX_VALUE), + (string, index) -> index + "-" + string); + + //when + observable.subscribe(results::add); + + //then + assertThat(results, notNullValue()); + assertThat(results, hasSize(5)); + assertThat(results, hasItems("1-A", "2-B", "3-C", "4-D", "5-E")); + } + + @Test + public void givenObservable_whenZip_shouldAssertOnTestSubscriber() { + //given + List letters = Arrays.asList("A", "B", "C", "D", "E"); + TestSubscriber subscriber = new TestSubscriber<>(); + + Observable observable = Observable + .from(letters) + .zipWith(Observable.range(1, Integer.MAX_VALUE), + ((string, index) -> index + "-" + string)); + + //when + observable.subscribe(subscriber); + + //then + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(5); + assertThat(subscriber.getOnNextEvents(), hasItems("1-A", "2-B", "3-C", "4-D", "5-E")); + } + + @Test + public void givenTestObserver_whenExceptionWasThrowsOnObservable_observerShouldGetError() { + //given + List letters = Arrays.asList("A", "B", "C", "D", "E"); + TestSubscriber subscriber = new TestSubscriber<>(); + + + Observable observable = Observable + .from(letters) + .zipWith(Observable.range(1, Integer.MAX_VALUE), + ((string, index) -> index + "-" + string)) + .concatWith(Observable.error(new RuntimeException("error in Observable"))); + + //when + observable.subscribe(subscriber); + + //then + subscriber.assertError(RuntimeException.class); + subscriber.assertNotCompleted(); + } + + @Test + public void givenObservableThatEmitsEventPerSecond_whenUseAdvanceByTime_shouldEmitEventPerSecond() { + //given + List letters = Arrays.asList("A", "B", "C", "D", "E"); + TestScheduler scheduler = new TestScheduler(); + TestSubscriber subscriber = new TestSubscriber<>(); + Observable tick = Observable.interval(1, TimeUnit.SECONDS, scheduler); + + Observable observable = Observable.from(letters) + .zipWith(tick, (string, index) -> index + "-" + string); + + observable.subscribeOn(scheduler) + .subscribe(subscriber); + + //expect + subscriber.assertNoValues(); + subscriber.assertNotCompleted(); + + //when + scheduler.advanceTimeBy(1, TimeUnit.SECONDS); + + //then + subscriber.assertNoErrors(); + subscriber.assertValueCount(1); + subscriber.assertValues("0-A"); + + //when + scheduler.advanceTimeTo(6, TimeUnit.SECONDS); + subscriber.assertCompleted(); + subscriber.assertNoErrors(); + subscriber.assertValueCount(5); + assertThat(subscriber.getOnNextEvents(), hasItems("0-A", "1-B", "2-C", "3-D", "4-E")); + } +} + From 7d9c4b5bb9cc123d0479a73a218554bc7311e999 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Wed, 8 Feb 2017 13:43:23 +0100 Subject: [PATCH 54/58] BAEL-685 do not need avaitility lib --- rxjava/pom.xml | 8 -------- 1 file changed, 8 deletions(-) diff --git a/rxjava/pom.xml b/rxjava/pom.xml index f22e6a000a..b3936bf78d 100644 --- a/rxjava/pom.xml +++ b/rxjava/pom.xml @@ -31,13 +31,6 @@ junit ${junit.version} - - com.jayway.awaitility - awaitility - ${avaitility.version} - test - - org.hamcrest hamcrest-all @@ -51,7 +44,6 @@ 4.12 1.2.5 - 1.7.0 1.3 From 0bbfa1e10b446deef15dfc8aafa561334a3748f6 Mon Sep 17 00:00:00 2001 From: Chima Ejiofor Date: Wed, 8 Feb 2017 16:35:33 +0100 Subject: [PATCH 55/58] Modification to Model Hibernate One to Many Tutorial (#1132) * Modifications to model on Hibernate One to manyTutorial * Modifications to model on Hibernate One to manyTutorial * Modifications to model on Hibernate One to manyTutorial --- .../HibernateOneToManyAnnotationMain.java | 7 ++-- .../hibernate/oneToMany/model/Cart.java | 20 ---------- .../hibernate/oneToMany/model/Items.java | 37 +------------------ .../src/main/resources/one_to_many.sql | 5 --- .../HibernateOneToManyAnnotationMainTest.java | 3 -- 5 files changed, 4 insertions(+), 68 deletions(-) diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java index 63b6450bf4..2bc5e514f7 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java @@ -16,16 +16,15 @@ public class HibernateOneToManyAnnotationMain { public static void main(String[] args) { Cart cart = new Cart(); - cart.setName("MyCart"); - Items item1 = new Items("I10", 10, 1, cart); - Items item2 = new Items("I20", 20, 2, cart); + Items item1 = new Items(cart); + Items item2 = new Items(cart); Set itemsSet = new HashSet(); itemsSet.add(item1); itemsSet.add(item2); cart.setItems(itemsSet); - cart.setTotal(10 * 1 + 20 * 2); + SessionFactory sessionFactory = null; Session session = null; diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java index 61a32ba43f..b8b991831e 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java @@ -19,11 +19,6 @@ public class Cart { @Column(name = "cart_id") private long id; - @Column(name = "total") - private double total; - - @Column(name = "name") - private String name; @OneToMany(mappedBy = "cart") private Set items; @@ -36,21 +31,6 @@ public class Cart { this.id = id; } - public double getTotal() { - return total; - } - - public void setTotal(double total) { - this.total = total; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } public Set getItems() { return items; diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java index 40ee6fdea1..f63a4855b5 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java @@ -18,14 +18,6 @@ public class Items { @Column(name = "id") private long id; - @Column(name = "item_id") - private String itemId; - - @Column(name = "item_total") - private double itemTotal; - - @Column(name = "quantity") - private int quantity; @ManyToOne @JoinColumn(name = "cart_id", nullable = false) @@ -35,37 +27,10 @@ public class Items { public Items() { } - public Items(String itemId, double total, int qty, Cart c) { - this.itemId = itemId; - this.itemTotal = total; - this.quantity = qty; + public Items(Cart c) { this.cart = c; } - public String getItemId() { - return itemId; - } - - public void setItemId(String itemId) { - this.itemId = itemId; - } - - public double getItemTotal() { - return itemTotal; - } - - public void setItemTotal(double itemTotal) { - this.itemTotal = itemTotal; - } - - public int getQuantity() { - return quantity; - } - - public void setQuantity(int quantity) { - this.quantity = quantity; - } - public Cart getCart() { return cart; } diff --git a/spring-hibernate4/src/main/resources/one_to_many.sql b/spring-hibernate4/src/main/resources/one_to_many.sql index 7887ff7d9c..2eb48fc262 100644 --- a/spring-hibernate4/src/main/resources/one_to_many.sql +++ b/spring-hibernate4/src/main/resources/one_to_many.sql @@ -1,16 +1,11 @@ CREATE TABLE `Cart` ( `cart_id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `total` decimal(10,0) NOT NULL, - `name` varchar(10) DEFAULT NULL, PRIMARY KEY (`cart_id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; CREATE TABLE `Items` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `cart_id` int(11) unsigned NOT NULL, - `item_id` varchar(10) NOT NULL, - `item_total` decimal(10,0) NOT NULL, - `quantity` int(3) NOT NULL, PRIMARY KEY (`id`), KEY `cart_id` (`cart_id`), CONSTRAINT `items_ibfk_1` FOREIGN KEY (`cart_id`) REFERENCES `Cart` (`cart_id`) diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainTest.java index 688329e329..e2d2bf9143 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainTest.java @@ -63,9 +63,6 @@ public class HibernateOneToManyAnnotationMainTest { cartItems = cart.getItems(); Assert.assertNull(cartItems); Items item1 = new Items(); - item1.setItemId("I10"); - item1.setItemTotal(10); - item1.setQuantity(1); item1.setCart(cart); assertNotNull(item1); Set itemsSet = new HashSet(); From 7aa774352de97555217eb9e18c0db27e633fbe66 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Wed, 8 Feb 2017 21:16:10 +0530 Subject: [PATCH 56/58] Joining/Splitting Strings with Java and Stream API (#1130) * rest with spark java * 4 * Update Application.java * indentation changes * spring @requestmapping shortcuts * removing spring requestmapping and pushing spring-mvc-java * Joining/Splitting Strings with Java and Stream API --- core-java/0.004102810554955205 | 0 core-java/0.04832801936270381 | 0 core-java/0.5633433244738808 | 0 core-java/0.6256429734439612 | 0 core-java/0.9799201796740292 | 0 .../baeldung/streamApi/JoinerSplitter.java | 23 +++++++++++ .../baeldung/stream/JoinerSplitterTest.java | 38 +++++++++++++++++++ 7 files changed, 61 insertions(+) create mode 100644 core-java/0.004102810554955205 create mode 100644 core-java/0.04832801936270381 create mode 100644 core-java/0.5633433244738808 create mode 100644 core-java/0.6256429734439612 create mode 100644 core-java/0.9799201796740292 create mode 100644 core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java create mode 100644 core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java diff --git a/core-java/0.004102810554955205 b/core-java/0.004102810554955205 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java/0.04832801936270381 b/core-java/0.04832801936270381 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java/0.5633433244738808 b/core-java/0.5633433244738808 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java/0.6256429734439612 b/core-java/0.6256429734439612 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java/0.9799201796740292 b/core-java/0.9799201796740292 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java b/core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java new file mode 100644 index 0000000000..5183921dea --- /dev/null +++ b/core-java/src/main/java/com/baeldung/streamApi/JoinerSplitter.java @@ -0,0 +1,23 @@ +package com.baeldung.streamApi; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class JoinerSplitter { + + public static String join ( String[] arrayOfString ) { + return Arrays.asList(arrayOfString) + .stream() + .map(x -> x) + .collect(Collectors.joining(",")); + } + + public static List split ( String str ) { + return Stream.of(str.split(",")) + .map (elem -> new String(elem)) + .collect(Collectors.toList()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java b/core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java new file mode 100644 index 0000000000..19d945f836 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/JoinerSplitterTest.java @@ -0,0 +1,38 @@ +package com.baeldung.stream; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.baeldung.streamApi.JoinerSplitter; + +public class JoinerSplitterTest { + + @Test + public void provided_array_convert_to_stream_and_convert_to_string() { + String[] programming_languages = {"java", "python", "nodejs", "ruby"}; + String expectation = "java,python,nodejs,ruby"; + + String result = JoinerSplitter.join(programming_languages); + assertEquals(result, expectation); + } + + @Test + public void provided_list_convert_to_stream_and_convert_to_list() { + String programming_languages = "java,python,nodejs,ruby"; + + List expectation = new ArrayList(); + expectation.add("java"); + expectation.add("python"); + expectation.add("nodejs"); + expectation.add("ruby"); + + List result = JoinerSplitter.split(programming_languages); + + assertEquals(result, expectation); + } + +} From 2c8e3c91799113f755215c2f52f98b9beb4a9670 Mon Sep 17 00:00:00 2001 From: Tian Baoqiang Date: Thu, 9 Feb 2017 02:51:21 +0800 Subject: [PATCH 57/58] #BAEL-100 tests and update spring boot to 1.5.1.RELEASE (#1135) * add tests for #BAEL-100 and upgrade spring boot to 1.5.1.RELEASE * uncomment integration test configurations --- spring-boot/pom.xml | 44 +++++++++- .../servletcomponentscan/JavaEEApp.java | 28 ++++++ .../SpringBootAnnotatedApp.java | 25 ++++++ .../SpringBootPlainApp.java | 13 +++ .../javaee/AttrListener.java | 23 +++++ .../javaee/EchoServlet.java | 30 +++++++ .../javaee/HelloFilter.java | 32 +++++++ .../javaee/HelloServlet.java | 33 +++++++ .../baeldung/{ => webjar}/TestController.java | 2 +- .../{ => webjar}/WebjarsdemoApplication.java | 3 +- .../SpringHelloServletRegistrationBean.java | 4 +- .../MyServletContainerCustomizationBean.java | 2 +- .../servletcomponentscan/JavaEEAppTest.java | 88 +++++++++++++++++++ .../SpringBootWithServletComponentTest.java | 65 ++++++++++++++ ...SpringBootWithoutServletComponentTest.java | 50 +++++++++++ .../java/com/baeldung/intro/AppLiveTest.java | 2 + ...WebjarsdemoApplicationIntegrationTest.java | 6 +- .../SpringBootApplicationIntegrationTest.java | 4 +- .../SpringBootJPAIntegrationTest.java | 4 +- .../SpringBootMailIntegrationTest.java | 4 +- 20 files changed, 444 insertions(+), 18 deletions(-) create mode 100644 spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/JavaEEApp.java create mode 100644 spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java create mode 100644 spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java create mode 100644 spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/AttrListener.java create mode 100644 spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/EchoServlet.java create mode 100644 spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloFilter.java create mode 100644 spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloServlet.java rename spring-boot/src/main/java/com/baeldung/{ => webjar}/TestController.java (91%) rename spring-boot/src/main/java/com/baeldung/{ => webjar}/WebjarsdemoApplication.java (77%) create mode 100644 spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/JavaEEAppTest.java create mode 100644 spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentTest.java create mode 100644 spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentTest.java rename spring-boot/src/test/java/com/baeldung/{ => webjar}/WebjarsdemoApplicationIntegrationTest.java (68%) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 68a5857865..b6a24b6cb7 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-boot @@ -12,8 +12,8 @@ org.springframework.boot spring-boot-starter-parent - 1.4.2.RELEASE - + 1.5.1.RELEASE + @@ -24,6 +24,26 @@ org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + org.apache.geronimo.specs + geronimo-osgi-locator + 1.1 + test + + + + org.apache.geronimo.components + geronimo-jaspi + 2.0.0 + test @@ -87,6 +107,20 @@ jquery ${jquery.version} + + + org.apache.tomee + arquillian-tomee-embedded + ${arquillian-tomee-embedded.version} + test + + + + org.apache.tomee + javaee-api + ${tomee-javaee-api.version} + provided + @@ -166,7 +200,7 @@ - json + json @@ -186,6 +220,8 @@ 3.1.1 3.3.7-1 3.1.7 + 7.0.2 + 7.0-1 diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/JavaEEApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/JavaEEApp.java new file mode 100644 index 0000000000..773503c5af --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/JavaEEApp.java @@ -0,0 +1,28 @@ +package com.baeldung.annotation.servletcomponentscan; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.Initialized; +import javax.enterprise.event.Observes; +import javax.servlet.ServletContext; + +@ApplicationScoped +public class JavaEEApp { + + private ServletContext context; + + /** + * act as a servletContext provider + */ + private void setContext(@Observes @Initialized(ApplicationScoped.class) final ServletContext context) { + if (this.context != null) { + throw new IllegalStateException("app context started twice"); + } + + this.context = context; + } + + public ServletContext getContext() { + return context; + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java new file mode 100644 index 0000000000..9fd66ee12a --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java @@ -0,0 +1,25 @@ +package com.baeldung.annotation.servletcomponentscan; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.ServletComponentScan; + +/** + * using the following annotations are equivalent: + *
  • + * @ServletComponentScan + *
  • + * @ServletComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.javaee") + *
  • + * @ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class}) + *
+ */ +@SpringBootApplication +@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.javaee") +public class SpringBootAnnotatedApp { + + public static void main(String[] args) { + SpringApplication.run(SpringBootAnnotatedApp.class, args); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java new file mode 100644 index 0000000000..9ce1c296e6 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java @@ -0,0 +1,13 @@ +package com.baeldung.annotation.servletcomponentscan; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.javaee") +public class SpringBootPlainApp { + + public static void main(String[] args) { + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/AttrListener.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/AttrListener.java new file mode 100644 index 0000000000..321ddd59d1 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/AttrListener.java @@ -0,0 +1,23 @@ +package com.baeldung.annotation.servletcomponentscan.javaee; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +@WebListener +public class AttrListener implements ServletContextListener { + + @Override + public void contextInitialized(ServletContextEvent servletContextEvent) { + servletContextEvent + .getServletContext() + .setAttribute("servlet-context-attr", "test"); + System.out.println("context init"); + } + + @Override + public void contextDestroyed(ServletContextEvent servletContextEvent) { + System.out.println("context destroy"); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/EchoServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/EchoServlet.java new file mode 100644 index 0000000000..b9fed314c7 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/EchoServlet.java @@ -0,0 +1,30 @@ +package com.baeldung.annotation.servletcomponentscan.javaee; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; +import java.nio.file.CopyOption; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +@WebServlet(name = "echo servlet", urlPatterns = "/echo") +public class EchoServlet extends HttpServlet { + + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) { + try { + Path path = File + .createTempFile("echo", "tmp") + .toPath(); + Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); + Files.copy(path, response.getOutputStream()); + Files.delete(path); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloFilter.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloFilter.java new file mode 100644 index 0000000000..81e90d69ad --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloFilter.java @@ -0,0 +1,32 @@ +package com.baeldung.annotation.servletcomponentscan.javaee; + +import javax.servlet.*; +import javax.servlet.annotation.WebFilter; +import javax.servlet.annotation.WebInitParam; +import java.io.IOException; + +@WebFilter(urlPatterns = "/hello", description = "a filter for hello servlet", initParams = { @WebInitParam(name = "msg", value = "filtering ") }, filterName = "hello filter", servletNames = { "echo servlet" }) +public class HelloFilter implements Filter { + + private FilterConfig filterConfig; + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + System.out.println("filter init"); + this.filterConfig = filterConfig; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + servletResponse + .getOutputStream() + .print(filterConfig.getInitParameter("msg")); + filterChain.doFilter(servletRequest, servletResponse); + } + + @Override + public void destroy() { + System.out.println("filter destroy"); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloServlet.java new file mode 100644 index 0000000000..4a46a56107 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/javaee/HelloServlet.java @@ -0,0 +1,33 @@ +package com.baeldung.annotation.servletcomponentscan.javaee; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebInitParam; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello")}) +public class HelloServlet extends HttpServlet { + + private ServletConfig servletConfig; + + @Override + public void init(ServletConfig servletConfig){ + this.servletConfig = servletConfig; + } + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) { + try { + response + .getOutputStream() + .write(servletConfig.getInitParameter("msg").getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/TestController.java b/spring-boot/src/main/java/com/baeldung/webjar/TestController.java similarity index 91% rename from spring-boot/src/main/java/com/baeldung/TestController.java rename to spring-boot/src/main/java/com/baeldung/webjar/TestController.java index 0e28ca67f8..e8e7fd5ce9 100644 --- a/spring-boot/src/main/java/com/baeldung/TestController.java +++ b/spring-boot/src/main/java/com/baeldung/webjar/TestController.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.webjar; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; diff --git a/spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java b/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java similarity index 77% rename from spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java rename to spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java index 35490131c6..d2135754c9 100644 --- a/spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java +++ b/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java @@ -1,7 +1,8 @@ -package com.baeldung; +package com.baeldung.webjar; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; @SpringBootApplication public class WebjarsdemoApplication { diff --git a/spring-boot/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java b/spring-boot/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java index 78680baf7d..723afddd06 100644 --- a/spring-boot/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java +++ b/spring-boot/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java @@ -1,8 +1,8 @@ package org.baeldung.common.error; -import javax.servlet.Servlet; +import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.boot.context.embedded.ServletRegistrationBean; +import javax.servlet.Servlet; public class SpringHelloServletRegistrationBean extends ServletRegistrationBean { diff --git a/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java b/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java index 97130bed6a..9b5a0aa948 100644 --- a/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java +++ b/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java @@ -2,7 +2,7 @@ package org.baeldung.common.properties; import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; -import org.springframework.boot.context.embedded.ErrorPage; +import org.springframework.boot.web.servlet.ErrorPage; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/JavaEEAppTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/JavaEEAppTest.java new file mode 100644 index 0000000000..00705be307 --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/JavaEEAppTest.java @@ -0,0 +1,88 @@ +package com.baeldung.annotation.servletcomponentscan; + +import com.baeldung.annotation.servletcomponentscan.javaee.AttrListener; +import com.baeldung.annotation.servletcomponentscan.javaee.EchoServlet; +import com.baeldung.annotation.servletcomponentscan.javaee.HelloFilter; +import com.baeldung.annotation.servletcomponentscan.javaee.HelloServlet; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.container.test.api.RunAsClient; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; +import javax.servlet.FilterRegistration; +import javax.servlet.ServletContext; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; + +import static org.junit.Assert.*; + +@RunWith(Arquillian.class) +public class JavaEEAppTest { + + @Deployment + public static WebArchive createDeployment() { + return ShrinkWrap + .create(WebArchive.class) + .addClass(JavaEEApp.class) + .addClasses(AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class); + } + + @Inject private ServletContext servletContext; + + @Test + public void givenServletContextListener_whenAccessSpecialAttrs_thenFound() throws MalformedURLException { + assertNotNull(servletContext); + assertNotNull(servletContext.getAttribute("servlet-context-attr")); + assertEquals("test", servletContext.getAttribute("servlet-context-attr")); + } + + @Test + public void givenServletContext_whenCheckHelloFilterMappings_thenCorrect() throws MalformedURLException { + assertNotNull(servletContext); + FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); + + assertNotNull(filterRegistration); + assertTrue(filterRegistration + .getServletNameMappings() + .contains("echo servlet")); + } + + @ArquillianResource private URL base; + + @Test + @RunAsClient + public void givenFilterAndServlet_whenGetHello_thenRespondFilteringHello() throws MalformedURLException { + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(URI.create(new URL(base, "hello").toExternalForm())); + Response response = target + .request() + .get(); + + assertEquals("filtering hello", response.readEntity(String.class)); + } + + @Test + @RunAsClient + public void givenFilterAndServlet_whenPostEcho_thenEchoFiltered() throws MalformedURLException { + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(URI.create(new URL(base, "echo").toExternalForm())); + Response response = target + .request() + .post(Entity.entity("echo", MediaType.TEXT_PLAIN_TYPE)); + + assertEquals("filtering echo", response.readEntity(String.class)); + } + +} diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentTest.java new file mode 100644 index 0000000000..524a4df480 --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentTest.java @@ -0,0 +1,65 @@ +package com.baeldung.annotation.servletcomponentscan; + +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.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.servlet.FilterRegistration; +import javax.servlet.ServletContext; + +import static org.junit.Assert.*; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) +@AutoConfigureMockMvc +@TestPropertySource(properties = { "security.basic.enabled=false", "server.tomcat.additional-tld-skip-patterns=tomee-*.jar,tomcat-*.jar,openejb-*.jar,cxf-*.jar,activemq-*.jar" }) +public class SpringBootWithServletComponentTest { + + @Autowired private ServletContext servletContext; + + @Test + public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() { + assertNotNull(servletContext); + assertNotNull(servletContext.getAttribute("servlet-context-attr")); + assertEquals("test", servletContext.getAttribute("servlet-context-attr")); + } + + @Test + public void givenServletContext_whenCheckHelloFilterMappings_thenCorrect() { + assertNotNull(servletContext); + FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); + + assertNotNull(filterRegistration); + assertTrue(filterRegistration + .getServletNameMappings() + .contains("echo servlet")); + } + + @Autowired private TestRestTemplate restTemplate; + + @Test + public void givenServletFilter_whenGetHello_thenRequestFiltered() { + ResponseEntity responseEntity = this.restTemplate.getForEntity("/hello", String.class); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertEquals("filtering hello", responseEntity.getBody()); + } + + @Test + public void givenFilterAndServlet_whenPostEcho_thenEchoFiltered() { + ResponseEntity responseEntity = this.restTemplate.postForEntity("/echo", "echo", String.class); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertEquals("filtering echo", responseEntity.getBody()); + } + + + +} + + diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentTest.java new file mode 100644 index 0000000000..811323826b --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentTest.java @@ -0,0 +1,50 @@ +package com.baeldung.annotation.servletcomponentscan; + +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.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.servlet.FilterRegistration; +import javax.servlet.ServletContext; + +import static org.junit.Assert.*; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class) +@AutoConfigureMockMvc +@TestPropertySource(properties = { "security.basic.enabled=false", "server.tomcat.additional-tld-skip-patterns=tomee-*.jar,tomcat-*.jar,openejb-*.jar,cxf-*.jar,activemq-*.jar" }) +public class SpringBootWithoutServletComponentTest { + + @Autowired private ServletContext servletContext; + + @Autowired private TestRestTemplate restTemplate; + + @Test + public void givenServletContext_whenAccessAttrs_thenNotFound() { + assertNull(servletContext.getAttribute("servlet-context-attr")); + } + + @Test + public void givenServletFilter_whenGetHello_thenEndpointNotFound() { + ResponseEntity responseEntity = this.restTemplate.getForEntity("/hello", String.class); + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); + } + + @Test + public void givenServletContext_whenCheckFilterMappings_thenEmpty() { + assertNotNull(servletContext); + FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); + + assertNull(filterRegistration); + } + +} + + 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 772709dc30..af46fe0423 100644 --- a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -6,6 +6,7 @@ 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.http.MediaType; +import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @@ -17,6 +18,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc +@TestPropertySource(properties = { "security.basic.enabled=false" }) public class AppLiveTest { @Autowired diff --git a/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java similarity index 68% rename from spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationIntegrationTest.java rename to spring-boot/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java index 3558682b97..d6e71dcf6b 100644 --- a/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java @@ -1,13 +1,13 @@ -package com.baeldung; +package com.baeldung.webjar; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = WebjarsdemoApplication.class) +@SpringBootTest(classes = WebjarsdemoApplication.class) @WebAppConfiguration public class WebjarsdemoApplicationIntegrationTest { diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java index 8cdcdb2216..3499952ab4 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java @@ -9,7 +9,7 @@ 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.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @@ -22,7 +22,7 @@ import org.springframework.web.context.WebApplicationContext; import java.nio.charset.Charset; @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = Application.class) +@SpringBootTest(classes = Application.class) @WebAppConfiguration public class SpringBootApplicationIntegrationTest { @Autowired diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java index 233684bc24..d4b19e6a1d 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java @@ -5,14 +5,14 @@ import org.baeldung.repository.GenericEntityRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = Application.class) +@SpringBootTest(classes = Application.class) public class SpringBootJPAIntegrationTest { @Autowired private GenericEntityRepository genericEntityRepository; diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java index cec25f20f9..10e3d6d60b 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java @@ -5,7 +5,7 @@ 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.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -23,7 +23,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = Application.class) +@SpringBootTest(classes = Application.class) public class SpringBootMailIntegrationTest { @Autowired private JavaMailSender javaMailSender; From 6e114b6fb0ebda58c9d0ee3bf2cdfd1ad3ac1b9e Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 9 Feb 2017 01:34:42 +0200 Subject: [PATCH 58/58] add simple java config --- .../baeldung/config/SimpleMongoConfig.java | 25 +++++++++++++++++++ .../MongoTemplateProjectionLiveTest.java | 14 ++++++----- 2 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java diff --git a/spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java b/spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java new file mode 100644 index 0000000000..6140382f82 --- /dev/null +++ b/spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java @@ -0,0 +1,25 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; + +import com.mongodb.Mongo; +import com.mongodb.MongoClient; + +@Configuration +@EnableMongoRepositories(basePackages = "org.baeldung.repository") +public class SimpleMongoConfig { + + @Bean + public Mongo mongo() throws Exception { + return new MongoClient("localhost"); + } + + @Bean + public MongoTemplate mongoTemplate() throws Exception { + return new MongoTemplate(mongo(), "test"); + } + +} diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java index 04e474f71b..61115faede 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java @@ -1,8 +1,10 @@ package org.baeldung.mongotemplate; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; -import org.baeldung.config.MongoConfig; +import org.baeldung.config.SimpleMongoConfig; import org.baeldung.model.User; import org.junit.After; import org.junit.Before; @@ -15,7 +17,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = MongoConfig.class) +@ContextConfiguration(classes = SimpleMongoConfig.class) public class MongoTemplateProjectionLiveTest { @Autowired @@ -38,7 +40,7 @@ public class MongoTemplateProjectionLiveTest { mongoTemplate.insert(new User("John", 30)); mongoTemplate.insert(new User("Ringo", 35)); - Query query = new Query(); + final Query query = new Query(); query.fields() .include("name"); @@ -55,7 +57,7 @@ public class MongoTemplateProjectionLiveTest { mongoTemplate.insert(new User("John", 30)); mongoTemplate.insert(new User("Ringo", 35)); - Query query = new Query(); + final Query query = new Query(); query.fields() .exclude("_id"); @@ -64,7 +66,7 @@ public class MongoTemplateProjectionLiveTest { assertNull(user.getId()); assertNotNull(user.getAge()); }); - + } }