diff --git a/core-java-8/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java b/core-java-8/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java new file mode 100644 index 0000000000..a72f811336 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java @@ -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 rgbList = new ArrayList(); + 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 rgbList = Arrays.asList("Red", "Green", "Blue"); + String commaSeparatedRGB = rgbList.stream() + .map(color -> color.toString()) + .collect(Collectors.joining(",")); + + assertEquals(commaSeparatedRGB, "Red,Green,Blue"); + } +} diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml index 6b82744954..0f43265916 100644 --- a/core-java-9/pom.xml +++ b/core-java-9/pom.xml @@ -2,10 +2,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - core-java9 + core-java-9 0.2-SNAPSHOT - core-java9 + core-java-9 diff --git a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java new file mode 100644 index 0000000000..c75813baba --- /dev/null +++ b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java @@ -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); + } + +} \ No newline at end of file diff --git a/flyway/myFlywayConfig.properties b/flyway/myFlywayConfig.properties index 8bb102930a..6b11f6f277 100644 --- a/flyway/myFlywayConfig.properties +++ b/flyway/myFlywayConfig.properties @@ -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 \ No newline at end of file diff --git a/flyway/pom.xml b/flyway/pom.xml index a090b9458e..84009e4579 100644 --- a/flyway/pom.xml +++ b/flyway/pom.xml @@ -58,6 +58,13 @@ org.flywaydb flyway-maven-plugin 5.0.2 + + + com.h2database + h2 + ${h2.version} + + org.springframework.boot @@ -66,5 +73,4 @@ - diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java b/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java index 5045c3ee8e..601eba651c 100644 --- a/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java +++ b/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java @@ -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); diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryIntegrationTest.java similarity index 95% rename from persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java rename to persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryIntegrationTest.java index 1a7c28df6c..636f91cf8e 100644 --- a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryTest.java +++ b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/PersonsRepositoryIntegrationTest.java @@ -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; diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java new file mode 100644 index 0000000000..5fc932b256 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java @@ -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(); + } +} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java new file mode 100644 index 0000000000..150e3778af --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java @@ -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; + } +} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java new file mode 100644 index 0000000000..b3e979478f --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java @@ -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 { + +} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java new file mode 100644 index 0000000000..cae41db831 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java @@ -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; + } +} diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/hibernate5Configuration.xml b/persistence-modules/spring-hibernate-5/src/main/resources/hibernate5Configuration.xml new file mode 100644 index 0000000000..cb6cf0aa5c --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/resources/hibernate5Configuration.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + ${hibernate.hbm2ddl.auto} + ${hibernate.dialect} + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties index 915bc4317b..0325174b67 100644 --- a/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties +++ b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties @@ -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 diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java new file mode 100644 index 0000000000..ffe82b7ced --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java @@ -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); + } + +} diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java new file mode 100644 index 0000000000..5b811ad576 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java @@ -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); + } + +} diff --git a/pom.xml b/pom.xml index 8906b1c8d2..19e42009c9 100644 --- a/pom.xml +++ b/pom.xml @@ -152,6 +152,8 @@ spring-boot spring-boot-keycloak spring-boot-bootstrap + spring-boot-admin + spring-boot-security spring-cloud-data-flow spring-cloud spring-core @@ -263,7 +265,6 @@ vertx-and-rxjava saas deeplearning4j - spring-boot-admin lucene vraptor diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java index 712f07324c..bc59f72fd9 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java @@ -194,6 +194,7 @@ public class SchedulersLiveTest { } @Test + @Ignore public void givenObservable_whenComputationScheduling_thenReturnThreadName() throws InterruptedException { System.out.println("computation"); Observable.just("computation") diff --git a/spring-boot-security/README.md b/spring-boot-security/README.md new file mode 100644 index 0000000000..26ab8b2337 --- /dev/null +++ b/spring-boot-security/README.md @@ -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 diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml new file mode 100644 index 0000000000..c35191a7fc --- /dev/null +++ b/spring-boot-security/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + + com.baeldung + spring-boot-security + 0.0.1-SNAPSHOT + jar + + spring-boot-security + Spring Boot Security Auto-Configuration + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-dependencies + 1.5.9.RELEASE + pom + import + + + + + + UTF-8 + UTF-8 + 1.8 + + + + + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/SpringBootSecurityApplication.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/SpringBootSecurityApplication.java new file mode 100644 index 0000000000..3a85da72e5 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/SpringBootSecurityApplication.java @@ -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); + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/config/BasicConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/config/BasicConfiguration.java new file mode 100644 index 0000000000..1b08e5ee22 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/config/BasicConfiguration.java @@ -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(); + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/config/FormLoginConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/config/FormLoginConfiguration.java new file mode 100644 index 0000000000..b4902a9ffc --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/config/FormLoginConfiguration.java @@ -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(); + } +} diff --git a/spring-boot-security/src/main/resources/application.properties b/spring-boot-security/src/main/resources/application.properties new file mode 100644 index 0000000000..6ca2edb175 --- /dev/null +++ b/spring-boot-security/src/main/resources/application.properties @@ -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 \ No newline at end of file diff --git a/spring-boot-security/src/main/resources/static/index.html b/spring-boot-security/src/main/resources/static/index.html new file mode 100644 index 0000000000..5e3506dde6 --- /dev/null +++ b/spring-boot-security/src/main/resources/static/index.html @@ -0,0 +1,10 @@ + + + + + Index + + +Welcome to Baeldung Secured Page !!! + + \ No newline at end of file diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/BasicConfigurationIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/BasicConfigurationIntegrationTest.java new file mode 100644 index 0000000000..63e1c2ac73 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/BasicConfigurationIntegrationTest.java @@ -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 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 response = restTemplate.getForEntity(base.toString(), String.class); + assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); + assertTrue(response + .getBody() + .contains("Unauthorized")); + } +} diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/FormConfigurationIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/FormConfigurationIntegrationTest.java new file mode 100644 index 0000000000..697a4f2868 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/FormConfigurationIntegrationTest.java @@ -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 responseEntity = restTemplate.exchange("/login", HttpMethod.GET, new HttpEntity(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 form = getFormSubmitCorrectCredentials(); + ResponseEntity 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 form = getFormSubmitIncorrectCredentials(); + ResponseEntity 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 getFormSubmitCorrectCredentials() { + MultiValueMap form = new LinkedMultiValueMap<>(); + form.set("username", "user"); + form.set("password", "password"); + return form; + } + + private MultiValueMap getFormSubmitIncorrectCredentials() { + MultiValueMap form = new LinkedMultiValueMap<>(); + form.set("username", "user"); + form.set("password", "wrongpassword"); + return form; + } + + private HttpHeaders getHeaders() { + HttpHeaders headers = new HttpHeaders(); + ResponseEntity 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; + } + +} diff --git a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java index 360dbf883c..c9a06b5bab 100644 --- a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java @@ -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 { - public int countByStatus(int status); + + int countByStatus(int status); + + Optional findOneByName(String name); + + Stream findAllByName(String name); + + @Async + CompletableFuture findOneByStatus(Integer status); + } diff --git a/spring-boot/src/test/java/org/baeldung/converter/CustomConverterTest.java b/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java similarity index 97% rename from spring-boot/src/test/java/org/baeldung/converter/CustomConverterTest.java rename to spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java index fb773fc44c..fc94fe7d7d 100644 --- a/spring-boot/src/test/java/org/baeldung/converter/CustomConverterTest.java +++ b/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java @@ -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; diff --git a/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerTest.java b/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java similarity index 95% rename from spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerTest.java rename to spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java index 06c3f740c2..3310eb9984 100644 --- a/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerTest.java +++ b/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java @@ -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; diff --git a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryTest.java b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryTest.java new file mode 100644 index 0000000000..227bb02db2 --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryTest.java @@ -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 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 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 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 userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS); + + assertThat(userByStatus.get() + .getName(), equalTo(USER_NAME_ADAM)); + + } + + @After + public void cleanUp() { + userRepository.deleteAll(); + } + +} diff --git a/spring-rest-embedded-tomcat/pom.xml b/spring-rest-embedded-tomcat/pom.xml index 554040e763..cee9933c0d 100644 --- a/spring-rest-embedded-tomcat/pom.xml +++ b/spring-rest-embedded-tomcat/pom.xml @@ -69,10 +69,30 @@ spring-rest-embedded-tomcat + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + + 5.0.1.RELEASE + 2.19.1 4.12 2.9.2 1.8 diff --git a/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java b/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java index 1f2a3761eb..dd678bcad0 100644 --- a/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java @@ -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 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 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 resultFuture = Future.of(() -> Util.appendData(initialValue)); + Thread.sleep(20); resultFuture.await(); Option> futureOption = resultFuture.getValue(); Try 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 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 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 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 resultFuture = Future.of(() -> Util.divideByZero(10)); + Thread.sleep(20); Future 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 resultFuture = Future.of(() -> Util.divideByZero(10)); + Thread.sleep(20); resultFuture.await(); Option 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 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 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> 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(error, 0))) + .isEqualTo(Tuple.of("John", new Integer(5))); } @Test public void whenConvertToCompletableFuture_thenCorrect() throws InterruptedException, ExecutionException { String initialValue = "Welcome to "; Future resultFuture = Future.of(() -> Util.appendData(initialValue)); + Thread.sleep(20); CompletableFuture convertedFuture = resultFuture.toCompletableFuture(); assertThat(convertedFuture.get()).isEqualTo("Welcome to Baeldung!"); } @Test - public void whenCallMap_thenCorrect() { + public void whenCallMap_thenCorrect() throws InterruptedException { Future 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 resultFuture = Future.of(() -> Util.getSubstringMinusOne("Hello")); + Thread.sleep(20); Future 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 resultFuture = Future.of(() -> Util.getSubstringMinusOne("Hello")); + Thread.sleep(20); Future 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 future1 = Future.of(() -> Util.getSubstringMinusOne("Hello")); Future future2 = Future.of(() -> Util.getSubstringMinusTwo("Hello")); + Thread.sleep(20); Future errorMessageFuture = future1.fallbackTo(future2); Future errorMessage = errorMessageFuture.failed(); assertThat( - errorMessage.get().getMessage()) + errorMessage.getOrElse(new Throwable()).getMessage()) .isEqualTo("String index out of range: -1"); } }