Merge pull request #2 from eugenp/master

Update
This commit is contained in:
markusgulden
2018-01-02 15:09:57 +01:00
committed by GitHub
33 changed files with 834 additions and 55 deletions
@@ -0,0 +1,101 @@
package com.baeldung.stringjoiner;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import org.junit.Test;
public class StringJoinerUnitTest {
private final String DELIMITER_COMMA = ",";
private final String DELIMITER_HYPHEN = "-";
private final String PREFIX = "[";
private final String SUFFIX = "]";
private final String EMPTY_JOINER = "empty";
@Test
public void whenJoinerWithoutPrefixSuffixWithoutEmptyValue_thenReturnDefault() {
StringJoiner commaSeparatedJoiner = new StringJoiner(DELIMITER_COMMA);
assertEquals(0, commaSeparatedJoiner.toString().length());
}
@Test
public void whenJoinerWithPrefixSuffixWithoutEmptyValue_thenReturnDefault() {
StringJoiner commaSeparatedPrefixSuffixJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
assertEquals(commaSeparatedPrefixSuffixJoiner.toString(), PREFIX + SUFFIX);
}
@Test
public void whenJoinerWithoutPrefixSuffixWithEmptyValue_thenReturnDefault() {
StringJoiner commaSeparatedJoiner = new StringJoiner(DELIMITER_COMMA);
commaSeparatedJoiner.setEmptyValue(EMPTY_JOINER);
assertEquals(commaSeparatedJoiner.toString(), EMPTY_JOINER);
}
@Test
public void whenJoinerWithPrefixSuffixWithEmptyValue_thenReturnDefault() {
StringJoiner commaSeparatedPrefixSuffixJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
commaSeparatedPrefixSuffixJoiner.setEmptyValue(EMPTY_JOINER);
assertEquals(commaSeparatedPrefixSuffixJoiner.toString(), EMPTY_JOINER);
}
@Test
public void whenAddElements_thenJoinElements() {
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
rgbJoiner.add("Red")
.add("Green")
.add("Blue");
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
}
@Test
public void whenAddListElements_thenJoinListElements() {
List<String> rgbList = new ArrayList<String>();
rgbList.add("Red");
rgbList.add("Green");
rgbList.add("Blue");
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
for (String color : rgbList) {
rgbJoiner.add(color);
}
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
}
@Test
public void whenMergeJoiners_thenReturnMerged() {
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
StringJoiner cmybJoiner = new StringJoiner(DELIMITER_HYPHEN, PREFIX, SUFFIX);
rgbJoiner.add("Red")
.add("Green")
.add("Blue");
cmybJoiner.add("Cyan")
.add("Magenta")
.add("Yellow")
.add("Black");
rgbJoiner.merge(cmybJoiner);
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue,Cyan-Magenta-Yellow-Black]");
}
@Test
public void whenUsedWithinCollectors_thenJoin() {
List<String> rgbList = Arrays.asList("Red", "Green", "Blue");
String commaSeparatedRGB = rgbList.stream()
.map(color -> color.toString())
.collect(Collectors.joining(","));
assertEquals(commaSeparatedRGB, "Red,Green,Blue");
}
}
+3 -3
View File
@@ -1,5 +1,5 @@
flyway.user=root
flyway.password=mysql
flyway.user=sa
flyway.password=
flyway.schemas=app-db
flyway.url=jdbc:mysql://localhost:3306/
flyway.url=jdbc:h2:mem:DATABASE
flyway.locations=filesystem:db/migration
+7 -1
View File
@@ -58,6 +58,13 @@
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>5.0.2</version>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
@@ -66,5 +73,4 @@
</plugins>
</build>
</project>
@@ -8,12 +8,15 @@ import java.util.Properties;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.junit.Assert;
@SuppressWarnings("serial")
public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider {
private final ConnectionProvider connectionProvider = initConnectionProvider();
private final ConnectionProvider connectionProvider;
public SchemaMultiTenantConnectionProvider() throws IOException {
connectionProvider = initConnectionProvider();
}
@Override
protected ConnectionProvider getAnyConnectionProvider() {
@@ -33,13 +36,9 @@ public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConn
return connection;
}
private ConnectionProvider initConnectionProvider() {
private ConnectionProvider initConnectionProvider() throws IOException {
Properties properties = new Properties();
try {
properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties"));
} catch (IOException e) {
Assert.fail("Error loading resource. Cause: " + e.getMessage());
}
properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties"));
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
connectionProvider.configure(properties);
@@ -14,13 +14,10 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.notNullValue;
/**
* Created by adam.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
public class PersonsRepositoryTest {
public class PersonsRepositoryIntegrationTest {
@Autowired
private PersonsRepository personsRepository;
+2 -1
View File
@@ -152,6 +152,8 @@
<module>spring-boot</module>
<module>spring-boot-keycloak</module>
<module>spring-boot-bootstrap</module>
<module>spring-boot-admin</module>
<module>spring-boot-security</module>
<module>spring-cloud-data-flow</module>
<module>spring-cloud</module>
<module>spring-core</module>
@@ -263,7 +265,6 @@
<module>vertx-and-rxjava</module>
<module>saas</module>
<module>deeplearning4j</module>
<module>spring-boot-admin</module>
<module>lucene</module>
<module>vraptor</module>
</modules>
@@ -194,6 +194,7 @@ public class SchedulersLiveTest {
}
@Test
@Ignore
public void givenObservable_whenComputationScheduling_thenReturnThreadName() throws InterruptedException {
System.out.println("computation");
Observable.just("computation")
+1 -1
View File
@@ -28,7 +28,7 @@
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -1,4 +1,4 @@
package com.baeldung.web;
package com.baeldung.reactive.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -0,0 +1,23 @@
package com.baeldung.reactive.urlmatch;
class Actor {
private String firstname;
private String lastname;
public Actor() {
}
public Actor(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
}
@@ -1,4 +1,4 @@
package com.baeldung.functional;
package com.baeldung.reactive.urlmatch;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
@@ -0,0 +1,41 @@
package com.baeldung.reactive.urlmatch;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers;
import static org.springframework.web.reactive.function.BodyExtractors.toFormData;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
public class FormHandler {
Mono<ServerResponse> handleLogin(ServerRequest request) {
return request.body(toFormData())
.map(MultiValueMap::toSingleValueMap)
.filter(formData -> "baeldung".equals(formData.get("user")))
.filter(formData -> "you_know_what_to_do".equals(formData.get("token")))
.flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class))
.switchIfEmpty(ServerResponse.badRequest()
.build());
}
Mono<ServerResponse> handleUpload(ServerRequest request) {
return request.body(toDataBuffers())
.collectList()
.flatMap(dataBuffers -> ok().body(fromObject(extractData(dataBuffers).toString())));
}
private AtomicLong extractData(List<DataBuffer> dataBuffers) {
AtomicLong atomicLong = new AtomicLong(0);
dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
.array().length));
return atomicLong;
}
}
@@ -0,0 +1,80 @@
package com.baeldung.reactive.urlmatch;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
import static org.springframework.web.reactive.function.server.RequestPredicates.path;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
import org.springframework.boot.web.server.WebServer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ServletHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.WebHandler;
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
import reactor.core.publisher.Flux;
public class FunctionalWebApplication {
private static final Actor BRAD_PITT = new Actor("Brad", "Pitt");
private static final Actor TOM_HANKS = new Actor("Tom", "Hanks");
private static final List<Actor> actors = new CopyOnWriteArrayList<>(Arrays.asList(BRAD_PITT, TOM_HANKS));
private RouterFunction<ServerResponse> routingFunction() {
FormHandler formHandler = new FormHandler();
RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
.doOnNext(actors::add)
.then(ok().build()));
return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin)
.andRoute(POST("/upload"), formHandler::handleUpload)
.and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
.andNest(path("/actor"), restfulRouter)
.filter((request, next) -> {
System.out.println("Before handler invocation: " + request.path());
return next.handle(request);
});
}
WebServer start() throws Exception {
WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
.filter(new IndexRewriteFilter())
.build();
Tomcat tomcat = new Tomcat();
tomcat.setHostname("localhost");
tomcat.setPort(9090);
Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
rootContext.addServletMappingDecoded("/", "httpHandlerServlet");
TomcatWebServer server = new TomcatWebServer(tomcat);
server.start();
return server;
}
public static void main(String[] args) {
try {
new FunctionalWebApplication().start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,27 @@
package com.baeldung.reactive.urlmatch;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
class IndexRewriteFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
ServerHttpRequest request = serverWebExchange.getRequest();
if (request.getURI()
.getPath()
.equals("/")) {
return webFilterChain.filter(serverWebExchange.mutate()
.request(builder -> builder.method(request.getMethod())
.contextPath(request.getPath()
.toString())
.path("/test"))
.build());
}
return webFilterChain.filter(serverWebExchange);
}
}
@@ -0,0 +1 @@
hello
@@ -0,0 +1 @@
test
@@ -1,4 +1,4 @@
package com.baeldung.functional;
package com.baeldung.reactive.urlmatch;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@@ -6,7 +6,9 @@ import org.junit.Test;
import org.springframework.boot.web.server.WebServer;
import org.springframework.test.web.reactive.server.WebTestClient;
public class ExploreSpring5URLPatternUsingRouterFunctionsTest {
import com.baeldung.reactive.urlmatch.ExploreSpring5URLPatternUsingRouterFunctions;
public class ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest {
private static WebTestClient client;
private static WebServer server;
@@ -1,6 +1,5 @@
package com.baeldung.web;
package com.baeldung.reactive.urlmatch;
import com.baeldung.Spring5Application;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -8,8 +7,11 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import com.baeldung.reactive.Spring5ReactiveApplication;
import com.baeldung.reactive.controller.PathPatternController;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Spring5Application.class)
@SpringBootTest(classes = Spring5ReactiveApplication.class)
public class PathPatternsUsingHandlerMethodIntegrationTest {
private static WebTestClient client;
+6
View File
@@ -0,0 +1,6 @@
### Spring Boot Security Auto-Configuration
- mvn clean install
- uncomment in application.properties spring.profiles.active=basic # for basic auth config
- uncomment in application.properties spring.profiles.active=form # for form based auth config
- uncomment actuator dependency simultaneously with the line from main class
+73
View File
@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>
<groupId>com.baeldung</groupId>
<artifactId>spring-boot-security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-security</name>
<description>Spring Boot Security Auto-Configuration</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.9.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-actuator</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,16 @@
package com.baeldung.springbootsecurity;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
@SpringBootApplication(exclude = {
SecurityAutoConfiguration.class
// ,ManagementWebSecurityAutoConfiguration.class
})
public class SpringBootSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSecurityApplication.class, args);
}
}
@@ -0,0 +1,37 @@
package com.baeldung.springbootsecurity.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
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;
@Configuration
@EnableWebSecurity
@Profile("basic")
public class BasicConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER")
.and()
.withUser("admin")
.password("admin")
.roles("USER", "ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
}
@@ -0,0 +1,39 @@
package com.baeldung.springbootsecurity.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
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;
@Configuration
@EnableWebSecurity
@Profile("form")
public class FormLoginConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER")
.and()
.withUser("admin")
.password("password")
.roles("USER", "ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
}
@@ -0,0 +1,4 @@
#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
#spring.profiles.active=form
#spring.profiles.active=basic
#security.user.password=password
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
Welcome to Baeldung Secured Page !!!
</body>
</html>
@@ -0,0 +1,56 @@
package com.baeldung.springbootsecurity;
import org.junit.Before;
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.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
@ActiveProfiles("basic")
public class BasicConfigurationIntegrationTest {
TestRestTemplate restTemplate;
URL base;
@LocalServerPort int port;
@Before
public void setUp() throws MalformedURLException {
restTemplate = new TestRestTemplate("user", "password");
base = new URL("http://localhost:" + port);
}
@Test
public void whenLoggedUserRequestsHomePage_ThenSuccess() throws IllegalStateException, IOException {
ResponseEntity<String> response = restTemplate.getForEntity(base.toString(), String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(response
.getBody()
.contains("Baeldung"));
}
@Test
public void whenUserWithWrongCredentialsRequestsHomePage_ThenUnauthorizedPage() throws IllegalStateException, IOException {
restTemplate = new TestRestTemplate("user", "wrongpassword");
ResponseEntity<String> response = restTemplate.getForEntity(base.toString(), String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
assertTrue(response
.getBody()
.contains("Unauthorized"));
}
}
@@ -0,0 +1,106 @@
package com.baeldung.springbootsecurity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.*;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
@ActiveProfiles("form")
public class FormConfigurationIntegrationTest {
@Autowired TestRestTemplate restTemplate;
@LocalServerPort int port;
@Test
public void whenLoginPageIsRequested_ThenSuccess() {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
ResponseEntity<String> responseEntity = restTemplate.exchange("/login", HttpMethod.GET, new HttpEntity<Void>(httpHeaders), String.class);
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertTrue(responseEntity
.getBody()
.contains("_csrf"));
}
@Test
public void whenTryingToLoginWithCorrectCredentials_ThenAuthenticateWithSuccess() {
HttpHeaders httpHeaders = getHeaders();
httpHeaders.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> form = getFormSubmitCorrectCredentials();
ResponseEntity<String> responseEntity = this.restTemplate.exchange("/login", HttpMethod.POST, new HttpEntity<>(form, httpHeaders), String.class);
assertEquals(responseEntity.getStatusCode(), HttpStatus.FOUND);
assertTrue(responseEntity
.getHeaders()
.getLocation()
.toString()
.endsWith(this.port + "/"));
assertNotNull(responseEntity
.getHeaders()
.get("Set-Cookie"));
}
@Test
public void whenTryingToLoginWithInorrectCredentials_ThenAuthenticationFailed() {
HttpHeaders httpHeaders = getHeaders();
httpHeaders.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> form = getFormSubmitIncorrectCredentials();
ResponseEntity<String> responseEntity = this.restTemplate.exchange("/login", HttpMethod.POST, new HttpEntity<>(form, httpHeaders), String.class);
assertEquals(responseEntity.getStatusCode(), HttpStatus.FOUND);
assertTrue(responseEntity
.getHeaders()
.getLocation()
.toString()
.endsWith(this.port + "/login?error"));
assertNull(responseEntity
.getHeaders()
.get("Set-Cookie"));
}
private MultiValueMap<String, String> getFormSubmitCorrectCredentials() {
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
form.set("username", "user");
form.set("password", "password");
return form;
}
private MultiValueMap<String, String> getFormSubmitIncorrectCredentials() {
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
form.set("username", "user");
form.set("password", "wrongpassword");
return form;
}
private HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
ResponseEntity<String> page = this.restTemplate.getForEntity("/login", String.class);
assertEquals(page.getStatusCode(), HttpStatus.OK);
String cookie = page
.getHeaders()
.getFirst("Set-Cookie");
headers.set("Cookie", cookie);
Pattern pattern = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*");
Matcher matcher = pattern.matcher(page.getBody());
assertTrue(matcher.matches());
headers.set("X-CSRF-TOKEN", matcher.group(1));
return headers;
}
}
@@ -2,9 +2,23 @@ package org.baeldung.repository;
import org.baeldung.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
@Repository("userRepository")
public interface UserRepository extends JpaRepository<User, Integer> {
public int countByStatus(int status);
int countByStatus(int status);
Optional<User> findOneByName(String name);
Stream<User> findAllByName(String name);
@Async
CompletableFuture<User> findOneByStatus(Integer status);
}
@@ -19,7 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class CustomConverterTest {
public class CustomConverterIntegrationTest {
@Autowired
ConversionService conversionService;
@@ -19,7 +19,7 @@ import org.baeldung.boot.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class)
@AutoConfigureMockMvc
public class StringToEmployeeConverterControllerTest {
public class StringToEmployeeConverterControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;

Some files were not shown because too many files have changed in this diff Show More