Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
4a7cde7d32
|
@ -1,6 +1,8 @@
|
||||||
package com.baeldung.date;
|
package com.baeldung.date;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import org.joda.time.Days;
|
||||||
|
import org.joda.time.Minutes;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.text.ParseException;
|
import java.text.ParseException;
|
||||||
import java.text.SimpleDateFormat;
|
import java.text.SimpleDateFormat;
|
||||||
|
@ -16,7 +18,7 @@ import java.util.Locale;
|
||||||
import java.util.TimeZone;
|
import java.util.TimeZone;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import org.junit.Test;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class DateDiffUnitTest {
|
public class DateDiffUnitTest {
|
||||||
|
|
||||||
|
@ -29,18 +31,39 @@ public class DateDiffUnitTest {
|
||||||
long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
|
long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
|
||||||
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
|
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() {
|
public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenWorks() {
|
||||||
LocalDate now = LocalDate.now();
|
LocalDate aDate = LocalDate.of(2020, 9, 11);
|
||||||
LocalDate sixDaysBehind = now.minusDays(6);
|
LocalDate sixDaysBehind = aDate.minusDays(6);
|
||||||
|
|
||||||
Period period = Period.between(now, sixDaysBehind);
|
Period period = Period.between(aDate, sixDaysBehind);
|
||||||
int diff = Math.abs(period.getDays());
|
int diff = Math.abs(period.getDays());
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenDoesNotWork() {
|
||||||
|
LocalDate aDate = LocalDate.of(2020, 9, 11);
|
||||||
|
LocalDate sixtyDaysBehind = aDate.minusDays(60);
|
||||||
|
Period period = Period.between(aDate, sixtyDaysBehind);
|
||||||
|
int diff = Math.abs(period.getDays());
|
||||||
|
//not equals
|
||||||
|
assertNotEquals(60, diff);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoDatesInJava8_whenUsingPeriod_thenWeGet0Year1Month29Days() {
|
||||||
|
LocalDate aDate = LocalDate.of(2020, 9, 11);
|
||||||
|
LocalDate sixtyDaysBehind = aDate.minusDays(60);
|
||||||
|
Period period = Period.between(aDate, sixtyDaysBehind);
|
||||||
|
int years = Math.abs(period.getYears());
|
||||||
|
int months = Math.abs(period.getMonths());
|
||||||
|
int days = Math.abs(period.getDays());
|
||||||
|
assertArrayEquals(new int[] { 0, 1, 29 }, new int[] { years, months, days });
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -51,7 +74,7 @@ public class DateDiffUnitTest {
|
||||||
Duration duration = Duration.between(now, sixMinutesBehind);
|
Duration duration = Duration.between(now, sixMinutesBehind);
|
||||||
long diff = Math.abs(duration.toMinutes());
|
long diff = Math.abs(duration.toMinutes());
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -61,7 +84,7 @@ public class DateDiffUnitTest {
|
||||||
|
|
||||||
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
|
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
|
||||||
|
|
||||||
assertEquals(diff, 10);
|
assertEquals(10, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -71,7 +94,7 @@ public class DateDiffUnitTest {
|
||||||
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore"))
|
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore"))
|
||||||
.minusDays(6);
|
.minusDays(6);
|
||||||
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
|
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -81,7 +104,7 @@ public class DateDiffUnitTest {
|
||||||
|
|
||||||
long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS);
|
long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS);
|
||||||
|
|
||||||
assertEquals(diff, 10);
|
assertEquals(10, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -89,10 +112,9 @@ public class DateDiffUnitTest {
|
||||||
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
|
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
|
||||||
org.joda.time.LocalDate sixDaysBehind = now.minusDays(6);
|
org.joda.time.LocalDate sixDaysBehind = now.minusDays(6);
|
||||||
|
|
||||||
org.joda.time.Period period = new org.joda.time.Period(now, sixDaysBehind);
|
long diff = Math.abs(Days.daysBetween(now, sixDaysBehind).getDays());
|
||||||
long diff = Math.abs(period.getDays());
|
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -100,8 +122,9 @@ public class DateDiffUnitTest {
|
||||||
org.joda.time.LocalDateTime now = org.joda.time.LocalDateTime.now();
|
org.joda.time.LocalDateTime now = org.joda.time.LocalDateTime.now();
|
||||||
org.joda.time.LocalDateTime sixMinutesBehind = now.minusMinutes(6);
|
org.joda.time.LocalDateTime sixMinutesBehind = now.minusMinutes(6);
|
||||||
|
|
||||||
org.joda.time.Period period = new org.joda.time.Period(now, sixMinutesBehind);
|
long diff = Math.abs(Minutes.minutesBetween(now, sixMinutesBehind).getMinutes());
|
||||||
long diff = Math.abs(period.getDays());
|
assertEquals(6, diff);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -111,6 +134,6 @@ public class DateDiffUnitTest {
|
||||||
|
|
||||||
long diff = Math.abs(now.numDaysFrom(sixDaysBehind));
|
long diff = Math.abs(now.numDaysFrom(sixDaysBehind));
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,12 +1,12 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<hazelcast xsi:schemaLocation="http://www.hazelcast.com/schema/config hazelcast-config-3.7.xsd"
|
<hazelcast xmlns="http://www.hazelcast.com/schema/config"
|
||||||
xmlns="http://www.hazelcast.com/schema/config"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
xsi:schemaLocation="http://www.hazelcast.com/schema/config
|
||||||
|
http://www.hazelcast.com/schema/config/hazelcast-config-4.0.xsd">
|
||||||
<network>
|
<network>
|
||||||
<port auto-increment="true" port-count="20">5701</port>
|
<port auto-increment="true" port-count="20">5701</port>
|
||||||
<join>
|
<join>
|
||||||
<multicast enabled="false">
|
<multicast enabled="false"/>
|
||||||
</multicast>
|
|
||||||
<tcp-ip enabled="true">
|
<tcp-ip enabled="true">
|
||||||
<member>machine1</member>
|
<member>machine1</member>
|
||||||
<member>localhost</member>
|
<member>localhost</member>
|
||||||
|
|
|
@ -99,6 +99,8 @@
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>${surefire-plugin.version}</version>
|
<version>${surefire-plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
|
<forkCount>1</forkCount>
|
||||||
|
<reuseForks>true</reuseForks>
|
||||||
<systemProperties>
|
<systemProperties>
|
||||||
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
|
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
|
||||||
</systemProperties>
|
</systemProperties>
|
||||||
|
|
|
@ -32,6 +32,10 @@
|
||||||
<groupId>org.thymeleaf.extras</groupId>
|
<groupId>org.thymeleaf.extras</groupId>
|
||||||
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
|
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-jersey</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- oauth2 -->
|
<!-- oauth2 -->
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.jersey;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.context.annotation.PropertySource;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
@PropertySource("classpath:jersey-application.properties")
|
||||||
|
public class JerseyApplication {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(JerseyApplication.class, args);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.jersey;
|
||||||
|
|
||||||
|
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
|
||||||
|
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
|
||||||
|
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.core.Context;
|
||||||
|
import javax.ws.rs.core.MediaType;
|
||||||
|
import javax.ws.rs.core.SecurityContext;
|
||||||
|
|
||||||
|
@Path("/")
|
||||||
|
public class JerseyResource {
|
||||||
|
@GET
|
||||||
|
@Path("login")
|
||||||
|
@Produces(MediaType.TEXT_HTML)
|
||||||
|
public String login() {
|
||||||
|
return "Log in with <a href=\"/oauth2/authorization/github\">GitHub</a>";
|
||||||
|
}
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Produces(MediaType.TEXT_PLAIN)
|
||||||
|
public String home(@Context SecurityContext securityContext) {
|
||||||
|
OAuth2AuthenticationToken authenticationToken = (OAuth2AuthenticationToken) securityContext.getUserPrincipal();
|
||||||
|
OAuth2AuthenticatedPrincipal authenticatedPrincipal = authenticationToken.getPrincipal();
|
||||||
|
String userName = authenticatedPrincipal.getAttribute("login");
|
||||||
|
return "Hello " + userName;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,11 @@
|
||||||
|
package com.baeldung.jersey;
|
||||||
|
|
||||||
|
import org.glassfish.jersey.server.ResourceConfig;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class RestConfig extends ResourceConfig {
|
||||||
|
public RestConfig() {
|
||||||
|
register(JerseyResource.class);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.jersey;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||||
|
@Override
|
||||||
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
|
http
|
||||||
|
.authorizeRequests()
|
||||||
|
.antMatchers("/login")
|
||||||
|
.permitAll()
|
||||||
|
.anyRequest()
|
||||||
|
.authenticated()
|
||||||
|
.and()
|
||||||
|
.oauth2Login()
|
||||||
|
.loginPage("/login");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,3 @@
|
||||||
|
server.port=8083
|
||||||
|
spring.security.oauth2.client.registration.github.client-id=<your-client-id>
|
||||||
|
spring.security.oauth2.client.registration.github.client-secret=<your-client-secret>
|
|
@ -0,0 +1,72 @@
|
||||||
|
package com.baeldung.jersey;
|
||||||
|
|
||||||
|
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.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||||
|
import org.springframework.boot.web.server.LocalServerPort;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.test.context.TestPropertySource;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||||
|
import static org.springframework.http.MediaType.TEXT_HTML;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(webEnvironment = RANDOM_PORT)
|
||||||
|
@TestPropertySource(properties = "spring.security.oauth2.client.registration.github.client-id:test-id")
|
||||||
|
public class JerseyResourceUnitTest {
|
||||||
|
@Autowired
|
||||||
|
private TestRestTemplate restTemplate;
|
||||||
|
|
||||||
|
@LocalServerPort
|
||||||
|
private int port;
|
||||||
|
|
||||||
|
private String basePath;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() {
|
||||||
|
basePath = "http://localhost:" + port + "/";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUserIsUnauthenticated_thenTheyAreRedirectedToLoginPage() {
|
||||||
|
ResponseEntity<Object> response = restTemplate.getForEntity(basePath, Object.class);
|
||||||
|
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||||
|
assertThat(response.getBody()).isNull();
|
||||||
|
|
||||||
|
URI redirectLocation = response.getHeaders().getLocation();
|
||||||
|
assertThat(redirectLocation).isNotNull();
|
||||||
|
assertThat(redirectLocation.toString()).isEqualTo(basePath + "login");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUserAttemptsToLogin_thenAuthorizationPathIsReturned() {
|
||||||
|
ResponseEntity<String> response = restTemplate.getForEntity(basePath + "login", String.class);
|
||||||
|
assertThat(response.getHeaders().getContentType()).isEqualTo(TEXT_HTML);
|
||||||
|
assertThat(response.getBody()).isEqualTo("Log in with <a href=\"/oauth2/authorization/github\">GitHub</a>");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUserAccessesAuthorizationEndpoint_thenTheyAresRedirectedToProvider() {
|
||||||
|
ResponseEntity<String> response = restTemplate.getForEntity(basePath + "oauth2/authorization/github", String.class);
|
||||||
|
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND);
|
||||||
|
assertThat(response.getBody()).isNull();
|
||||||
|
|
||||||
|
URI redirectLocation = response.getHeaders().getLocation();
|
||||||
|
assertThat(redirectLocation).isNotNull();
|
||||||
|
assertThat(redirectLocation.getHost()).isEqualTo("github.com");
|
||||||
|
assertThat(redirectLocation.getPath()).isEqualTo("/login/oauth/authorize");
|
||||||
|
|
||||||
|
String redirectionQuery = redirectLocation.getQuery();
|
||||||
|
assertThat(redirectionQuery.contains("response_type=code"));
|
||||||
|
assertThat(redirectionQuery.contains("client_id=test-id"));
|
||||||
|
assertThat(redirectionQuery.contains("scope=read:user"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.inmemory;
|
||||||
|
|
||||||
|
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.WebSecurityConfigurerAdapter;
|
||||||
|
|
||||||
|
//@Configuration
|
||||||
|
public class InMemoryNoOpAuthWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||||
|
auth.inMemoryAuthentication()
|
||||||
|
.withUser("spring")
|
||||||
|
.password("{noop}secret")
|
||||||
|
.roles("USER");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
|
http.authorizeRequests()
|
||||||
|
.antMatchers("/private/**")
|
||||||
|
.authenticated()
|
||||||
|
.antMatchers("/public/**")
|
||||||
|
.permitAll()
|
||||||
|
.and()
|
||||||
|
.httpBasic();
|
||||||
|
}
|
||||||
|
}
|
|
@ -22,6 +22,10 @@
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-validation</artifactId>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||||
|
|
|
@ -0,0 +1,12 @@
|
||||||
|
package com.baeldung.springvalidation;
|
||||||
|
|
||||||
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
|
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||||
|
|
||||||
|
public class ServletInitializer extends SpringBootServletInitializer {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
|
||||||
|
return application.sources(SpringValidationApplication.class);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.springvalidation;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class SpringValidationApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(SpringValidationApplication.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,44 @@
|
||||||
|
package com.baeldung.springvalidation.controller;
|
||||||
|
|
||||||
|
import javax.validation.Valid;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
import org.springframework.ui.Model;
|
||||||
|
import org.springframework.ui.ModelMap;
|
||||||
|
import org.springframework.validation.BindingResult;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMethod;
|
||||||
|
|
||||||
|
import com.baeldung.springvalidation.domain.UserAccount;
|
||||||
|
import com.baeldung.springvalidation.interfaces.BasicInfo;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
public class UserAccountController {
|
||||||
|
|
||||||
|
@GetMapping("/getUserForm")
|
||||||
|
public String showUserForm(Model theModel) {
|
||||||
|
UserAccount theUser = new UserAccount();
|
||||||
|
theModel.addAttribute("useraccount", theUser);
|
||||||
|
return "userHome";
|
||||||
|
}
|
||||||
|
|
||||||
|
@RequestMapping(value = "/saveBasicInfo", method = RequestMethod.POST)
|
||||||
|
public String saveBasicInfo(@Valid @ModelAttribute("useraccount") UserAccount useraccount, BindingResult result, ModelMap model) {
|
||||||
|
if (result.hasErrors()) {
|
||||||
|
return "error";
|
||||||
|
}
|
||||||
|
return "success";
|
||||||
|
}
|
||||||
|
|
||||||
|
@RequestMapping(value = "/saveBasicInfoStep1", method = RequestMethod.POST)
|
||||||
|
public String saveBasicInfoStep1(@Validated(BasicInfo.class) @ModelAttribute("useraccount") UserAccount useraccount, BindingResult result, ModelMap model) {
|
||||||
|
if (result.hasErrors()) {
|
||||||
|
return "error";
|
||||||
|
}
|
||||||
|
return "success";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,80 @@
|
||||||
|
package com.baeldung.springvalidation.domain;
|
||||||
|
|
||||||
|
import javax.validation.Valid;
|
||||||
|
import javax.validation.constraints.Min;
|
||||||
|
import javax.validation.constraints.NotBlank;
|
||||||
|
import javax.validation.constraints.NotNull;
|
||||||
|
import javax.validation.constraints.Size;
|
||||||
|
|
||||||
|
import com.baeldung.springvalidation.interfaces.AdvanceInfo;
|
||||||
|
import com.baeldung.springvalidation.interfaces.BasicInfo;
|
||||||
|
|
||||||
|
public class UserAccount {
|
||||||
|
|
||||||
|
@NotNull(groups = BasicInfo.class)
|
||||||
|
@Size(min = 4, max = 15, groups = BasicInfo.class)
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
@NotBlank(groups = BasicInfo.class)
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Min(value = 18, message = "Age should not be less than 18", groups = AdvanceInfo.class)
|
||||||
|
private int age;
|
||||||
|
|
||||||
|
@NotBlank(groups = AdvanceInfo.class)
|
||||||
|
private String phone;
|
||||||
|
|
||||||
|
@Valid
|
||||||
|
@NotNull(groups = AdvanceInfo.class)
|
||||||
|
private UserAddress useraddress;
|
||||||
|
|
||||||
|
public UserAddress getUseraddress() {
|
||||||
|
return useraddress;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUseraddress(UserAddress useraddress) {
|
||||||
|
this.useraddress = useraddress;
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserAccount() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserAccount(String email, String password, String name, int age) {
|
||||||
|
this.password = password;
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPassword() {
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPassword(String password) {
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAge(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPhone() {
|
||||||
|
return phone;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPhone(String phone) {
|
||||||
|
this.phone = phone;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.springvalidation.domain;
|
||||||
|
|
||||||
|
import javax.validation.constraints.NotBlank;
|
||||||
|
public class UserAddress {
|
||||||
|
|
||||||
|
@NotBlank
|
||||||
|
private String countryCode;
|
||||||
|
|
||||||
|
public String getCountryCode() {
|
||||||
|
return countryCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCountryCode(String countryCode) {
|
||||||
|
this.countryCode = countryCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,6 @@
|
||||||
|
package com.baeldung.springvalidation.interfaces;
|
||||||
|
|
||||||
|
public interface AdvanceInfo {
|
||||||
|
// validation group marker interface
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,6 @@
|
||||||
|
package com.baeldung.springvalidation.interfaces;
|
||||||
|
|
||||||
|
public interface BasicInfo {
|
||||||
|
// validation group marker interface
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,2 @@
|
||||||
|
spring.mvc.view.prefix=/WEB-INF/views/
|
||||||
|
spring.mvc.view.suffix=.html
|
|
@ -0,0 +1,10 @@
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||||
|
<title>SpringValidation</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<h3>Error!!!</h3>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -0,0 +1,10 @@
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||||
|
<title>SpringValidation</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<h3>SUCCESS!!!</h3>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -0,0 +1,57 @@
|
||||||
|
package com.baeldung.springvalidation;
|
||||||
|
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
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.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||||
|
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||||
|
@AutoConfigureMockMvc
|
||||||
|
public class UserAccountUnitTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MockMvc mockMvc;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSaveBasicInfo_whenCorrectInput_thenSuccess() throws Exception {
|
||||||
|
this.mockMvc.perform(MockMvcRequestBuilders.post("/saveBasicInfo")
|
||||||
|
.accept(MediaType.TEXT_HTML)
|
||||||
|
.param("name", "test123")
|
||||||
|
.param("password", "pass"))
|
||||||
|
.andExpect(view().name("success"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andDo(print());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSaveBasicInfoStep1_whenCorrectInput_thenSuccess() throws Exception {
|
||||||
|
this.mockMvc.perform(MockMvcRequestBuilders.post("/saveBasicInfoStep1")
|
||||||
|
.accept(MediaType.TEXT_HTML)
|
||||||
|
.param("name", "test123")
|
||||||
|
.param("password", "pass"))
|
||||||
|
.andExpect(view().name("success"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andDo(print());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSaveBasicInfoStep1_whenIncorrectInput_thenError() throws Exception {
|
||||||
|
this.mockMvc.perform(MockMvcRequestBuilders.post("/saveBasicInfoStep1")
|
||||||
|
.accept(MediaType.TEXT_HTML))
|
||||||
|
// .param("name", "test123")
|
||||||
|
// .param("password", "pass"))
|
||||||
|
.andExpect(model().errorCount(2))
|
||||||
|
// .andExpect(view().name("error"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andDo(print());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -42,6 +42,7 @@
|
||||||
<module>xmlunit-2</module>
|
<module>xmlunit-2</module>
|
||||||
<module>junit-4</module>
|
<module>junit-4</module>
|
||||||
<module>testing-libraries</module>
|
<module>testing-libraries</module>
|
||||||
|
<module>testing-libraries-2</module>
|
||||||
<module>powermock</module>
|
<module>powermock</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,43 @@
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>testing-libraries-2</artifactId>
|
||||||
|
<name>testing-libraries-2</name>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>testing-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.github.stefanbirkner</groupId>
|
||||||
|
<artifactId>system-rules</artifactId>
|
||||||
|
<version>${system-rules.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.github.stefanbirkner</groupId>
|
||||||
|
<artifactId>system-lambda</artifactId>
|
||||||
|
<version>${system-lambda.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>testing-libraries</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/test/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<system-rules.version>1.19.0</system-rules.version>
|
||||||
|
<system-lambda.version>1.0.0</system-lambda.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.systemrules;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.contrib.java.lang.system.ClearSystemProperties;
|
||||||
|
|
||||||
|
public class ClearSystemPropertiesWithRuleUnitTest {
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public final ClearSystemProperties userNameIsClearedRule = new ClearSystemProperties("user.name");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenClearUsernameProperty_whenGetUserName_thenNull() {
|
||||||
|
assertNull(System.getProperty("user.name"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.systemrules;
|
||||||
|
|
||||||
|
import static com.github.stefanbirkner.systemlambda.SystemLambda.restoreSystemProperties;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class ProvidesSystemPropertyUnitTest {
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void setUpBeforeClass() throws Exception {
|
||||||
|
System.setProperty("log_dir", "/tmp/baeldung/logs");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenSetSystemProperty_whenGetLogDir_thenLogDirIsProvidedSuccessfully() throws Exception {
|
||||||
|
restoreSystemProperties(() -> {
|
||||||
|
System.setProperty("log_dir", "test/resources");
|
||||||
|
assertEquals("log_dir should be provided", "test/resources", System.getProperty("log_dir"));
|
||||||
|
});
|
||||||
|
|
||||||
|
assertEquals("log_dir should be provided", "/tmp/baeldung/logs", System.getProperty("log_dir"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,44 @@
|
||||||
|
package com.baeldung.systemrules;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.AfterClass;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.contrib.java.lang.system.ProvideSystemProperty;
|
||||||
|
|
||||||
|
public class ProvidesSystemPropertyWithRuleUnitTest {
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public final ProvideSystemProperty providesSystemPropertyRule = new ProvideSystemProperty("log_dir", "test/resources").and("another_property", "another_value");
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public final ProvideSystemProperty providesSystemPropertyFromFileRule = ProvideSystemProperty.fromResource("/test.properties");
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setUpBeforeClass() {
|
||||||
|
setLogs();
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterClass
|
||||||
|
public static void tearDownAfterClass() throws Exception {
|
||||||
|
System.out.println(System.getProperty("log_dir"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenProvideSystemProperty_whenGetLogDir_thenLogDirIsProvidedSuccessfully() {
|
||||||
|
assertEquals("log_dir should be provided", "test/resources", System.getProperty("log_dir"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenProvideSystemPropertyFromFile_whenGetName_thenNameIsProvidedSuccessfully() {
|
||||||
|
assertEquals("name should be provided", "baeldung", System.getProperty("name"));
|
||||||
|
assertEquals("version should be provided", "1.0", System.getProperty("version"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void setLogs() {
|
||||||
|
System.setProperty("log_dir", "/tmp/baeldung/logs");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
package com.baeldung.systemrules;
|
||||||
|
|
||||||
|
import static com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemErr;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class SystemErrPrintlnUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTapSystemErr_whenInvokePrintln_thenOutputIsReturnedSuccessfully() throws Exception {
|
||||||
|
|
||||||
|
String text = tapSystemErr(() -> {
|
||||||
|
printError("An error occurred Baeldung Readers!!");
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.assertEquals("An error occurred Baeldung Readers!!", text.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void printError(String output) {
|
||||||
|
System.err.println(output);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.systemrules;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.contrib.java.lang.system.SystemErrRule;
|
||||||
|
|
||||||
|
public class SystemErrPrintlnWithRuleUnitTest {
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public final SystemErrRule systemErrRule = new SystemErrRule().enableLog();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSystemErrRule_whenInvokePrintln_thenLogSuccess() {
|
||||||
|
printError("An Error occurred Baeldung Readers!!");
|
||||||
|
|
||||||
|
Assert.assertEquals("An Error occurred Baeldung Readers!!", systemErrRule.getLog()
|
||||||
|
.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void printError(String output) {
|
||||||
|
System.err.println(output);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
package com.baeldung.systemrules;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import static com.github.stefanbirkner.systemlambda.SystemLambda.catchSystemExit;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class SystemExitUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenCatchSystemExit_whenAppCallsSystemExit_thenStatusIsReturnedSuccessfully() throws Exception {
|
||||||
|
int statusCode = catchSystemExit(() -> {
|
||||||
|
exit();
|
||||||
|
});
|
||||||
|
assertEquals("status code should be 1:", 1, statusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void exit() {
|
||||||
|
System.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
package com.baeldung.systemrules;
|
||||||
|
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.contrib.java.lang.system.ExpectedSystemExit;
|
||||||
|
|
||||||
|
public class SystemExitWithRuleUnitTest {
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public final ExpectedSystemExit exitRule = ExpectedSystemExit.none();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSystemExitRule_whenAppCallsSystemExit_thenExitRuleWorkssAsExpected() {
|
||||||
|
exitRule.expectSystemExitWithStatus(1);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void exit() {
|
||||||
|
System.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.systemrules;
|
||||||
|
|
||||||
|
import static com.github.stefanbirkner.systemlambda.SystemLambda.withTextFromSystemIn;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class SystemInUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTwoNames_whenSystemInMock_thenNamesJoinedTogether() throws Exception {
|
||||||
|
withTextFromSystemIn("Jonathan", "Cook").execute(() -> {
|
||||||
|
assertEquals("Names should be concatenated", "Jonathan Cook", getFullname());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getFullname() {
|
||||||
|
try (Scanner scanner = new Scanner(System.in)) {
|
||||||
|
String firstName = scanner.next();
|
||||||
|
String surname = scanner.next();
|
||||||
|
return String.join(" ", firstName, surname);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
package com.baeldung.systemrules;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.contrib.java.lang.system.TextFromStandardInputStream;
|
||||||
|
import static org.junit.contrib.java.lang.system.TextFromStandardInputStream.emptyStandardInputStream;
|
||||||
|
|
||||||
|
public class SystemInWithRuleUnitTest {
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public final TextFromStandardInputStream systemInMock = emptyStandardInputStream();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoNames_whenSystemInMock_thenNamesJoinedTogether() {
|
||||||
|
systemInMock.provideLines("Jonathan", "Cook");
|
||||||
|
assertEquals("Names should be concatenated", "Jonathan Cook", getFullname());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getFullname() {
|
||||||
|
try (Scanner scanner = new Scanner(System.in)) {
|
||||||
|
String firstName = scanner.next();
|
||||||
|
String surname = scanner.next();
|
||||||
|
return String.join(" ", firstName, surname);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,2 @@
|
||||||
|
name=baeldung
|
||||||
|
version=1.0
|
Loading…
Reference in New Issue