commit
0b892bcd3c
|
@ -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");
|
||||
}
|
||||
}
|
|
@ -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
|
|
@ -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;
|
3
pom.xml
3
pom.xml
|
@ -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")
|
||||
|
|
|
@ -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;
|
|
@ -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
|
|
@ -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;
|
|
@ -0,0 +1,97 @@
|
|||
package org.baeldung.repository;
|
||||
|
||||
import org.baeldung.boot.Application;
|
||||
import org.baeldung.model.User;
|
||||
import org.junit.After;
|
||||
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.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
public class UserRepositoryTest {
|
||||
|
||||
private final String USER_NAME_ADAM = "Adam";
|
||||
private final Integer ACTIVE_STATUS = 1;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Test
|
||||
public void shouldReturnEmptyOptionalWhenSearchByNameInEmptyDB() {
|
||||
Optional<User> foundUser = userRepository.findOneByName(USER_NAME_ADAM);
|
||||
|
||||
assertThat(foundUser.isPresent(), equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnOptionalWithPresentUserWhenExistsWithGivenName() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
userRepository.save(user);
|
||||
|
||||
Optional<User> foundUser = userRepository.findOneByName(USER_NAME_ADAM);
|
||||
|
||||
assertThat(foundUser.isPresent(), equalTo(true));
|
||||
assertThat(foundUser.get()
|
||||
.getName(), equalTo(USER_NAME_ADAM));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void shouldReturnStreamOfUsersWithNameWhenExistWithSameGivenName() {
|
||||
User user1 = new User();
|
||||
user1.setName(USER_NAME_ADAM);
|
||||
userRepository.save(user1);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_ADAM);
|
||||
userRepository.save(user2);
|
||||
|
||||
User user3 = new User();
|
||||
user3.setName(USER_NAME_ADAM);
|
||||
userRepository.save(user3);
|
||||
|
||||
User user4 = new User();
|
||||
user4.setName("SAMPLE");
|
||||
userRepository.save(user4);
|
||||
|
||||
try (Stream<User> foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) {
|
||||
assertThat(foundUsersStream.count(), equalTo(3l));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnUserWithGivenStatusAsync() throws ExecutionException, InterruptedException {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
CompletableFuture<User> userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS);
|
||||
|
||||
assertThat(userByStatus.get()
|
||||
.getName(), equalTo(USER_NAME_ADAM));
|
||||
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanUp() {
|
||||
userRepository.deleteAll();
|
||||
}
|
||||
|
||||
}
|
|
@ -69,10 +69,30 @@
|
|||
|
||||
<build>
|
||||
<finalName>spring-rest-embedded-tomcat</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<forkCount>3</forkCount>
|
||||
<reuseForks>true</reuseForks>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
<exclude>**/JdbcTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<spring.version>5.0.1.RELEASE</spring.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<jackson.library>2.9.2</jackson.library>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
|
|
|
@ -15,86 +15,96 @@ import io.vavr.control.Option;
|
|||
import io.vavr.control.Try;
|
||||
|
||||
public class FutureTest {
|
||||
|
||||
private static final String error = "Failed to get underlying value.";
|
||||
|
||||
@Test
|
||||
public void whenChangeExecutorService_thenCorrect() {
|
||||
public void whenChangeExecutorService_thenCorrect() throws InterruptedException {
|
||||
String initialValue = "Welcome to ";
|
||||
Future<String> resultFuture = Future.of(
|
||||
Executors.newSingleThreadExecutor(),
|
||||
() -> Util.appendData(initialValue));
|
||||
String result = resultFuture.get();
|
||||
Thread.sleep(20);
|
||||
String result = resultFuture.getOrElse(error);
|
||||
|
||||
assertThat(result).isEqualTo("Welcome to Baeldung!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendData_thenCorrect1() {
|
||||
public void whenAppendData_thenCorrect1() throws InterruptedException {
|
||||
String initialValue = "Welcome to ";
|
||||
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue));
|
||||
String result = resultFuture.get();
|
||||
Thread.sleep(20);
|
||||
String result = resultFuture.getOrElse(new String(error));
|
||||
|
||||
assertThat(result).isEqualTo("Welcome to Baeldung!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendData_thenCorrect2() {
|
||||
public void whenAppendData_thenCorrect2() throws InterruptedException {
|
||||
String initialValue = "Welcome to ";
|
||||
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue));
|
||||
Thread.sleep(20);
|
||||
resultFuture.await();
|
||||
Option<Try<String>> futureOption = resultFuture.getValue();
|
||||
Try<String> futureTry = futureOption.get();
|
||||
String result = futureTry.get();
|
||||
String result = futureTry.getOrElse(error);
|
||||
|
||||
assertThat(result).isEqualTo("Welcome to Baeldung!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendData_thenSuccess() {
|
||||
public void whenAppendData_thenSuccess() throws InterruptedException {
|
||||
String initialValue = "Welcome to ";
|
||||
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue))
|
||||
.onSuccess(finalResult -> System.out.println("Successfully Completed - Result: " + finalResult))
|
||||
.onFailure(finalResult -> System.out.println("Failed - Result: " + finalResult));
|
||||
String result = resultFuture.get();
|
||||
Thread.sleep(20);
|
||||
String result = resultFuture.getOrElse(error);
|
||||
|
||||
assertThat(result).isEqualTo("Welcome to Baeldung!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenChainingCallbacks_thenCorrect() {
|
||||
public void whenChainingCallbacks_thenCorrect() throws InterruptedException {
|
||||
String initialValue = "Welcome to ";
|
||||
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue))
|
||||
.andThen(finalResult -> System.out.println("Completed - 1: " + finalResult))
|
||||
.andThen(finalResult -> System.out.println("Completed - 2: " + finalResult));
|
||||
String result = resultFuture.get();
|
||||
Thread.sleep(20);
|
||||
String result = resultFuture.getOrElse(error);
|
||||
|
||||
assertThat(result).isEqualTo("Welcome to Baeldung!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCallAwait_thenCorrect() {
|
||||
public void whenCallAwait_thenCorrect() throws InterruptedException {
|
||||
String initialValue = "Welcome to ";
|
||||
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue));
|
||||
Thread.sleep(20);
|
||||
resultFuture = resultFuture.await();
|
||||
String result = resultFuture.get();
|
||||
String result = resultFuture.getOrElse(error);
|
||||
|
||||
assertThat(result).isEqualTo("Welcome to Baeldung!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivideByZero_thenGetThrowable1() {
|
||||
public void whenDivideByZero_thenGetThrowable1() throws InterruptedException {
|
||||
Future<Integer> resultFuture = Future.of(() -> Util.divideByZero(10));
|
||||
Thread.sleep(20);
|
||||
Future<Throwable> throwableFuture = resultFuture.failed();
|
||||
Throwable throwable = throwableFuture.get();
|
||||
Throwable throwable = throwableFuture.getOrElse(new Throwable());
|
||||
|
||||
assertThat(throwable.getMessage()).isEqualTo("/ by zero");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivideByZero_thenGetThrowable2() {
|
||||
public void whenDivideByZero_thenGetThrowable2() throws InterruptedException {
|
||||
Future<Integer> resultFuture = Future.of(() -> Util.divideByZero(10));
|
||||
Thread.sleep(20);
|
||||
resultFuture.await();
|
||||
Option<Throwable> throwableOption = resultFuture.getCause();
|
||||
Throwable throwable = throwableOption.get();
|
||||
Throwable throwable = throwableOption.getOrElse(new Throwable());
|
||||
|
||||
assertThat(throwable.getMessage()).isEqualTo("/ by zero");
|
||||
}
|
||||
|
@ -102,6 +112,7 @@ public class FutureTest {
|
|||
@Test
|
||||
public void whenDivideByZero_thenCorrect() throws InterruptedException {
|
||||
Future<Integer> resultFuture = Future.of(() -> Util.divideByZero(10));
|
||||
Thread.sleep(20);
|
||||
resultFuture.await();
|
||||
|
||||
assertThat(resultFuture.isCompleted()).isTrue();
|
||||
|
@ -110,68 +121,76 @@ public class FutureTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendData_thenFutureNotEmpty() {
|
||||
public void whenAppendData_thenFutureNotEmpty() throws InterruptedException {
|
||||
String initialValue = "Welcome to ";
|
||||
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue));
|
||||
Thread.sleep(20);
|
||||
resultFuture.await();
|
||||
|
||||
assertThat(resultFuture.isEmpty()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCallZip_thenCorrect() {
|
||||
public void whenCallZip_thenCorrect() throws InterruptedException {
|
||||
Future<Tuple2<String, Integer>> future = Future.of(() -> "John")
|
||||
.zip(Future.of(() -> new Integer(5)));
|
||||
Thread.sleep(20);
|
||||
future.await();
|
||||
|
||||
assertThat(future.get()).isEqualTo(Tuple.of("John", new Integer(5)));
|
||||
assertThat(future.getOrElse(new Tuple2<String, Integer>(error, 0)))
|
||||
.isEqualTo(Tuple.of("John", new Integer(5)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertToCompletableFuture_thenCorrect() throws InterruptedException, ExecutionException {
|
||||
String initialValue = "Welcome to ";
|
||||
Future<String> resultFuture = Future.of(() -> Util.appendData(initialValue));
|
||||
Thread.sleep(20);
|
||||
CompletableFuture<String> convertedFuture = resultFuture.toCompletableFuture();
|
||||
|
||||
assertThat(convertedFuture.get()).isEqualTo("Welcome to Baeldung!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCallMap_thenCorrect() {
|
||||
public void whenCallMap_thenCorrect() throws InterruptedException {
|
||||
Future<String> futureResult = Future.of(() -> new StringBuilder("from Baeldung"))
|
||||
.map(a -> "Hello " + a);
|
||||
Thread.sleep(20);
|
||||
futureResult.await();
|
||||
|
||||
assertThat(futureResult.get()).isEqualTo("Hello from Baeldung");
|
||||
assertThat(futureResult.getOrElse(error)).isEqualTo("Hello from Baeldung");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFutureFails_thenGetErrorMessage() {
|
||||
public void whenFutureFails_thenGetErrorMessage() throws InterruptedException {
|
||||
Future<String> resultFuture = Future.of(() -> Util.getSubstringMinusOne("Hello"));
|
||||
Thread.sleep(20);
|
||||
Future<String> errorMessageFuture = resultFuture.recover(Throwable::getMessage);
|
||||
String errorMessage = errorMessageFuture.get();
|
||||
String errorMessage = errorMessageFuture.getOrElse(error);
|
||||
|
||||
assertThat(errorMessage).isEqualTo("String index out of range: -1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFutureFails_thenGetAnotherFuture() {
|
||||
public void whenFutureFails_thenGetAnotherFuture() throws InterruptedException {
|
||||
Future<String> resultFuture = Future.of(() -> Util.getSubstringMinusOne("Hello"));
|
||||
Thread.sleep(20);
|
||||
Future<String> errorMessageFuture = resultFuture.recoverWith(a -> Future.of(a::getMessage));
|
||||
String errorMessage = errorMessageFuture.get();
|
||||
String errorMessage = errorMessageFuture.getOrElse(error);
|
||||
|
||||
assertThat(errorMessage).isEqualTo("String index out of range: -1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBothFuturesFail_thenGetErrorMessage() {
|
||||
public void whenBothFuturesFail_thenGetErrorMessage() throws InterruptedException {
|
||||
Future<String> future1 = Future.of(() -> Util.getSubstringMinusOne("Hello"));
|
||||
Future<String> future2 = Future.of(() -> Util.getSubstringMinusTwo("Hello"));
|
||||
Thread.sleep(20);
|
||||
Future<String> errorMessageFuture = future1.fallbackTo(future2);
|
||||
Future<Throwable> errorMessage = errorMessageFuture.failed();
|
||||
|
||||
assertThat(
|
||||
errorMessage.get().getMessage())
|
||||
errorMessage.getOrElse(new Throwable()).getMessage())
|
||||
.isEqualTo("String index out of range: -1");
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue