Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2018-01-03 22:10:28 +02:00
commit 172cd46585
32 changed files with 972 additions and 49 deletions

View File

@ -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");
}
}

View File

@ -2,10 +2,10 @@
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>core-java9</artifactId>
<artifactId>core-java-9</artifactId>
<version>0.2-SNAPSHOT</version>
<name>core-java9</name>
<name>core-java-9</name>
<pluginRepositories>
<pluginRepository>

View File

@ -0,0 +1,63 @@
package com.baeldung.threadlocalrandom;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ThreadLocalRandomTest {
@Test
public void givenUsingThreadLocalRandom_whenGeneratingRandomIntBounded_thenCorrect() {
int leftLimit = 1;
int rightLimit = 100;
int generatedInt = ThreadLocalRandom.current().nextInt(leftLimit, rightLimit);
assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit);
}
@Test
public void givenUsingThreadLocalRandom_whenGeneratingRandomIntUnbounded_thenCorrect() {
int generatedInt = ThreadLocalRandom.current().nextInt();
assertTrue(generatedInt < Integer.MAX_VALUE && generatedInt >= Integer.MIN_VALUE);
}
@Test
public void givenUsingThreadLocalRandom_whenGeneratingRandomLongBounded_thenCorrect() {
long leftLimit = 1L;
long rightLimit = 100L;
long generatedLong = ThreadLocalRandom.current().nextLong(leftLimit, rightLimit);
assertTrue(generatedLong < rightLimit && generatedLong >= leftLimit);
}
@Test
public void givenUsingThreadLocalRandom_whenGeneratingRandomLongUnbounded_thenCorrect() {
long generatedInt = ThreadLocalRandom.current().nextLong();
assertTrue(generatedInt < Long.MAX_VALUE && generatedInt >= Long.MIN_VALUE);
}
@Test
public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleBounded_thenCorrect() {
double leftLimit = 1D;
double rightLimit = 100D;
double generatedInt = ThreadLocalRandom.current().nextDouble(leftLimit, rightLimit);
assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit);
}
@Test
public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
double generatedInt = ThreadLocalRandom.current().nextDouble();
assertTrue(generatedInt < Double.MAX_VALUE && generatedInt >= Double.MIN_VALUE);
}
@Test(expected = UnsupportedOperationException.class)
public void givenUsingThreadLocalRandom_whenSettingSeed_thenThrowUnsupportedOperationException() {
ThreadLocalRandom.current().setSeed(0l);
}
}

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

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>

View File

@ -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);

View File

@ -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;

View File

@ -0,0 +1,39 @@
package com.baeldung.hibernate.bootstrap;
import com.baeldung.hibernate.bootstrap.model.TestEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class BarHibernateDAO {
@Autowired
private SessionFactory sessionFactory;
public TestEntity findEntity(int id) {
return getCurrentSession().find(TestEntity.class, 1);
}
public void createEntity(TestEntity entity) {
getCurrentSession().save(entity);
}
public void createEntity(int id, String newDescription) {
TestEntity entity = findEntity(id);
entity.setDescription(newDescription);
getCurrentSession().save(entity);
}
public void deleteEntity(int id) {
TestEntity entity = findEntity(id);
getCurrentSession().delete(entity);
}
protected Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.hibernate.bootstrap;
import com.google.common.base.Preconditions;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
public class HibernateConf {
@Autowired
private Environment env;
@Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.bootstrap.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource dataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
return hibernateProperties;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.hibernate.bootstrap;
import com.google.common.base.Preconditions;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
@ImportResource({ "classpath:hibernate5Configuration.xml" })
public class HibernateXMLConf {
}

View File

@ -0,0 +1,29 @@
package com.baeldung.hibernate.bootstrap.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class TestEntity {
private int id;
private String description;
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:persistence-h2.properties"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.baeldung.hibernate.bootstrap.model"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.pass}"/>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>

View File

@ -2,6 +2,7 @@
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.eventGeneratedId=sa
jdbc.user=sa
jdbc.pass=sa
# hibernate.X

View File

@ -0,0 +1,38 @@
package com.baeldung.hibernate.bootstrap;
import com.baeldung.hibernate.bootstrap.model.TestEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { HibernateConf.class })
@Transactional
public class HibernateBootstrapIntegrationTest {
@Autowired
private SessionFactory sessionFactory;
@Test
public void whenBootstrapHibernateSession_thenNoException() {
Session session = sessionFactory.getCurrentSession();
TestEntity newEntity = new TestEntity();
newEntity.setId(1);
session.save(newEntity);
TestEntity searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.hibernate.bootstrap;
import com.baeldung.hibernate.bootstrap.model.TestEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { HibernateXMLConf.class })
@Transactional
public class HibernateXMLBootstrapIntegrationTest {
@Autowired
private SessionFactory sessionFactory;
@Test
public void whenBootstrapHibernateSession_thenNoException() {
Session session = sessionFactory.getCurrentSession();
TestEntity newEntity = new TestEntity();
newEntity.setId(1);
session.save(newEntity);
TestEntity searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
}
}

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>

View File

@ -194,6 +194,7 @@ public class SchedulersLiveTest {
}
@Test
@Ignore
public void givenObservable_whenComputationScheduling_thenReturnThreadName() throws InterruptedException {
System.out.println("computation");
Observable.just("computation")

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

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>

View File

@ -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);
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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

View File

@ -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>

View File

@ -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"));
}
}

View File

@ -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;
}
}

View File

@ -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);
}

View File

@ -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;

View File

@ -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;

View File

@ -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();
}
}

View File

@ -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>

View File

@ -16,85 +16,95 @@ 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");
}
}