From 1c6ece18d92f048e6263e79f8f04a60860f982c6 Mon Sep 17 00:00:00 2001 From: Ahmed Tawila Date: Sat, 16 Dec 2017 21:33:15 +0200 Subject: [PATCH 01/58] wait for some time before retrieving values --- .../com/baeldung/vavr/future/FutureTest.java | 44 +++++++++++++------ 1 file changed, 30 insertions(+), 14 deletions(-) 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..2d2e6939f1 100644 --- a/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java @@ -17,29 +17,32 @@ import io.vavr.control.Try; public class FutureTest { @Test - public void whenChangeExecutorService_thenCorrect() { + public void whenChangeExecutorService_thenCorrect() throws InterruptedException { String initialValue = "Welcome to "; Future resultFuture = Future.of( Executors.newSingleThreadExecutor(), () -> Util.appendData(initialValue)); + Thread.sleep(20); String result = resultFuture.get(); 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)); + Thread.sleep(20); String result = resultFuture.get(); 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(); @@ -49,31 +52,34 @@ public class FutureTest { } @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)); + Thread.sleep(20); String result = resultFuture.get(); 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)); + Thread.sleep(20); String result = resultFuture.get(); 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(); @@ -81,8 +87,9 @@ public class FutureTest { } @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(); @@ -90,8 +97,9 @@ public class FutureTest { } @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(); @@ -102,6 +110,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,18 +119,20 @@ 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))); @@ -131,23 +142,26 @@ public class FutureTest { 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"); } @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(); @@ -155,8 +169,9 @@ public class FutureTest { } @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(); @@ -164,9 +179,10 @@ public class FutureTest { } @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(); From c52b2a4ff3d12d427c9fdb08f06ff9c38f02f96b Mon Sep 17 00:00:00 2001 From: ocheja Date: Sat, 30 Dec 2017 03:51:24 +0900 Subject: [PATCH 02/58] BAEL-1440 (#3320) * Define beans for handling different message types in a lean chat app * Add class based spring beans configuration * Define spring configuration in XML for constructor based bean injection * Refactor package structure to separate constructor based bean injection code set from setter based bean injection code set * Define configuration and classes specific to setter-based bean injection. * Implement tests for constructor-based and setter-based bean injections * develop codes for explaining type erasure * Write unit tests for type erasure examples * Remove evaluation article code * Modify type erasure examples and unit tests * Modify type erasure examples and unit tests * Add expected exception in TypeErasureUnitTest * Correct grammar in class name * Implement File Manager app to demonstrate Polymorphism. Develop unit tests for Polymorphism article code * Add examples for static polymorphism * Change sysout statments to slf4j log info statements * Add assertions and expected errors check on Test * Add assertions and expected errors check on Test * Correct compile time error of symbol not found * Removed commented out non-compiling test. * Replace string concatenations with String.format * Replace string concatenations with String.format * Remove verbose file info descriptor and replace with simpler one * Add example codes for Hibernate Interceptors article Write tests for session-scoped and sessionFactory-scoped interceptors --- .../interceptors/CustomInterceptor.java | 32 +++++ .../interceptors/CustomInterceptorImpl.java | 122 ++++++++++++++++++ .../hibernate/interceptors/HibernateUtil.java | 79 ++++++++++++ .../hibernate/interceptors/entity/User.java | 64 +++++++++ .../HibernateInterceptorTest.java | 62 +++++++++ .../hibernate-interceptors.properties | 10 ++ 6 files changed, 369 insertions(+) create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java create mode 100644 hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorTest.java create mode 100644 hibernate5/src/test/resources/hibernate-interceptors.properties diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java new file mode 100644 index 0000000000..1d60ccb6c0 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java @@ -0,0 +1,32 @@ +package com.baeldung.hibernate.interceptors; + +import java.io.Serializable; +import java.util.Date; + +import org.hibernate.EmptyInterceptor; +import org.hibernate.type.Type; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.hibernate.interceptors.entity.User; + +public class CustomInterceptor extends EmptyInterceptor { + private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class); + + @Override + public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { + if (entity instanceof User) { + logger.info(((User) entity).toString()); + } + return super.onSave(entity, id, state, propertyNames, types); + } + + @Override + public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object [] previousState, String[] propertyNames, Type[] types) { + if (entity instanceof User) { + ((User) entity).setLastModified(new Date()); + logger.info(((User) entity).toString()); + } + return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types); + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java new file mode 100644 index 0000000000..a84a981f7f --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java @@ -0,0 +1,122 @@ +package com.baeldung.hibernate.interceptors; + +import java.io.Serializable; +import java.util.Iterator; + +import org.hibernate.CallbackException; +import org.hibernate.EntityMode; +import org.hibernate.Interceptor; +import org.hibernate.Transaction; +import org.hibernate.type.Type; + +public class CustomInterceptorImpl implements Interceptor { + + @Override + public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { + // TODO Auto-generated method stub + return false; + } + + @Override + public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { + // TODO Auto-generated method stub + + } + + @Override + public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException { + // TODO Auto-generated method stub + + } + + @Override + public void onCollectionRemove(Object collection, Serializable key) throws CallbackException { + // TODO Auto-generated method stub + + } + + @Override + public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException { + // TODO Auto-generated method stub + + } + + @Override + public void preFlush(Iterator entities) throws CallbackException { + // TODO Auto-generated method stub + + } + + @Override + public void postFlush(Iterator entities) throws CallbackException { + // TODO Auto-generated method stub + + } + + @Override + public Boolean isTransient(Object entity) { + // TODO Auto-generated method stub + return null; + } + + @Override + public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getEntityName(Object object) throws CallbackException { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object getEntity(String entityName, Serializable id) throws CallbackException { + // TODO Auto-generated method stub + return null; + } + + @Override + public void afterTransactionBegin(Transaction tx) { + // TODO Auto-generated method stub + + } + + @Override + public void beforeTransactionCompletion(Transaction tx) { + // TODO Auto-generated method stub + + } + + @Override + public void afterTransactionCompletion(Transaction tx) { + // TODO Auto-generated method stub + + } + + @Override + public String onPrepareStatement(String sql) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java new file mode 100644 index 0000000000..11dce698ca --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java @@ -0,0 +1,79 @@ +package com.baeldung.hibernate.interceptors; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.Interceptor; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.SessionFactoryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.interceptors.entity.User; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = getSessionFactoryBuilder(serviceRegistry).build(); + } + return sessionFactory; + } + + public static SessionFactory getSessionFactoryWithInterceptor(String propertyFileName, Interceptor interceptor) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(interceptor) + .build(); + } + return sessionFactory; + } + + public static Session getSessionWithInterceptor(Interceptor interceptor) throws IOException { + return getSessionFactory().withOptions() + .interceptor(interceptor) + .openSession(); + } + + private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addPackage("com.baeldung.hibernate.interceptors"); + metadataSources.addAnnotatedClass(User.class); + + Metadata metadata = metadataSources.buildMetadata(); + return metadata.getSessionFactoryBuilder(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate-interceptors.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java new file mode 100644 index 0000000000..2b1dbe702b --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java @@ -0,0 +1,64 @@ +package com.baeldung.hibernate.interceptors.entity; + +import java.util.Date; + +import javax.persistence.Basic; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity(name = "hbi_user") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + private String name; + private String about; + @Basic + @Temporal(TemporalType.DATE) + private Date lastModified; + + public User() { + } + + public User(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getLastModified() { + return lastModified; + } + + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } + + public long getId() { + return id; + } + + public String getAbout() { + return about; + } + + public void setAbout(String about) { + this.about = about; + } + + @Override + public String toString() { + return String.format("ID: %d\nName: %s\nLast Modified: %s\nAbout: %s\n", getId(), getName(), getLastModified(), getAbout()); + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorTest.java new file mode 100644 index 0000000000..cbf28497bb --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorTest.java @@ -0,0 +1,62 @@ +package com.baeldung.hibernate.interceptors; + +import java.io.IOException; +import java.io.Serializable; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.interceptors.entity.User; + +public class HibernateInterceptorTest { + private static SessionFactory sessionFactory; + private static Serializable userId; + + @Before + public void init() throws IOException { + sessionFactory = HibernateUtil.getSessionFactoryWithInterceptor(null, new CustomInterceptor()); + } + + @AfterClass + public static void finish() { + if(userId != null) { + Session session = sessionFactory.getCurrentSession(); + Transaction transaction = session.beginTransaction(); + User user = session.load(User.class, userId); + if(user != null) { + session.delete(user); + } + transaction.commit(); + session.close(); + } + } + + @Test + public void givenHibernateInterceptorAndSessionScoped_whenUserCreated_shouldSucceed() { + Session session = sessionFactory.withOptions().interceptor(new CustomInterceptor()).openSession(); + User user = new User("Benjamin Franklin"); + Transaction transaction = session.beginTransaction(); + userId = session.save(user); + transaction.commit(); + session.close(); + } + + @Test + public void givenHibernateInterceptorAndSessionFactoryScoped_whenUserModified_shouldSucceed() { + Session session = sessionFactory.openSession(); + Transaction transaction = session.beginTransaction(); + User user = session.load(User.class, userId); + if(user != null) { + user.setAbout("I am a scientist."); + session.update(user); + } + transaction.commit(); + session.close(); + } + +} diff --git a/hibernate5/src/test/resources/hibernate-interceptors.properties b/hibernate5/src/test/resources/hibernate-interceptors.properties new file mode 100644 index 0000000000..58b55d0a09 --- /dev/null +++ b/hibernate5/src/test/resources/hibernate-interceptors.properties @@ -0,0 +1,10 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop +hibernate.current_session_context_class=org.hibernate.context.internal.ThreadLocalSessionContext \ No newline at end of file From 91be3244f231028cfb4b1dca862ad32a112662ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Carlos=20Valero=20S=C3=A1nchez?= Date: Sat, 30 Dec 2017 05:05:05 +0100 Subject: [PATCH 03/58] Consolidate flyway modules (#3319) --- flyway/flyway-callbacks/.gitignore | 24 ----- flyway/flyway-callbacks/pom.xml | 58 ---------- flyway/pom.xml | 102 ++++++++++++------ .../ExampleFlywayCallback.java | 0 .../flywaycallbacks/FlywayApplication.java | 0 .../src/main/resources/application.properties | 0 .../db/callbacks/beforeEachMigrate.sql | 0 .../resources/db/callbacks/beforeMigrate.sql | 0 .../db/migration/V1_0__add_table_one.sql | 0 .../db/migration/V1_1__add_table_two.sql | 0 .../src/main/resources/logback.xml | 0 .../FlywayApplicationTest.java | 0 .../FlywayCallbackTestConfig.java | 0 13 files changed, 69 insertions(+), 115 deletions(-) delete mode 100644 flyway/flyway-callbacks/.gitignore delete mode 100644 flyway/flyway-callbacks/pom.xml rename flyway/{flyway-callbacks => }/src/main/java/com/baeldung/flywaycallbacks/ExampleFlywayCallback.java (100%) rename flyway/{flyway-callbacks => }/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java (100%) rename flyway/{flyway-callbacks => }/src/main/resources/application.properties (100%) rename flyway/{flyway-callbacks => }/src/main/resources/db/callbacks/beforeEachMigrate.sql (100%) rename flyway/{flyway-callbacks => }/src/main/resources/db/callbacks/beforeMigrate.sql (100%) rename flyway/{flyway-callbacks => }/src/main/resources/db/migration/V1_0__add_table_one.sql (100%) rename flyway/{flyway-callbacks => }/src/main/resources/db/migration/V1_1__add_table_two.sql (100%) rename flyway/{flyway-callbacks => }/src/main/resources/logback.xml (100%) rename flyway/{flyway-callbacks => }/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java (100%) rename flyway/{flyway-callbacks => }/src/test/java/com/baeldung/flywaycallbacks/FlywayCallbackTestConfig.java (100%) diff --git a/flyway/flyway-callbacks/.gitignore b/flyway/flyway-callbacks/.gitignore deleted file mode 100644 index 2af7cefb0a..0000000000 --- a/flyway/flyway-callbacks/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -nbproject/private/ -build/ -nbbuild/ -dist/ -nbdist/ -.nb-gradle/ \ No newline at end of file diff --git a/flyway/flyway-callbacks/pom.xml b/flyway/flyway-callbacks/pom.xml deleted file mode 100644 index 9506c2c0c9..0000000000 --- a/flyway/flyway-callbacks/pom.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - 4.0.0 - - flyway-callbacks - jar - - flyway-callbacks - Flyway Callbacks Demo - - - parent-boot-5 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-5 - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.flywaydb - flyway-core - 5.0.2 - - - - org.springframework.boot - spring-boot-starter-jdbc - - - - com.h2database - h2 - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - diff --git a/flyway/pom.xml b/flyway/pom.xml index c3806ed3bd..a090b9458e 100644 --- a/flyway/pom.xml +++ b/flyway/pom.xml @@ -1,34 +1,70 @@ + - 4.0.0 - com.baeldung - flyway - 1.0 - flyway - A sample project to demonstrate Flyway migrations - - - mysql - mysql-connector-java - 6.0.3 - - - - - - org.flywaydb - flyway-maven-plugin - 4.0.3 - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + flyway + jar + + flyway + Flyway Callbacks Demo + + + parent-boot-5 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-5 + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.flywaydb + flyway-core + 5.0.2 + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + mysql + mysql-connector-java + 6.0.3 + + + + com.h2database + h2 + test + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.flywaydb + flyway-maven-plugin + 5.0.2 + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/flyway/flyway-callbacks/src/main/java/com/baeldung/flywaycallbacks/ExampleFlywayCallback.java b/flyway/src/main/java/com/baeldung/flywaycallbacks/ExampleFlywayCallback.java similarity index 100% rename from flyway/flyway-callbacks/src/main/java/com/baeldung/flywaycallbacks/ExampleFlywayCallback.java rename to flyway/src/main/java/com/baeldung/flywaycallbacks/ExampleFlywayCallback.java diff --git a/flyway/flyway-callbacks/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java b/flyway/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java similarity index 100% rename from flyway/flyway-callbacks/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java rename to flyway/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java diff --git a/flyway/flyway-callbacks/src/main/resources/application.properties b/flyway/src/main/resources/application.properties similarity index 100% rename from flyway/flyway-callbacks/src/main/resources/application.properties rename to flyway/src/main/resources/application.properties diff --git a/flyway/flyway-callbacks/src/main/resources/db/callbacks/beforeEachMigrate.sql b/flyway/src/main/resources/db/callbacks/beforeEachMigrate.sql similarity index 100% rename from flyway/flyway-callbacks/src/main/resources/db/callbacks/beforeEachMigrate.sql rename to flyway/src/main/resources/db/callbacks/beforeEachMigrate.sql diff --git a/flyway/flyway-callbacks/src/main/resources/db/callbacks/beforeMigrate.sql b/flyway/src/main/resources/db/callbacks/beforeMigrate.sql similarity index 100% rename from flyway/flyway-callbacks/src/main/resources/db/callbacks/beforeMigrate.sql rename to flyway/src/main/resources/db/callbacks/beforeMigrate.sql diff --git a/flyway/flyway-callbacks/src/main/resources/db/migration/V1_0__add_table_one.sql b/flyway/src/main/resources/db/migration/V1_0__add_table_one.sql similarity index 100% rename from flyway/flyway-callbacks/src/main/resources/db/migration/V1_0__add_table_one.sql rename to flyway/src/main/resources/db/migration/V1_0__add_table_one.sql diff --git a/flyway/flyway-callbacks/src/main/resources/db/migration/V1_1__add_table_two.sql b/flyway/src/main/resources/db/migration/V1_1__add_table_two.sql similarity index 100% rename from flyway/flyway-callbacks/src/main/resources/db/migration/V1_1__add_table_two.sql rename to flyway/src/main/resources/db/migration/V1_1__add_table_two.sql diff --git a/flyway/flyway-callbacks/src/main/resources/logback.xml b/flyway/src/main/resources/logback.xml similarity index 100% rename from flyway/flyway-callbacks/src/main/resources/logback.xml rename to flyway/src/main/resources/logback.xml diff --git a/flyway/flyway-callbacks/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java b/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java similarity index 100% rename from flyway/flyway-callbacks/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java rename to flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java diff --git a/flyway/flyway-callbacks/src/test/java/com/baeldung/flywaycallbacks/FlywayCallbackTestConfig.java b/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayCallbackTestConfig.java similarity index 100% rename from flyway/flyway-callbacks/src/test/java/com/baeldung/flywaycallbacks/FlywayCallbackTestConfig.java rename to flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayCallbackTestConfig.java From b5c7ffeb19aaa9ca36b67df8cb655689ff1b3e51 Mon Sep 17 00:00:00 2001 From: krishan-gandhi2 <34406463+krishan-gandhi2@users.noreply.github.com> Date: Sat, 30 Dec 2017 15:49:08 +0530 Subject: [PATCH 04/58] BAEL-4453 (#3304) --- spring-katharsis/pom.xml | 8 ++++++-- .../persistence/katharsis/RoleResourceRepository.java | 8 ++++---- .../persistence/katharsis/UserResourceRepository.java | 8 ++++---- .../katharsis/UserToRoleRelationshipRepository.java | 6 +++--- 4 files changed, 17 insertions(+), 13 deletions(-) diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 822eac7873..a5e79e138b 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -36,12 +36,16 @@ katharsis-servlet ${katharsis.version} - + + org.reflections + reflections + 0.9.10 + - 1.0.1 + 2.1.3 1.6.1 diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java index da59d505e4..101e4c2b7e 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java @@ -1,6 +1,6 @@ package org.baeldung.persistence.katharsis; -import io.katharsis.queryParams.RequestParams; +import io.katharsis.queryParams.QueryParams; import io.katharsis.repository.ResourceRepository; import org.baeldung.persistence.dao.RoleRepository; @@ -15,17 +15,17 @@ public class RoleResourceRepository implements ResourceRepository { private RoleRepository roleRepository; @Override - public Role findOne(Long id, RequestParams params) { + public Role findOne(Long id, QueryParams params) { return roleRepository.findOne(id); } @Override - public Iterable findAll(RequestParams params) { + public Iterable findAll(QueryParams params) { return roleRepository.findAll(); } @Override - public Iterable findAll(Iterable ids, RequestParams params) { + public Iterable findAll(Iterable ids, QueryParams params) { return roleRepository.findAll(ids); } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java index 4c7ce70765..b6d519ab80 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java @@ -1,6 +1,6 @@ package org.baeldung.persistence.katharsis; -import io.katharsis.queryParams.RequestParams; +import io.katharsis.queryParams.QueryParams; import io.katharsis.repository.ResourceRepository; import org.baeldung.persistence.dao.UserRepository; @@ -15,17 +15,17 @@ public class UserResourceRepository implements ResourceRepository { private UserRepository userRepository; @Override - public User findOne(Long id, RequestParams params) { + public User findOne(Long id, QueryParams params) { return userRepository.findOne(id); } @Override - public Iterable findAll(RequestParams params) { + public Iterable findAll(QueryParams params) { return userRepository.findAll(); } @Override - public Iterable findAll(Iterable ids, RequestParams params) { + public Iterable findAll(Iterable ids, QueryParams params) { return userRepository.findAll(ids); } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java index e10c29aece..168cd1c866 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java @@ -1,6 +1,6 @@ package org.baeldung.persistence.katharsis; -import io.katharsis.queryParams.RequestParams; +import io.katharsis.queryParams.QueryParams; import io.katharsis.repository.RelationshipRepository; import java.util.HashSet; @@ -52,13 +52,13 @@ public class UserToRoleRelationshipRepository implements RelationshipRepository< } @Override - public Role findOneTarget(Long sourceId, String fieldName, RequestParams requestParams) { + public Role findOneTarget(Long sourceId, String fieldName, QueryParams QueryParams) { // not for many-to-many return null; } @Override - public Iterable findManyTargets(Long sourceId, String fieldName, RequestParams requestParams) { + public Iterable findManyTargets(Long sourceId, String fieldName, QueryParams QueryParams) { final User user = userRepository.findOne(sourceId); return user.getRoles(); } From ff2cf57772a8317f857d9d250986475660d310a9 Mon Sep 17 00:00:00 2001 From: Ahmed Tawila Date: Sat, 30 Dec 2017 23:23:08 +0200 Subject: [PATCH 05/58] BAEL-1080 Introduction to Future in Vavr --- .../com/baeldung/vavr/future/FutureTest.java | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) 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 2d2e6939f1..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,6 +15,8 @@ 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() throws InterruptedException { @@ -23,7 +25,7 @@ public class FutureTest { Executors.newSingleThreadExecutor(), () -> Util.appendData(initialValue)); Thread.sleep(20); - String result = resultFuture.get(); + String result = resultFuture.getOrElse(error); assertThat(result).isEqualTo("Welcome to Baeldung!"); } @@ -33,7 +35,7 @@ public class FutureTest { String initialValue = "Welcome to "; Future resultFuture = Future.of(() -> Util.appendData(initialValue)); Thread.sleep(20); - String result = resultFuture.get(); + String result = resultFuture.getOrElse(new String(error)); assertThat(result).isEqualTo("Welcome to Baeldung!"); } @@ -46,7 +48,7 @@ public class FutureTest { 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!"); } @@ -58,7 +60,7 @@ public class FutureTest { .onSuccess(finalResult -> System.out.println("Successfully Completed - Result: " + finalResult)) .onFailure(finalResult -> System.out.println("Failed - Result: " + finalResult)); Thread.sleep(20); - String result = resultFuture.get(); + String result = resultFuture.getOrElse(error); assertThat(result).isEqualTo("Welcome to Baeldung!"); } @@ -70,7 +72,7 @@ public class FutureTest { .andThen(finalResult -> System.out.println("Completed - 1: " + finalResult)) .andThen(finalResult -> System.out.println("Completed - 2: " + finalResult)); Thread.sleep(20); - String result = resultFuture.get(); + String result = resultFuture.getOrElse(error); assertThat(result).isEqualTo("Welcome to Baeldung!"); } @@ -81,7 +83,7 @@ public class FutureTest { 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!"); } @@ -91,7 +93,7 @@ public class FutureTest { 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"); } @@ -102,7 +104,7 @@ public class FutureTest { 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"); } @@ -135,7 +137,8 @@ public class FutureTest { 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 @@ -155,7 +158,7 @@ public class FutureTest { Thread.sleep(20); futureResult.await(); - assertThat(futureResult.get()).isEqualTo("Hello from Baeldung"); + assertThat(futureResult.getOrElse(error)).isEqualTo("Hello from Baeldung"); } @Test @@ -163,7 +166,7 @@ public class FutureTest { 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"); } @@ -173,7 +176,7 @@ public class FutureTest { 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"); } @@ -187,7 +190,7 @@ public class FutureTest { Future errorMessage = errorMessageFuture.failed(); assertThat( - errorMessage.get().getMessage()) + errorMessage.getOrElse(new Throwable()).getMessage()) .isEqualTo("String index out of range: -1"); } } From c7ba3a08aa7b77d77f99921f25b4d24b44a9d3bf Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 30 Dec 2017 23:10:54 +0100 Subject: [PATCH 06/58] Build optimize (#3328) * CustomConverterIntegrationTest * StringToEmployeeConverterControllerIntegrationTest * PersonsRepositoryIntegrationTest * Refactor spring-rest-embedded-tomcat pom * Disable Rxjava test --- ... => PersonsRepositoryIntegrationTest.java} | 5 +---- .../baeldung/rxjava/SchedulersLiveTest.java | 1 + ...va => CustomConverterIntegrationTest.java} | 2 +- ...eeConverterControllerIntegrationTest.java} | 2 +- spring-rest-embedded-tomcat/pom.xml | 20 +++++++++++++++++++ 5 files changed, 24 insertions(+), 6 deletions(-) rename persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/repo/{PersonsRepositoryTest.java => PersonsRepositoryIntegrationTest.java} (95%) rename spring-boot/src/test/java/org/baeldung/converter/{CustomConverterTest.java => CustomConverterIntegrationTest.java} (97%) rename spring-boot/src/test/java/org/baeldung/converter/controller/{StringToEmployeeConverterControllerTest.java => StringToEmployeeConverterControllerIntegrationTest.java} (95%) 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/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/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-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 From fc2521b4d6fb7c8d81891aecccf80ecae76c701d Mon Sep 17 00:00:00 2001 From: Jose Carvajal Date: Sun, 31 Dec 2017 10:49:13 +0100 Subject: [PATCH 07/58] Bael 1457 (#3330) * BAEL-399: A Guide to Multitenancy in Hibernate 5 * Removed unused properties in profile 2 * Changes after code review * Updated to use H2 for flyway plugin * Updated schema property * Fixed pom format * Undo things from another PR --- flyway/myFlywayConfig.properties | 6 +++--- flyway/pom.xml | 8 +++++++- 2 files changed, 10 insertions(+), 4 deletions(-) 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 @@ - From 62e53959ef842ce6eace822cc67ec5c55b24bb8c Mon Sep 17 00:00:00 2001 From: Ganesh Date: Sun, 31 Dec 2017 20:24:02 +0530 Subject: [PATCH 08/58] PR for BAEL-1340 - Java StringJoiner class (#3324) * unit tests for stringjoiner * formatting changes * slit test cases and formatting fixes * minor formatting fix --- .../stringjoiner/StringJoinerUnitTest.java | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java 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"); + } +} From 8de8770eecc255e4dfea382c6848c4add1190e53 Mon Sep 17 00:00:00 2001 From: Bogdan Stoean <4540392+BogdanStoean@users.noreply.github.com> Date: Sun, 31 Dec 2017 17:04:37 +0200 Subject: [PATCH 09/58] [BAEL-1410] Spring Boot Security auto-configuration (#3329) * [BAEL-1410] Spring Boot Security Auto-Configuration * [BAEL-1410] Added some tests for incorrect credentials use case * [BAEL-1410] Added readme and some code improvements --- pom.xml | 3 +- spring-boot-security/README.md | 6 + spring-boot-security/pom.xml | 73 ++++++++++++ .../SpringBootSecurityApplication.java | 16 +++ .../config/BasicConfiguration.java | 37 ++++++ .../config/FormLoginConfiguration.java | 39 +++++++ .../src/main/resources/application.properties | 4 + .../src/main/resources/static/index.html | 10 ++ .../BasicConfigurationIntegrationTest.java | 56 +++++++++ .../FormConfigurationIntegrationTest.java | 106 ++++++++++++++++++ 10 files changed, 349 insertions(+), 1 deletion(-) create mode 100644 spring-boot-security/README.md create mode 100644 spring-boot-security/pom.xml create mode 100644 spring-boot-security/src/main/java/com/baeldung/springbootsecurity/SpringBootSecurityApplication.java create mode 100644 spring-boot-security/src/main/java/com/baeldung/springbootsecurity/config/BasicConfiguration.java create mode 100644 spring-boot-security/src/main/java/com/baeldung/springbootsecurity/config/FormLoginConfiguration.java create mode 100644 spring-boot-security/src/main/resources/application.properties create mode 100644 spring-boot-security/src/main/resources/static/index.html create mode 100644 spring-boot-security/src/test/java/com/baeldung/springbootsecurity/BasicConfigurationIntegrationTest.java create mode 100644 spring-boot-security/src/test/java/com/baeldung/springbootsecurity/FormConfigurationIntegrationTest.java 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/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; + } + +} From 23f7f658e48ae921787039adde5a289ac9270a2e Mon Sep 17 00:00:00 2001 From: Jose Carvajal Date: Mon, 1 Jan 2018 00:28:27 +0100 Subject: [PATCH 10/58] BAEL-399 A Guide to Multitenancy in Hibernate 5 (#3323) * BAEL-399: A Guide to Multitenancy in Hibernate 5 * Removed unused properties in profile 2 * Changes after code review --- .../SchemaMultiTenantConnectionProvider.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) 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); From ccf1f4ed27c1781a2565b95582f8c4c741135105 Mon Sep 17 00:00:00 2001 From: abialas Date: Mon, 1 Jan 2018 13:07:35 +0100 Subject: [PATCH 11/58] BAEL-1412 add java 8 spring data features (#3306) --- .../baeldung/repository/UserRepository.java | 16 ++- .../repository/UserRepositoryTest.java | 97 +++++++++++++++++++ 2 files changed, 112 insertions(+), 1 deletion(-) create mode 100644 spring-boot/src/test/java/org/baeldung/repository/UserRepositoryTest.java 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/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(); + } + +} From f6f8f8debe151b41b49aed5c6720fad38d3f3fad Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Tue, 2 Jan 2018 13:33:37 +0200 Subject: [PATCH 12/58] move url matching (#3326) * make sure modules using java8 * move url matching code --- spring-5-reactive/pom.xml | 2 +- .../controller}/PathPatternController.java | 2 +- .../com/baeldung/reactive/urlmatch/Actor.java | 23 ++++++ ...Spring5URLPatternUsingRouterFunctions.java | 2 +- .../reactive/urlmatch/FormHandler.java | 41 ++++++++++ .../urlmatch/FunctionalWebApplication.java | 80 +++++++++++++++++++ .../reactive/urlmatch/IndexRewriteFilter.java | 27 +++++++ .../src/main/resources/files/hello.txt | 1 + .../src/main/resources/files/test/test.txt | 1 + ...rnUsingRouterFunctionsIntegrationTest.java | 6 +- ...ernsUsingHandlerMethodIntegrationTest.java | 8 +- 11 files changed, 185 insertions(+), 8 deletions(-) rename {spring-5/src/main/java/com/baeldung/web => spring-5-reactive/src/main/java/com/baeldung/reactive/controller}/PathPatternController.java (93%) create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/Actor.java rename {spring-5/src/main/java/com/baeldung/functional => spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch}/ExploreSpring5URLPatternUsingRouterFunctions.java (98%) create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/IndexRewriteFilter.java create mode 100644 spring-5-reactive/src/main/resources/files/hello.txt create mode 100644 spring-5-reactive/src/main/resources/files/test/test.txt rename spring-5/src/test/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctionsTest.java => spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java (93%) rename {spring-5/src/test/java/com/baeldung/web => spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch}/PathPatternsUsingHandlerMethodIntegrationTest.java (92%) diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index 5d7cf0d7e5..e5b35de2f5 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -28,7 +28,7 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-tomcat org.springframework.boot diff --git a/spring-5/src/main/java/com/baeldung/web/PathPatternController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/PathPatternController.java similarity index 93% rename from spring-5/src/main/java/com/baeldung/web/PathPatternController.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/controller/PathPatternController.java index 6fd972f2a4..f5a5d9e769 100644 --- a/spring-5/src/main/java/com/baeldung/web/PathPatternController.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/PathPatternController.java @@ -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; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/Actor.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/Actor.java new file mode 100644 index 0000000000..ee06b94be7 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/Actor.java @@ -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; + } + +} diff --git a/spring-5/src/main/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java similarity index 98% rename from spring-5/src/main/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctions.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java index 2a6d04538c..78f40be57a 100644 --- a/spring-5/src/main/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctions.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java @@ -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; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java new file mode 100644 index 0000000000..0781230379 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java @@ -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 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 handleUpload(ServerRequest request) { + return request.body(toDataBuffers()) + .collectList() + .flatMap(dataBuffers -> ok().body(fromObject(extractData(dataBuffers).toString()))); + } + + private AtomicLong extractData(List dataBuffers) { + AtomicLong atomicLong = new AtomicLong(0); + dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer() + .array().length)); + return atomicLong; + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java new file mode 100644 index 0000000000..2ea5420a2b --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java @@ -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 actors = new CopyOnWriteArrayList<>(Arrays.asList(BRAD_PITT, TOM_HANKS)); + + private RouterFunction routingFunction() { + FormHandler formHandler = new FormHandler(); + + RouterFunction 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(); + } + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/IndexRewriteFilter.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/IndexRewriteFilter.java new file mode 100644 index 0000000000..2eb252ed2b --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/IndexRewriteFilter.java @@ -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 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); + } + +} diff --git a/spring-5-reactive/src/main/resources/files/hello.txt b/spring-5-reactive/src/main/resources/files/hello.txt new file mode 100644 index 0000000000..b6fc4c620b --- /dev/null +++ b/spring-5-reactive/src/main/resources/files/hello.txt @@ -0,0 +1 @@ +hello \ No newline at end of file diff --git a/spring-5-reactive/src/main/resources/files/test/test.txt b/spring-5-reactive/src/main/resources/files/test/test.txt new file mode 100644 index 0000000000..30d74d2584 --- /dev/null +++ b/spring-5-reactive/src/main/resources/files/test/test.txt @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctionsTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java similarity index 93% rename from spring-5/src/test/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctionsTest.java rename to spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java index 7a38fa697f..21ba11616d 100644 --- a/spring-5/src/test/java/com/baeldung/functional/ExploreSpring5URLPatternUsingRouterFunctionsTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java @@ -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; diff --git a/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java similarity index 92% rename from spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java rename to spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java index c2ed8ff071..9f31608ff7 100644 --- a/spring-5/src/test/java/com/baeldung/web/PathPatternsUsingHandlerMethodIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java @@ -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; From 036fabc9f7e8920c4c18240e4157d7ec0ee5a670 Mon Sep 17 00:00:00 2001 From: Tarang Bhalodia Date: Tue, 2 Jan 2018 22:38:50 +0530 Subject: [PATCH 13/58] BAEL-1422: added BDD style tests for generating random values using ThreadLocalRandom --- .../ThreadLocalRandomTest.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java 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..37dcdeccf7 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java @@ -0,0 +1,58 @@ +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); + } + +} \ No newline at end of file From 12a1924cb372026cd7ea7532209fd4c4b7266515 Mon Sep 17 00:00:00 2001 From: Tarang Bhalodia Date: Tue, 2 Jan 2018 23:47:39 +0530 Subject: [PATCH 14/58] BAEL-1422: added BDD style test for asserting UnsupportedOperationException while setting seed for ThreadLocalRandom --- .../baeldung/threadlocalrandom/ThreadLocalRandomTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java index 37dcdeccf7..c75813baba 100644 --- a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java +++ b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java @@ -54,5 +54,10 @@ public class ThreadLocalRandomTest { 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 From 2ded3d36d96cff64bf0b0067d72436374dfac9ce Mon Sep 17 00:00:00 2001 From: markusgulden Date: Wed, 3 Jan 2018 14:07:02 +0100 Subject: [PATCH 15/58] BAEL-592 Guide to Hibernate 5 with Spring (#3346) --- .../hibernate/bootstrap/BarHibernateDAO.java | 39 ++++++++++++ .../hibernate/bootstrap/HibernateConf.java | 61 +++++++++++++++++++ .../hibernate/bootstrap/HibernateXMLConf.java | 24 ++++++++ .../hibernate/bootstrap/model/TestEntity.java | 29 +++++++++ .../resources/hibernate5Configuration.xml | 30 +++++++++ .../main/resources/persistence-h2.properties | 1 + .../HibernateBootstrapIntegrationTest.java | 38 ++++++++++++ .../HibernateXMLBootstrapIntegrationTest.java | 36 +++++++++++ 8 files changed, 258 insertions(+) create mode 100644 persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java create mode 100644 persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java create mode 100644 persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java create mode 100644 persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java create mode 100644 persistence-modules/spring-hibernate-5/src/main/resources/hibernate5Configuration.xml create mode 100644 persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java create mode 100644 persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java 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); + } + +} From 5459445826d51522be7377b9d6ee3ecdfa124d9d Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Wed, 3 Jan 2018 15:19:56 +0200 Subject: [PATCH 16/58] small module name change --- core-java-9/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 From b54440ddb398ad78390aa29e3b6470c5d5ddb3f2 Mon Sep 17 00:00:00 2001 From: markusgulden Date: Thu, 4 Jan 2018 16:20:53 +0100 Subject: [PATCH 17/58] BAEL-592: Upgraded Hibernate 5-module to Spring 5 (#3351) * BAEL-592 Guide to Hibernate 5 with Spring * BAEL-592: Upgrade to Spring 5 --- persistence-modules/spring-hibernate-5/pom.xml | 2 +- .../com/baeldung/manytomany/spring/PersistenceConfig.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml index 88db38b2fc..86e952c0e4 100644 --- a/persistence-modules/spring-hibernate-5/pom.xml +++ b/persistence-modules/spring-hibernate-5/pom.xml @@ -179,7 +179,7 @@ - 4.3.10.RELEASE + 5.0.2.RELEASE 1.10.6.RELEASE diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java index 6f359054b6..5dace1f742 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java @@ -10,8 +10,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; From 2afc7dc62353433c1d1b4cde2ab17b153a7b441c Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Thu, 4 Jan 2018 17:21:16 +0200 Subject: [PATCH 18/58] Refactor Vavr Future (#3349) --- .../java/com/baeldung/vavr/future/Util.java | 20 -- .../com/baeldung/vavr/future/FutureTest.java | 207 ++++++++---------- 2 files changed, 92 insertions(+), 135 deletions(-) delete mode 100644 vavr/src/main/java/com/baeldung/vavr/future/Util.java diff --git a/vavr/src/main/java/com/baeldung/vavr/future/Util.java b/vavr/src/main/java/com/baeldung/vavr/future/Util.java deleted file mode 100644 index 790ef2bf88..0000000000 --- a/vavr/src/main/java/com/baeldung/vavr/future/Util.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.vavr.future; - -public class Util { - - public static String appendData(String initial) { - return initial + "Baeldung!"; - } - - public static int divideByZero(int num) { - return num / 0; - } - - public static String getSubstringMinusOne(String s) { - return s.substring(-1); - } - - public static String getSubstringMinusTwo(String s) { - return s.substring(-2); - } -} 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 dd678bcad0..002919a937 100644 --- a/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java @@ -1,119 +1,102 @@ package com.baeldung.vavr.future; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; - -import org.junit.Test; - import io.vavr.Tuple; -import io.vavr.Tuple2; import io.vavr.concurrent.Future; import io.vavr.control.Option; import io.vavr.control.Try; +import org.junit.Test; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import static java.util.concurrent.Executors.newSingleThreadExecutor; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class FutureTest { - + private static final String error = "Failed to get underlying value."; + private static final String HELLO = "Welcome to Baeldung!"; @Test - public void whenChangeExecutorService_thenCorrect() throws InterruptedException { - String initialValue = "Welcome to "; - Future resultFuture = Future.of( - Executors.newSingleThreadExecutor(), - () -> Util.appendData(initialValue)); - Thread.sleep(20); - String result = resultFuture.getOrElse(error); + public void whenChangeExecutorService_thenCorrect() { + String result = Future.of(newSingleThreadExecutor(), () -> HELLO) + .getOrElse(error); - assertThat(result).isEqualTo("Welcome to Baeldung!"); + assertThat(result) + .isEqualTo(HELLO); } @Test - public void whenAppendData_thenCorrect1() throws InterruptedException { - String initialValue = "Welcome to "; - Future resultFuture = Future.of(() -> Util.appendData(initialValue)); - Thread.sleep(20); - String result = resultFuture.getOrElse(new String(error)); + public void whenAppendData_thenCorrect1() { + String result = Future.of(() -> HELLO) + .getOrElse(error); - assertThat(result).isEqualTo("Welcome to Baeldung!"); + assertThat(result) + .isEqualTo(HELLO); } @Test - public void whenAppendData_thenCorrect2() throws InterruptedException { - String initialValue = "Welcome to "; - Future resultFuture = Future.of(() -> Util.appendData(initialValue)); - Thread.sleep(20); - resultFuture.await(); + public void whenAppendData_thenCorrect2() { + Future resultFuture = Future.of(() -> HELLO) + .await(); + Option> futureOption = resultFuture.getValue(); - Try futureTry = futureOption.get(); - String result = futureTry.getOrElse(error); + String result = futureOption.get().getOrElse(error); - assertThat(result).isEqualTo("Welcome to Baeldung!"); + assertThat(result) + .isEqualTo(HELLO); } @Test - public void whenAppendData_thenSuccess() throws InterruptedException { - String initialValue = "Welcome to "; - Future resultFuture = Future.of(() -> Util.appendData(initialValue)) + public void whenAppendData_thenSuccess() { + String result = Future.of(() -> HELLO) .onSuccess(finalResult -> System.out.println("Successfully Completed - Result: " + finalResult)) - .onFailure(finalResult -> System.out.println("Failed - Result: " + finalResult)); - Thread.sleep(20); - String result = resultFuture.getOrElse(error); + .onFailure(finalResult -> System.out.println("Failed - Result: " + finalResult)) + .getOrElse(error); - assertThat(result).isEqualTo("Welcome to Baeldung!"); + assertThat(result) + .isEqualTo(HELLO); } @Test - 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)); - Thread.sleep(20); - String result = resultFuture.getOrElse(error); - - assertThat(result).isEqualTo("Welcome to Baeldung!"); + public void whenChainingCallbacks_thenCorrect() { + Future.of(() -> HELLO) + .andThen(r -> System.out.println("Completed - 1: " + r)) + .andThen(r -> System.out.println("Completed - 2: " + r)); } @Test - 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.getOrElse(error); + public void whenCallAwait_thenCorrect() { + Future resultFuture = Future.of(() -> HELLO) + .await(); + String result = resultFuture.getValue().get().getOrElse(error); - assertThat(result).isEqualTo("Welcome to Baeldung!"); + assertThat(result) + .isEqualTo(HELLO); } @Test - public void whenDivideByZero_thenGetThrowable1() throws InterruptedException { - Future resultFuture = Future.of(() -> Util.divideByZero(10)); - Thread.sleep(20); - Future throwableFuture = resultFuture.failed(); - Throwable throwable = throwableFuture.getOrElse(new Throwable()); + public void whenDivideByZero_thenGetThrowable1() { + Future resultFuture = Future.of(() -> 10 / 0); - assertThat(throwable.getMessage()).isEqualTo("/ by zero"); + assertThatThrownBy(resultFuture::get) + .isInstanceOf(ArithmeticException.class); } @Test - 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.getOrElse(new Throwable()); + public void whenDivideByZero_thenGetThrowable2() { + Future resultFuture = Future.of(() -> 10 / 0) + .await(); - assertThat(throwable.getMessage()).isEqualTo("/ by zero"); + assertThat(resultFuture.getCause().get().getMessage()) + .isEqualTo("/ by zero"); } @Test - public void whenDivideByZero_thenCorrect() throws InterruptedException { - Future resultFuture = Future.of(() -> Util.divideByZero(10)); - Thread.sleep(20); - resultFuture.await(); + public void whenDivideByZero_thenCorrect() { + Future resultFuture = Future.of(() -> 10 / 0) + .await(); assertThat(resultFuture.isCompleted()).isTrue(); assertThat(resultFuture.isSuccess()).isFalse(); @@ -121,76 +104,70 @@ public class FutureTest { } @Test - public void whenAppendData_thenFutureNotEmpty() throws InterruptedException { - String initialValue = "Welcome to "; - Future resultFuture = Future.of(() -> Util.appendData(initialValue)); - Thread.sleep(20); - resultFuture.await(); + public void whenAppendData_thenFutureNotEmpty() { + Future resultFuture = Future.of(() -> HELLO) + .await(); - assertThat(resultFuture.isEmpty()).isFalse(); + assertThat(resultFuture.isEmpty()) + .isFalse(); } @Test - public void whenCallZip_thenCorrect() throws InterruptedException { - Future> future = Future.of(() -> "John") - .zip(Future.of(() -> new Integer(5))); - Thread.sleep(20); - future.await(); + public void whenCallZip_thenCorrect() { + Future f1 = Future.of(() -> "hello1"); + Future f2 = Future.of(() -> "hello2"); - assertThat(future.getOrElse(new Tuple2(error, 0))) - .isEqualTo(Tuple.of("John", new Integer(5))); + assertThat(f1.zip(f2).get()) + .isEqualTo(Tuple.of("hello1", "hello2")); } @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(); + CompletableFuture convertedFuture = Future.of(() -> HELLO) + .toCompletableFuture(); - assertThat(convertedFuture.get()).isEqualTo("Welcome to Baeldung!"); + assertThat(convertedFuture.get()) + .isEqualTo(HELLO); } @Test - public void whenCallMap_thenCorrect() throws InterruptedException { - Future futureResult = Future.of(() -> new StringBuilder("from Baeldung")) - .map(a -> "Hello " + a); - Thread.sleep(20); - futureResult.await(); + public void whenCallMap_thenCorrect() { + Future futureResult = Future.of(() -> "from Baeldung") + .map(a -> "Hello " + a) + .await(); - assertThat(futureResult.getOrElse(error)).isEqualTo("Hello from Baeldung"); + assertThat(futureResult.get()) + .isEqualTo("Hello from Baeldung"); } @Test - 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.getOrElse(error); + public void whenFutureFails_thenGetErrorMessage() { + Future future = Future.of(() -> "Hello".substring(-1)) + .recover(x -> "fallback value"); - assertThat(errorMessage).isEqualTo("String index out of range: -1"); + assertThat(future.get()) + .isEqualTo("fallback value"); } @Test - 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.getOrElse(error); + public void whenFutureFails_thenGetAnotherFuture() { + Future future = Future.of(() -> "Hello".substring(-1)) + .recoverWith(x -> Future.of(() -> "fallback value")); - assertThat(errorMessage).isEqualTo("String index out of range: -1"); + assertThat(future.get()) + .isEqualTo("fallback value"); } @Test - 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); + public void whenBothFuturesFail_thenGetErrorMessage() { + Future f1 = Future.of(() -> "Hello".substring(-1)); + Future f2 = Future.of(() -> "Hello".substring(-2)); + + Future errorMessageFuture = f1.fallbackTo(f2); Future errorMessage = errorMessageFuture.failed(); - + assertThat( - errorMessage.getOrElse(new Throwable()).getMessage()) + errorMessage.get().getMessage()) .isEqualTo("String index out of range: -1"); } } From da4bd50cdb472461849602a8151d5605569c0454 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Thu, 4 Jan 2018 17:21:32 +0200 Subject: [PATCH 19/58] Core Java 8 refactor (#3342) --- .../java/com/baeldung/{streamApi => stream}/Product.java | 2 +- core-java-8/src/main/java/com/baeldung/stream/StreamApi.java | 2 +- .../test/java/com/baeldung/java8/Java8StreamApiUnitTest.java | 2 +- .../java/com/baeldung/stream/PrimitiveStreamsUnitTest.java | 5 ++++- 4 files changed, 7 insertions(+), 4 deletions(-) rename core-java-8/src/main/java/com/baeldung/{streamApi => stream}/Product.java (96%) diff --git a/core-java-8/src/main/java/com/baeldung/streamApi/Product.java b/core-java-8/src/main/java/com/baeldung/stream/Product.java similarity index 96% rename from core-java-8/src/main/java/com/baeldung/streamApi/Product.java rename to core-java-8/src/main/java/com/baeldung/stream/Product.java index 1b7478551f..e99a969b81 100644 --- a/core-java-8/src/main/java/com/baeldung/streamApi/Product.java +++ b/core-java-8/src/main/java/com/baeldung/stream/Product.java @@ -1,4 +1,4 @@ -package com.baeldung.streamApi; +package com.baeldung.stream; import java.util.List; import java.util.stream.Stream; diff --git a/core-java-8/src/main/java/com/baeldung/stream/StreamApi.java b/core-java-8/src/main/java/com/baeldung/stream/StreamApi.java index 364fdeffbb..f0d5f1aa7e 100644 --- a/core-java-8/src/main/java/com/baeldung/stream/StreamApi.java +++ b/core-java-8/src/main/java/com/baeldung/stream/StreamApi.java @@ -16,7 +16,7 @@ public class StreamApi { } public static String getLastElementUsingSkip(List valueList) { - long count = valueList.stream().count(); + long count = (long) valueList.size(); Stream stream = valueList.stream(); return stream.skip(count - 1).findFirst().orElse(null); } diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java index 73a10a57f4..5005cf7f47 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java @@ -1,6 +1,6 @@ package com.baeldung.java8; -import com.baeldung.streamApi.Product; +import com.baeldung.stream.Product; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; diff --git a/core-java-8/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java b/core-java-8/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java index c28d6300e0..2c88dc5ec7 100644 --- a/core-java-8/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java @@ -6,6 +6,7 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; +import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -65,7 +66,9 @@ public class PrimitiveStreamsUnitTest { @Test public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() { - int sum = Arrays.asList(33,45).stream().mapToInt(a -> a).sum(); + int sum = Stream.of(33,45) + .mapToInt(i -> i) + .sum(); assertEquals(78, sum); } From e99619dcdc1c7173d7b6e0f09249e6a5001983b7 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Thu, 4 Jan 2018 17:21:52 +0200 Subject: [PATCH 20/58] Update .travis.yml (#3334) * Update .travis.yml * Update .travis.yml --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 3a953a2e7b..3d28a5cd76 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,7 +3,8 @@ language: java before_install: - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc -install: travis_wait 60 mvn -q test -fae +install: skip +script: travis_wait 60 mvn -q test -fae sudo: required From e039960365ce3455c8b0733328b8816efc0833af Mon Sep 17 00:00:00 2001 From: Tarang Bhalodia Date: Fri, 5 Jan 2018 01:28:04 +0530 Subject: [PATCH 21/58] BAEL-1422: Guide to ThreadLocalRandom [tarangbhalodia@gmail.com] (#3347) * BAEL-1422: measure performance of Random and ThreadLocalRandom using JMH * BAEL-1422: updated benchmarking examples of Random and ThreadLocalRandom to use newWorkStealingPool that leverages ForkJoinPool * BAEL-1422: refactored benchmarking examples for comparing performance of ThreadLocalRandom and Random - initialised the collection of Callable before running benchmarking - removed for loop for submitting task and instead used executor.invokeAll(collection_of_callable) --- .../ThreadLocalRandomBenchMarkRunner.java | 22 +++++++ .../ThreadLocalRandomBenchMarker.java | 64 +++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java create mode 100644 core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java diff --git a/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java b/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java new file mode 100644 index 0000000000..e9c8056ff5 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java @@ -0,0 +1,22 @@ +package com.baeldung.threadlocalrandom; + +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +public class ThreadLocalRandomBenchMarkRunner { + + public static void main(String[] args) throws Exception { + + Options options = new OptionsBuilder().include(ThreadLocalRandomBenchMarker.class.getSimpleName()) + .threads(1) + .forks(1) + .shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server") + .build(); + + new Runner(options).run(); + + } +} diff --git a/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java b/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java new file mode 100644 index 0000000000..8a0e2d2826 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java @@ -0,0 +1,64 @@ +package com.baeldung.threadlocalrandom; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +@BenchmarkMode(Mode.AverageTime) +@Warmup(iterations = 1) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@State(Scope.Benchmark) +public class ThreadLocalRandomBenchMarker { + + List> randomCallables = new ArrayList<>(); + List> threadLocalRandomCallables = new ArrayList<>(); + + @Setup(Level.Iteration) + public void init() { + Random random = new Random(); + randomCallables = new ArrayList<>(); + threadLocalRandomCallables = new ArrayList<>(); + for (int i = 0; i < 1000; i++) { + randomCallables.add(() -> { + return random.nextInt(); + }); + } + + for (int i = 0; i < 1000; i++) { + threadLocalRandomCallables.add(() -> { + return ThreadLocalRandom.current() + .nextInt(); + }); + } + } + + @Benchmark + public void randomValuesUsingRandom() throws InterruptedException { + ExecutorService executor = Executors.newWorkStealingPool(); + executor.invokeAll(randomCallables); + executor.shutdown(); + } + + @Benchmark + public void randomValuesUsingThreadLocalRandom() throws InterruptedException { + ExecutorService executor = Executors.newWorkStealingPool(); + executor.invokeAll(threadLocalRandomCallables); + executor.shutdown(); + } + +} From 4e8506652391cb37dcd08304107f8406472ef01a Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Fri, 5 Jan 2018 20:11:33 +0200 Subject: [PATCH 22/58] fix list endpoints actuator endpoint (#3348) --- spring-custom-aop/spring-custom-aop/pom.xml | 2 +- .../org/baeldung/endpoints/EndpointDTO.java | 39 +++++++++++++++++++ .../org/baeldung/endpoints/ListEndpoints.java | 11 +++--- 3 files changed, 46 insertions(+), 6 deletions(-) create mode 100644 spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/EndpointDTO.java diff --git a/spring-custom-aop/spring-custom-aop/pom.xml b/spring-custom-aop/spring-custom-aop/pom.xml index 7e9da03b54..0bab7a4057 100644 --- a/spring-custom-aop/spring-custom-aop/pom.xml +++ b/spring-custom-aop/spring-custom-aop/pom.xml @@ -2,7 +2,7 @@ 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 - spring-boot + spring-custom-aop 0.0.1-SNAPSHOT war spring-boot diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/EndpointDTO.java b/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/EndpointDTO.java new file mode 100644 index 0000000000..d12d6419e1 --- /dev/null +++ b/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/EndpointDTO.java @@ -0,0 +1,39 @@ +package org.baeldung.endpoints; + +public class EndpointDTO { + private String id; + private boolean enabled; + private boolean sensitive; + + public EndpointDTO(String id, boolean enabled, boolean sensitive) { + super(); + this.id = id; + this.enabled = enabled; + this.sensitive = sensitive; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public boolean isSensitive() { + return sensitive; + } + + public void setSensitive(boolean sensitive) { + this.sensitive = sensitive; + } + +} diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/ListEndpoints.java b/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/ListEndpoints.java index 0add741a1f..f434351a51 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/ListEndpoints.java +++ b/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/ListEndpoints.java @@ -1,6 +1,7 @@ package org.baeldung.endpoints; import java.util.List; +import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.AbstractEndpoint; @@ -8,16 +9,16 @@ import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.stereotype.Component; @Component -public class ListEndpoints extends AbstractEndpoint> { - private List endpoints; +public class ListEndpoints extends AbstractEndpoint> { + private List endpointDTOs; @Autowired public ListEndpoints(List endpoints) { super("listEndpoints"); - this.endpoints = endpoints; + this.endpointDTOs = endpoints.stream().map(endpoint -> new EndpointDTO(endpoint.getId(), endpoint.isEnabled(), endpoint.isSensitive())).collect(Collectors.toList()); } - public List invoke() { - return this.endpoints; + public List invoke() { + return this.endpointDTOs; } } \ No newline at end of file From 749533e14dfa401a0e55b63bd186005865b7fa97 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Fri, 5 Jan 2018 20:18:24 +0200 Subject: [PATCH 23/58] fix start instead of run (#3353) --- .../src/main/java/com/baeldung/socket/EchoMultiServer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java index a9f055f8f4..d2f9f0459c 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java @@ -16,7 +16,7 @@ public class EchoMultiServer { try { serverSocket = new ServerSocket(port); while (true) - new EchoClientHandler(serverSocket.accept()).run(); + new EchoClientHandler(serverSocket.accept()).start(); } catch (IOException e) { e.printStackTrace(); From 1273bb4aeef13b8823acc2adfd3d8312735aaaae Mon Sep 17 00:00:00 2001 From: Magdalena Krause Date: Fri, 5 Jan 2018 16:51:47 -0300 Subject: [PATCH 24/58] BAEL-1277: RESTFul CRUD application with JavaLite (#3359) * BAEL-1277: RESTFul CRUD application with JavaLite. * BAEL-1277: RESTFul CRUD application with JavaLite. Adding exception handling. --- java-lite/README.md | 2 + java-lite/pom.xml | 105 ++++++++++++++++++ .../main/java/app/config/AppBootstrap.java | 9 ++ .../java/app/config/AppControllerConfig.java | 15 +++ .../src/main/java/app/config/DbConfig.java | 11 ++ .../app/controllers/ProductsController.java | 101 +++++++++++++++++ .../src/main/java/app/models/Product.java | 7 ++ .../src/main/resources/database.properties | 4 + .../webapp/WEB-INF/views/products/_comma.ftl | 1 + .../WEB-INF/views/products/_product.ftl | 4 + .../webapp/WEB-INF/views/products/index.ftl | 1 + .../webapp/WEB-INF/views/products/message.ftl | 4 + java-lite/src/main/webapp/WEB-INF/web.xml | 25 +++++ .../src/test/java/app/models/ProductTest.java | 25 +++++ pom.xml | 1 + 15 files changed, 315 insertions(+) create mode 100644 java-lite/README.md create mode 100644 java-lite/pom.xml create mode 100644 java-lite/src/main/java/app/config/AppBootstrap.java create mode 100644 java-lite/src/main/java/app/config/AppControllerConfig.java create mode 100644 java-lite/src/main/java/app/config/DbConfig.java create mode 100644 java-lite/src/main/java/app/controllers/ProductsController.java create mode 100644 java-lite/src/main/java/app/models/Product.java create mode 100644 java-lite/src/main/resources/database.properties create mode 100644 java-lite/src/main/webapp/WEB-INF/views/products/_comma.ftl create mode 100644 java-lite/src/main/webapp/WEB-INF/views/products/_product.ftl create mode 100644 java-lite/src/main/webapp/WEB-INF/views/products/index.ftl create mode 100644 java-lite/src/main/webapp/WEB-INF/views/products/message.ftl create mode 100644 java-lite/src/main/webapp/WEB-INF/web.xml create mode 100644 java-lite/src/test/java/app/models/ProductTest.java diff --git a/java-lite/README.md b/java-lite/README.md new file mode 100644 index 0000000000..bcb84e186e --- /dev/null +++ b/java-lite/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [RESTFul CRUD application with JavaLite] () \ No newline at end of file diff --git a/java-lite/pom.xml b/java-lite/pom.xml new file mode 100644 index 0000000000..554819f6e4 --- /dev/null +++ b/java-lite/pom.xml @@ -0,0 +1,105 @@ + + + 4.0.0 + + org.baeldung + java-lite + 1.0-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 9.3.4.RC1 + 1.4.13 + 1.15 + 5.1.45 + 1.7.0 + 1.8.2 + 4.11 + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty.maven.plugin.version} + + + + activejdbc.log + + + + active_reload + true + + + activeweb.log.request + true + + + + + + + org.javalite + activejdbc-instrumentation + ${activejdbc.version} + + + process-classes + + instrument + + + + + + + + + + org.javalite + activeweb + ${activeweb.version} + + + + mysql + mysql-connector-java + ${mysql.connector.java.version} + + + + com.sun + tools + ${sun.tools.version} + system + ${java.home}/../lib/tools.jar + + + + org.codehaus.jackson + jackson-core-lgpl + ${jackson.version} + + + org.codehaus.jackson + jackson-mapper-lgpl + ${jackson.version} + + + junit + junit + ${junit.version} + + + + \ No newline at end of file diff --git a/java-lite/src/main/java/app/config/AppBootstrap.java b/java-lite/src/main/java/app/config/AppBootstrap.java new file mode 100644 index 0000000000..7a87c2d0a7 --- /dev/null +++ b/java-lite/src/main/java/app/config/AppBootstrap.java @@ -0,0 +1,9 @@ +package app.config; + +import org.javalite.activeweb.AppContext; +import org.javalite.activeweb.Bootstrap; + +public class AppBootstrap extends Bootstrap { + public void init(AppContext context) { + } +} diff --git a/java-lite/src/main/java/app/config/AppControllerConfig.java b/java-lite/src/main/java/app/config/AppControllerConfig.java new file mode 100644 index 0000000000..42b7e728ec --- /dev/null +++ b/java-lite/src/main/java/app/config/AppControllerConfig.java @@ -0,0 +1,15 @@ +package app.config; + +import app.controllers.ProductsController; +import org.javalite.activeweb.AbstractControllerConfig; +import org.javalite.activeweb.AppContext; +import org.javalite.activeweb.controller_filters.DBConnectionFilter; +import org.javalite.activeweb.controller_filters.TimingFilter; + +public class AppControllerConfig extends AbstractControllerConfig { + @Override + public void init(AppContext appContext) { + addGlobalFilters(new TimingFilter()); + add(new DBConnectionFilter()).to(ProductsController.class); + } +} diff --git a/java-lite/src/main/java/app/config/DbConfig.java b/java-lite/src/main/java/app/config/DbConfig.java new file mode 100644 index 0000000000..25ba378b22 --- /dev/null +++ b/java-lite/src/main/java/app/config/DbConfig.java @@ -0,0 +1,11 @@ +package app.config; + +import org.javalite.activeweb.AbstractDBConfig; +import org.javalite.activeweb.AppContext; + +public class DbConfig extends AbstractDBConfig { + @Override + public void init(AppContext appContext) { + this.configFile("/database.properties"); + } +} diff --git a/java-lite/src/main/java/app/controllers/ProductsController.java b/java-lite/src/main/java/app/controllers/ProductsController.java new file mode 100644 index 0000000000..f68dd9a013 --- /dev/null +++ b/java-lite/src/main/java/app/controllers/ProductsController.java @@ -0,0 +1,101 @@ +package app.controllers; + +import app.models.Product; +import org.codehaus.jackson.map.ObjectMapper; +import org.javalite.activeweb.AppController; +import org.javalite.activeweb.annotations.RESTful; + +import java.util.Map; + +@RESTful +public class ProductsController extends AppController { + + public void index() { + try { + view("products", Product.findAll()); + render().contentType("application/json"); + } catch (Exception e) { + view("message", "There was an error.", "code", 200); + render("message"); + } + } + + public void create() { + try { + Map payload = new ObjectMapper().readValue(getRequestString(), Map.class); + Product p = new Product(); + p.fromMap(payload); + p.saveIt(); + view("message", "Successfully saved product id " + p.get("id"), "code", 200); + render("message"); + } catch (Exception e) { + view("message", "There was an error.", "code", 200); + render("message"); + } + } + + public void update() { + try { + Map payload = new ObjectMapper().readValue(getRequestString(), Map.class); + String id = getId(); + Product p = Product.findById(id); + if (p == null) { + view("message", "Product id " + id + " not found.", "code", 200); + render("message"); + return; + } + p.fromMap(payload); + p.saveIt(); + view("message", "Successfully updated product id " + id, "code", 200); + render("message"); + } catch (Exception e) { + view("message", "There was an error.", "code", 200); + render("message"); + } + } + + public void show() { + try { + String id = getId(); + Product p = Product.findById(id); + if (p == null) { + view("message", "Product id " + id + " not found.", "code", 200); + render("message"); + return; + } + view("product", p); + render("_product"); + } catch (Exception e) { + view("message", "There was an error.", "code", 200); + render("message"); + } + } + + public void destroy() { + try { + String id = getId(); + Product p = Product.findById(id); + if (p == null) { + view("message", "Product id " + id + " not found.", "code", 200); + render("message"); + return; + } + p.delete(); + view("message", "Successfully deleted product id " + id, "code", 200); + render("message"); + } catch (Exception e) { + view("message", "There was an error.", "code", 200); + render("message"); + } + } + + @Override + protected String getContentType() { + return "application/json"; + } + + @Override + protected String getLayout() { + return null; + } +} diff --git a/java-lite/src/main/java/app/models/Product.java b/java-lite/src/main/java/app/models/Product.java new file mode 100644 index 0000000000..7fa32b75d9 --- /dev/null +++ b/java-lite/src/main/java/app/models/Product.java @@ -0,0 +1,7 @@ +package app.models; + +import org.javalite.activejdbc.Model; + +public class Product extends Model { + +} diff --git a/java-lite/src/main/resources/database.properties b/java-lite/src/main/resources/database.properties new file mode 100644 index 0000000000..55b3851d33 --- /dev/null +++ b/java-lite/src/main/resources/database.properties @@ -0,0 +1,4 @@ +development.driver=com.mysql.jdbc.Driver +development.username=user +development.password=password +development.url=jdbc:mysql://localhost/dbname \ No newline at end of file diff --git a/java-lite/src/main/webapp/WEB-INF/views/products/_comma.ftl b/java-lite/src/main/webapp/WEB-INF/views/products/_comma.ftl new file mode 100644 index 0000000000..41622b4720 --- /dev/null +++ b/java-lite/src/main/webapp/WEB-INF/views/products/_comma.ftl @@ -0,0 +1 @@ +, \ No newline at end of file diff --git a/java-lite/src/main/webapp/WEB-INF/views/products/_product.ftl b/java-lite/src/main/webapp/WEB-INF/views/products/_product.ftl new file mode 100644 index 0000000000..562af0499e --- /dev/null +++ b/java-lite/src/main/webapp/WEB-INF/views/products/_product.ftl @@ -0,0 +1,4 @@ +{ +"id" : ${product.id}, +"name" : "${product.name}" +} \ No newline at end of file diff --git a/java-lite/src/main/webapp/WEB-INF/views/products/index.ftl b/java-lite/src/main/webapp/WEB-INF/views/products/index.ftl new file mode 100644 index 0000000000..c343f20910 --- /dev/null +++ b/java-lite/src/main/webapp/WEB-INF/views/products/index.ftl @@ -0,0 +1 @@ +[<@render partial="product" collection=products spacer="comma"/>] \ No newline at end of file diff --git a/java-lite/src/main/webapp/WEB-INF/views/products/message.ftl b/java-lite/src/main/webapp/WEB-INF/views/products/message.ftl new file mode 100644 index 0000000000..3e7faf1459 --- /dev/null +++ b/java-lite/src/main/webapp/WEB-INF/views/products/message.ftl @@ -0,0 +1,4 @@ +{ +"message" : "${message}", +"code" : ${code} +} \ No newline at end of file diff --git a/java-lite/src/main/webapp/WEB-INF/web.xml b/java-lite/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..c285876c86 --- /dev/null +++ b/java-lite/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,25 @@ + + + + + + dispatcher + org.javalite.activeweb.RequestDispatcher + + exclusions + css,images,js,ico + + + encoding + UTF-8 + + + + + + dispatcher + /* + + + diff --git a/java-lite/src/test/java/app/models/ProductTest.java b/java-lite/src/test/java/app/models/ProductTest.java new file mode 100644 index 0000000000..f6ee0a3d0a --- /dev/null +++ b/java-lite/src/test/java/app/models/ProductTest.java @@ -0,0 +1,25 @@ +package app.models; + +import org.javalite.activejdbc.Base; +import org.junit.Assert; +import org.junit.Test; + +public class ProductTest { + + //@Test + public void givenSavedProduct_WhenFindFirst_ThenSavedProductIsReturned() { + //Open DB connection + Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/dbname", "user", "password"); + + //Create a product and save it + Product toSaveProduct = new Product(); + toSaveProduct.set("name", "Bread"); + toSaveProduct.saveIt(); + + //Find product + Product savedProduct = Product.findFirst("name = ?", "Bread"); + + Assert.assertEquals(toSaveProduct.get("name"), savedProduct.get("name")); + } + +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 19e42009c9..7022fa3a38 100644 --- a/pom.xml +++ b/pom.xml @@ -85,6 +85,7 @@ jackson vavr + java-lite javax-servlets javaxval jaxb From fe0e0ba1151087892485b5ebe9c353239fdcb738 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Fri, 5 Jan 2018 21:56:21 +0200 Subject: [PATCH 25/58] upgrade boot parent (#3352) * make sure modules using java8 * move url matching code * upgrade boot parent * minor cleanup --- hystrix/pom.xml | 4 +- jjwt/pom.xml | 4 +- .../DemoApplicationIntegrationTest.java | 4 +- parent-boot-4/README.md | 1 - parent-boot-4/pom.xml | 81 ------------------- parent-boot-5/pom.xml | 6 +- pom.xml | 1 + spring-all/pom.xml | 4 +- spring-boot-keycloak/pom.xml | 4 +- spring-cloud-data-flow/batch-job/pom.xml | 4 +- .../data-flow-server/pom.xml | 4 +- .../data-flow-shell/pom.xml | 4 +- spring-cloud-data-flow/log-sink/pom.xml | 4 +- spring-cloud-data-flow/time-processor/pom.xml | 4 +- spring-cloud-data-flow/time-source/pom.xml | 4 +- .../spring-cloud-bootstrap/config/pom.xml | 4 +- .../spring-cloud-bootstrap/discovery/pom.xml | 4 +- .../spring-cloud-bootstrap/gateway/pom.xml | 4 +- .../spring-cloud-bootstrap/svc-book/pom.xml | 4 +- .../spring-cloud-bootstrap/svc-rating/pom.xml | 4 +- .../spring-cloud-bootstrap/zipkin/pom.xml | 4 +- .../config/client/ConfigClientLiveTest.java | 5 +- spring-cloud/spring-cloud-config/pom.xml | 4 +- .../ConfigServerListIntegrationTest.java | 4 +- .../spring-cloud-rest-books-api/pom.xml | 4 +- .../spring-cloud-rest-config-server/pom.xml | 4 +- .../pom.xml | 4 +- .../spring-cloud-rest-reviews-api/pom.xml | 4 +- .../spring-cloud-ribbon-client/pom.xml | 4 +- spring-cucumber/pom.xml | 4 +- .../com/baeldung/SpringIntegrationTest.java | 13 ++- spring-katharsis/pom.xml | 4 +- .../main/java/org/baeldung/Application.java | 2 +- spring-mobile/pom.xml | 4 +- spring-mockito/pom.xml | 4 +- .../baeldung/UserServiceIntegrationTest.java | 4 +- spring-mvc-email/pom.xml | 4 +- spring-protobuf/pom.xml | 4 +- .../protobuf/ApplicationIntegrationTest.java | 22 ++--- spring-quartz/pom.xml | 4 +- spring-reactor/pom.xml | 4 +- spring-remoting/pom.xml | 4 +- spring-rest-docs/pom.xml | 4 +- .../ApiDocumentationIntegrationTest.java | 45 ++++++----- ...ngStartedDocumentationIntegrationTest.java | 33 ++++---- spring-rest-full/pom.xml | 4 +- spring-rest-query-language/pom.xml | 4 +- spring-rest/pom.xml | 4 +- spring-security-cache-control/pom.xml | 4 +- .../pom.xml | 4 +- .../spring-security-jsp-authorize/pom.xml | 4 +- .../spring-security-jsp-config/pom.xml | 4 +- .../spring-security-mvc/pom.xml | 4 +- .../java/org/baeldung/config/Application.java | 2 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../spring-security-thymeleaf-config/pom.xml | 4 +- spring-security-core/pom.xml | 4 +- spring-security-mvc-ldap/pom.xml | 4 +- spring-security-rest-custom/pom.xml | 4 +- spring-security-stormpath/pom.xml | 4 +- spring-security-x509/pom.xml | 4 +- spring-session/pom.xml | 4 +- spring-sleuth/pom.xml | 4 +- spring-social-login/pom.xml | 4 +- spring-zuul/pom.xml | 4 +- .../config/ResourceServerApplication.java | 2 +- 67 files changed, 175 insertions(+), 258 deletions(-) delete mode 100644 parent-boot-4/README.md delete mode 100644 parent-boot-4/pom.xml diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 58e09816ea..9e4b2bb082 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -7,10 +7,10 @@ hystrix - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/jjwt/pom.xml b/jjwt/pom.xml index 83a1131211..cd2dd9f97e 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -12,10 +12,10 @@ Exercising the JJWT - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java b/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java index df147232d9..846445ab2b 100644 --- a/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java +++ b/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java @@ -2,12 +2,12 @@ package io.jsonwebtoken.jjwtfun; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = JJWTFunApplication.class) +@SpringBootTest(classes = JJWTFunApplication.class) @WebAppConfiguration public class DemoApplicationIntegrationTest { diff --git a/parent-boot-4/README.md b/parent-boot-4/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/parent-boot-4/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/parent-boot-4/pom.xml b/parent-boot-4/pom.xml deleted file mode 100644 index 51ef9f4854..0000000000 --- a/parent-boot-4/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - 4.0.0 - com.baeldung - parent-boot-4 - 0.0.1-SNAPSHOT - pom - Parent Boot 4 - Parent for all spring boot 1.4 modules - - - UTF-8 - UTF-8 - 1.8 - 3.0.1 - - 2.19.1 - 3.7.0 - - - - spring-boot-starter-parent - org.springframework.boot - 1.4.4.RELEASE - - - - - - junit - junit - test - - - io.rest-assured - rest-assured - ${rest-assured.version} - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - - - - \ No newline at end of file diff --git a/parent-boot-5/pom.xml b/parent-boot-5/pom.xml index 6b1445fcdd..55ac0957ff 100644 --- a/parent-boot-5/pom.xml +++ b/parent-boot-5/pom.xml @@ -12,16 +12,16 @@ UTF-8 UTF-8 1.8 - 3.0.1 + 3.0.6 - 2.19.1 + 2.20.1 3.7.0 spring-boot-starter-parent org.springframework.boot - 1.5.3.RELEASE + 1.5.9.RELEASE diff --git a/pom.xml b/pom.xml index 7022fa3a38..68edf19cb2 100644 --- a/pom.xml +++ b/pom.xml @@ -28,6 +28,7 @@ + parent-boot-5 asm atomix apache-cayenne diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 6615e1d6cd..b04ffae9c8 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-boot-keycloak/pom.xml b/spring-boot-keycloak/pom.xml index ab76d0af43..741e2313b4 100644 --- a/spring-boot-keycloak/pom.xml +++ b/spring-boot-keycloak/pom.xml @@ -14,9 +14,9 @@ com.baeldung - parent-boot-4 + parent-boot-5 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-cloud-data-flow/batch-job/pom.xml b/spring-cloud-data-flow/batch-job/pom.xml index 9a40c80e37..f2e9f35c8e 100644 --- a/spring-cloud-data-flow/batch-job/pom.xml +++ b/spring-cloud-data-flow/batch-job/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-cloud-data-flow/data-flow-server/pom.xml b/spring-cloud-data-flow/data-flow-server/pom.xml index ec0057191b..456a8abf4b 100644 --- a/spring-cloud-data-flow/data-flow-server/pom.xml +++ b/spring-cloud-data-flow/data-flow-server/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-cloud-data-flow/data-flow-shell/pom.xml b/spring-cloud-data-flow/data-flow-shell/pom.xml index b34c3cefeb..edb300a3b3 100644 --- a/spring-cloud-data-flow/data-flow-shell/pom.xml +++ b/spring-cloud-data-flow/data-flow-shell/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-cloud-data-flow/log-sink/pom.xml b/spring-cloud-data-flow/log-sink/pom.xml index b97a72d9c4..c07380de56 100644 --- a/spring-cloud-data-flow/log-sink/pom.xml +++ b/spring-cloud-data-flow/log-sink/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-cloud-data-flow/time-processor/pom.xml b/spring-cloud-data-flow/time-processor/pom.xml index 9b190e7250..08d5e2b9be 100644 --- a/spring-cloud-data-flow/time-processor/pom.xml +++ b/spring-cloud-data-flow/time-processor/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-cloud-data-flow/time-source/pom.xml b/spring-cloud-data-flow/time-source/pom.xml index 3112c7ede8..4d35e30be2 100644 --- a/spring-cloud-data-flow/time-source/pom.xml +++ b/spring-cloud-data-flow/time-source/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-cloud/spring-cloud-bootstrap/config/pom.xml b/spring-cloud/spring-cloud-bootstrap/config/pom.xml index 77ceedab39..f01ab55eb2 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/config/pom.xml @@ -7,10 +7,10 @@ 1.0.0-SNAPSHOT - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-4 + ../../../parent-boot-5 diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml index 3156e0f3e6..137e9bebad 100644 --- a/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml @@ -7,10 +7,10 @@ 1.0.0-SNAPSHOT - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-4 + ../../../parent-boot-5 diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml index 84dc2a6ca9..f32de88076 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml @@ -7,10 +7,10 @@ 1.0.0-SNAPSHOT - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-4 + ../../../parent-boot-5 diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml index d35e4f6576..9cc3cdb516 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml @@ -8,10 +8,10 @@ 1.0.0-SNAPSHOT - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-4 + ../../../parent-boot-5 diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml index 736a6114cf..3aa5cfa250 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml @@ -8,10 +8,10 @@ 1.0.0-SNAPSHOT - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-4 + ../../../parent-boot-5 diff --git a/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml b/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml index 3b4c984721..7e0d146f95 100644 --- a/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml @@ -7,10 +7,10 @@ 1.0.0-SNAPSHOT - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-4 + ../../../parent-boot-5 diff --git a/spring-cloud/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java b/spring-cloud/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java index 058fd45f35..9bca369c64 100644 --- a/spring-cloud/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java +++ b/spring-cloud/spring-cloud-config/client/src/test/java/com/baeldung/spring/cloud/config/client/ConfigClientLiveTest.java @@ -1,14 +1,13 @@ package com.baeldung.spring.cloud.config.client; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = ConfigClient.class) +@SpringBootTest(classes = ConfigClient.class) @WebAppConfiguration public class ConfigClientLiveTest { @Test diff --git a/spring-cloud/spring-cloud-config/pom.xml b/spring-cloud/spring-cloud-config/pom.xml index 81693b7e2e..a5f3f5271d 100644 --- a/spring-cloud/spring-cloud-config/pom.xml +++ b/spring-cloud/spring-cloud-config/pom.xml @@ -15,10 +15,10 @@ - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListIntegrationTest.java b/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListIntegrationTest.java index 34c08cc815..c521a0d2ef 100644 --- a/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListIntegrationTest.java +++ b/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/ConfigServerListIntegrationTest.java @@ -3,12 +3,12 @@ package com.baeldung.spring.cloud.config.server; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = ConfigServer.class) +@SpringBootTest(classes = ConfigServer.class) @WebAppConfiguration @Ignore public class ConfigServerListIntegrationTest { diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml index fb84b33876..07f6ae3b55 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml @@ -12,10 +12,10 @@ Simple books API - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-4 + ../../../parent-boot-5 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml index f0a563f16f..11320107be 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml @@ -12,10 +12,10 @@ Spring Cloud REST configuration server - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-4 + ../../../parent-boot-5 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml index 0735808eea..d8dbc660d0 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml @@ -12,10 +12,10 @@ Spring Cloud REST server - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-4 + ../../../parent-boot-5 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml index 2574cae4eb..4252947664 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml @@ -12,10 +12,10 @@ Simple reviews API - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-4 + ../../../parent-boot-5 diff --git a/spring-cloud/spring-cloud-ribbon-client/pom.xml b/spring-cloud/spring-cloud-ribbon-client/pom.xml index 68f3bd9439..85baff12cd 100644 --- a/spring-cloud/spring-cloud-ribbon-client/pom.xml +++ b/spring-cloud/spring-cloud-ribbon-client/pom.xml @@ -9,10 +9,10 @@ Introduction to Spring Cloud Rest Client with Netflix Ribbon - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index 8270fc3ae2..df4723484d 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java index 9fbaeb348d..f4d47d7871 100644 --- a/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java @@ -1,8 +1,10 @@ package com.baeldung; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.IntegrationTest; -import org.springframework.boot.test.SpringApplicationContextLoader; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.context.ContextConfiguration; @@ -10,14 +12,9 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestTemplate; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - //@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = SpringDemoApplication.class, loader = SpringApplicationContextLoader.class) +@ContextConfiguration(classes = SpringDemoApplication.class) @WebAppConfiguration -@IntegrationTest public class SpringIntegrationTest { static ResponseResults latestResponse = null; diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index a5e79e138b..49c0a5acf9 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -7,10 +7,10 @@ war - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-katharsis/src/main/java/org/baeldung/Application.java b/spring-katharsis/src/main/java/org/baeldung/Application.java index e7beb16e04..b61151d87f 100644 --- a/spring-katharsis/src/main/java/org/baeldung/Application.java +++ b/spring-katharsis/src/main/java/org/baeldung/Application.java @@ -2,7 +2,7 @@ package org.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class Application extends SpringBootServletInitializer { diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index 8b8618aeee..3a129c179e 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -11,10 +11,10 @@ http://maven.apache.org - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index d8bcc5682a..8c2949275c 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -12,10 +12,10 @@ Injecting Mockito Mocks into Spring Beans - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java b/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java index 70861a96e1..d70f916b12 100644 --- a/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java +++ b/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java @@ -5,13 +5,13 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ActiveProfiles("test") @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = MocksApplication.class) +@SpringBootTest(classes = MocksApplication.class) public class UserServiceIntegrationTest { @Autowired diff --git a/spring-mvc-email/pom.xml b/spring-mvc-email/pom.xml index 9228054878..ddb1765af0 100644 --- a/spring-mvc-email/pom.xml +++ b/spring-mvc-email/pom.xml @@ -10,10 +10,10 @@ war - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-protobuf/pom.xml b/spring-protobuf/pom.xml index 36310e08f1..1771c3e1f2 100644 --- a/spring-protobuf/pom.xml +++ b/spring-protobuf/pom.xml @@ -7,10 +7,10 @@ spring-protobuf - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java index 914cf18627..4b9f41ace3 100644 --- a/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java +++ b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java @@ -1,7 +1,11 @@ package com.baeldung.protobuf; -import com.baeldung.protobuf.BaeldungTraining.Course; -import com.googlecode.protobuf.format.JsonFormat; +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.io.InputStream; + import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; @@ -9,21 +13,17 @@ import org.apache.http.impl.client.HttpClients; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.boot.test.WebIntegrationTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; -import java.io.IOException; -import java.io.InputStream; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertThat; +import com.baeldung.protobuf.BaeldungTraining.Course; +import com.googlecode.protobuf.format.JsonFormat; @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = Application.class) -@WebIntegrationTest +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) public class ApplicationIntegrationTest { private static final String COURSE1_URL = "http://localhost:8080/courses/1"; diff --git a/spring-quartz/pom.xml b/spring-quartz/pom.xml index eb00911543..78beab6e38 100644 --- a/spring-quartz/pom.xml +++ b/spring-quartz/pom.xml @@ -11,10 +11,10 @@ Demo project for Scheduling in Spring with Quartz - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-reactor/pom.xml b/spring-reactor/pom.xml index 759e9f2b58..1a19d9c6d9 100644 --- a/spring-reactor/pom.xml +++ b/spring-reactor/pom.xml @@ -9,10 +9,10 @@ http://maven.apache.org - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-remoting/pom.xml b/spring-remoting/pom.xml index b40f77eb50..aac8357c10 100644 --- a/spring-remoting/pom.xml +++ b/spring-remoting/pom.xml @@ -11,10 +11,10 @@ Parent for all projects related to Spring Remoting. - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-rest-docs/pom.xml b/spring-rest-docs/pom.xml index 4647577629..ffd3cb89b6 100644 --- a/spring-rest-docs/pom.xml +++ b/spring-rest-docs/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java b/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java index f2ac9d0f82..1c3aef4845 100644 --- a/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java +++ b/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java @@ -1,26 +1,5 @@ package com.example; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.hateoas.MediaTypes; -import org.springframework.restdocs.RestDocumentation; -import org.springframework.restdocs.constraints.ConstraintDescriptions; -import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler; -import org.springframework.restdocs.payload.FieldDescriptor; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import java.util.HashMap; -import java.util.Map; - import static java.util.Collections.singletonList; import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders; @@ -43,8 +22,30 @@ import static org.springframework.restdocs.snippet.Attributes.key; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.util.StringUtils.collectionToDelimitedString; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Rule; +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.hateoas.MediaTypes; +import org.springframework.restdocs.RestDocumentation; +import org.springframework.restdocs.constraints.ConstraintDescriptions; +import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler; +import org.springframework.restdocs.payload.FieldDescriptor; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.fasterxml.jackson.databind.ObjectMapper; + @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SpringRestDocsApplication.class) +@SpringBootTest(classes = SpringRestDocsApplication.class) @WebAppConfiguration public class ApiDocumentationIntegrationTest { diff --git a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java index c02c0c27f8..3300fc519c 100644 --- a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java +++ b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java @@ -1,20 +1,5 @@ package com.example; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.hateoas.MediaTypes; -import org.springframework.restdocs.RestDocumentation; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; @@ -26,8 +11,24 @@ import static org.springframework.restdocs.operation.preprocess.Preprocessors.pr import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.junit.Before; +import org.junit.Rule; +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.hateoas.MediaTypes; +import org.springframework.restdocs.RestDocumentation; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.fasterxml.jackson.databind.ObjectMapper; + @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SpringRestDocsApplication.class) +@SpringBootTest(classes = SpringRestDocsApplication.class) @WebAppConfiguration public class GettingStartedDocumentationIntegrationTest { diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index c596e79b31..c00387e7de 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index bf3eb8cb78..6826634bc9 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 06747ffd41..6da891b054 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -8,10 +8,10 @@ war - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml index e525cd4e8e..4ccb83c29b 100644 --- a/spring-security-cache-control/pom.xml +++ b/spring-security-cache-control/pom.xml @@ -8,10 +8,10 @@ 1.0-SNAPSHOT - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-security-client/spring-security-jsp-authentication/pom.xml b/spring-security-client/spring-security-jsp-authentication/pom.xml index 6f4095c2d5..b29ce90aa4 100644 --- a/spring-security-client/spring-security-jsp-authentication/pom.xml +++ b/spring-security-client/spring-security-jsp-authentication/pom.xml @@ -12,10 +12,10 @@ Spring Security JSP Authentication tag sample - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-security-client/spring-security-jsp-authorize/pom.xml b/spring-security-client/spring-security-jsp-authorize/pom.xml index 2e1a57a468..6fd89933bb 100644 --- a/spring-security-client/spring-security-jsp-authorize/pom.xml +++ b/spring-security-client/spring-security-jsp-authorize/pom.xml @@ -12,10 +12,10 @@ Spring Security JSP Authorize tag sample - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-security-client/spring-security-jsp-config/pom.xml b/spring-security-client/spring-security-jsp-config/pom.xml index 4f92e24563..f533410acc 100644 --- a/spring-security-client/spring-security-jsp-config/pom.xml +++ b/spring-security-client/spring-security-jsp-config/pom.xml @@ -12,10 +12,10 @@ Spring Security JSP configuration - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-security-client/spring-security-mvc/pom.xml b/spring-security-client/spring-security-mvc/pom.xml index a642e8719d..c67bc336f6 100644 --- a/spring-security-client/spring-security-mvc/pom.xml +++ b/spring-security-client/spring-security-mvc/pom.xml @@ -12,10 +12,10 @@ Spring Security MVC - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java index 4057a85f13..34c43fbe5a 100644 --- a/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java @@ -3,7 +3,7 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class Application extends SpringBootServletInitializer { diff --git a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml index 7573d430d3..941cbb8a76 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml @@ -12,10 +12,10 @@ Spring Security thymeleaf authentication tag sample - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml index 20d141e70c..c70a099e68 100644 --- a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml @@ -12,10 +12,10 @@ Spring Security thymeleaf authorize tag sample - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-security-client/spring-security-thymeleaf-config/pom.xml b/spring-security-client/spring-security-thymeleaf-config/pom.xml index ad856c7e20..9ef2444d6c 100644 --- a/spring-security-client/spring-security-thymeleaf-config/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-config/pom.xml @@ -12,10 +12,10 @@ Spring Security thymeleaf configuration sample project - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-4 + ../../parent-boot-5 diff --git a/spring-security-core/pom.xml b/spring-security-core/pom.xml index 7deea5deb0..db8837df46 100644 --- a/spring-security-core/pom.xml +++ b/spring-security-core/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index e6452ea70b..4b0b9525e4 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index 77a58a56d8..746ddb6615 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-security-stormpath/pom.xml b/spring-security-stormpath/pom.xml index 982c677bf5..060f8a553d 100644 --- a/spring-security-stormpath/pom.xml +++ b/spring-security-stormpath/pom.xml @@ -24,10 +24,10 @@ - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-security-x509/pom.xml b/spring-security-x509/pom.xml index 77830ebe5a..6225f73ebc 100644 --- a/spring-security-x509/pom.xml +++ b/spring-security-x509/pom.xml @@ -15,10 +15,10 @@ - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-session/pom.xml b/spring-session/pom.xml index bb644c8b2e..b62d814665 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -8,10 +8,10 @@ jar - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-sleuth/pom.xml b/spring-sleuth/pom.xml index dda5e09a26..aac0084720 100644 --- a/spring-sleuth/pom.xml +++ b/spring-sleuth/pom.xml @@ -9,10 +9,10 @@ jar - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml index 0ca04ac298..50e2abfbfc 100644 --- a/spring-social-login/pom.xml +++ b/spring-social-login/pom.xml @@ -7,10 +7,10 @@ war - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-zuul/pom.xml b/spring-zuul/pom.xml index e1a551bc84..ca9cbc765d 100644 --- a/spring-zuul/pom.xml +++ b/spring-zuul/pom.xml @@ -9,10 +9,10 @@ pom - parent-boot-4 + parent-boot-5 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-4 + ../parent-boot-5 diff --git a/spring-zuul/spring-zuul-foos-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java b/spring-zuul/spring-zuul-foos-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java index 1e35eff551..9f1d2e162b 100644 --- a/spring-zuul/spring-zuul-foos-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java +++ b/spring-zuul/spring-zuul-foos-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java @@ -2,7 +2,7 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class ResourceServerApplication extends SpringBootServletInitializer { From 21c41cfd99b78d9496f9767b6aa1c3e9c329162d Mon Sep 17 00:00:00 2001 From: Mansi Date: Sat, 6 Jan 2018 08:08:02 +0530 Subject: [PATCH 26/58] BAEL-1297 Find kth largest element in a sequence of numbers (#3332) * Example Code For Evaluation Article This is an example code for the evaluation article on "Different Types of Bean Injection in Spring" * Added unit tests * Minor changes to application context * Removed code committed for evaluation article * BAEL-944 Demonstrating the problems with new Url pattern matching in Spring 5 * BAEL-944 Demonstrating the problems with new Url pattern matching in Spring 5 * BAEL-944 Exploring the Spring MVC URL Matching Improvements * BAEL-944 Exploring the Spring MVC URL Matching Improvements * BAEL-944 Exploring the Spring MVC URL Matching Improvements * BAEL-944 Code Formatting and solving build issue * BAEL-944 Resolving build issue due to change in Spring version * BAEL-944 Resolving build issue * BAEL-944 Formatting code * BAEL-944 Moving tests to correct package * BAEL-944 Moving tests to correct package * BAEL-944 Replacing @RequestMapping by @GetMapping * BAEL-944 Remove unnecessary attribute name, "value" in annotations * BAEL-79 Intro to Activiti with Spring * BAEL-79 Intro to Activiti with Spring * BAEL-79 Adding activiti module to the parent modules * BAEL-79 Using latest version * BAEL-79 Update Spring boot version that works with Activiti * BAEL-79 Replace RequestMapping with GetMapping * BAEL-79 Use Java 8 Syntax * BAEL-79 Formatting * BAEL-79 changed module name * BAEL-378 A Guide to Activiti with Java * BAEL-79 Fixed unit tests * BAEL-79 Simplified the process * BAEL-79 Fix test cases * BAEL-1045 Lambda Behave * BAEL-1045 Lambda Behave * BAEL-1045 Lambda Behave * BAEL-1090 Difference between compact and compressed strings in Java 9 * BAEL-1237 String Formatter * BAEL-1237 String Formatter * BAEL-1237 String Formatter * BAEL-1237 String Formatter * BAEL-1237 Guide to java.util.Formatter * BAEL-1297 Find kth largest element in a sequence of numbers * BAEL-1297 fixed issues and modified file name * BAEL-1297 Modified randomized quickselect * BAEL-1297 added additional sorting method * BAEL-1297 UnitTest fix * BAEL-1297 Additional method Added QuickSelect With Iterative Partition method * BAEL-1297 Added AssertJ annotations * BAEL-1297 added missing assertj dependancy --- algorithms/pom.xml | 6 + .../algorithms/kthlargest/FindKthLargest.java | 111 ++++++++++++++++++ .../kthlargest/FindKthLargestUnitTest.java | 57 +++++++++ 3 files changed, 174 insertions(+) create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java diff --git a/algorithms/pom.xml b/algorithms/pom.xml index e972f39494..2eb8cd42b6 100644 --- a/algorithms/pom.xml +++ b/algorithms/pom.xml @@ -39,6 +39,12 @@ jgrapht-core 1.0.1 + + org.assertj + assertj-core + 3.9.0 + test + diff --git a/algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java b/algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java new file mode 100644 index 0000000000..822abdae02 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java @@ -0,0 +1,111 @@ +package com.baeldung.algorithms.kthlargest; + +import java.util.Arrays; +import java.util.Collections; +import java.util.stream.IntStream; + +public class FindKthLargest { + + public int findKthLargestBySorting(Integer[] arr, int k) { + Arrays.sort(arr); + int targetIndex = arr.length - k; + return arr[targetIndex]; + } + + public int findKthLargestBySortingDesc(Integer[] arr, int k) { + Arrays.sort(arr, Collections.reverseOrder()); + return arr[k - 1]; + } + + public int findKthElementByQuickSelect(Integer[] arr, int left, int right, int k) { + if (k >= 0 && k <= right - left + 1) { + int pos = partition(arr, left, right); + if (pos - left == k) { + return arr[pos]; + } + if (pos - left > k) { + return findKthElementByQuickSelect(arr, left, pos - 1, k); + } + return findKthElementByQuickSelect(arr, pos + 1, right, k - pos + left - 1); + } + return 0; + } + + public int findKthElementByQuickSelectWithIterativePartition(Integer[] arr, int left, int right, int k) { + if (k >= 0 && k <= right - left + 1) { + int pos = partitionIterative(arr, left, right); + if (pos - left == k) { + return arr[pos]; + } + if (pos - left > k) { + return findKthElementByQuickSelectWithIterativePartition(arr, left, pos - 1, k); + } + return findKthElementByQuickSelectWithIterativePartition(arr, pos + 1, right, k - pos + left - 1); + } + return 0; + } + + private int partition(Integer[] arr, int left, int right) { + int pivot = arr[right]; + Integer[] leftArr; + Integer[] rightArr; + + leftArr = IntStream.range(left, right) + .filter(i -> arr[i] < pivot) + .map(i -> arr[i]) + .boxed() + .toArray(Integer[]::new); + + rightArr = IntStream.range(left, right) + .filter(i -> arr[i] > pivot) + .map(i -> arr[i]) + .boxed() + .toArray(Integer[]::new); + + int leftArraySize = leftArr.length; + System.arraycopy(leftArr, 0, arr, left, leftArraySize); + arr[leftArraySize + left] = pivot; + System.arraycopy(rightArr, 0, arr, left + leftArraySize + 1, rightArr.length); + + return left + leftArraySize; + } + + private int partitionIterative(Integer[] arr, int left, int right) { + int pivot = arr[right], i = left; + for (int j = left; j <= right - 1; j++) { + if (arr[j] <= pivot) { + swap(arr, i, j); + i++; + } + } + swap(arr, i, right); + return i; + } + + public int findKthElementByRandomizedQuickSelect(Integer[] arr, int left, int right, int k) { + if (k >= 0 && k <= right - left + 1) { + int pos = randomPartition(arr, left, right); + if (pos - left == k) { + return arr[pos]; + } + if (pos - left > k) { + return findKthElementByRandomizedQuickSelect(arr, left, pos - 1, k); + } + return findKthElementByRandomizedQuickSelect(arr, pos + 1, right, k - pos + left - 1); + } + return 0; + } + + private int randomPartition(Integer arr[], int left, int right) { + int n = right - left + 1; + int pivot = (int) (Math.random()) % n; + swap(arr, left + pivot, right); + return partition(arr, left, right); + } + + private void swap(Integer[] arr, int n1, int n2) { + int temp = arr[n2]; + arr[n2] = arr[n1]; + arr[n1] = temp; + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java new file mode 100644 index 0000000000..6fbb7c163a --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.algorithms.kthlargest; + +import static org.assertj.core.api.Assertions.*; + +import org.junit.Before; +import org.junit.Test; + +public class FindKthLargestUnitTest { + + private FindKthLargest findKthLargest; + private Integer[] arr = { 3, 7, 1, 2, 8, 10, 4, 5, 6, 9 }; + + @Before + public void setup() { + findKthLargest = new FindKthLargest(); + } + + @Test + public void givenIntArray_whenFindKthLargestBySorting_thenGetResult() { + int k = 3; + assertThat(findKthLargest.findKthLargestBySorting(arr, k)).isEqualTo(8); + } + + @Test + public void givenIntArray_whenFindKthLargestBySortingDesc_thenGetResult() { + int k = 3; + assertThat(findKthLargest.findKthLargestBySortingDesc(arr, k)).isEqualTo(8); + } + + @Test + public void givenIntArray_whenFindKthLargestByQuickSelect_thenGetResult() { + int k = 3; + int kthLargest = arr.length - k; + assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8); + } + + @Test + public void givenIntArray_whenFindKthElementByQuickSelectIterative_thenGetResult() { + int k = 3; + int kthLargest = arr.length - k; + assertThat(findKthLargest.findKthElementByQuickSelectWithIterativePartition(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8); + } + + @Test + public void givenIntArray_whenFindKthSmallestByQuickSelect_thenGetResult() { + int k = 3; + assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, k - 1)).isEqualTo(3); + } + + @Test + public void givenIntArray_whenFindKthLargestByRandomizedQuickSelect_thenGetResult() { + int k = 3; + int kthLargest = arr.length - k; + assertThat(findKthLargest.findKthElementByRandomizedQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8); + } + +} From 93273366dcbd9d24a1d368a4c0920cabb0cb02be Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 6 Jan 2018 11:28:35 +0200 Subject: [PATCH 27/58] Update README.md --- core-java/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java/README.md b/core-java/README.md index b965d25f88..4352768bca 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -131,4 +131,4 @@ - [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array) - [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class) - [A Guide to Java Initialization](http://www.baeldung.com/java-initialization) - +- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random) From 7546281a71c1bc28e248747763b6af4c789a23c0 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 6 Jan 2018 11:33:42 +0200 Subject: [PATCH 28/58] Update README.md --- spring-jenkins-pipeline/README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/spring-jenkins-pipeline/README.md b/spring-jenkins-pipeline/README.md index 7e562664e6..8c10e85da2 100644 --- a/spring-jenkins-pipeline/README.md +++ b/spring-jenkins-pipeline/README.md @@ -10,7 +10,6 @@ This is the code of a simple API for some CRUD operations build using Spring Boo - MongoDB ### Running - To build and start the server simply type ```bash @@ -20,4 +19,8 @@ $ mvn spring-boot:run -Dserver.port=8989 Now with default configurations it will be available at: [http://localhost:8080](http://localhost:8080) -Enjoy it :) \ No newline at end of file +Enjoy it :) + +### Relevant articles + +- [Intro to Jenkins 2 and the Power of Pipelines](http://www.baeldung.com/jenkins-pipelines) From 7674ec43be51139fba43025356cdee0eb8b39691 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 6 Jan 2018 11:35:44 +0200 Subject: [PATCH 29/58] Update README.md --- core-java/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core-java/README.md b/core-java/README.md index b965d25f88..1259e61b62 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -131,4 +131,6 @@ - [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array) - [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class) - [A Guide to Java Initialization](http://www.baeldung.com/java-initialization) +- [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree) + From bcae968f99f869370959531bac8db223afad059e Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 6 Jan 2018 18:43:48 +0200 Subject: [PATCH 30/58] Update README.md --- core-java/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java/README.md b/core-java/README.md index 911e22cc48..94d203533e 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -133,4 +133,3 @@ - [A Guide to Java Initialization](http://www.baeldung.com/java-initialization) - [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree) - [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random) - From 81088757230d885be7d13cc5376120eb7c7730be Mon Sep 17 00:00:00 2001 From: Jonathan Date: Sat, 6 Jan 2018 11:01:49 -0600 Subject: [PATCH 31/58] BAEL-1068 (#3070) * BAEL-1068 - Javadoc example classes * BAEL-1068 - Formatting change for pom.xml * Updated javadoc comments to reflect article example --- core-java/pom.xml | 10 +++ .../java/com/baeldung/javadoc/Person.java | 22 +++++++ .../java/com/baeldung/javadoc/SuperHero.java | 64 +++++++++++++++++++ 3 files changed, 96 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/javadoc/Person.java create mode 100644 core-java/src/main/java/com/baeldung/javadoc/SuperHero.java diff --git a/core-java/pom.xml b/core-java/pom.xml index f99e4d68cf..5c1e9fcad0 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -389,6 +389,16 @@ + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.0.0-M1 + + 1.8 + 1.8 + + diff --git a/core-java/src/main/java/com/baeldung/javadoc/Person.java b/core-java/src/main/java/com/baeldung/javadoc/Person.java new file mode 100644 index 0000000000..5efb410de4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/javadoc/Person.java @@ -0,0 +1,22 @@ +package com.baeldung.javadoc; + +public class Person { + /** + * This is a first name + */ + private String firstName; + private String lastName; + + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } +} diff --git a/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java b/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java new file mode 100644 index 0000000000..029a779cdb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java @@ -0,0 +1,64 @@ +package com.baeldung.javadoc; + +/** + * Hero is the main entity we will be using to . . . + * @author Captain America + * + */ +public class SuperHero extends Person { + + /** + * The public name of a hero that is common knowledge + */ + private String heroName; + private String uniquePower; + private int health; + private int defense; + + /** + *

This is a simple description of the method. . . + * Superman! + *

+ * @param incomingDamage the amount of incoming damage + * @return the amount of health hero has after attack + * @see HERO-402 + * @since 1.0 + */ + public int successfullyAttacked(int incomingDamage, String damageType) { + // do things + return 0; + } + + public String getHeroName() { + return heroName; + } + + public void setHeroName(String heroName) { + this.heroName = heroName; + } + + public String getUniquePower() { + return uniquePower; + } + + public void setUniquePower(String uniquePower) { + this.uniquePower = uniquePower; + } + + public int getHealth() { + return health; + } + + public void setHealth(int health) { + this.health = health; + } + + public int getDefense() { + return defense; + } + + public void setDefense(int defense) { + this.defense = defense; + } + +} From fa92d1db3d3fb1b0ddd4573c41717f909466b244 Mon Sep 17 00:00:00 2001 From: araknoid Date: Sat, 6 Jan 2018 20:38:33 +0100 Subject: [PATCH 32/58] BAEL-1419: Guide to cockroachDB in Java (#3325) * adding CockroachDB code * Fixed database name * Added handling transaction examples --- .../java-cockroachdb/README.md | 2 + persistence-modules/java-cockroachdb/pom.xml | 74 +++++++ .../baeldung/cockroachdb/domain/Article.java | 43 ++++ .../repository/ArticleRepository.java | 172 +++++++++++++++ .../ArticleRepositoryIntegrationTest.java | 208 ++++++++++++++++++ pom.xml | 1 + 6 files changed, 500 insertions(+) create mode 100644 persistence-modules/java-cockroachdb/README.md create mode 100644 persistence-modules/java-cockroachdb/pom.xml create mode 100644 persistence-modules/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/domain/Article.java create mode 100644 persistence-modules/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/repository/ArticleRepository.java create mode 100644 persistence-modules/java-cockroachdb/src/test/java/com/baeldung/cockroachdb/ArticleRepositoryIntegrationTest.java diff --git a/persistence-modules/java-cockroachdb/README.md b/persistence-modules/java-cockroachdb/README.md new file mode 100644 index 0000000000..0f0381212d --- /dev/null +++ b/persistence-modules/java-cockroachdb/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Guide to CockroachDB in Java](http://www.baeldung.com/) diff --git a/persistence-modules/java-cockroachdb/pom.xml b/persistence-modules/java-cockroachdb/pom.xml new file mode 100644 index 0000000000..2b6f9651bc --- /dev/null +++ b/persistence-modules/java-cockroachdb/pom.xml @@ -0,0 +1,74 @@ + + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + ../../ + + + 4.0.0 + + com.baeldung + java-cockroachdb + 1.0-SNAPSHOT + + + 42.1.4 + + + + + org.postgresql + postgresql + ${postgresql.version} + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + + Central + Central + http://repo1.maven.org/maven2/ + default + + + \ No newline at end of file diff --git a/persistence-modules/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/domain/Article.java b/persistence-modules/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/domain/Article.java new file mode 100644 index 0000000000..dcc9dfb5b7 --- /dev/null +++ b/persistence-modules/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/domain/Article.java @@ -0,0 +1,43 @@ +package com.baeldung.cockroachdb.domain; + +import java.util.UUID; + +public class Article { + + private UUID id; + + private String title; + + private String author; + + public Article(UUID id, String title, String author) { + this.id = id; + this.title = title; + this.author = author; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + +} diff --git a/persistence-modules/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/repository/ArticleRepository.java b/persistence-modules/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/repository/ArticleRepository.java new file mode 100644 index 0000000000..a37c19e397 --- /dev/null +++ b/persistence-modules/java-cockroachdb/src/main/java/com/baeldung/cockroachdb/repository/ArticleRepository.java @@ -0,0 +1,172 @@ +package com.baeldung.cockroachdb.repository; + +import com.baeldung.cockroachdb.domain.Article; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * Repository for the articles table related operations + */ +public class ArticleRepository { + + private static final String TABLE_NAME = "articles"; + private Connection connection; + + public ArticleRepository(Connection connection) { + this.connection = connection; + } + + /** + * Creates the articles table. + */ + public void createTable() throws SQLException { + StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS ").append(TABLE_NAME) + .append("(id uuid PRIMARY KEY, ") + .append("title string,") + .append("author string)"); + + final String query = sb.toString(); + Statement stmt = connection.createStatement(); + stmt.execute(query); + } + + /** + * Alter the articles table adding a column + * + * @param columnName Column name of the additional column + * @param columnType Column type of the additional column + * @throws SQLException + */ + public void alterTable(String columnName, String columnType) throws SQLException { + StringBuilder sb = new StringBuilder("ALTER TABLE ").append(TABLE_NAME) + .append(" ADD ") + .append(columnName) + .append(" ") + .append(columnType); + + final String query = sb.toString(); + Statement stmt = connection.createStatement(); + stmt.execute(query); + } + + /** + * Insert a new article in the articles table + * + * @param article New article to insert + * @throws SQLException + */ + public void insertArticle(Article article) throws SQLException { + StringBuilder sb = new StringBuilder("INSERT INTO ").append(TABLE_NAME) + .append("(id, title, author) ") + .append("VALUES (?,?,?)"); + + final String query = sb.toString(); + PreparedStatement preparedStatement = connection.prepareStatement(query); + preparedStatement.setString(1, article.getId().toString()); + preparedStatement.setString(2, article.getTitle()); + preparedStatement.setString(3, article.getAuthor()); + preparedStatement.execute(); + } + + /** + * Select article by Title + * + * @param title title of the article to retrieve + * @return article with the given title + * @throws SQLException + */ + public Article selectByTitle(String title) throws SQLException { + StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME) + .append(" WHERE title = ?"); + + final String query = sb.toString(); + PreparedStatement preparedStatement = connection.prepareStatement(query); + preparedStatement.setString(1, title); + + try (ResultSet rs = preparedStatement.executeQuery()) { + + List
articles = new ArrayList<>(); + + while (rs.next()) { + Article article = new Article( + UUID.fromString(rs.getString("id")), + rs.getString("title"), + rs.getString("author") + ); + articles.add(article); + } + return articles.get(0); + } + + } + + /** + * Select all the articles + * + * @return list of all articles + * @throws SQLException + */ + public List
selectAll() throws SQLException { + StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME); + + final String query = sb.toString(); + PreparedStatement preparedStatement = connection.prepareStatement(query); + try (ResultSet rs = preparedStatement.executeQuery()) { + + List
articles = new ArrayList<>(); + + while (rs.next()) { + Article article = new Article( + UUID.fromString(rs.getString("id")), + rs.getString("title"), + rs.getString("author") + ); + articles.add(article); + } + return articles; + } + } + + /** + * Delete article by title + * + * @param title title of the article to delete + * @throws SQLException + */ + public void deleteArticleByTitle(String title) throws SQLException { + StringBuilder sb = new StringBuilder("DELETE FROM ").append(TABLE_NAME) + .append(" WHERE title = ?"); + + final String query = sb.toString(); + PreparedStatement preparedStatement = connection.prepareStatement(query); + preparedStatement.setString(1, title); + preparedStatement.execute(); + } + + /** + * Delete all rows in the table + * + * @throws SQLException + */ + public void truncateTable() throws SQLException { + StringBuilder sb = new StringBuilder("TRUNCATE TABLE ").append(TABLE_NAME); + + final String query = sb.toString(); + Statement stmt = connection.createStatement(); + stmt.execute(query); + } + + /** + * Delete table + */ + public void deleteTable() throws SQLException { + StringBuilder sb = new StringBuilder("DROP TABLE IF EXISTS ").append(TABLE_NAME); + + final String query = sb.toString(); + Statement stmt = connection.createStatement(); + stmt.execute(query); + } +} diff --git a/persistence-modules/java-cockroachdb/src/test/java/com/baeldung/cockroachdb/ArticleRepositoryIntegrationTest.java b/persistence-modules/java-cockroachdb/src/test/java/com/baeldung/cockroachdb/ArticleRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9eb00b3651 --- /dev/null +++ b/persistence-modules/java-cockroachdb/src/test/java/com/baeldung/cockroachdb/ArticleRepositoryIntegrationTest.java @@ -0,0 +1,208 @@ +package com.baeldung.cockroachdb; + +import com.baeldung.cockroachdb.domain.Article; +import com.baeldung.cockroachdb.repository.ArticleRepository; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.postgresql.util.PSQLException; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ArticleRepositoryIntegrationTest { + + private static final String TABLE_NAME = "articles"; + + private Connection con; + private ArticleRepository articleRepository; + + @Before + public void connect() throws Exception { + Class.forName("org.postgresql.Driver"); + con = DriverManager.getConnection("jdbc:postgresql://localhost:26257/testdb", "user17", "qwerty"); + + articleRepository = new ArticleRepository(con); + } + + @Test + public void whenCreatingTable_thenCreatedCorrectly() throws Exception { + articleRepository.deleteTable(); + articleRepository.createTable(); + + PreparedStatement preparedStatement = con.prepareStatement("SHOW TABLES"); + ResultSet resultSet = preparedStatement.executeQuery(); + List tables = new ArrayList<>(); + while (resultSet.next()) { + tables.add(resultSet.getString("Table")); + } + + assertTrue(tables.stream().anyMatch(t -> t.equals(TABLE_NAME))); + } + + @Test + public void whenAlteringTheTable_thenColumnAddedCorrectly() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + String columnName = "creationdate"; + articleRepository.alterTable(columnName, "DATE"); + + String query = "SHOW COLUMNS FROM " + TABLE_NAME; + PreparedStatement preparedStatement = con.prepareStatement(query); + ResultSet resultSet = preparedStatement.executeQuery(); + List columns = new ArrayList<>(); + while (resultSet.next()) { + columns.add(resultSet.getString("Field")); + } + + assertTrue(columns.stream().anyMatch(c -> c.equals(columnName))); + } + + @Test + public void whenInsertingNewArticle_thenArticleExists() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + String title = "Guide to CockroachDB in Java"; + String author = "baeldung"; + Article article = new Article(UUID.randomUUID(), title, author); + articleRepository.insertArticle(article); + + Article savedArticle = articleRepository.selectByTitle(title); + assertEquals(article.getTitle(), savedArticle.getTitle()); + } + + @Test + public void whenSelectingAllArticles_thenAllArticlesAreReturned() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung"); + articleRepository.insertArticle(article); + + article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung"); + articleRepository.insertArticle(article); + + List
savedArticles = articleRepository.selectAll(); + + assertEquals(2, savedArticles.size()); + assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("Guide to CockroachDB in Java"))); + assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("A Guide to MongoDB with Java"))); + } + + @Test + public void whenDeletingArticleByTtile_thenArticleIsDeleted() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung"); + articleRepository.insertArticle(article); + + article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung"); + articleRepository.insertArticle(article); + + articleRepository.deleteArticleByTitle("A Guide to MongoDB with Java"); + + List
savedArticles = articleRepository.selectAll(); + assertEquals(1, savedArticles.size()); + assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("Guide to CockroachDB in Java"))); + assertFalse(savedArticles.stream().anyMatch(a -> a.getTitle().equals("A Guide to MongoDB with Java"))); + } + + @Test(expected = PSQLException.class) + public void whenDeletingATable_thenExceptionIfAccessed() throws SQLException { + articleRepository.createTable(); + articleRepository.deleteTable(); + + StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME); + + final String query = sb.toString(); + PreparedStatement preparedStatement = con.prepareStatement(query); + preparedStatement.executeQuery(); + } + + @Test + public void whenTruncatingATable_thenEmptyTable() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung"); + articleRepository.insertArticle(article); + + article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung"); + articleRepository.insertArticle(article); + + articleRepository.truncateTable(); + + List
savedArticles = articleRepository.selectAll(); + assertEquals(0, savedArticles.size()); + } + + @Test + public void whenInsertingTwoArticlesWithSamePrimaryKeyInASingleTransaction_thenRollback() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + try { + con.setAutoCommit(false); + + UUID articleId = UUID.randomUUID(); + + Article article = new Article(articleId, "Guide to CockroachDB in Java", "baeldung"); + articleRepository.insertArticle(article); + + article = new Article(articleId, "A Guide to MongoDB with Java", "baeldung"); + articleRepository.insertArticle(article); + + con.commit(); + } catch (Exception e) { + con.rollback(); + } finally { + con.setAutoCommit(true); + } + + List
savedArticles = articleRepository.selectAll(); + assertEquals(0, savedArticles.size()); + } + + @Test + public void whenInsertingTwoArticlesInASingleTransaction_thenInserted() throws SQLException { + articleRepository.deleteTable(); + articleRepository.createTable(); + + try { + con.setAutoCommit(false); + + Article article = new Article(UUID.randomUUID(), "Guide to CockroachDB in Java", "baeldung"); + articleRepository.insertArticle(article); + + article = new Article(UUID.randomUUID(), "A Guide to MongoDB with Java", "baeldung"); + articleRepository.insertArticle(article); + + con.commit(); + } catch (Exception e) { + con.rollback(); + } finally { + con.setAutoCommit(true); + } + + List
savedArticles = articleRepository.selectAll(); + assertEquals(2, savedArticles.size()); + assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("Guide to CockroachDB in Java"))); + assertTrue(savedArticles.stream().anyMatch(a -> a.getTitle().equals("A Guide to MongoDB with Java"))); + } + + @After + public void disconnect() throws SQLException { + articleRepository = null; + con.close(); + con = null; + } +} diff --git a/pom.xml b/pom.xml index 68edf19cb2..1050bb8ba2 100644 --- a/pom.xml +++ b/pom.xml @@ -269,6 +269,7 @@ deeplearning4j lucene vraptor + persistence-modules/java-cockroachdb From 477e8cfef488de917bc2c87c40533502e0f5ecef Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sat, 6 Jan 2018 16:38:17 -0600 Subject: [PATCH 33/58] 399 update README (#3365) * BAEL-973: updated README * BAEL-1069: Updated README * BAEL-817: add README file * BAEL-1084: README update * BAEL-960: Update README * BAEL-1155: updated README * BAEL-1041: updated README * BAEL-973: Updated README * BAEL-1187: updated README * BAEL-1183: Update README * BAEL-1133: Updated README * BAEL-1098: README update * BAEL-719: add README.md * BAEL-1272: README update * BAEL-1272: README update * BAEL-1196: Update README * BAEL-1328: Updated README * BAEL-1371: Update README.md * BAEL-1371: Update README.md * BAEL-1278: Update README * BAEL-1326: Update README * BAEL-399: Update README --- hibernate5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/hibernate5/README.md b/hibernate5/README.md index d480a7455c..1eb090f05d 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -4,3 +4,4 @@ - [An Overview of Identifiers in Hibernate](http://www.baeldung.com/hibernate-identifiers) - [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time) - [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance) +- [A Guide to Multitenancy in Hibernate 5](http://www.baeldung.com/hibernate-5-multitenancy) From 50743f20c07ec78f69398c1c6d83497e0d38f0b9 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 7 Jan 2018 17:05:18 +0200 Subject: [PATCH 34/58] update restdocs, move to spring-5 --- pom.xml | 1 - spring-5/pom.xml | 45 ++++ .../baeldung/restdocs}/CRUDController.java | 34 +-- .../java/com/baeldung/restdocs/CrudInput.java | 66 ++++++ .../baeldung/restdocs}/IndexController.java | 6 +- .../restdocs}/SpringRestDocsApplication.java | 2 +- spring-rest-docs/README.MD | 5 - spring-rest-docs/pom.xml | 112 ---------- .../src/docs/asciidocs/api-guide.adoc | 203 ------------------ .../src/main/java/com/example/CrudInput.java | 41 ---- .../src/main/resources/application.properties | 0 .../ApiDocumentationIntegrationTest.java | 181 ---------------- ...ngStartedDocumentationIntegrationTest.java | 147 ------------- 13 files changed, 134 insertions(+), 709 deletions(-) rename {spring-rest-docs/src/main/java/com/example => spring-5/src/main/java/com/baeldung/restdocs}/CRUDController.java (59%) create mode 100644 spring-5/src/main/java/com/baeldung/restdocs/CrudInput.java rename {spring-rest-docs/src/main/java/com/example => spring-5/src/main/java/com/baeldung/restdocs}/IndexController.java (79%) rename {spring-rest-docs/src/main/java/com/example => spring-5/src/main/java/com/baeldung/restdocs}/SpringRestDocsApplication.java (90%) delete mode 100644 spring-rest-docs/README.MD delete mode 100644 spring-rest-docs/pom.xml delete mode 100644 spring-rest-docs/src/docs/asciidocs/api-guide.adoc delete mode 100644 spring-rest-docs/src/main/java/com/example/CrudInput.java delete mode 100644 spring-rest-docs/src/main/resources/application.properties delete mode 100644 spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java delete mode 100644 spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java diff --git a/pom.xml b/pom.xml index 68edf19cb2..863de4c20e 100644 --- a/pom.xml +++ b/pom.xml @@ -201,7 +201,6 @@ spring-protobuf spring-quartz spring-rest-angular - spring-rest-docs spring-rest-full spring-rest-query-language spring-rest diff --git a/spring-5/pom.xml b/spring-5/pom.xml index ac49e8d6f4..81e7ae3123 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -39,6 +39,10 @@ org.springframework.boot spring-boot-starter-webflux + + org.springframework.boot + spring-boot-starter-hateoas + org.projectreactor reactor-spring @@ -135,6 +139,22 @@ ${junit.platform.version} test + + org.springframework.restdocs + spring-restdocs-mockmvc + test + + + org.springframework.restdocs + spring-restdocs-webtestclient + test + + + org.springframework.restdocs + spring-restdocs-restassured + test + + @@ -163,6 +183,29 @@ + + org.asciidoctor + asciidoctor-maven-plugin + ${asciidoctor-plugin.version} + + + generate-docs + package + + process-asciidoc + + + html + book + + ${snippetsDirectory} + + src/docs/asciidocs + target/generated-docs + + + + @@ -199,6 +242,8 @@ 1.1.3 1.0 1.0 + 1.5.6 + ${project.build.directory}/generated-snippets diff --git a/spring-rest-docs/src/main/java/com/example/CRUDController.java b/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java similarity index 59% rename from spring-rest-docs/src/main/java/com/example/CRUDController.java rename to spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java index ff8c91d6cd..9c8e436fa9 100644 --- a/spring-rest-docs/src/main/java/com/example/CRUDController.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java @@ -1,4 +1,4 @@ -package com.example; +package com.baeldung.restdocs; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; @@ -7,10 +7,14 @@ import java.util.List; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @@ -18,8 +22,7 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/crud") public class CRUDController { - @RequestMapping(method = RequestMethod.GET) - @ResponseStatus(HttpStatus.OK) + @GetMapping public List read(@RequestBody CrudInput crudInput) { List returnList = new ArrayList(); returnList.add(crudInput); @@ -27,29 +30,30 @@ public class CRUDController { } @ResponseStatus(HttpStatus.CREATED) - @RequestMapping(method = RequestMethod.POST) + @PostMapping public HttpHeaders save(@RequestBody CrudInput crudInput) { HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.setLocation(linkTo(CRUDController.class).slash(crudInput.getTitle()).toUri()); + httpHeaders.setLocation(linkTo(CRUDController.class).slash(crudInput.getId()).toUri()); return httpHeaders; } - @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) + @DeleteMapping(value = "/{id}") @ResponseStatus(HttpStatus.OK) - HttpHeaders delete(@RequestBody CrudInput crudInput) { - HttpHeaders httpHeaders = new HttpHeaders(); - return httpHeaders; + HttpHeaders delete(@PathVariable("id") long id) { + return new HttpHeaders(); } - @RequestMapping(value = "/{id}", method = RequestMethod.PUT) + @PutMapping(value = "/{id}") @ResponseStatus(HttpStatus.ACCEPTED) void put(@PathVariable("id") long id, @RequestBody CrudInput crudInput) { } - @RequestMapping(value = "/{id}", method = RequestMethod.PATCH) - @ResponseStatus(HttpStatus.NO_CONTENT) - void patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) { - + @PatchMapping(value = "/{id}") + public List patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) { + List returnList = new ArrayList(); + crudInput.setId(id); + returnList.add(crudInput); + return returnList; } } diff --git a/spring-5/src/main/java/com/baeldung/restdocs/CrudInput.java b/spring-5/src/main/java/com/baeldung/restdocs/CrudInput.java new file mode 100644 index 0000000000..29046d7725 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/restdocs/CrudInput.java @@ -0,0 +1,66 @@ +package com.baeldung.restdocs; + +import java.net.URI; +import java.util.Collections; +import java.util.List; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CrudInput { + + @NotNull + private long id; + + @NotBlank + private String title; + + private String body; + + private List tagUris; + + @JsonCreator + public CrudInput(@JsonProperty("id") long id, @JsonProperty("title") String title, @JsonProperty("body") String body, @JsonProperty("tags") List tagUris) { + this.id=id; + this.title = title; + this.body = body; + this.tagUris = tagUris == null ? Collections. emptyList() : tagUris; + } + + public String getTitle() { + return title; + } + + public String getBody() { + return body; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public void setTitle(String title) { + this.title = title; + } + + public void setBody(String body) { + this.body = body; + } + + public void setTagUris(List tagUris) { + this.tagUris = tagUris; + } + + @JsonProperty("tags") + public List getTagUris() { + return this.tagUris; + } + +} \ No newline at end of file diff --git a/spring-rest-docs/src/main/java/com/example/IndexController.java b/spring-5/src/main/java/com/baeldung/restdocs/IndexController.java similarity index 79% rename from spring-rest-docs/src/main/java/com/example/IndexController.java rename to spring-5/src/main/java/com/baeldung/restdocs/IndexController.java index 6b896da416..2c58d5fe6b 100644 --- a/spring-rest-docs/src/main/java/com/example/IndexController.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/IndexController.java @@ -1,17 +1,17 @@ -package com.example; +package com.baeldung.restdocs; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import org.springframework.hateoas.ResourceSupport; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/") public class IndexController { - @RequestMapping(method = RequestMethod.GET) + @GetMapping public ResourceSupport index() { ResourceSupport index = new ResourceSupport(); index.add(linkTo(CRUDController.class).withRel("crud")); diff --git a/spring-rest-docs/src/main/java/com/example/SpringRestDocsApplication.java b/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java similarity index 90% rename from spring-rest-docs/src/main/java/com/example/SpringRestDocsApplication.java rename to spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java index da09f9accc..02332ee7b6 100644 --- a/spring-rest-docs/src/main/java/com/example/SpringRestDocsApplication.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java @@ -1,4 +1,4 @@ -package com.example; +package com.baeldung.restdocs; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-rest-docs/README.MD b/spring-rest-docs/README.MD deleted file mode 100644 index f5d001d126..0000000000 --- a/spring-rest-docs/README.MD +++ /dev/null @@ -1,5 +0,0 @@ -###The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring - -###Relevant Articles: -- [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs) diff --git a/spring-rest-docs/pom.xml b/spring-rest-docs/pom.xml deleted file mode 100644 index ffd3cb89b6..0000000000 --- a/spring-rest-docs/pom.xml +++ /dev/null @@ -1,112 +0,0 @@ - - - 4.0.0 - - com.example - spring-rest-docs - 0.0.1-SNAPSHOT - jar - - spring-rest-docs - Demo project for Spring Boot - - - parent-boot-5 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-5 - - - - ${project.build.directory}/generated-snippets - 1.1.2.RELEASE - 2.2.0 - 1.5.3 - - - - - org.springframework.boot - spring-boot-starter-hateoas - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.restdocs - spring-restdocs-mockmvc - test - - - com.jayway.jsonpath - json-path - - - - - - - org.asciidoctor - asciidoctor-maven-plugin - ${asciidoctor-plugin.version} - - - generate-docs - package - - process-asciidoc - - - html - book - - ${snippetsDirectory} - - src/docs/asciidocs - target/generated-docs - - - - - - - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - - diff --git a/spring-rest-docs/src/docs/asciidocs/api-guide.adoc b/spring-rest-docs/src/docs/asciidocs/api-guide.adoc deleted file mode 100644 index 9fbe74c072..0000000000 --- a/spring-rest-docs/src/docs/asciidocs/api-guide.adoc +++ /dev/null @@ -1,203 +0,0 @@ -= RESTful Notes API Guide -Baeldung; -:doctype: book -:icons: font -:source-highlighter: highlightjs -:toc: left -:toclevels: 4 -:sectlinks: - -[[overview]] -= Overview - -[[overview-http-verbs]] -== HTTP verbs - -RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its -use of HTTP verbs. - -|=== -| Verb | Usage - -| `GET` -| Used to retrieve a resource - -| `POST` -| Used to create a new resource - -| `PATCH` -| Used to update an existing resource, including partial updates - -| `DELETE` -| Used to delete an existing resource -|=== - -RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its -use of HTTP status codes. - -|=== -| Status code | Usage - -| `200 OK` -| The request completed successfully - -| `201 Created` -| A new resource has been created successfully. The resource's URI is available from the response's -`Location` header - -| `204 No Content` -| An update to an existing resource has been applied successfully - -| `400 Bad Request` -| The request was malformed. The response body will include an error providing further information - -| `404 Not Found` -| The requested resource did not exist -|=== - -[[overview-headers]] -== Headers - -Every response has the following header(s): - -include::{snippets}/headers-example/response-headers.adoc[] - -[[overview-hypermedia]] -== Hypermedia - -RESTful Notes uses hypermedia and resources include links to other resources in their -responses. Responses are in http://stateless.co/hal_specification.html[Hypertext Application -from resource to resource. -Language (HAL)] format. Links can be found beneath the `_links` key. Users of the API should -not create URIs themselves, instead they should use the above-described links to navigate - -[[resources]] -= Resources - - - -[[resources-index]] -== Index - -The index provides the entry point into the service. - -[[resources-index-access]] -=== Accessing the index - -A `GET` request is used to access the index - -==== Response structure - -include::{snippets}/index-example/http-response.adoc[] - -==== Example response - -include::{snippets}/index-example/http-response.adoc[] - -==== Example request - -include::{snippets}/index-example/http-request.adoc[] - -==== CURL request - -include::{snippets}/index-example/curl-request.adoc[] - -[[resources-index-links]] -==== Links - -include::{snippets}/index-example/links.adoc[] - - -[[resources-CRUD]] -== CRUD REST Service - -The CRUD provides the entry point into the service. - -[[resources-crud-access]] -=== Accessing the crud GET - -A `GET` request is used to access the CRUD read - -==== Response structure - -include::{snippets}/crud-get-example/http-request.adoc[] - -==== Example response - -include::{snippets}/crud-get-example/http-response.adoc[] - -==== CURL request - -include::{snippets}/crud-get-example/curl-request.adoc[] - -[[resources-crud-access]] -=== Accessing the crud POST - -A `POST` request is used to access the CRUD create - -==== Response structure - -include::{snippets}/crud-create-example/http-request.adoc[] - -==== Example response - -include::{snippets}/crud-create-example/http-response.adoc[] - -==== CURL request - -include::{snippets}/crud-create-example/curl-request.adoc[] - -[[resources-crud-access]] -=== Accessing the crud DELETE - -A `DELETE` request is used to access the CRUD create - -==== Response structure - -include::{snippets}/crud-delete-example/http-request.adoc[] - -==== Example response - -include::{snippets}/crud-delete-example/http-response.adoc[] - -==== CURL request - -include::{snippets}/crud-delete-example/curl-request.adoc[] - -[[resources-crud-access]] -=== Accessing the crud PATCH - -A `PATCH` request is used to access the CRUD create - -==== Response structure - -include::{snippets}/crud-patch-example/http-request.adoc[] - -==== Example response - -include::{snippets}/crud-patch-example/http-response.adoc[] - -==== CURL request - -include::{snippets}/crud-patch-example/curl-request.adoc[] - -[[resources-crud-access]] -=== Accessing the crud PUT - -A `PUT` request is used to access the CRUD create - -==== Response structure - -include::{snippets}/crud-put-example/http-request.adoc[] - -==== Example response - -include::{snippets}/crud-put-example/http-response.adoc[] - -==== CURL request - -include::{snippets}/crud-put-example/curl-request.adoc[] - - - - diff --git a/spring-rest-docs/src/main/java/com/example/CrudInput.java b/spring-rest-docs/src/main/java/com/example/CrudInput.java deleted file mode 100644 index 36ad67eb21..0000000000 --- a/spring-rest-docs/src/main/java/com/example/CrudInput.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.example; - -import java.net.URI; -import java.util.Collections; -import java.util.List; - -import org.hibernate.validator.constraints.NotBlank; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class CrudInput { - - // @NotBlank - private final String title; - - private final String body; - - private final List tagUris; - - @JsonCreator - public CrudInput(@JsonProperty("title") String title, @JsonProperty("body") String body, @JsonProperty("tags") List tagUris) { - this.title = title; - this.body = body; - this.tagUris = tagUris == null ? Collections. emptyList() : tagUris; - } - - public String getTitle() { - return title; - } - - public String getBody() { - return body; - } - - @JsonProperty("tags") - public List getTagUris() { - return this.tagUris; - } - -} \ No newline at end of file diff --git a/spring-rest-docs/src/main/resources/application.properties b/spring-rest-docs/src/main/resources/application.properties deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java b/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java deleted file mode 100644 index 1c3aef4845..0000000000 --- a/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.example; - -import static java.util.Collections.singletonList; -import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; -import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders; -import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; -import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; -import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; -import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; -import static org.springframework.restdocs.snippet.Attributes.key; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.util.StringUtils.collectionToDelimitedString; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Rule; -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.hateoas.MediaTypes; -import org.springframework.restdocs.RestDocumentation; -import org.springframework.restdocs.constraints.ConstraintDescriptions; -import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler; -import org.springframework.restdocs.payload.FieldDescriptor; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = SpringRestDocsApplication.class) -@WebAppConfiguration -public class ApiDocumentationIntegrationTest { - - @Rule - public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets"); - - @Autowired - private WebApplicationContext context; - - @Autowired - private ObjectMapper objectMapper; - - private RestDocumentationResultHandler document; - - private MockMvc mockMvc; - - @Before - public void setUp() { - this.document = document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())); - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(documentationConfiguration(this.restDocumentation)).alwaysDo(this.document).build(); - } - - @Test - public void headersExample() throws Exception { - this.document.snippets(responseHeaders(headerWithName("Content-Type").description("The Content-Type of the payload, e.g. `application/hal+json`"))); - this.mockMvc.perform(get("/")).andExpect(status().isOk()); - } - - @Test - public void indexExample() throws Exception { - this.document.snippets(links(linkWithRel("crud").description("The <>")), responseFields(fieldWithPath("_links").description("<> to other resources"))); - this.mockMvc.perform(get("/")).andExpect(status().isOk()); - } - - @Test - public void crudGetExample() throws Exception { - - Map tag = new HashMap<>(); - tag.put("name", "GET"); - - String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isOk()).andReturn().getResponse().getHeader("Location"); - - Map crud = new HashMap<>(); - crud.put("title", "Sample Model"); - crud.put("body", "http://www.baeldung.com/"); - crud.put("tags", singletonList(tagLocation)); - - this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isOk()); - } - - @Test - public void crudCreateExample() throws Exception { - Map tag = new HashMap<>(); - tag.put("name", "CREATE"); - - String tagLocation = this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isCreated()).andReturn().getResponse().getHeader("Location"); - - Map crud = new HashMap<>(); - crud.put("title", "Sample Model"); - crud.put("body", "http://www.baeldung.com/"); - crud.put("tags", singletonList(tagLocation)); - - ConstrainedFields fields = new ConstrainedFields(CrudInput.class); - this.document.snippets(requestFields(fields.withPath("title").description("The title of the note"), fields.withPath("body").description("The body of the note"), fields.withPath("tags").description("An array of tag resource URIs"))); - this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isCreated()); - - } - - @Test - public void crudDeleteExample() throws Exception { - - Map tag = new HashMap<>(); - tag.put("name", "DELETE"); - - String tagLocation = this.mockMvc.perform(delete("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isOk()).andReturn().getResponse().getHeader("Location"); - - Map crud = new HashMap<>(); - crud.put("title", "Sample Model"); - crud.put("body", "http://www.baeldung.com/"); - crud.put("tags", singletonList(tagLocation)); - - this.mockMvc.perform(delete("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isOk()); - } - - @Test - public void crudPatchExample() throws Exception { - - Map tag = new HashMap<>(); - tag.put("name", "PATCH"); - - String tagLocation = this.mockMvc.perform(patch("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isNoContent()).andReturn().getResponse().getHeader("Location"); - - Map crud = new HashMap<>(); - crud.put("title", "Sample Model"); - crud.put("body", "http://www.baeldung.com/"); - crud.put("tags", singletonList(tagLocation)); - - this.mockMvc.perform(patch("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isNoContent()); - } - - @Test - public void crudPutExample() throws Exception { - Map tag = new HashMap<>(); - tag.put("name", "PUT"); - - String tagLocation = this.mockMvc.perform(put("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(tag))).andExpect(status().isAccepted()).andReturn().getResponse().getHeader("Location"); - - Map crud = new HashMap<>(); - crud.put("title", "Sample Model"); - crud.put("body", "http://www.baeldung.com/"); - crud.put("tags", singletonList(tagLocation)); - - this.mockMvc.perform(put("/crud/10").contentType(MediaTypes.HAL_JSON).content(this.objectMapper.writeValueAsString(crud))).andExpect(status().isAccepted()); - } - - @Test - public void contextLoads() { - } - - private static class ConstrainedFields { - - private final ConstraintDescriptions constraintDescriptions; - - ConstrainedFields(Class input) { - this.constraintDescriptions = new ConstraintDescriptions(input); - } - - private FieldDescriptor withPath(String path) { - return fieldWithPath(path).attributes(key("constraints").value(collectionToDelimitedString(this.constraintDescriptions.descriptionsForProperty(path), ". "))); - } - } - -} diff --git a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java deleted file mode 100644 index 3300fc519c..0000000000 --- a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.example; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Before; -import org.junit.Rule; -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.hateoas.MediaTypes; -import org.springframework.restdocs.RestDocumentation; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = SpringRestDocsApplication.class) -@WebAppConfiguration -public class GettingStartedDocumentationIntegrationTest { - - @Rule - public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets"); - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private WebApplicationContext context; - - private MockMvc mockMvc; - - @Before - public void setUp() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(documentationConfiguration(this.restDocumentation)).alwaysDo(document("{method-name}/{step}/", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()))).build(); - } - - @Test - public void index() throws Exception { - this.mockMvc.perform(get("/").accept(MediaTypes.HAL_JSON)).andExpect(status().isOk()).andExpect(jsonPath("_links.crud", is(notNullValue()))).andExpect(jsonPath("_links.crud", is(notNullValue()))); - } - - // String createNote() throws Exception { - // Map note = new HashMap(); - // note.put("title", "Note creation with cURL"); - // note.put("body", "An example of how to create a note using curl"); - // String noteLocation = this.mockMvc.perform(post("/crud") - // .contentType(MediaTypes.HAL_JSON) - // .content(objectMapper.writeValueAsString(note))) - // .andExpect(status().isCreated()) - // .andExpect(header().string("Location", notNullValue())) - // .andReturn() - // .getResponse() - // .getHeader("Location"); - // return noteLocation; - // } - // - // MvcResult getNote(String noteLocation) throws Exception { - // return this.mockMvc.perform(get(noteLocation)) - // .andExpect(status().isOk()) - // .andExpect(jsonPath("title", is(notNullValue()))) - // .andExpect(jsonPath("body", is(notNullValue()))) - // .andExpect(jsonPath("_links.crud", is(notNullValue()))) - // .andReturn(); - // } - // - // - // String createTag() throws Exception, JsonProcessingException { - // Map tag = new HashMap(); - // tag.put("name", "getting-started"); - // String tagLocation = this.mockMvc.perform(post("/crud") - // .contentType(MediaTypes.HAL_JSON) - // .content(objectMapper.writeValueAsString(tag))) - // .andExpect(status().isCreated()) - // .andExpect(header().string("Location", notNullValue())) - // .andReturn() - // .getResponse() - // .getHeader("Location"); - // return tagLocation; - // } - // - // void getTag(String tagLocation) throws Exception { - // this.mockMvc.perform(get(tagLocation)).andExpect(status().isOk()) - // .andExpect(jsonPath("name", is(notNullValue()))) - // .andExpect(jsonPath("_links.tagged-notes", is(notNullValue()))); - // } - // - // String createTaggedNote(String tag) throws Exception { - // Map note = new HashMap(); - // note.put("title", "Tagged note creation with cURL"); - // note.put("body", "An example of how to create a tagged note using cURL"); - // note.put("tags", Arrays.asList(tag)); - // - // String noteLocation = this.mockMvc.perform(post("/notes") - // .contentType(MediaTypes.HAL_JSON) - // .content(objectMapper.writeValueAsString(note))) - // .andExpect(status().isCreated()) - // .andExpect(header().string("Location", notNullValue())) - // .andReturn() - // .getResponse() - // .getHeader("Location"); - // return noteLocation; - // } - // - // void getTags(String noteTagsLocation) throws Exception { - // this.mockMvc.perform(get(noteTagsLocation)) - // .andExpect(status().isOk()) - // .andExpect(jsonPath("_embedded.tags", hasSize(1))); - // } - // - // void tagExistingNote(String noteLocation, String tagLocation) throws Exception { - // Map update = new HashMap(); - // update.put("tags", Arrays.asList(tagLocation)); - // this.mockMvc.perform(patch(noteLocation) - // .contentType(MediaTypes.HAL_JSON) - // .content(objectMapper.writeValueAsString(update))) - // .andExpect(status().isNoContent()); - // } - // - // MvcResult getTaggedExistingNote(String noteLocation) throws Exception { - // return this.mockMvc.perform(get(noteLocation)).andExpect(status().isOk()).andReturn(); - // } - // - // void getTagsForExistingNote(String noteTagsLocation) throws Exception { - // this.mockMvc.perform(get(noteTagsLocation)) - // .andExpect(status().isOk()).andExpect(jsonPath("_embedded.tags", hasSize(1))); - // } - // - // private String getLink(MvcResult result, String rel) - // throws UnsupportedEncodingException { - // return JsonPath.parse(result.getResponse().getContentAsString()).read("_links." + rel + ".href"); - // } - -} From 630acd7959ff8e3d94b64e7518bd39d7a4894992 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 7 Jan 2018 17:09:37 +0200 Subject: [PATCH 35/58] formatting, add tests --- spring-5/pom.xml | 5 +- ...ApiDocumentationJUnit4IntegrationTest.java | 184 ++++++++++++++++++ ...ApiDocumentationJUnit5IntegrationTest.java | 181 +++++++++++++++++ 3 files changed, 368 insertions(+), 2 deletions(-) create mode 100644 spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit4IntegrationTest.java create mode 100644 spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit5IntegrationTest.java diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 81e7ae3123..a76730f628 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -139,7 +139,8 @@ ${junit.platform.version} test - + + org.springframework.restdocs spring-restdocs-mockmvc test @@ -183,7 +184,7 @@ - + org.asciidoctor asciidoctor-maven-plugin ${asciidoctor-plugin.version} diff --git a/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit4IntegrationTest.java b/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit4IntegrationTest.java new file mode 100644 index 0000000000..de1d3f8b6a --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit4IntegrationTest.java @@ -0,0 +1,184 @@ +package com.baeldung.restdocs; + +import com.baeldung.restdocs.CrudInput; +import com.baeldung.restdocs.SpringRestDocsApplication; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Before; +import org.junit.Rule; +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.hateoas.MediaTypes; +import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.constraints.ConstraintDescriptions; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.util.HashMap; +import java.util.Map; + +import static java.util.Collections.singletonList; +import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; +import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders; +import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; +import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; +import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; +import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; +import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.util.StringUtils.collectionToDelimitedString; +import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath; +import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; +import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringRestDocsApplication.class) +public class ApiDocumentationJUnit4IntegrationTest { + + @Rule + public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets"); + + @Autowired + private WebApplicationContext context; + + @Autowired + private ObjectMapper objectMapper; + + private MockMvc mockMvc; + + @Before + public void setUp() { + + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) + .apply(documentationConfiguration(this.restDocumentation)) + .alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()))) + .build(); + } + + @Test + public void indexExample() throws Exception { + this.mockMvc.perform(get("/")) + .andExpect(status().isOk()) + .andDo(document("index-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links(linkWithRel("crud").description("The CRUD resource")), responseFields(subsectionWithPath("_links").description("Links to other resources")), + responseHeaders(headerWithName("Content-Type").description("The Content-Type of the payload, e.g. `application/hal+json`")))); + } + + @Test + public void crudGetExample() throws Exception { + + Map tag = new HashMap<>(); + tag.put("name", "GET"); + + String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(tag))) + .andExpect(status().isOk()) + .andReturn() + .getResponse() + .getHeader("Location"); + + Map crud = new HashMap<>(); + crud.put("id", 1L); + crud.put("title", "Sample Model"); + crud.put("body", "http://www.baeldung.com/"); + crud.put("tags", singletonList(tagLocation)); + + ConstraintDescriptions desc = new ConstraintDescriptions(CrudInput.class); + + this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(crud))) + .andExpect(status().isOk()) + .andDo(document("crud-get-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")), + fieldWithPath("title").description("The title of the input"), fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs")))); + } + + @Test + public void crudCreateExample() throws Exception { + Map tag = new HashMap<>(); + tag.put("name", "CREATE"); + + String tagLocation = this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(tag))) + .andExpect(status().isCreated()) + .andReturn() + .getResponse() + .getHeader("Location"); + + Map crud = new HashMap<>(); + crud.put("id", 2L); + crud.put("title", "Sample Model"); + crud.put("body", "http://www.baeldung.com/"); + crud.put("tags", singletonList(tagLocation)); + + this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(crud))) + .andExpect(status().isCreated()) + .andDo(document("crud-create-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input"), fieldWithPath("title").description("The title of the input"), + fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs")))); + } + + @Test + public void crudDeleteExample() throws Exception { + this.mockMvc.perform(delete("/crud/{id}", 10)) + .andExpect(status().isOk()) + .andDo(document("crud-delete-example", pathParameters(parameterWithName("id").description("The id of the input to delete")))); + } + + @Test + public void crudPatchExample() throws Exception { + + Map tag = new HashMap<>(); + tag.put("name", "PATCH"); + + String tagLocation = this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(tag))) + .andExpect(status().isOk()) + .andReturn() + .getResponse() + .getHeader("Location"); + + Map crud = new HashMap<>(); + crud.put("title", "Sample Model Patch"); + crud.put("body", "http://www.baeldung.com/"); + crud.put("tags", singletonList(tagLocation)); + + this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(crud))) + .andExpect(status().isOk()); + } + + @Test + public void crudPutExample() throws Exception { + Map tag = new HashMap<>(); + tag.put("name", "PUT"); + + String tagLocation = this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(tag))) + .andExpect(status().isAccepted()) + .andReturn() + .getResponse() + .getHeader("Location"); + + Map crud = new HashMap<>(); + crud.put("title", "Sample Model"); + crud.put("body", "http://www.baeldung.com/"); + crud.put("tags", singletonList(tagLocation)); + + this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(crud))) + .andExpect(status().isAccepted()); + } + + @Test + public void contextLoads() { + } + +} diff --git a/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit5IntegrationTest.java b/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit5IntegrationTest.java new file mode 100644 index 0000000000..d915a4fdde --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit5IntegrationTest.java @@ -0,0 +1,181 @@ +package com.baeldung.restdocs; + +import static java.util.Collections.singletonList; +import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; +import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders; +import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; +import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; +import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; +import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; +import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; +import static org.springframework.restdocs.request.RequestDocumentation.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.util.StringUtils.collectionToDelimitedString; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.hateoas.MediaTypes; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; +import org.springframework.restdocs.constraints.ConstraintDescriptions; +import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.restdocs.CrudInput; +import com.baeldung.restdocs.SpringRestDocsApplication; +import com.fasterxml.jackson.databind.ObjectMapper; + +@ExtendWith({ RestDocumentationExtension.class, SpringExtension.class }) +@SpringBootTest(classes = SpringRestDocsApplication.class) +public class ApiDocumentationJUnit5IntegrationTest { + + @Autowired + private ObjectMapper objectMapper; + + private MockMvc mockMvc; + + @BeforeEach + public void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) { + this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) + .apply(documentationConfiguration(restDocumentation)) + .alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()))) + .build(); + } + + @Test + public void indexExample() throws Exception { + this.mockMvc.perform(get("/")) + .andExpect(status().isOk()) + .andDo(document("index-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links(linkWithRel("crud").description("The CRUD resource")), responseFields(subsectionWithPath("_links").description("Links to other resources")), + responseHeaders(headerWithName("Content-Type").description("The Content-Type of the payload, e.g. `application/hal+json`")))); + } + + @Test + public void crudGetExample() throws Exception { + + Map tag = new HashMap<>(); + tag.put("name", "GET"); + + String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(tag))) + .andExpect(status().isOk()) + .andReturn() + .getResponse() + .getHeader("Location"); + + Map crud = new HashMap<>(); + crud.put("id", 1L); + crud.put("title", "Sample Model"); + crud.put("body", "http://www.baeldung.com/"); + crud.put("tags", singletonList(tagLocation)); + + ConstraintDescriptions desc = new ConstraintDescriptions(CrudInput.class); + + this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(crud))) + .andExpect(status().isOk()) + .andDo(document("crud-get-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")), + fieldWithPath("title").description("The title of the input"), fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs")))); + } + + @Test + public void crudCreateExample() throws Exception { + Map tag = new HashMap<>(); + tag.put("name", "CREATE"); + + String tagLocation = this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(tag))) + .andExpect(status().isCreated()) + .andReturn() + .getResponse() + .getHeader("Location"); + + Map crud = new HashMap<>(); + crud.put("id", 2L); + crud.put("title", "Sample Model"); + crud.put("body", "http://www.baeldung.com/"); + crud.put("tags", singletonList(tagLocation)); + + this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(crud))) + .andExpect(status().isCreated()) + .andDo(document("crud-create-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input"), fieldWithPath("title").description("The title of the input"), + fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs")))); + } + + @Test + public void crudDeleteExample() throws Exception { + this.mockMvc.perform(delete("/crud/{id}", 10)) + .andExpect(status().isOk()) + .andDo(document("crud-delete-example", pathParameters(parameterWithName("id").description("The id of the input to delete")))); + } + + @Test + public void crudPatchExample() throws Exception { + + Map tag = new HashMap<>(); + tag.put("name", "PATCH"); + + String tagLocation = this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(tag))) + .andExpect(status().isOk()) + .andReturn() + .getResponse() + .getHeader("Location"); + + Map crud = new HashMap<>(); + crud.put("title", "Sample Model Patch"); + crud.put("body", "http://www.baeldung.com/"); + crud.put("tags", singletonList(tagLocation)); + + this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(crud))) + .andExpect(status().isOk()); + } + + @Test + public void crudPutExample() throws Exception { + Map tag = new HashMap<>(); + tag.put("name", "PUT"); + + String tagLocation = this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(tag))) + .andExpect(status().isAccepted()) + .andReturn() + .getResponse() + .getHeader("Location"); + + Map crud = new HashMap<>(); + crud.put("title", "Sample Model"); + crud.put("body", "http://www.baeldung.com/"); + crud.put("tags", singletonList(tagLocation)); + + this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(crud))) + .andExpect(status().isAccepted()); + } + + @Test + public void contextLoads() { + } + +} From 3d233f5ede85e00163dbfa6ff1dd7e7d5009d101 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 7 Jan 2018 17:12:07 +0200 Subject: [PATCH 36/58] add api guide --- spring-5/src/docs/asciidocs/api-guide.adoc | 195 +++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 spring-5/src/docs/asciidocs/api-guide.adoc diff --git a/spring-5/src/docs/asciidocs/api-guide.adoc b/spring-5/src/docs/asciidocs/api-guide.adoc new file mode 100644 index 0000000000..6eadfb5efd --- /dev/null +++ b/spring-5/src/docs/asciidocs/api-guide.adoc @@ -0,0 +1,195 @@ += RESTful Notes API Guide +Baeldung; +:doctype: book +:icons: font +:source-highlighter: highlightjs +:toc: left +:toclevels: 4 +:sectlinks: + +[[overview]] += Overview + +[[overview-http-verbs]] +== HTTP verbs + +RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its +use of HTTP verbs. + +|=== +| Verb | Usage + +| `GET` +| Used to retrieve a resource + +| `POST` +| Used to create a new resource + +| `PATCH` +| Used to update an existing resource, including partial updates + +| `DELETE` +| Used to delete an existing resource +|=== + +RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its +use of HTTP status codes. + +|=== +| Status code | Usage + +| `200 OK` +| The request completed successfully + +| `201 Created` +| A new resource has been created successfully. The resource's URI is available from the response's +`Location` header + +| `204 No Content` +| An update to an existing resource has been applied successfully + +| `400 Bad Request` +| The request was malformed. The response body will include an error providing further information + +| `404 Not Found` +| The requested resource did not exist +|=== + +[[overview-hypermedia]] +== Hypermedia + +RESTful Notes uses hypermedia and resources include links to other resources in their +responses. Responses are in http://stateless.co/hal_specification.html[Hypertext Application +from resource to resource. +Language (HAL)] format. Links can be found beneath the `_links` key. Users of the API should +not create URIs themselves, instead they should use the above-described links to navigate + +[[resources]] += Resources + + + +[[resources-index]] +== Index + +The index provides the entry point into the service. + +[[resources-index-access]] +=== Accessing the index + +A `GET` request is used to access the index + +==== Request structure + +include::{snippets}/index-example/http-request.adoc[] + +==== Example response + +include::{snippets}/index-example/http-response.adoc[] + +==== CURL request + +include::{snippets}/index-example/curl-request.adoc[] + +[[resources-index-links]] +==== Links + +include::{snippets}/index-example/links.adoc[] + + +[[resources-CRUD]] +== CRUD REST Service + +The CRUD provides the entry point into the service. + +[[resources-crud-get]] +=== Accessing the crud GET + +A `GET` request is used to access the CRUD read. + +==== Request structure + +include::{snippets}/crud-get-example/http-request.adoc[] + +==== Example response + +include::{snippets}/crud-get-example/http-response.adoc[] + +==== CURL request + +include::{snippets}/crud-get-example/curl-request.adoc[] + +[[resources-crud-post]] +=== Accessing the crud POST + +A `POST` request is used to access the CRUD create. + +==== Request structure + +include::{snippets}/crud-create-example/http-request.adoc[] + +==== Example response + +include::{snippets}/crud-create-example/http-response.adoc[] + +==== CURL request + +include::{snippets}/crud-create-example/curl-request.adoc[] + +[[resources-crud-delete]] +=== Accessing the crud DELETE + +A `DELETE` request is used to access the CRUD delete. + +==== Request structure + +include::{snippets}/crud-delete-example/http-request.adoc[] + +==== Path Parameters +include::{snippets}/crud-delete-example/path-parameters.adoc[] + +==== Example response + +include::{snippets}/crud-delete-example/http-response.adoc[] + +==== CURL request + +include::{snippets}/crud-delete-example/curl-request.adoc[] + +[[resources-crud-patch]] +=== Accessing the crud PATCH + +A `PATCH` request is used to access the CRUD update. + +==== Request structure + +include::{snippets}/crud-patch-example/http-request.adoc[] + +==== Example response + +include::{snippets}/crud-patch-example/http-response.adoc[] + +==== CURL request + +include::{snippets}/crud-patch-example/curl-request.adoc[] + +[[resources-crud-put]] +=== Accessing the crud PUT + +A `PUT` request is used to access the CRUD update. + +==== Request structure + +include::{snippets}/crud-put-example/http-request.adoc[] + +==== Example response + +include::{snippets}/crud-put-example/http-response.adoc[] + +==== CURL request + +include::{snippets}/crud-put-example/curl-request.adoc[] + + + + From 44380f6bd9a7175cb47f60cb071050d5b1563343 Mon Sep 17 00:00:00 2001 From: Dassi orleando Date: Sun, 7 Jan 2018 17:42:06 +0100 Subject: [PATCH 37/58] BAEL-1318: Quick Guide to Setting up the Maven Wrapper on an Application (#3371) * BAEL-1216: improve tests * BAEL-1448: Update Spring 5 articles to use the release version * Setting up the Maven Wrapper on a maven project --- mvn-wrapper/.gitignore | 24 ++ mvn-wrapper/.mvn/wrapper/maven-wrapper.jar | Bin 0 -> 48336 bytes .../.mvn/wrapper/maven-wrapper.properties | 1 + mvn-wrapper/README.md | 22 ++ mvn-wrapper/mvnw | 227 ++++++++++++++++++ mvn-wrapper/mvnw.cmd | 145 +++++++++++ mvn-wrapper/pom.xml | 45 ++++ .../com/baeldung/MvnWrapperApplication.java | 11 + .../src/main/resources/application.properties | 0 pom.xml | 1 + 10 files changed, 476 insertions(+) create mode 100644 mvn-wrapper/.gitignore create mode 100755 mvn-wrapper/.mvn/wrapper/maven-wrapper.jar create mode 100755 mvn-wrapper/.mvn/wrapper/maven-wrapper.properties create mode 100644 mvn-wrapper/README.md create mode 100755 mvn-wrapper/mvnw create mode 100755 mvn-wrapper/mvnw.cmd create mode 100644 mvn-wrapper/pom.xml create mode 100644 mvn-wrapper/src/main/java/com/baeldung/MvnWrapperApplication.java create mode 100644 mvn-wrapper/src/main/resources/application.properties diff --git a/mvn-wrapper/.gitignore b/mvn-wrapper/.gitignore new file mode 100644 index 0000000000..2af7cefb0a --- /dev/null +++ b/mvn-wrapper/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/mvn-wrapper/.mvn/wrapper/maven-wrapper.jar b/mvn-wrapper/.mvn/wrapper/maven-wrapper.jar new file mode 100755 index 0000000000000000000000000000000000000000..f775b1c04cf89b25c7814d3a8a7c810301092e57 GIT binary patch literal 48336 zcmbTe1CVCTvMxMr+qUiQY1_8@ZQJIwjcMDqjcHHYwr%^)#=(F7yT3U5z7Z9%BGxKo zRaWJbnNPh6(jcIy-yk6&zkT~g^r!sS59-gOtf-10our%?1IRZ8X^6jl^9}f)Unu;` zim3m+qO72tq?o9(3cajYQtTLXA0wjZlmEN0FJYc2=*eVzIUyu^3vxUaybZpL(O^$Y zRjGpdWr$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Bq5q|(=1-!}pT-&OhNVE4|j_d#ycs9rnmZv+UQ zuJ+GCZu=YVBitr|ygOAWI{zHu_rS@Ykh9*0z0JJGe={o36$oCV|G&ZhKFB}#Chx=D z=H$Aj^Scosc%9L|hWiP*-+kQM{7Q;9pr9)d9Nzq2PXZ=N8tN8)b}B8rygD>n%)Qy{P@-X2>JU;zQyx#AM+1_qKie&DJGHJImp1|g z#{jt|etsbP=WfjVGj!XTB6 \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvn-wrapper/mvnw.cmd b/mvn-wrapper/mvnw.cmd new file mode 100755 index 0000000000..4f0b068a03 --- /dev/null +++ b/mvn-wrapper/mvnw.cmd @@ -0,0 +1,145 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/mvn-wrapper/pom.xml b/mvn-wrapper/pom.xml new file mode 100644 index 0000000000..209c4b9403 --- /dev/null +++ b/mvn-wrapper/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + mvn-wrapper + 0.0.1-SNAPSHOT + jar + + mvn-wrapper + Setting up the Maven Wrapper + + + parent-boot-5 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-5 + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-web + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/mvn-wrapper/src/main/java/com/baeldung/MvnWrapperApplication.java b/mvn-wrapper/src/main/java/com/baeldung/MvnWrapperApplication.java new file mode 100644 index 0000000000..3007d24ed0 --- /dev/null +++ b/mvn-wrapper/src/main/java/com/baeldung/MvnWrapperApplication.java @@ -0,0 +1,11 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MvnWrapperApplication { + public static void main(String[] args) { + SpringApplication.run(MvnWrapperApplication.class, args); + } +} diff --git a/mvn-wrapper/src/main/resources/application.properties b/mvn-wrapper/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pom.xml b/pom.xml index 1050bb8ba2..b018fdd778 100644 --- a/pom.xml +++ b/pom.xml @@ -117,6 +117,7 @@ testing-modules/mockito-2 testing-modules/mocks mustache + mvn-wrapper noexception orientdb osgi From 1f3099731b124d82e28d1edcea20f10574ec7237 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 7 Jan 2018 20:58:14 +0200 Subject: [PATCH 38/58] remove extra spring-boot-actuator project --- spring-boot-actuator/.gitignore | 4 - spring-boot-actuator/README.MD | 0 spring-boot-actuator/pom.xml | 122 ------------------ .../java/org/baeldung/MainApplication.java | 13 -- .../java/org/baeldung/config/MainConfig.java | 17 --- .../src/main/resources/application.properties | 1 - .../config/ActuatorInfoIntegrationTest.java | 32 ----- .../src/test/resources/expectedResponse.json | 1 - 8 files changed, 190 deletions(-) delete mode 100644 spring-boot-actuator/.gitignore delete mode 100644 spring-boot-actuator/README.MD delete mode 100644 spring-boot-actuator/pom.xml delete mode 100644 spring-boot-actuator/src/main/java/org/baeldung/MainApplication.java delete mode 100644 spring-boot-actuator/src/main/java/org/baeldung/config/MainConfig.java delete mode 100644 spring-boot-actuator/src/main/resources/application.properties delete mode 100644 spring-boot-actuator/src/test/java/org/baeldung/config/ActuatorInfoIntegrationTest.java delete mode 100644 spring-boot-actuator/src/test/resources/expectedResponse.json diff --git a/spring-boot-actuator/.gitignore b/spring-boot-actuator/.gitignore deleted file mode 100644 index 60be5b80aa..0000000000 --- a/spring-boot-actuator/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/target/ -.settings/ -.classpath -.project diff --git a/spring-boot-actuator/README.MD b/spring-boot-actuator/README.MD deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-boot-actuator/pom.xml b/spring-boot-actuator/pom.xml deleted file mode 100644 index 299c7e76a5..0000000000 --- a/spring-boot-actuator/pom.xml +++ /dev/null @@ -1,122 +0,0 @@ - - 4.0.0 - com.baeldung - spring-boot-actuator - 0.0.1-SNAPSHOT - jar - spring-boot - This is simple boot application for Spring boot actuator test - - - - org.springframework.boot - spring-boot-starter-parent - 1.5.2.RELEASE - - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-actuator - - - - org.springframework.boot - spring-boot-starter - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - spring-boot-actuator - - - src/main/resources - true - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.7.0 - - 1.8 - 1.8 - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*IntegrationTest.java - - - - - - - - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - - - - org.baeldung.MainApplication - UTF-8 - 1.8 - - - diff --git a/spring-boot-actuator/src/main/java/org/baeldung/MainApplication.java b/spring-boot-actuator/src/main/java/org/baeldung/MainApplication.java deleted file mode 100644 index 7c9054dbf8..0000000000 --- a/spring-boot-actuator/src/main/java/org/baeldung/MainApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.baeldung.config.MainConfig; - -@SpringBootApplication -public class MainApplication { - - public static void main(String args[]) { - SpringApplication.run(MainConfig.class, args); - } -} diff --git a/spring-boot-actuator/src/main/java/org/baeldung/config/MainConfig.java b/spring-boot-actuator/src/main/java/org/baeldung/config/MainConfig.java deleted file mode 100644 index 27c97cc006..0000000000 --- a/spring-boot-actuator/src/main/java/org/baeldung/config/MainConfig.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.config; - -import java.util.Collections; -import org.springframework.boot.actuate.info.InfoContributor; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Bean; - -@EnableAutoConfiguration -public class MainConfig { - - public MainConfig() {} - - @Bean - public InfoContributor getInfoContributor() { - return (infoBuilder) -> infoBuilder.withDetail("applicationInfo", Collections.singletonMap("ActiveUserCount", "10")); - } -} diff --git a/spring-boot-actuator/src/main/resources/application.properties b/spring-boot-actuator/src/main/resources/application.properties deleted file mode 100644 index 835c78eda2..0000000000 --- a/spring-boot-actuator/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -info.app.name=Sample application \ No newline at end of file diff --git a/spring-boot-actuator/src/test/java/org/baeldung/config/ActuatorInfoIntegrationTest.java b/spring-boot-actuator/src/test/java/org/baeldung/config/ActuatorInfoIntegrationTest.java deleted file mode 100644 index 0b5e3b3eef..0000000000 --- a/spring-boot-actuator/src/test/java/org/baeldung/config/ActuatorInfoIntegrationTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.baeldung.config; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.*; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = MainConfig.class) -@TestPropertySource(properties = { "security.basic.enabled=false" }) -public class ActuatorInfoIntegrationTest { - - @Autowired - private TestRestTemplate restTemplate; - - @Test - public void whenGetInfo_thenAdditionalInfoReturned() throws IOException { - final String expectedResponse = new String(Files.readAllBytes(Paths.get("src/test/resources/expectedResponse.json"))); - final ResponseEntity responseEntity = this.restTemplate.getForEntity("/info", String.class); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertEquals(expectedResponse, responseEntity.getBody()); - } -} \ No newline at end of file diff --git a/spring-boot-actuator/src/test/resources/expectedResponse.json b/spring-boot-actuator/src/test/resources/expectedResponse.json deleted file mode 100644 index caa0bdbbf8..0000000000 --- a/spring-boot-actuator/src/test/resources/expectedResponse.json +++ /dev/null @@ -1 +0,0 @@ -{"app":{"name":"Sample application"},"applicationInfo":{"ActiveUserCount":"10"}} \ No newline at end of file From 09cbc1c6eeafc18249cfa32ed1d442c0b9fb5969 Mon Sep 17 00:00:00 2001 From: Juan Moreno Date: Sun, 7 Jan 2018 20:51:53 -0300 Subject: [PATCH 39/58] Sample code for BAEL-1148 - earth001@gmail.com (#3268) * Sample code for BAEL-1148 - earth001@gmail.com * Change tabs for spaces in non java files * Change tabs for spaces in non java files * Removed unnecessary argument --- spring-mvc-push/.gitignore | 1 + spring-mvc-push/pom.xml | 91 ++++++++++++++++++ .../baeldung/config/PushConfiguration.java | 48 +++++++++ .../baeldung/controller/PushController.java | 31 ++++++ .../src/main/webapp/WEB-INF/views/demo.jsp | 22 +++++ spring-mvc-push/src/main/webapp/index.jsp | 14 +++ .../src/main/webapp/resources/logo.png | Bin 0 -> 7391 bytes .../src/main/webapp/resources/script.js | 1 + .../src/main/webapp/resources/style.css | 9 ++ .../PushControllerIntegrationTest.java | 41 ++++++++ 10 files changed, 258 insertions(+) create mode 100644 spring-mvc-push/.gitignore create mode 100644 spring-mvc-push/pom.xml create mode 100644 spring-mvc-push/src/main/java/com/baeldung/config/PushConfiguration.java create mode 100644 spring-mvc-push/src/main/java/com/baeldung/controller/PushController.java create mode 100644 spring-mvc-push/src/main/webapp/WEB-INF/views/demo.jsp create mode 100644 spring-mvc-push/src/main/webapp/index.jsp create mode 100644 spring-mvc-push/src/main/webapp/resources/logo.png create mode 100644 spring-mvc-push/src/main/webapp/resources/script.js create mode 100644 spring-mvc-push/src/main/webapp/resources/style.css create mode 100644 spring-mvc-push/src/test/java/com/baeldung/controller/PushControllerIntegrationTest.java diff --git a/spring-mvc-push/.gitignore b/spring-mvc-push/.gitignore new file mode 100644 index 0000000000..448298d47f --- /dev/null +++ b/spring-mvc-push/.gitignore @@ -0,0 +1 @@ +/.tern-project diff --git a/spring-mvc-push/pom.xml b/spring-mvc-push/pom.xml new file mode 100644 index 0000000000..2eb10381be --- /dev/null +++ b/spring-mvc-push/pom.xml @@ -0,0 +1,91 @@ + + 4.0.0 + com.baeldung + spring-mvc-push + war + 0.0.1-SNAPSHOT + spring-mvc-push + + 1.8 + 1.8 + 2.20 + 3.7.0 + 3.2.0 + UTF-8 + 5.0.2 + 5.0.2.RELEASE + 4.0.0 + 1.2 + 2.3.2-b02 + 5.0.2 + 1.0.2 + + + + org.springframework + spring-webmvc + ${spring.version} + + + javax.servlet + javax.servlet-api + ${servlet.version} + provided + + + javax.servlet + jstl + ${jstl.version} + + + javax.servlet.jsp + javax.servlet.jsp-api + ${jsp-api.version} + + + + org.springframework + spring-test + ${spring.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.version} + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + spring-mvc-push + false + ${deploy-path} + + + + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + spring-mvc-push + + diff --git a/spring-mvc-push/src/main/java/com/baeldung/config/PushConfiguration.java b/spring-mvc-push/src/main/java/com/baeldung/config/PushConfiguration.java new file mode 100644 index 0000000000..e6188da92d --- /dev/null +++ b/spring-mvc-push/src/main/java/com/baeldung/config/PushConfiguration.java @@ -0,0 +1,48 @@ +package com.baeldung.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "com.baeldung.controller") +public class PushConfiguration implements WebApplicationInitializer, WebMvcConfigurer { + + @Override + public void onStartup(ServletContext container) throws ServletException { + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + context.register(PushConfiguration.class); + container.addListener(new ContextLoaderListener(context)); + ServletRegistration.Dynamic dispatcher = container.addServlet("DispatcherServlet", new DispatcherServlet(context)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/"); + } + + @Bean + public InternalResourceViewResolver jspViewResolver() { + InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setPrefix("/WEB-INF/views/"); + bean.setSuffix(".jsp"); + return bean; + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**") + .addResourceLocations("/resources/"); + } + +} diff --git a/spring-mvc-push/src/main/java/com/baeldung/controller/PushController.java b/spring-mvc-push/src/main/java/com/baeldung/controller/PushController.java new file mode 100644 index 0000000000..efee3a840f --- /dev/null +++ b/spring-mvc-push/src/main/java/com/baeldung/controller/PushController.java @@ -0,0 +1,31 @@ +package com.baeldung.controller; + +import javax.servlet.http.PushBuilder; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class PushController { + + @RequestMapping(value = "/demoWithPush") + public String demoWithPush(PushBuilder pushBuilder) { + if (null != pushBuilder) { + pushBuilder.path("resources/logo.png") + .addHeader("Content-Type", "image/png") + .push(); + pushBuilder.path("resources/script.js") + .addHeader("Content-Type", "text/javascript") + .push(); + pushBuilder.path("resources/style.css") + .addHeader("Content-Type", "text/css") + .push(); + } + return "demo"; + } + + @RequestMapping(value = "/demoWithoutPush") + public String demoWithoutPush() { + return "demo"; + } +} \ No newline at end of file diff --git a/spring-mvc-push/src/main/webapp/WEB-INF/views/demo.jsp b/spring-mvc-push/src/main/webapp/WEB-INF/views/demo.jsp new file mode 100644 index 0000000000..d77619283a --- /dev/null +++ b/spring-mvc-push/src/main/webapp/WEB-INF/views/demo.jsp @@ -0,0 +1,22 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + + +PushBuilder demo +" rel="stylesheet" /> + + + + PushBuilder demo +
+ " alt="Logo" height="126" + width="411"> +
+ +
Go to + index + + \ No newline at end of file diff --git a/spring-mvc-push/src/main/webapp/index.jsp b/spring-mvc-push/src/main/webapp/index.jsp new file mode 100644 index 0000000000..82ecb68003 --- /dev/null +++ b/spring-mvc-push/src/main/webapp/index.jsp @@ -0,0 +1,14 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + + + +PushBuilder demo + + +

+ Go to PushBuilder demo
Go to + Simple demo +

+ + \ No newline at end of file diff --git a/spring-mvc-push/src/main/webapp/resources/logo.png b/spring-mvc-push/src/main/webapp/resources/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..edb83efbe3d4f083363fea616d5c0e2df6e1fe03 GIT binary patch literal 7391 zcmc(E=?>`{LP{DWMH&Vi zfp`1-2k(dHdgjBKGuN5D&))m4wbmV{rKv=SPlJzvfkCLEte}H|aW5O(hv4CW>#1E^ zF!;jqlvB~e1D_x~n^^Fh+Dp;MOV`cL%lEa1Erz|Tn~N=vr?rQzt*fVlo7WL$rxXST z-5V7JSv|j;-^-yv(-*n8$5cW*4{qehXjmgZ7ZRFe%bCWdseJaWb@r+aXw|;BocGi6 z_VXpK$qrQ4UP@VPrg*URRm;*s;pHslH|Pyxw9Tj&@jf{V3}CL z9vfrH;cHp50(cMr9tcT0G0>=r6bd0J(VZ293Dbs8I-J^YTzvPl)7KaChYL^ZuX%zUg~Q1xKQps ze8x@66zPD8O&j%h>?>rmyT@@9nU(3)D(1N@lb;bWINwK}kw_vpl@gw$F2dKs5NdJm zPrhyP0W}0KmdE;cxV5<0v~gc7wBC-5%zbNih}sSI_N>+8_%|&THf^ez9qwWKAA`yq zp&aANN-?3091P0#2bAs4_JqR*pWILFCePrI0y{37W?$|n+gH(s4yr45zkKVeNja<$ z<-V1<2K)Pndy>|c(evQ+!~Lf$g0JfP;xrmQe_TAcXe^#wg%v&OYn(BU@UVV8<>DH+ zIZ2)oJ*r3UyfHYl_eSlO&?ws?9KzE=)O;V}ZIxuM!#;n&9jaBMqjmqTZkc8`Qo;{w zeK&T0hc$B4ncSIwC1>5pkI-O?Cx+$7r1FC@PcdwAL|Z?lTDar7Y{@9r-3u$}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Nc5f>mck zdA_*5TEUqOZnh+Kb6?vIq;T)MQ_=QF?^#KBy`OUT=vbORGQa2Y3)@5UhZP<{a)SqC ze4hS52QT@f_*H-vXf(FNfsGcu6G0_|M8Y?zwM8BR!Cr6hs%~bek<8&_nk#h;MFTWeHs{B9d$z0SQr0>02Iws6LL z!}Iw_5&+i?RN#-(0Xq0%60XM-|1dbD2dx(5GnB-?hPO<-tseIQQZ5u)07Tx$!$oqMo!HL@WlvV zNQ-c%ZN7d1`H-p0;lX(h9Hkid?M=_)JTw7OuEag0C9zb;$6PPL$af177M&_p-m!i| zrz0g(iG;#&Kljhqyl}WDs4WMFyPGFp2YJ0wo)J2YBw?NbNy{-I$6xNnKRM!Sy3mk~ z8R%5KgZCGSsHnPU#j<}V^YxzhD*D&bq5;Uo3f|Jkn+tU1F0y?fx9XC)3F!V$Z!76D zKV{hT9@(W*MTWl_A=Fqh3G}%5L*Q6E&tp_FW^IA$9yv<%f87-O|8Kvw+~Edlh`bM1 TggyZsN(>c6O@%LVmf`;o*#$Af literal 0 HcmV?d00001 diff --git a/spring-mvc-push/src/main/webapp/resources/script.js b/spring-mvc-push/src/main/webapp/resources/script.js new file mode 100644 index 0000000000..9bc97c006a --- /dev/null +++ b/spring-mvc-push/src/main/webapp/resources/script.js @@ -0,0 +1 @@ +console.log('Script') \ No newline at end of file diff --git a/spring-mvc-push/src/main/webapp/resources/style.css b/spring-mvc-push/src/main/webapp/resources/style.css new file mode 100644 index 0000000000..d5fc158135 --- /dev/null +++ b/spring-mvc-push/src/main/webapp/resources/style.css @@ -0,0 +1,9 @@ +.single-title { + font-size: 30px; + color: #535353; + font-weight: 200; + letter-spacing: -1.5px; + line-height: 64px; + max-width: 750px; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif +} \ No newline at end of file diff --git a/spring-mvc-push/src/test/java/com/baeldung/controller/PushControllerIntegrationTest.java b/spring-mvc-push/src/test/java/com/baeldung/controller/PushControllerIntegrationTest.java new file mode 100644 index 0000000000..570e05cad6 --- /dev/null +++ b/spring-mvc-push/src/test/java/com/baeldung/controller/PushControllerIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.config.PushConfiguration; + +@Disabled +@SpringJUnitWebConfig(PushConfiguration.class) +public class PushControllerIntegrationTest { + @Autowired + private WebApplicationContext webAppContext; + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext) + .build(); + } + + @Test + public void whenDemoWithPushGETisPerformed_thenRetrievedStatusOk() throws Exception { + mockMvc.perform(get("/demoWithPush")) + .andExpect(status().isOk()); + } + + @Test + public void whenDemoWithoutPushGETisPerformed_thenRetrievedStatusOk() throws Exception { + mockMvc.perform(get("/demoWithoutPush")) + .andExpect(status().isOk()); + } +} \ No newline at end of file From cf32e14a9bc8796facda3dbdb68135691491f8c5 Mon Sep 17 00:00:00 2001 From: Allan Vital Date: Sun, 7 Jan 2018 21:59:53 -0200 Subject: [PATCH 40/58] [BAEL-1218] Guide to Spring EJB Integration (#3266) * Evaluation article about types of bean injection in spring * BAEL-1319 Quick Guide on Data.sql and Schema.sql Files in Spring * Revert "Evaluation article about types of bean injection in spring" This reverts commit eb071171673e0b8fa2b7ecffdad86f596e5fb114. * BAEL-1218: adding spring-ejb and configuring ejb start and deploy * BAEL-1218: adding spring * BAEL-1218: wrapping all together * BAEL-1218: new spring-ejb module * BAEL-1218: tests and improvements * BAEL-1218: removing moved files from old article * BAEL-1218: code review requested changes * BAEL-1218: test methods nomenclature correction * BAEL-1418: removing tabs * BAEL-1218: removing tabs * BAEL-1218: correcting boot parent module path --- pom.xml | 1 + spring-ejb/ejb-remote-for-spring/pom.xml | 76 +++++++++++++ .../ejb/tutorial/HelloStatefulWorld.java | 11 ++ .../ejb/tutorial/HelloStatefulWorldBean.java | 19 ++++ .../ejb/tutorial/HelloStatelessWorld.java | 10 ++ .../ejb/tutorial/HelloStatelessWorldBean.java | 12 +++ .../src/main/resources/META-INF/ejb-jar.xml | 7 ++ .../HelloStatefulWorldTestUnitTest.java | 32 ++++++ .../HelloStatelessWorldTestUnitTest.java | 24 +++++ spring-ejb/pom.xml | 77 ++++++++++++++ spring-ejb/spring-ejb-client/pom.xml | 100 ++++++++++++++++++ .../SpringEjbClientApplication.java | 50 +++++++++ .../endpoint/HomeEndpoint.java | 30 ++++++ .../src/main/resources/application.properties | 3 + ...ngEjbClientApplicationIntegrationTest.java | 11 ++ 15 files changed, 463 insertions(+) create mode 100755 spring-ejb/ejb-remote-for-spring/pom.xml create mode 100644 spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatefulWorld.java create mode 100644 spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatefulWorldBean.java create mode 100755 spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatelessWorld.java create mode 100755 spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatelessWorldBean.java create mode 100755 spring-ejb/ejb-remote-for-spring/src/main/resources/META-INF/ejb-jar.xml create mode 100644 spring-ejb/ejb-remote-for-spring/src/test/java/com/baeldung/ejb/tutorial/HelloStatefulWorldTestUnitTest.java create mode 100644 spring-ejb/ejb-remote-for-spring/src/test/java/com/baeldung/ejb/tutorial/HelloStatelessWorldTestUnitTest.java create mode 100755 spring-ejb/pom.xml create mode 100644 spring-ejb/spring-ejb-client/pom.xml create mode 100644 spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/SpringEjbClientApplication.java create mode 100644 spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/endpoint/HomeEndpoint.java create mode 100644 spring-ejb/spring-ejb-client/src/main/resources/application.properties create mode 100644 spring-ejb/spring-ejb-client/src/test/java/com/baeldung/springejbclient/SpringEjbClientApplicationIntegrationTest.java diff --git a/pom.xml b/pom.xml index b018fdd778..0d26188082 100644 --- a/pom.xml +++ b/pom.xml @@ -161,6 +161,7 @@ spring-cloud spring-core spring-cucumber + spring-ejb spring-aop persistence-modules/spring-data-cassandra spring-data-couchbase-2 diff --git a/spring-ejb/ejb-remote-for-spring/pom.xml b/spring-ejb/ejb-remote-for-spring/pom.xml new file mode 100755 index 0000000000..fd1095420c --- /dev/null +++ b/spring-ejb/ejb-remote-for-spring/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + + + com.baeldung.spring.ejb + ejb-for-spring + 1.0.1 + + + ejb-remote-for-spring + ejb + + + + javax + javaee-api + provided + + + org.assertj + assertj-core + 3.9.0 + test + + + + + + + + wildfly-standalone + + false + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + + + + wildfly10x + + http://download.jboss.org/wildfly/10.1.0.Final/wildfly-10.1.0.Final.zip + + + + + + 127.0.0.1 + standalone-full + 9990 + testUser:admin1234! + + + + + + + + + + + + 7.0 + 1.6.1 + + + + + diff --git a/spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatefulWorld.java b/spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatefulWorld.java new file mode 100644 index 0000000000..6d1c26ef4a --- /dev/null +++ b/spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatefulWorld.java @@ -0,0 +1,11 @@ +package com.baeldung.ejb.tutorial; + +import javax.ejb.Remote; + +@Remote +public interface HelloStatefulWorld { + + int howManyTimes(); + String getHelloWorld(); + +} diff --git a/spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatefulWorldBean.java b/spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatefulWorldBean.java new file mode 100644 index 0000000000..0619f5593a --- /dev/null +++ b/spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatefulWorldBean.java @@ -0,0 +1,19 @@ +package com.baeldung.ejb.tutorial; + +import javax.ejb.Stateful; + +@Stateful(name = "HelloStatefulWorld") +public class HelloStatefulWorldBean implements HelloStatefulWorld { + + private int howManyTimes = 0; + + public int howManyTimes() { + return howManyTimes; + } + + public String getHelloWorld() { + howManyTimes++; + return "Hello Stateful World!"; + } + +} diff --git a/spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatelessWorld.java b/spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatelessWorld.java new file mode 100755 index 0000000000..6b4db29e95 --- /dev/null +++ b/spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatelessWorld.java @@ -0,0 +1,10 @@ +package com.baeldung.ejb.tutorial; + +import javax.ejb.Remote; + +@Remote +public interface HelloStatelessWorld { + + String getHelloWorld(); + +} diff --git a/spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatelessWorldBean.java b/spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatelessWorldBean.java new file mode 100755 index 0000000000..7de499c618 --- /dev/null +++ b/spring-ejb/ejb-remote-for-spring/src/main/java/com/baeldung/ejb/tutorial/HelloStatelessWorldBean.java @@ -0,0 +1,12 @@ +package com.baeldung.ejb.tutorial; + +import javax.ejb.Stateless; + +@Stateless(name = "HelloStatelessWorld") +public class HelloStatelessWorldBean implements HelloStatelessWorld { + + public String getHelloWorld() { + return "Hello Stateless World!"; + } + +} diff --git a/spring-ejb/ejb-remote-for-spring/src/main/resources/META-INF/ejb-jar.xml b/spring-ejb/ejb-remote-for-spring/src/main/resources/META-INF/ejb-jar.xml new file mode 100755 index 0000000000..f51523ac14 --- /dev/null +++ b/spring-ejb/ejb-remote-for-spring/src/main/resources/META-INF/ejb-jar.xml @@ -0,0 +1,7 @@ + + + ejb-remote-for-spring + + diff --git a/spring-ejb/ejb-remote-for-spring/src/test/java/com/baeldung/ejb/tutorial/HelloStatefulWorldTestUnitTest.java b/spring-ejb/ejb-remote-for-spring/src/test/java/com/baeldung/ejb/tutorial/HelloStatefulWorldTestUnitTest.java new file mode 100644 index 0000000000..61373079f6 --- /dev/null +++ b/spring-ejb/ejb-remote-for-spring/src/test/java/com/baeldung/ejb/tutorial/HelloStatefulWorldTestUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.ejb.tutorial; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Before; +import org.junit.Test; + +public class HelloStatefulWorldTestUnitTest { + + private HelloStatefulWorldBean statefulBean; + + @Before + public void setup() { + statefulBean = new HelloStatefulWorldBean(); + } + + @Test + public void whenGetHelloWorld_thenHelloStatefulWorldIsReturned() { + String helloWorld = statefulBean.getHelloWorld(); + + assertThat(helloWorld).isEqualTo("Hello Stateful World!"); + } + + @Test + public void whenGetHelloWorldIsCalledTwice_thenCounterIs2() { + statefulBean.getHelloWorld(); + statefulBean.getHelloWorld(); + + assertThat(statefulBean.howManyTimes()).isEqualTo(2); + } + +} diff --git a/spring-ejb/ejb-remote-for-spring/src/test/java/com/baeldung/ejb/tutorial/HelloStatelessWorldTestUnitTest.java b/spring-ejb/ejb-remote-for-spring/src/test/java/com/baeldung/ejb/tutorial/HelloStatelessWorldTestUnitTest.java new file mode 100644 index 0000000000..b95618e4d4 --- /dev/null +++ b/spring-ejb/ejb-remote-for-spring/src/test/java/com/baeldung/ejb/tutorial/HelloStatelessWorldTestUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.ejb.tutorial; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Before; +import org.junit.Test; + +public class HelloStatelessWorldTestUnitTest { + + private HelloStatelessWorldBean statelessBean; + + @Before + public void setup() { + statelessBean = new HelloStatelessWorldBean(); + } + + @Test + public void whenGetHelloWorld_thenHelloStatelessWorldIsReturned() { + String helloWorld = statelessBean.getHelloWorld(); + + assertThat(helloWorld).isEqualTo("Hello Stateless World!"); + } + +} diff --git a/spring-ejb/pom.xml b/spring-ejb/pom.xml new file mode 100755 index 0000000000..0b2a8445c5 --- /dev/null +++ b/spring-ejb/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + com.baeldung.spring.ejb + ejb-for-spring + 1.0.1 + pom + ejb + Spring EJB Tutorial + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + jboss-public-repository-group + JBoss Public Maven Repository Group + http://repository.jboss.org/nexus/content/groups/public/ + default + + true + never + + + true + never + + + + + + + + com.baeldung.spring.ejb + ejb-remote-for-spring + 1.0.1 + ejb + + + javax + javaee-api + 7.0 + provided + + + org.wildfly + wildfly-ejb-client-bom + 10.1.0.Final + pom + import + + + + + + + + + maven-ejb-plugin + 2.4 + + 3.2 + + + + + + + + ejb-remote-for-spring + spring-ejb-client + + diff --git a/spring-ejb/spring-ejb-client/pom.xml b/spring-ejb/spring-ejb-client/pom.xml new file mode 100644 index 0000000000..c77ce09a2d --- /dev/null +++ b/spring-ejb/spring-ejb-client/pom.xml @@ -0,0 +1,100 @@ + + + 4.0.0 + + spring-ejb-client + jar + + spring-ejb-client + Spring EJB Client + + + com.baeldung + parent-boot-5 + 0.0.1-SNAPSHOT + ../../parent-boot-5 + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.wildfly + wildfly-ejb-client-bom + 10.1.0.Final + pom + + + + com.baeldung.spring.ejb + ejb-remote-for-spring + 1.0.1 + ejb + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + diff --git a/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/SpringEjbClientApplication.java b/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/SpringEjbClientApplication.java new file mode 100644 index 0000000000..d3542a2158 --- /dev/null +++ b/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/SpringEjbClientApplication.java @@ -0,0 +1,50 @@ +package com.baeldung.springejbclient; + +import java.util.Properties; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +import com.baeldung.ejb.tutorial.HelloStatefulWorld; +import com.baeldung.ejb.tutorial.HelloStatelessWorld; + +@SpringBootApplication +public class SpringEjbClientApplication { + + @Bean + public Context context() throws NamingException { + Properties jndiProps = new Properties(); + jndiProps.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory"); + jndiProps.put("jboss.naming.client.ejb.context", true); + jndiProps.put("java.naming.provider.url", "http-remoting://localhost:8080"); + return new InitialContext(jndiProps); + } + + @Bean + public HelloStatelessWorld helloStatelessWorld(Context context) throws NamingException { + return (HelloStatelessWorld) context.lookup(this.getFullName(HelloStatelessWorld.class)); + } + + @Bean + public HelloStatefulWorld helloStatefulWorld(Context context) throws NamingException { + return (HelloStatefulWorld) context.lookup(this.getFullName(HelloStatefulWorld.class)); + } + + @SuppressWarnings("rawtypes") + private String getFullName(Class classType) { + String moduleName = "ejb-remote-for-spring/"; + String beanName = classType.getSimpleName(); + String viewClassName = classType.getName(); + + return moduleName + beanName + "!" + viewClassName; + } + + public static void main(String[] args) { + SpringApplication.run(SpringEjbClientApplication.class, args); + } +} diff --git a/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/endpoint/HomeEndpoint.java b/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/endpoint/HomeEndpoint.java new file mode 100644 index 0000000000..e72e3b310e --- /dev/null +++ b/spring-ejb/spring-ejb-client/src/main/java/com/baeldung/springejbclient/endpoint/HomeEndpoint.java @@ -0,0 +1,30 @@ +package com.baeldung.springejbclient.endpoint; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.ejb.tutorial.HelloStatefulWorld; +import com.baeldung.ejb.tutorial.HelloStatelessWorld; + +@RestController +public class HomeEndpoint { + + private HelloStatelessWorld helloStatelessWorld; + private HelloStatefulWorld helloStatefulWorld; + + public HomeEndpoint(HelloStatelessWorld helloStatelessWorld, HelloStatefulWorld helloStatefulWorld) { + this.helloStatelessWorld = helloStatelessWorld; + this.helloStatefulWorld = helloStatefulWorld; + } + + @GetMapping("/stateless") + public String getStateless() { + return helloStatelessWorld.getHelloWorld(); + } + + @GetMapping("/stateful") + public String getStateful() { + return helloStatefulWorld.getHelloWorld() + " called " + helloStatefulWorld.howManyTimes() + " times"; + } + +} diff --git a/spring-ejb/spring-ejb-client/src/main/resources/application.properties b/spring-ejb/spring-ejb-client/src/main/resources/application.properties new file mode 100644 index 0000000000..d564d40356 --- /dev/null +++ b/spring-ejb/spring-ejb-client/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8081 + +#logging.level.root=DEBUG \ No newline at end of file diff --git a/spring-ejb/spring-ejb-client/src/test/java/com/baeldung/springejbclient/SpringEjbClientApplicationIntegrationTest.java b/spring-ejb/spring-ejb-client/src/test/java/com/baeldung/springejbclient/SpringEjbClientApplicationIntegrationTest.java new file mode 100644 index 0000000000..89c88fe5a5 --- /dev/null +++ b/spring-ejb/spring-ejb-client/src/test/java/com/baeldung/springejbclient/SpringEjbClientApplicationIntegrationTest.java @@ -0,0 +1,11 @@ +package com.baeldung.springejbclient; + +import org.junit.Test; + +public class SpringEjbClientApplicationIntegrationTest { + + @Test + public void contextLoads() { + } + +} From db04ce54f042b4564b9e90be28e4606d71b35ef8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hakan=20=C3=96zler?= Date: Mon, 8 Jan 2018 18:40:32 +0300 Subject: [PATCH 41/58] [BAEL-1455] add docker client test cases and update pom (#3375) --- libraries/pom.xml | 30 +++- .../baeldung/dockerapi/ContainerLiveTest.java | 165 ++++++++++++++++++ .../dockerapi/DockerClientLiveTest.java | 83 +++++++++ .../com/baeldung/dockerapi/ImageLiveTest.java | 155 ++++++++++++++++ .../baeldung/dockerapi/NetworkLiveTest.java | 91 ++++++++++ .../baeldung/dockerapi/VolumeLiveTest.java | 86 +++++++++ .../src/test/resources/dockerapi/Dockerfile | 8 + 7 files changed, 617 insertions(+), 1 deletion(-) create mode 100644 libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java create mode 100644 libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java create mode 100644 libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java create mode 100644 libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java create mode 100644 libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java create mode 100644 libraries/src/test/resources/dockerapi/Dockerfile diff --git a/libraries/pom.xml b/libraries/pom.xml index 712a7df786..09c8cb8335 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -107,7 +107,7 @@ maven-compiler-plugin - 3.7.0 + 3.7.0 1.8 1.8 @@ -639,6 +639,33 @@ ${googleclient.version}
+ + + com.github.docker-java + docker-java + ${docker.version} + + + org.slf4j + slf4j-log4j12 + + + org.slf4j + jcl-over-slf4j + + + ch.qos.logback + logback-classic + + + + + com.sun.jersey + jersey-client + 1.19.4 + + + com.google.api-client @@ -758,5 +785,6 @@ 1.23.0 v4-rev493-1.21.0 1.0.0 + 3.0.14 \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java new file mode 100644 index 0000000000..531e7e7c5b --- /dev/null +++ b/libraries/src/test/java/com/baeldung/dockerapi/ContainerLiveTest.java @@ -0,0 +1,165 @@ +package com.baeldung.dockerapi; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.PortBinding; +import com.github.dockerjava.core.DockerClientBuilder; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.core.Is.is; + +public class ContainerLiveTest { + + private static DockerClient dockerClient; + + @BeforeClass + public static void setup() { + dockerClient = DockerClientBuilder.getInstance().build(); + } + + @Test + public void whenListingRunningContainers_thenReturnNonEmptyList() { + + //when + List containers = dockerClient.listContainersCmd().exec(); + + //then + assertThat(containers.size(), is(not(0))); + } + + @Test + public void whenListingExitedContainers_thenReturnNonEmptyList() { + + //when + List containers = dockerClient.listContainersCmd() + .withShowSize(true) + .withShowAll(true) + .withStatusFilter("exited") + .exec(); + + //then + assertThat(containers.size(), is(not(0))); + } + + @Test + public void whenCreatingContainer_thenMustReturnContainerId() { + + //when + CreateContainerResponse container + = dockerClient.createContainerCmd("mongo:3.6") + .withCmd("--bind_ip_all") + .withName("mongo") + .withHostName("baeldung") + .withEnv("MONGO_LATEST_VERSION=3.6") + .withPortBindings(PortBinding.parse("9999:27017")) + .exec(); + + //then + assertThat(container.getId(), is(not(null))); + } + + + @Test + public void whenHavingContainer_thenRunContainer() throws InterruptedException { + + //when + CreateContainerResponse container + = dockerClient.createContainerCmd("alpine:3.6") + .withCmd("sleep", "10000") + .exec(); + + Thread.sleep(3000); + //then + dockerClient.startContainerCmd(container.getId()) + .exec(); + + dockerClient.stopContainerCmd(container.getId()) + .exec(); + } + + @Test + public void whenRunningContainer_thenStopContainer() throws InterruptedException { + + //when + CreateContainerResponse container + = dockerClient.createContainerCmd("alpine:3.6") + .withCmd("sleep", "10000") + .exec(); + + Thread.sleep(3000); + dockerClient.startContainerCmd(container.getId()) + .exec(); + + //then + dockerClient.stopContainerCmd(container.getId()) + .exec(); + } + + @Test + public void whenRunningContainer_thenKillContainer() throws InterruptedException { + + //when + CreateContainerResponse container + = dockerClient.createContainerCmd("alpine:3.6") + .withCmd("sleep", "10000") + .exec(); + + dockerClient.startContainerCmd(container.getId()) + .exec(); + + Thread.sleep(3000); + dockerClient.stopContainerCmd(container.getId()) + .exec(); + + //then + dockerClient.killContainerCmd(container.getId()) + .exec(); + } + + @Test + public void whenHavingContainer_thenInspectContainer() { + + //when + CreateContainerResponse container + = dockerClient.createContainerCmd("alpine:3.6") + .withCmd("sleep", "10000") + .exec(); + + //then + InspectContainerResponse containerResponse + = dockerClient.inspectContainerCmd(container.getId()) + .exec(); + + assertThat(containerResponse.getId(), is(container.getId())); + } + + + @Test + public void givenContainer_whenCommittingContainer_thenMustReturnImageId() { + + //given + CreateContainerResponse container + = dockerClient.createContainerCmd("alpine:3.6") + .withCmd("sleep", "10000") + .exec(); + + //when + String imageId = dockerClient.commitCmd(container.getId()) + .withEnv("SNAPSHOT_YEAR=2018") + .withMessage("add git support") + .withCmd("sleep", "10000") + .withRepository("alpine") + .withTag("3.6.v2").exec(); + + //then + assertThat(imageId, is(not(null))); + } + +} diff --git a/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java new file mode 100644 index 0000000000..1023298e25 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/dockerapi/DockerClientLiveTest.java @@ -0,0 +1,83 @@ +package com.baeldung.dockerapi; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.core.DefaultDockerClientConfig; +import com.github.dockerjava.core.DockerClientBuilder; +import org.junit.Test; + +import java.util.Properties; + +import static org.junit.Assert.assertNotNull; + +public class DockerClientLiveTest { + + @Test + public void whenCreatingDockerClient_thenReturnDefaultInstance() { + + //when + DefaultDockerClientConfig.Builder config + = DefaultDockerClientConfig.createDefaultConfigBuilder(); + DockerClient dockerClient = DockerClientBuilder.getInstance(config).build(); + + //then + assertNotNull(dockerClient); + } + + @Test + public void whenCreatingDockerClientWithDockerHost_thenReturnInstance() { + //when + DockerClient dockerClient + = DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375") + .build(); + + //then + assertNotNull(dockerClient); + } + + @Test + public void whenCreatingAdvanceDockerClient_thenReturnInstance() { + + //when + DefaultDockerClientConfig config + = DefaultDockerClientConfig.createDefaultConfigBuilder() + .withRegistryEmail("info@bealdung.com") + .withRegistryUrl("register.bealdung.io/v2/") + .withRegistryPassword("strongpassword") + .withRegistryUsername("bealdung") + .withDockerCertPath("/home/bealdung/public/.docker/certs") + .withDockerConfig("/home/bealdung/public/.docker/") + .withDockerTlsVerify("1") + .withDockerHost("tcp://docker.beauldung.com:2376") + .build(); + + DockerClient dockerClient = DockerClientBuilder.getInstance(config).build(); + + //then + assertNotNull(dockerClient); + } + + @Test + public void whenCreatingDockerClientWithProperties_thenReturnInstance() { + + //when + Properties properties = new Properties(); + properties.setProperty("registry.email", "info@bealdung.com"); + properties.setProperty("registry.url", "register.bealdung.io/v2/"); + properties.setProperty("registry.password", "strongpassword"); + properties.setProperty("registry.username", "bealdung"); + properties.setProperty("DOCKER_CERT_PATH", "/home/bealdung/public/.docker/certs"); + properties.setProperty("DOCKER_CONFIG", "/home/bealdung/public/.docker/"); + properties.setProperty("DOCKER_TLS_VERIFY", "1"); + properties.setProperty("DOCKER_HOST", "tcp://docker.bealdung.com:2376"); + + DefaultDockerClientConfig config + = DefaultDockerClientConfig.createDefaultConfigBuilder() + .withProperties(properties) + .build(); + + DockerClient dockerClient = DockerClientBuilder.getInstance(config).build(); + + //then + assertNotNull(dockerClient); + } +} diff --git a/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java new file mode 100644 index 0000000000..ef894b2773 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/dockerapi/ImageLiveTest.java @@ -0,0 +1,155 @@ +package com.baeldung.dockerapi; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.InspectImageResponse; +import com.github.dockerjava.api.model.Image; +import com.github.dockerjava.api.model.SearchItem; +import com.github.dockerjava.core.DockerClientBuilder; +import com.github.dockerjava.core.command.BuildImageResultCallback; +import com.github.dockerjava.core.command.PullImageResultCallback; +import com.github.dockerjava.core.command.PushImageResultCallback; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.core.Is.is; + +public class ImageLiveTest { + + private static DockerClient dockerClient; + + @BeforeClass + public static void setup() { + dockerClient = DockerClientBuilder.getInstance().build(); + } + + @Test + public void whenListingImages_thenReturnNonEmptyList() { + + //when + List images = dockerClient.listImagesCmd().exec(); + + //then + assertThat(images.size(), is(not(0))); + } + + @Test + public void whenListingImagesWithIntermediateImages_thenReturnNonEmptyList() { + + //when + List images = dockerClient.listImagesCmd() + .withShowAll(true).exec(); + + //then + assertThat(images.size(), is(not(0))); + } + + @Test + public void whenListingDanglingImages_thenReturnNonNullList() { + + //when + List images = dockerClient.listImagesCmd() + .withDanglingFilter(true).exec(); + + //then + assertThat(images, is(not(null))); + } + + @Test + public void whenBuildingImage_thenMustReturnImageId() { + + //when + String imageId = dockerClient.buildImageCmd() + .withDockerfile(new File("src/test/resources/dockerapi/Dockerfile")) + .withPull(true) + .withNoCache(true) + .withTag("alpine:git") + .exec(new BuildImageResultCallback()) + .awaitImageId(); + + //then + assertThat(imageId, is(not(null))); + } + + @Test + public void givenListOfImages_whenInspectImage_thenMustReturnObject() { + + //given + List images = dockerClient.listImagesCmd().exec(); + Image image = images.get(0); + + //when + InspectImageResponse imageResponse + = dockerClient.inspectImageCmd(image.getId()).exec(); + + //then + assertThat(imageResponse.getId(), is(image.getId())); + } + + @Test + public void givenListOfImages_whenTagImage_thenListMustIncrement() { + + //given + List images = dockerClient.listImagesCmd().exec(); + Image image = images.get(0); + + //when + dockerClient.tagImageCmd(image.getId(), "baeldung/alpine", "3.6.v2").exec(); + + //then + List imagesNow = dockerClient.listImagesCmd().exec(); + assertThat(imagesNow.size(), is(greaterThan(images.size()))); + } + + public void pushingAnImage() throws InterruptedException { + + dockerClient.pushImageCmd("baeldung/alpine") + .withTag("3.6.v2") + .exec(new PushImageResultCallback()) + .awaitCompletion(90, TimeUnit.SECONDS); + } + + @Test + public void whenPullingImage_thenImageListNotEmpty() throws InterruptedException { + + //when + dockerClient.pullImageCmd("alpine") + .withTag("latest") + .exec(new PullImageResultCallback()) + .awaitCompletion(30, TimeUnit.SECONDS); + + //then + List images = dockerClient.listImagesCmd().exec(); + assertThat(images.size(), is(not(0))); + } + + @Test + public void whenRemovingImage_thenImageListDecrease() { + + //when + List images = dockerClient.listImagesCmd().exec(); + Image image = images.get(0); + dockerClient.removeImageCmd(image.getId()).exec(); + + //then + List imagesNow = dockerClient.listImagesCmd().exec(); + assertThat(imagesNow.size(), is(lessThan(images.size()))); + } + + @Test + public void whenSearchingImage_thenMustReturn25Items() { + + //when + List items = dockerClient.searchImagesCmd("Java").exec(); + + //then + assertThat(items.size(), is(25)); + } +} diff --git a/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java new file mode 100644 index 0000000000..2031a3ebb4 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/dockerapi/NetworkLiveTest.java @@ -0,0 +1,91 @@ +package com.baeldung.dockerapi; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CreateNetworkResponse; +import com.github.dockerjava.api.model.Network; +import com.github.dockerjava.api.model.Network.Ipam; +import com.github.dockerjava.core.DockerClientBuilder; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.core.Is.is; + +public class NetworkLiveTest { + + private static DockerClient dockerClient; + + @BeforeClass + public static void setup() { + dockerClient = DockerClientBuilder.getInstance().build(); + } + + @Test + public void whenListingNetworks_thenSizeMustBeGreaterThanZero() { + + //when + List networks = dockerClient.listNetworksCmd().exec(); + + //then + assertThat(networks.size(), is(greaterThan(0))); + } + + @Test + public void whenCreatingNetwork_thenRetrieveResponse() { + + //when + CreateNetworkResponse networkResponse + = dockerClient.createNetworkCmd() + .withName("baeldungDefault") + .withDriver("bridge").exec(); + + //then + assertThat(networkResponse, is(not(null))); + } + + @Test + public void whenCreatingAdvanceNetwork_thenRetrieveResponse() { + + //when + CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd() + .withName("baeldungAdvanced") + .withIpam(new Ipam() + .withConfig(new Ipam.Config() + .withSubnet("172.36.0.0/16") + .withIpRange("172.36.5.0/24"))) + .withDriver("bridge").exec(); + + //then + assertThat(networkResponse, is(not(null))); + } + + @Test + public void whenInspectingNetwork_thenSizeMustBeGreaterThanZero() { + + //when + String networkName = "bridge"; + Network network + = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec(); + + //then + assertThat(network.getName(), is(networkName)); + } + + @Test + public void whenCreatingNetwork_thenRemove() throws InterruptedException { + + //when + CreateNetworkResponse networkResponse + = dockerClient.createNetworkCmd() + .withName("baeldungDefault") + .withDriver("bridge").exec(); + + //then + Thread.sleep(4000); + dockerClient.removeNetworkCmd(networkResponse.getId()).exec(); + } +} diff --git a/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java b/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java new file mode 100644 index 0000000000..060af0728c --- /dev/null +++ b/libraries/src/test/java/com/baeldung/dockerapi/VolumeLiveTest.java @@ -0,0 +1,86 @@ +package com.baeldung.dockerapi; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CreateVolumeResponse; +import com.github.dockerjava.api.command.InspectVolumeResponse; +import com.github.dockerjava.api.command.ListVolumesResponse; +import com.github.dockerjava.core.DockerClientBuilder; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.core.Is.is; + +public class VolumeLiveTest { + + private static DockerClient dockerClient; + + @BeforeClass + public static void setup() { + dockerClient = DockerClientBuilder.getInstance().build(); + } + + @Test + public void whenListingVolumes_thenSizeMustBeGreaterThanZero() { + + //when + ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec(); + + //then + List volumes = volumesResponse.getVolumes(); + assertThat(volumes.size(), is(greaterThan(0))); + } + + @Test + public void givenVolumes_whenInspectingVolume_thenReturnNonNullResponse() { + + //given + ListVolumesResponse volumesResponse = dockerClient.listVolumesCmd().exec(); + List volumes = volumesResponse.getVolumes(); + InspectVolumeResponse volume = volumes.get(0); + + //when + InspectVolumeResponse volumeResponse + = dockerClient.inspectVolumeCmd(volume.getName()).exec(); + + //then + assertThat(volumeResponse, is(not(null))); + } + + @Test + public void whenCreatingUnnamedVolume_thenGetVolumeId() { + + //when + CreateVolumeResponse unnamedVolume = dockerClient.createVolumeCmd().exec(); + + //then + assertThat(unnamedVolume.getName(), is(not(null))); + } + + @Test + public void whenCreatingNamedVolume_thenGetVolumeId() { + + //when + CreateVolumeResponse namedVolume + = dockerClient.createVolumeCmd().withName("myNamedVolume").exec(); + + //then + assertThat(namedVolume.getName(), is(not(null))); + } + + @Test + public void whenGettingNamedVolume_thenRemove() throws InterruptedException { + + //when + CreateVolumeResponse namedVolume + = dockerClient.createVolumeCmd().withName("anotherNamedVolume").exec(); + + //then + Thread.sleep(4000); + dockerClient.removeVolumeCmd(namedVolume.getName()).exec(); + } +} diff --git a/libraries/src/test/resources/dockerapi/Dockerfile b/libraries/src/test/resources/dockerapi/Dockerfile new file mode 100644 index 0000000000..f9ad47f032 --- /dev/null +++ b/libraries/src/test/resources/dockerapi/Dockerfile @@ -0,0 +1,8 @@ +FROM alpine:3.6 + +RUN apk --update add git openssh && \ + rm -rf /var/lib/apt/lists/* && \ + rm /var/cache/apk/* + +ENTRYPOINT ["git"] +CMD ["--help"] \ No newline at end of file From 23d47601d8ecf80722fdb993c8378f18a7fe72bd Mon Sep 17 00:00:00 2001 From: ShyamVeda Date: Mon, 8 Jan 2018 21:52:04 +0530 Subject: [PATCH 42/58] Zuul and Eureka Integration for discovering routes (#3363) --- spring-cloud/pom.xml | 4 +- .../bin/eureka-client/pom.xml | 68 +++++++++++++++++++ .../src/main/resources/application.yml | 13 ++++ .../bin/eureka-server/pom.xml | 68 +++++++++++++++++++ .../src/main/resources/application.yml | 7 ++ .../bin/pom.xml | 55 +++++++++++++++ .../bin/zuul-server/pom.xml | 61 +++++++++++++++++ .../src/main/resources/application.properties | 9 +++ .../eureka-client/pom.xml | 68 +++++++++++++++++++ .../client/EurekaClientApplication.java | 32 +++++++++ .../eureka/client/GreetingController.java | 8 +++ .../src/main/resources/application.yml | 13 ++++ .../eureka-server/pom.xml | 68 +++++++++++++++++++ .../server/EurekaServerApplication.java | 13 ++++ .../src/main/resources/application.yml | 7 ++ .../pom.xml | 56 +++++++++++++++ .../zuul-server/pom.xml | 66 ++++++++++++++++++ .../spring/cloud/zuul/config/ZuulConfig.java | 15 ++++ .../src/main/resources/application.properties | 9 +++ 19 files changed, 639 insertions(+), 1 deletion(-) create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/pom.xml create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/src/main/resources/application.yml create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/pom.xml create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/src/main/resources/application.yml create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/bin/zuul-server/pom.xml create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/bin/zuul-server/src/main/resources/application.properties create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/GreetingController.java create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/resources/application.yml create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/main/java/com/baeldung/spring/cloud/eureka/server/EurekaServerApplication.java create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/main/resources/application.yml create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/main/java/com/baeldung/spring/cloud/zuul/config/ZuulConfig.java create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/main/resources/application.properties diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 374f7010c6..d94b334bc8 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -20,7 +20,8 @@ spring-cloud-connectors-heroku spring-cloud-aws spring-cloud-consul - + spring-cloud-zuul-eureka-integration + pom spring-cloud @@ -45,6 +46,7 @@ 1.4.2.RELEASE 3.7.0 1.4.2.RELEASE + 1.2.3.RELEASE diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/pom.xml new file mode 100644 index 0000000000..a3185a44d4 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + eureka-client + 1.0.0-SNAPSHOT + jar + + Spring Cloud Eureka Client + Spring Cloud Eureka Sample Client + + + com.baeldung.spring.cloud + spring-cloud-zuul-eureka-integration + 1.0.0-SNAPSHOT + + + + + org.springframework.cloud + spring-cloud-starter-eureka + ${spring-cloud-starter-eureka.version} + + + org.springframework.boot + spring-boot-starter-web + ${spring-boot-starter-web.version} + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + ${spring-cloud-dependencies.version} + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + Brixton.SR7 + 1.2.3.RELEASE + 1.4.2.RELEASE + + diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/src/main/resources/application.yml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/src/main/resources/application.yml new file mode 100644 index 0000000000..08624aa159 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-client/src/main/resources/application.yml @@ -0,0 +1,13 @@ +spring: + application: + name: spring-cloud-eureka-client + +server: + port: 0 + +eureka: + client: + serviceUrl: + defaultZone: ${EUREKA_URI:http://localhost:8761/eureka} + instance: + preferIpAddress: true \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/pom.xml new file mode 100644 index 0000000000..d86cfa8589 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + eureka-server + 1.0.0-SNAPSHOT + jar + + Spring Cloud Eureka Server + Spring Cloud Eureka Server Demo + + + com.baeldung.spring.cloud + spring-cloud-zuul-eureka-integration + 1.0.0-SNAPSHOT + + + + + org.springframework.cloud + spring-cloud-starter-eureka-server + ${spring-cloud-starter-eureka.version} + + + commons-configuration + commons-configuration + ${commons-config.version} + + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + ${spring-cloud-dependencies.version} + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + Brixton.SR7 + 1.2.3.RELEASE + + diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/src/main/resources/application.yml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/src/main/resources/application.yml new file mode 100644 index 0000000000..49c3179bb5 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/eureka-server/src/main/resources/application.yml @@ -0,0 +1,7 @@ +server: + port: 8761 + +eureka: + client: + registerWithEureka: false + fetchRegistry: false \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml new file mode 100644 index 0000000000..fabad77a77 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + com.baeldung.spring.cloud + spring-cloud-zuul-eureka-integration + 1.0.0-SNAPSHOT + + pom + + Spring Cloud Zuul and Eureka Integration + Spring Cloud Zuul and Eureka Integration + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + .. + + + + UTF-8 + 3.7.0 + 1.4.2.RELEASE + 1.10 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + + + zuul-server + eureka-server + eureka-client + + diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/zuul-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/zuul-server/pom.xml new file mode 100644 index 0000000000..2622a3e36b --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/zuul-server/pom.xml @@ -0,0 +1,61 @@ + + 4.0.0 + + com.baeldung.spring.cloud + spring-cloud-zuul-eureka-integration + 1.0.0-SNAPSHOT + + zuul-server + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-zuul + + + org.springframework.cloud + spring-cloud-starter-eureka + + + commons-configuration + commons-configuration + ${commons-config.version} + + + org.springframework.boot + spring-boot-starter-security + + + + + + org.springframework.cloud + spring-cloud-starter-parent + ${spring-cloud-dependencies.version} + pom + import + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/zuul-server/src/main/resources/application.properties b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/zuul-server/src/main/resources/application.properties new file mode 100644 index 0000000000..cb1dca78c2 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/zuul-server/src/main/resources/application.properties @@ -0,0 +1,9 @@ +server.port=8762 +spring.application.name=zuul-server +eureka.instance.preferIpAddress=true +eureka.client.registerWithEureka=true +eureka.client.fetchRegistry=true +eureka.serviceurl.defaultzone=http://localhost:8761/eureka/ +management.security.enabled=false +security.basic.enabled=false +hystrix.command.default.execution.timeout.enabled=false diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml new file mode 100644 index 0000000000..a3185a44d4 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + eureka-client + 1.0.0-SNAPSHOT + jar + + Spring Cloud Eureka Client + Spring Cloud Eureka Sample Client + + + com.baeldung.spring.cloud + spring-cloud-zuul-eureka-integration + 1.0.0-SNAPSHOT + + + + + org.springframework.cloud + spring-cloud-starter-eureka + ${spring-cloud-starter-eureka.version} + + + org.springframework.boot + spring-boot-starter-web + ${spring-boot-starter-web.version} + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + ${spring-cloud-dependencies.version} + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + Brixton.SR7 + 1.2.3.RELEASE + 1.4.2.RELEASE + + diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java new file mode 100644 index 0000000000..906d6e4cfd --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/EurekaClientApplication.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.cloud.eureka.client; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.context.annotation.Lazy; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.discovery.EurekaClient; + +@SpringBootApplication +@EnableEurekaClient +@RestController +public class EurekaClientApplication implements GreetingController { + @Autowired + @Lazy + private EurekaClient eurekaClient; + + @Value("${spring.application.name}") + private String appName; + + public static void main(String[] args) { + SpringApplication.run(EurekaClientApplication.class, args); + } + + @Override + public String greeting() { + return String.format("Hello from '%s'!", eurekaClient.getApplication(appName).getName()); + } +} diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/GreetingController.java b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/GreetingController.java new file mode 100644 index 0000000000..33ee2574b7 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/java/com/baeldung/spring/cloud/eureka/client/GreetingController.java @@ -0,0 +1,8 @@ +package com.baeldung.spring.cloud.eureka.client; + +import org.springframework.web.bind.annotation.RequestMapping; + +public interface GreetingController { + @RequestMapping("/greeting") + String greeting(); +} diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/resources/application.yml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/resources/application.yml new file mode 100644 index 0000000000..08624aa159 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/main/resources/application.yml @@ -0,0 +1,13 @@ +spring: + application: + name: spring-cloud-eureka-client + +server: + port: 0 + +eureka: + client: + serviceUrl: + defaultZone: ${EUREKA_URI:http://localhost:8761/eureka} + instance: + preferIpAddress: true \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml new file mode 100644 index 0000000000..d86cfa8589 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + eureka-server + 1.0.0-SNAPSHOT + jar + + Spring Cloud Eureka Server + Spring Cloud Eureka Server Demo + + + com.baeldung.spring.cloud + spring-cloud-zuul-eureka-integration + 1.0.0-SNAPSHOT + + + + + org.springframework.cloud + spring-cloud-starter-eureka-server + ${spring-cloud-starter-eureka.version} + + + commons-configuration + commons-configuration + ${commons-config.version} + + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + ${spring-cloud-dependencies.version} + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + Brixton.SR7 + 1.2.3.RELEASE + + diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/main/java/com/baeldung/spring/cloud/eureka/server/EurekaServerApplication.java b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/main/java/com/baeldung/spring/cloud/eureka/server/EurekaServerApplication.java new file mode 100644 index 0000000000..d55145448d --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/main/java/com/baeldung/spring/cloud/eureka/server/EurekaServerApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.eureka.server; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; + +@SpringBootApplication +@EnableEurekaServer +public class EurekaServerApplication { + public static void main(String[] args) { + SpringApplication.run(EurekaServerApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/main/resources/application.yml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/main/resources/application.yml new file mode 100644 index 0000000000..49c3179bb5 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/main/resources/application.yml @@ -0,0 +1,7 @@ +server: + port: 8761 + +eureka: + client: + registerWithEureka: false + fetchRegistry: false \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml new file mode 100644 index 0000000000..b4c7188abe --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + com.baeldung.spring.cloud + spring-cloud-zuul-eureka-integration + 1.0.0-SNAPSHOT + + pom + + Spring Cloud Zuul and Eureka Integration + Spring Cloud Zuul and Eureka Integration + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + .. + + + + UTF-8 + 3.7.0 + 1.4.2.RELEASE + 1.10 + 1.2.10 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + + + zuul-server + eureka-server + eureka-client + + diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml new file mode 100644 index 0000000000..b68fd63155 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + + com.baeldung.spring.cloud + spring-cloud-zuul-eureka-integration + 1.0.0-SNAPSHOT + + zuul-server + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-zuul + + + org.springframework.cloud + spring-cloud-starter-eureka + + + commons-configuration + commons-configuration + ${commons-config.version} + + + io.reactivex + rxjava + ${rxjava.version} + + + org.springframework.boot + spring-boot-starter-security + + + + + + org.springframework.cloud + spring-cloud-starter-parent + ${spring-cloud-dependencies.version} + pom + import + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/main/java/com/baeldung/spring/cloud/zuul/config/ZuulConfig.java b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/main/java/com/baeldung/spring/cloud/zuul/config/ZuulConfig.java new file mode 100644 index 0000000000..52488cad69 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/main/java/com/baeldung/spring/cloud/zuul/config/ZuulConfig.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.zuul.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.netflix.zuul.EnableZuulProxy; + +@SpringBootApplication +@EnableZuulProxy +@EnableDiscoveryClient +public class ZuulConfig { + public static void main(String[] args) { + SpringApplication.run(ZuulConfig.class, args); + } +} diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/main/resources/application.properties b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/main/resources/application.properties new file mode 100644 index 0000000000..cb1dca78c2 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/main/resources/application.properties @@ -0,0 +1,9 @@ +server.port=8762 +spring.application.name=zuul-server +eureka.instance.preferIpAddress=true +eureka.client.registerWithEureka=true +eureka.client.fetchRegistry=true +eureka.serviceurl.defaultzone=http://localhost:8761/eureka/ +management.security.enabled=false +security.basic.enabled=false +hystrix.command.default.execution.timeout.enabled=false From 92789f9ae6fe6a5f553e9f308d82b71e6d60d3c5 Mon Sep 17 00:00:00 2001 From: hugosama1 Date: Mon, 8 Jan 2018 11:22:36 -0500 Subject: [PATCH 43/58] Guidetoiterator (#3368) * Added code for iterator * missing imports.. --- .../baeldung/iteratorguide/IteratorGuide.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/iteratorguide/IteratorGuide.java diff --git a/core-java/src/main/java/com/baeldung/iteratorguide/IteratorGuide.java b/core-java/src/main/java/com/baeldung/iteratorguide/IteratorGuide.java new file mode 100644 index 0000000000..447f588fed --- /dev/null +++ b/core-java/src/main/java/com/baeldung/iteratorguide/IteratorGuide.java @@ -0,0 +1,39 @@ +package com.baeldung.iteratorguide; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +public class IteratorGuide { + + public static void main(String[] args) { + List items = new ArrayList<>(); + items.add("ONE"); + items.add("TWO"); + items.add("THREE"); + Iterator iter = items.iterator(); + while (iter.hasNext()) { + String next = iter.next(); + System.out.println(next); + iter.remove(); + } + ListIterator listIterator = items.listIterator(); + while(listIterator.hasNext()) { + String nextWithIndex = items.get(listIterator.nextIndex()); + String next = listIterator.next(); + if( "ONE".equals(next)) { + listIterator.set("SWAPPED"); + } + } + listIterator.add("FOUR"); + while(listIterator.hasPrevious()) { + String previousWithIndex = items.get(listIterator.previousIndex()); + String previous = listIterator.previous(); + System.out.println(previous); + } + listIterator.forEachRemaining(e -> { + System.out.println(e); + }); + } +} From fd9d956be3fcc528745e53fbfd34ec2d87a7bcf7 Mon Sep 17 00:00:00 2001 From: Igor Kugaudo Date: Mon, 8 Jan 2018 19:24:28 +0200 Subject: [PATCH 44/58] BAEL-1351 RegEx for matching Date Pattern in Java (#3217) * kugaudo/igor@kugaudo.com * BAEL-1351 RegEx for matching Date Pattern in Java * BAEL-1351 RegEx for matching Date Pattern in Java * BAEL-1351 RegEx for matching Date Pattern in Java * Fixed names of test methods * Refactored class names, split unit tests by classes * Reordered test cases in Gregorian date matcher unit test, formatted code * Added override annotation * Renamed mather main method for better semantics * Fixed names of test methods * Split Gregorian date matcher to separate branches * Fixed test cases according to the article * Revert "Merge branch 'master' into datepattern" This reverts commit 0d57456140bc9e1f36d32b3e707acd2729b2c60f, reversing changes made to c768132dcd24d4312567298f34c67cb31dcde9f8. --- .../regexp/datepattern/DateMatcher.java | 7 ++ .../datepattern/FormattedDateMatcher.java | 14 +++ .../regexp/datepattern/RangedDateMatcher.java | 14 +++ .../gregorian/February29thMatcher.java | 16 +++ .../gregorian/FebruaryGeneralMatcher.java | 16 +++ .../gregorian/GregorianDateMatcher.java | 19 ++++ .../gregorian/MonthsOf30DaysMatcher.java | 17 +++ .../gregorian/MonthsOf31DaysMatcher.java | 17 +++ .../FormattedDateMatcherUnitTest.java | 24 +++++ .../RangedDateMatcherUnitTest.java | 31 ++++++ .../February29thMatcherUnitTest.java | 17 +++ .../FebruaryGeneralMatcherUnitTest.java | 17 +++ .../GregorianDateMatcherUnitTest.java | 42 ++++++++ .../MonthsOf30DaysMatcherUnitTest.java | 17 +++ .../MonthsOf31DaysMatcherUnitTest.java | 17 +++ .../testhelper/GregorianDateTestHelper.java | 102 ++++++++++++++++++ 16 files changed, 387 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java create mode 100644 core-java/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java create mode 100644 core-java/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java create mode 100644 core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java create mode 100644 core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java create mode 100644 core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java create mode 100644 core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java create mode 100644 core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java create mode 100644 core-java/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java new file mode 100644 index 0000000000..3e85bf13bb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java @@ -0,0 +1,7 @@ +package com.baeldung.regexp.datepattern; + +public interface DateMatcher { + + boolean matches(String date); + +} diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java new file mode 100644 index 0000000000..1d3a609b55 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java @@ -0,0 +1,14 @@ +package com.baeldung.regexp.datepattern; + +import java.util.regex.Pattern; + +class FormattedDateMatcher implements DateMatcher { + + private static final Pattern DATE_PATTERN = Pattern.compile( + "^\\d{4}-\\d{2}-\\d{2}$"); + + @Override + public boolean matches(String date) { + return DATE_PATTERN.matcher(date).matches(); + } +} diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java new file mode 100644 index 0000000000..af4e183fef --- /dev/null +++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java @@ -0,0 +1,14 @@ +package com.baeldung.regexp.datepattern; + +import java.util.regex.Pattern; + +class RangedDateMatcher implements DateMatcher { + + private static final Pattern DATE_PATTERN = Pattern.compile( + "^((19|2[0-9])[0-9]{2})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$"); + + @Override + public boolean matches(String date) { + return DATE_PATTERN.matcher(date).matches(); + } +} diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java new file mode 100644 index 0000000000..b0243ae48f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java @@ -0,0 +1,16 @@ +package com.baeldung.regexp.datepattern.gregorian; + +import com.baeldung.regexp.datepattern.DateMatcher; + +import java.util.regex.Pattern; + +public class February29thMatcher implements DateMatcher { + + private static final Pattern DATE_PATTERN = Pattern.compile( + "^((2000|2400|2800|(19|2[0-9](0[48]|[2468][048]|[13579][26])))-02-29)$"); + + @Override + public boolean matches(String date) { + return DATE_PATTERN.matcher(date).matches(); + } +} diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java new file mode 100644 index 0000000000..f294348928 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java @@ -0,0 +1,16 @@ +package com.baeldung.regexp.datepattern.gregorian; + +import com.baeldung.regexp.datepattern.DateMatcher; + +import java.util.regex.Pattern; + +public class FebruaryGeneralMatcher implements DateMatcher { + + private static final Pattern DATE_PATTERN = Pattern.compile( + "^(((19|2[0-9])[0-9]{2})-02-(0[1-9]|1[0-9]|2[0-8]))$"); + + @Override + public boolean matches(String date) { + return DATE_PATTERN.matcher(date).matches(); + } +} diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java new file mode 100644 index 0000000000..fc8abdb201 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java @@ -0,0 +1,19 @@ +package com.baeldung.regexp.datepattern.gregorian; + +import com.baeldung.regexp.datepattern.DateMatcher; + +import java.util.regex.Pattern; + +class GregorianDateMatcher implements DateMatcher { + + private static final Pattern DATE_PATTERN = Pattern.compile( + "^((2000|2400|2800|(19|2[0-9](0[48]|[2468][048]|[13579][26])))-02-29)$" + + "|^(((19|2[0-9])[0-9]{2})-02-(0[1-9]|1[0-9]|2[0-8]))$" + + "|^(((19|2[0-9])[0-9]{2})-(0[13578]|10|12)-(0[1-9]|[12][0-9]|3[01]))$" + + "|^(((19|2[0-9])[0-9]{2})-(0[469]|11)-(0[1-9]|[12][0-9]|30))$"); + + @Override + public boolean matches(String date) { + return DATE_PATTERN.matcher(date).matches(); + } +} diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java new file mode 100644 index 0000000000..be202081e8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java @@ -0,0 +1,17 @@ +package com.baeldung.regexp.datepattern.gregorian; + +import com.baeldung.regexp.datepattern.DateMatcher; + +import java.util.regex.Pattern; + +public class MonthsOf30DaysMatcher implements DateMatcher { + + private static final Pattern DATE_PATTERN = Pattern.compile( + "^(((19|2[0-9])[0-9]{2})-(0[469]|11)-(0[1-9]|[12][0-9]|30))$"); + + @Override + public boolean matches(String date) { + return DATE_PATTERN.matcher(date).matches(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java new file mode 100644 index 0000000000..7f0943991b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java @@ -0,0 +1,17 @@ +package com.baeldung.regexp.datepattern.gregorian; + +import com.baeldung.regexp.datepattern.DateMatcher; + +import java.util.regex.Pattern; + +public class MonthsOf31DaysMatcher implements DateMatcher { + + private static final Pattern DATE_PATTERN = Pattern.compile( + "^(((19|2[0-9])[0-9]{2})-(0[13578]|10|12)-(0[1-9]|[12][0-9]|3[01]))$"); + + @Override + public boolean matches(String date) { + return DATE_PATTERN.matcher(date).matches(); + } + +} diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java new file mode 100644 index 0000000000..0a9599c3f9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.regexp.datepattern; + +import org.junit.Assert; +import org.junit.Test; + +public class FormattedDateMatcherUnitTest { + + private DateMatcher matcher = new FormattedDateMatcher(); + + @Test + public void whenUsingFormattedDateMatcher_thenFormatConstraintsSatisfied() { + Assert.assertTrue(matcher.matches("2017-12-31")); + Assert.assertTrue(matcher.matches("2018-01-01")); + Assert.assertTrue(matcher.matches("0000-00-00")); + Assert.assertTrue(matcher.matches("1029-99-72")); + + Assert.assertFalse(matcher.matches("2018-01")); + Assert.assertFalse(matcher.matches("2018-01-01-01")); + Assert.assertFalse(matcher.matches("2018-01-XX")); + Assert.assertFalse(matcher.matches(" 2018-01-01")); + Assert.assertFalse(matcher.matches("2018-01-01 ")); + Assert.assertFalse(matcher.matches("2018/01/01")); + } +} diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java new file mode 100644 index 0000000000..abbff83ec1 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.regexp.datepattern; + +import org.junit.Assert; +import org.junit.Test; + +public class RangedDateMatcherUnitTest { + + private DateMatcher matcher = new RangedDateMatcher(); + + @Test + public void whenUsingRangedDateMatcher_thenFormatConstraintsSatisfied() { + Assert.assertFalse(matcher.matches("2018-01")); + Assert.assertFalse(matcher.matches("2018-01-01-01")); + Assert.assertFalse(matcher.matches("2018-01-XX")); + Assert.assertFalse(matcher.matches(" 2018-01-01")); + Assert.assertFalse(matcher.matches("2018-01-01 ")); + Assert.assertFalse(matcher.matches("2018/01/01")); + } + + @Test + public void whenUsingRangedDateMatcher_thenRangeConstraintsSatisfied() { + Assert.assertTrue(matcher.matches("1900-01-01")); + Assert.assertTrue(matcher.matches("2018-02-31")); + Assert.assertTrue(matcher.matches("2999-12-31")); + + Assert.assertFalse(matcher.matches("1899-12-31")); + Assert.assertFalse(matcher.matches("2018-05-35")); + Assert.assertFalse(matcher.matches("2018-13-05")); + Assert.assertFalse(matcher.matches("3000-01-01")); + } +} diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java new file mode 100644 index 0000000000..67a4276728 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.regexp.datepattern.gregorian; + +import com.baeldung.regexp.datepattern.DateMatcher; +import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper; +import org.junit.Test; + +public class February29thMatcherUnitTest { + + private DateMatcher matcher = new February29thMatcher(); + + private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher); + + @Test + public void whenYearIsLeap_thenYearHasFebruary29th() { + testHelper.assertFebruary29th(); + } +} diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java new file mode 100644 index 0000000000..48ff140620 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.regexp.datepattern.gregorian; + +import com.baeldung.regexp.datepattern.DateMatcher; +import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper; +import org.junit.Test; + +public class FebruaryGeneralMatcherUnitTest { + + private DateMatcher matcher = new FebruaryGeneralMatcher(); + + private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher); + + @Test + public void whenMonthIsFebruary_thenMonthContainsUpTo28Days() { + testHelper.assertFebruaryGeneralDates(); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java new file mode 100644 index 0000000000..e6e896a09c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.regexp.datepattern.gregorian; + +import com.baeldung.regexp.datepattern.DateMatcher; +import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper; +import org.junit.Test; + +public class GregorianDateMatcherUnitTest { + + private DateMatcher matcher = new GregorianDateMatcher(); + + private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher); + + @Test + public void whenUsingGregorianDateMatcher_thenFormatConstraintsSatisfied() { + testHelper.assertFormat(); + } + + @Test + public void whenUsingGregorianDateMatcher_thenRangeConstraintsSatisfied() { + testHelper.assertRange(); + } + + @Test + public void whenYearIsLeap_thenFebruaryHas29Days() { + testHelper.assertFebruary29th(); + } + + @Test + public void whenMonthIsFebruary_thenMonthContainsUpTo28Days() { + testHelper.assertFebruaryGeneralDates(); + } + + @Test + public void whenMonthIsShort_thenMonthContainsUpTo30Days() { + testHelper.assertMonthsOf30Days(); + } + + @Test + public void whenMonthIsLong_thenMonthContainsUpTo31Days() { + testHelper.assertMonthsOf31Dates(); + } +} diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java new file mode 100644 index 0000000000..d1ce4a6d57 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.regexp.datepattern.gregorian; + +import com.baeldung.regexp.datepattern.DateMatcher; +import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper; +import org.junit.Test; + +public class MonthsOf30DaysMatcherUnitTest { + + private DateMatcher matcher = new MonthsOf30DaysMatcher(); + + private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher); + + @Test + public void whenMonthIsShort_thenMonthContainsUpTo30Days() { + testHelper.assertMonthsOf30Days(); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java new file mode 100644 index 0000000000..338c8de30c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.regexp.datepattern.gregorian; + +import com.baeldung.regexp.datepattern.DateMatcher; +import com.baeldung.regexp.datepattern.gregorian.testhelper.GregorianDateTestHelper; +import org.junit.Test; + +public class MonthsOf31DaysMatcherUnitTest { + + private DateMatcher matcher = new MonthsOf31DaysMatcher(); + + private GregorianDateTestHelper testHelper = new GregorianDateTestHelper(matcher); + + @Test + public void whenMonthIsLong_thenMonthContainsUpTo31Days() { + testHelper.assertMonthsOf31Dates(); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java new file mode 100644 index 0000000000..6429e4fe2d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java @@ -0,0 +1,102 @@ +package com.baeldung.regexp.datepattern.gregorian.testhelper; + +import com.baeldung.regexp.datepattern.DateMatcher; +import org.junit.Assert; + +public class GregorianDateTestHelper { + + private final DateMatcher matcher; + + public GregorianDateTestHelper(DateMatcher matcher) { + this.matcher = matcher; + } + + public void assertFormat() { + Assert.assertTrue(matcher.matches("2017-12-31")); + Assert.assertTrue(matcher.matches("2018-01-01")); + + Assert.assertFalse(matcher.matches("2018-02")); + Assert.assertFalse(matcher.matches("2018-02-01-01")); + Assert.assertFalse(matcher.matches("2018-02-XX")); + Assert.assertFalse(matcher.matches(" 2018-02-01")); + Assert.assertFalse(matcher.matches("2018-02-01 ")); + Assert.assertFalse(matcher.matches("2020/02/28")); + Assert.assertFalse(matcher.matches("2020.02.29")); + } + + public void assertRange() { + Assert.assertTrue(matcher.matches("1900-01-01")); + Assert.assertTrue(matcher.matches("2205-05-25")); + Assert.assertTrue(matcher.matches("2999-12-31")); + + Assert.assertFalse(matcher.matches("1899-12-31")); + Assert.assertFalse(matcher.matches("2018-05-35")); + Assert.assertFalse(matcher.matches("2018-13-05")); + Assert.assertFalse(matcher.matches("3000-01-01")); + Assert.assertFalse(matcher.matches("3200-02-29")); + } + + public void assertFebruary29th() { + Assert.assertTrue(matcher.matches("2000-02-29")); + Assert.assertTrue(matcher.matches("2400-02-29")); + Assert.assertTrue(matcher.matches("2800-02-29")); + Assert.assertTrue(matcher.matches("2020-02-29")); + Assert.assertTrue(matcher.matches("2024-02-29")); + Assert.assertTrue(matcher.matches("2028-02-29")); + + Assert.assertFalse(matcher.matches("2017-02-29")); + Assert.assertFalse(matcher.matches("2018-02-29")); + Assert.assertFalse(matcher.matches("2019-02-29")); + Assert.assertFalse(matcher.matches("2100-02-29")); + Assert.assertFalse(matcher.matches("2200-02-29")); + Assert.assertFalse(matcher.matches("2300-02-29")); + } + + public void assertFebruaryGeneralDates() { + Assert.assertTrue(matcher.matches("2018-02-01")); + Assert.assertTrue(matcher.matches("2019-02-13")); + Assert.assertTrue(matcher.matches("2020-02-25")); + + Assert.assertFalse(matcher.matches("2000-02-30")); + Assert.assertFalse(matcher.matches("2400-02-62")); + Assert.assertFalse(matcher.matches("2420-02-94")); + } + + public void assertMonthsOf30Days() { + Assert.assertTrue(matcher.matches("2018-04-30")); + Assert.assertTrue(matcher.matches("2019-06-30")); + Assert.assertTrue(matcher.matches("2020-09-30")); + Assert.assertTrue(matcher.matches("2021-11-30")); + + Assert.assertTrue(matcher.matches("2022-04-02")); + Assert.assertTrue(matcher.matches("2023-06-14")); + Assert.assertTrue(matcher.matches("2024-09-26")); + + Assert.assertFalse(matcher.matches("2018-04-31")); + Assert.assertFalse(matcher.matches("2019-06-31")); + Assert.assertFalse(matcher.matches("2020-09-31")); + Assert.assertFalse(matcher.matches("2021-11-31")); + + Assert.assertFalse(matcher.matches("2022-04-32")); + Assert.assertFalse(matcher.matches("2023-06-64")); + Assert.assertFalse(matcher.matches("2024-09-96")); + } + + public void assertMonthsOf31Dates() { + Assert.assertTrue(matcher.matches("2018-01-31")); + Assert.assertTrue(matcher.matches("2019-03-31")); + Assert.assertTrue(matcher.matches("2020-05-31")); + Assert.assertTrue(matcher.matches("2021-07-31")); + Assert.assertTrue(matcher.matches("2022-08-31")); + Assert.assertTrue(matcher.matches("2023-10-31")); + Assert.assertTrue(matcher.matches("2024-12-31")); + + Assert.assertTrue(matcher.matches("2025-01-03")); + Assert.assertTrue(matcher.matches("2026-03-15")); + Assert.assertTrue(matcher.matches("2027-05-27")); + + Assert.assertFalse(matcher.matches("2018-01-32")); + Assert.assertFalse(matcher.matches("2019-03-64")); + Assert.assertFalse(matcher.matches("2020-05-96")); + } +} From 92d256c7fd7efa12e4ae6733d60ddc8320192a7b Mon Sep 17 00:00:00 2001 From: daoire Date: Mon, 8 Jan 2018 17:27:04 +0000 Subject: [PATCH 45/58] Update README --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index 94d203533e..5f69f12c6f 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -133,3 +133,4 @@ - [A Guide to Java Initialization](http://www.baeldung.com/java-initialization) - [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree) - [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random) +- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions) From 556500a25961b03010ee5db6686c1e45771c077f Mon Sep 17 00:00:00 2001 From: daoire Date: Mon, 8 Jan 2018 17:29:00 +0000 Subject: [PATCH 46/58] Update README.md --- persistence-modules/java-cockroachdb/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/java-cockroachdb/README.md b/persistence-modules/java-cockroachdb/README.md index 0f0381212d..3bab6faa29 100644 --- a/persistence-modules/java-cockroachdb/README.md +++ b/persistence-modules/java-cockroachdb/README.md @@ -1,2 +1,2 @@ ### Relevant Articles: -- [Guide to CockroachDB in Java](http://www.baeldung.com/) +- [Guide to CockroachDB in Java](http://www.baeldung.com/cockroachdb-java) From fa2e225d6306ab78d00b45be666f208374991476 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Mon, 8 Jan 2018 21:13:31 +0200 Subject: [PATCH 47/58] add requested changes --- .../com/baeldung/restdocs/CRUDController.java | 15 ++++++---- ...ApiDocumentationJUnit4IntegrationTest.java | 24 +++++++-------- ...ApiDocumentationJUnit5IntegrationTest.java | 30 +++++++------------ 3 files changed, 30 insertions(+), 39 deletions(-) diff --git a/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java b/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java index 9c8e436fa9..f6183bc79e 100644 --- a/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java @@ -5,8 +5,11 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import java.util.ArrayList; import java.util.List; +import javax.validation.Valid; + import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; +import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; @@ -23,33 +26,33 @@ import org.springframework.web.bind.annotation.RestController; public class CRUDController { @GetMapping - public List read(@RequestBody CrudInput crudInput) { - List returnList = new ArrayList(); + public List read(@RequestBody @Valid CrudInput crudInput) { + List returnList = new ArrayList<>(); returnList.add(crudInput); return returnList; } @ResponseStatus(HttpStatus.CREATED) @PostMapping - public HttpHeaders save(@RequestBody CrudInput crudInput) { + public HttpHeaders save(@RequestBody @Valid CrudInput crudInput) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(linkTo(CRUDController.class).slash(crudInput.getId()).toUri()); return httpHeaders; } - @DeleteMapping(value = "/{id}") + @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.OK) HttpHeaders delete(@PathVariable("id") long id) { return new HttpHeaders(); } - @PutMapping(value = "/{id}") + @PutMapping("/{id}") @ResponseStatus(HttpStatus.ACCEPTED) void put(@PathVariable("id") long id, @RequestBody CrudInput crudInput) { } - @PatchMapping(value = "/{id}") + @PatchMapping("/{id}") public List patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) { List returnList = new ArrayList(); crudInput.setId(id); diff --git a/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit4IntegrationTest.java b/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit4IntegrationTest.java index de1d3f8b6a..20f0a47d83 100644 --- a/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit4IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit4IntegrationTest.java @@ -75,20 +75,18 @@ public class ApiDocumentationJUnit4IntegrationTest { @Test public void crudGetExample() throws Exception { - Map tag = new HashMap<>(); - tag.put("name", "GET"); + Map crud = new HashMap<>(); + crud.put("id", 1L); + crud.put("title", "Sample Model"); + crud.put("body", "http://www.baeldung.com/"); String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) + .content(this.objectMapper.writeValueAsString(crud))) .andExpect(status().isOk()) .andReturn() .getResponse() .getHeader("Location"); - Map crud = new HashMap<>(); - crud.put("id", 1L); - crud.put("title", "Sample Model"); - crud.put("body", "http://www.baeldung.com/"); crud.put("tags", singletonList(tagLocation)); ConstraintDescriptions desc = new ConstraintDescriptions(CrudInput.class); @@ -102,20 +100,18 @@ public class ApiDocumentationJUnit4IntegrationTest { @Test public void crudCreateExample() throws Exception { - Map tag = new HashMap<>(); - tag.put("name", "CREATE"); + Map crud = new HashMap<>(); + crud.put("id", 2L); + crud.put("title", "Sample Model"); + crud.put("body", "http://www.baeldung.com/"); String tagLocation = this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) + .content(this.objectMapper.writeValueAsString(crud))) .andExpect(status().isCreated()) .andReturn() .getResponse() .getHeader("Location"); - Map crud = new HashMap<>(); - crud.put("id", 2L); - crud.put("title", "Sample Model"); - crud.put("body", "http://www.baeldung.com/"); crud.put("tags", singletonList(tagLocation)); this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON) diff --git a/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit5IntegrationTest.java b/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit5IntegrationTest.java index d915a4fdde..748d5fb1b3 100644 --- a/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit5IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit5IntegrationTest.java @@ -7,11 +7,7 @@ import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.li import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; @@ -72,20 +68,18 @@ public class ApiDocumentationJUnit5IntegrationTest { @Test public void crudGetExample() throws Exception { - Map tag = new HashMap<>(); - tag.put("name", "GET"); + Map crud = new HashMap<>(); + crud.put("id", 1L); + crud.put("title", "Sample Model"); + crud.put("body", "http://www.baeldung.com/"); String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) + .content(this.objectMapper.writeValueAsString(crud))) .andExpect(status().isOk()) .andReturn() .getResponse() .getHeader("Location"); - Map crud = new HashMap<>(); - crud.put("id", 1L); - crud.put("title", "Sample Model"); - crud.put("body", "http://www.baeldung.com/"); crud.put("tags", singletonList(tagLocation)); ConstraintDescriptions desc = new ConstraintDescriptions(CrudInput.class); @@ -99,20 +93,18 @@ public class ApiDocumentationJUnit5IntegrationTest { @Test public void crudCreateExample() throws Exception { - Map tag = new HashMap<>(); - tag.put("name", "CREATE"); + Map crud = new HashMap<>(); + crud.put("id", 2L); + crud.put("title", "Sample Model"); + crud.put("body", "http://www.baeldung.com/"); String tagLocation = this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) + .content(this.objectMapper.writeValueAsString(crud))) .andExpect(status().isCreated()) .andReturn() .getResponse() .getHeader("Location"); - Map crud = new HashMap<>(); - crud.put("id", 2L); - crud.put("title", "Sample Model"); - crud.put("body", "http://www.baeldung.com/"); crud.put("tags", singletonList(tagLocation)); this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON) From cbd1a9dfbfdcc71200ae211f5af8bc56fd919d09 Mon Sep 17 00:00:00 2001 From: Magdalena Krause Date: Mon, 8 Jan 2018 18:34:16 -0300 Subject: [PATCH 48/58] Bael 1277 (#3379) * BAEL-1277: RESTFul CRUD application with JavaLite. * BAEL-1277: RESTFul CRUD application with JavaLite. Adding exception handling. * BAEL-1277: Changes after editors review. --- java-lite/pom.xml | 13 +- .../java/app/config/AppControllerConfig.java | 4 +- .../src/main/java/app/config/DbConfig.java | 2 +- .../app/controllers/ProductsController.java | 128 +++++++++--------- .../src/test/java/app/models/ProductTest.java | 18 +-- 5 files changed, 79 insertions(+), 86 deletions(-) diff --git a/java-lite/pom.xml b/java-lite/pom.xml index 554819f6e4..eb18bc40a5 100644 --- a/java-lite/pom.xml +++ b/java-lite/pom.xml @@ -7,6 +7,7 @@ org.baeldung java-lite 1.0-SNAPSHOT + war com.baeldung @@ -15,7 +16,7 @@ - 9.3.4.RC1 + 9.4.8.v20171121 1.4.13 1.15 5.1.45 @@ -85,16 +86,6 @@ ${java.home}/../lib/tools.jar - - org.codehaus.jackson - jackson-core-lgpl - ${jackson.version} - - - org.codehaus.jackson - jackson-mapper-lgpl - ${jackson.version} - junit junit diff --git a/java-lite/src/main/java/app/config/AppControllerConfig.java b/java-lite/src/main/java/app/config/AppControllerConfig.java index 42b7e728ec..da30c08ab2 100644 --- a/java-lite/src/main/java/app/config/AppControllerConfig.java +++ b/java-lite/src/main/java/app/config/AppControllerConfig.java @@ -9,7 +9,7 @@ import org.javalite.activeweb.controller_filters.TimingFilter; public class AppControllerConfig extends AbstractControllerConfig { @Override public void init(AppContext appContext) { - addGlobalFilters(new TimingFilter()); - add(new DBConnectionFilter()).to(ProductsController.class); + addGlobalFilters(new TimingFilter()); + add(new DBConnectionFilter()).to(ProductsController.class); } } diff --git a/java-lite/src/main/java/app/config/DbConfig.java b/java-lite/src/main/java/app/config/DbConfig.java index 25ba378b22..75de248619 100644 --- a/java-lite/src/main/java/app/config/DbConfig.java +++ b/java-lite/src/main/java/app/config/DbConfig.java @@ -6,6 +6,6 @@ import org.javalite.activeweb.AppContext; public class DbConfig extends AbstractDBConfig { @Override public void init(AppContext appContext) { - this.configFile("/database.properties"); + this.configFile("/database.properties"); } } diff --git a/java-lite/src/main/java/app/controllers/ProductsController.java b/java-lite/src/main/java/app/controllers/ProductsController.java index f68dd9a013..746d77e24a 100644 --- a/java-lite/src/main/java/app/controllers/ProductsController.java +++ b/java-lite/src/main/java/app/controllers/ProductsController.java @@ -10,92 +10,94 @@ import java.util.Map; @RESTful public class ProductsController extends AppController { + private ObjectMapper mapper = new ObjectMapper(); + public void index() { - try { - view("products", Product.findAll()); - render().contentType("application/json"); - } catch (Exception e) { - view("message", "There was an error.", "code", 200); - render("message"); - } + try { + view("products", Product.findAll()); + render().contentType("application/json"); + } catch (Exception e) { + view("message", "There was an error.", "code", 200); + render("message"); + } } public void create() { - try { - Map payload = new ObjectMapper().readValue(getRequestString(), Map.class); - Product p = new Product(); - p.fromMap(payload); - p.saveIt(); - view("message", "Successfully saved product id " + p.get("id"), "code", 200); - render("message"); - } catch (Exception e) { - view("message", "There was an error.", "code", 200); - render("message"); - } + try { + Map payload = mapper.readValue(getRequestString(), Map.class); + Product p = new Product(); + p.fromMap(payload); + p.saveIt(); + view("message", "Successfully saved product id " + p.get("id"), "code", 200); + render("message"); + } catch (Exception e) { + view("message", "There was an error.", "code", 200); + render("message"); + } } public void update() { - try { - Map payload = new ObjectMapper().readValue(getRequestString(), Map.class); - String id = getId(); - Product p = Product.findById(id); - if (p == null) { - view("message", "Product id " + id + " not found.", "code", 200); - render("message"); - return; + try { + Map payload = mapper.readValue(getRequestString(), Map.class); + String id = getId(); + Product p = Product.findById(id); + if (p == null) { + view("message", "Product id " + id + " not found.", "code", 200); + render("message"); + return; + } + p.fromMap(payload); + p.saveIt(); + view("message", "Successfully updated product id " + id, "code", 200); + render("message"); + } catch (Exception e) { + view("message", "There was an error.", "code", 200); + render("message"); } - p.fromMap(payload); - p.saveIt(); - view("message", "Successfully updated product id " + id, "code", 200); - render("message"); - } catch (Exception e) { - view("message", "There was an error.", "code", 200); - render("message"); - } } public void show() { - try { - String id = getId(); - Product p = Product.findById(id); - if (p == null) { - view("message", "Product id " + id + " not found.", "code", 200); - render("message"); - return; + try { + String id = getId(); + Product p = Product.findById(id); + if (p == null) { + view("message", "Product id " + id + " not found.", "code", 200); + render("message"); + return; + } + view("product", p); + render("_product"); + } catch (Exception e) { + view("message", "There was an error.", "code", 200); + render("message"); } - view("product", p); - render("_product"); - } catch (Exception e) { - view("message", "There was an error.", "code", 200); - render("message"); - } } public void destroy() { - try { - String id = getId(); - Product p = Product.findById(id); - if (p == null) { - view("message", "Product id " + id + " not found.", "code", 200); - render("message"); - return; + try { + String id = getId(); + Product p = Product.findById(id); + if (p == null) { + view("message", "Product id " + id + " not found.", "code", 200); + render("message"); + return; + } + p.delete(); + view("message", "Successfully deleted product id " + id, "code", 200); + render("message"); + } catch (Exception e) { + view("message", "There was an error.", "code", 200); + render("message"); } - p.delete(); - view("message", "Successfully deleted product id " + id, "code", 200); - render("message"); - } catch (Exception e) { - view("message", "There was an error.", "code", 200); - render("message"); - } } @Override protected String getContentType() { - return "application/json"; + return "application/json"; } @Override protected String getLayout() { - return null; + return null; } } diff --git a/java-lite/src/test/java/app/models/ProductTest.java b/java-lite/src/test/java/app/models/ProductTest.java index f6ee0a3d0a..5e5c6e8845 100644 --- a/java-lite/src/test/java/app/models/ProductTest.java +++ b/java-lite/src/test/java/app/models/ProductTest.java @@ -8,18 +8,18 @@ public class ProductTest { //@Test public void givenSavedProduct_WhenFindFirst_ThenSavedProductIsReturned() { - //Open DB connection - Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/dbname", "user", "password"); + //Open DB connection + Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/dbname", "user", "password"); - //Create a product and save it - Product toSaveProduct = new Product(); - toSaveProduct.set("name", "Bread"); - toSaveProduct.saveIt(); + //Create a product and save it + Product toSaveProduct = new Product(); + toSaveProduct.set("name", "Bread"); + toSaveProduct.saveIt(); - //Find product - Product savedProduct = Product.findFirst("name = ?", "Bread"); + //Find product + Product savedProduct = Product.findFirst("name = ?", "Bread"); - Assert.assertEquals(toSaveProduct.get("name"), savedProduct.get("name")); + Assert.assertEquals(toSaveProduct.get("name"), savedProduct.get("name")); } } \ No newline at end of file From ee86e6b6adec22c32a5fba4d7ad5aa03d8937583 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Mon, 8 Jan 2018 23:39:01 +0200 Subject: [PATCH 49/58] fix blocking tests (#3378) * make sure modules using java8 * move url matching code * upgrade boot parent * minor cleanup * fix blocking tests --- .../concurrent/stopping/StopThreadTest.java | 18 ++++--- ...estOne.java => EthControllerLiveTest.java} | 19 ++++--- .../baeldung/guava/GuavaCacheUnitTest.java | 7 +-- .../micrometer/MicrometerAtlasTest.java | 45 ++++++++++------ .../metrics/servo/MetricTypeTest.java | 52 ++++++++++--------- ... => CabBookingServiceIntegrationTest.java} | 4 +- 6 files changed, 85 insertions(+), 60 deletions(-) rename ethereumj/src/test/java/com/baeldung/ethereumj/controllers/{EthControllerTestOne.java => EthControllerLiveTest.java} (90%) rename spring-remoting/remoting-hessian-burlap/client/src/test/java/com/baeldung/client/{CabBookingServiceTest.java => CabBookingServiceIntegrationTest.java} (97%) diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java index 70854f013f..af54d6932e 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java @@ -1,20 +1,21 @@ package com.baeldung.concurrent.stopping; -import com.jayway.awaitility.Awaitility; -import org.junit.Test; - -import java.util.concurrent.TimeUnit; - import static com.jayway.awaitility.Awaitility.await; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import java.util.concurrent.TimeUnit; + +import org.junit.Test; + +import com.jayway.awaitility.Awaitility; + public class StopThreadTest { @Test public void whenStoppedThreadIsStopped() throws InterruptedException { - int interval = 100; + int interval = 5; ControlSubThread controlSubThread = new ControlSubThread(interval); controlSubThread.start(); @@ -33,13 +34,13 @@ public class StopThreadTest { @Test public void whenInterruptedThreadIsStopped() throws InterruptedException { - int interval = 5000; + int interval = 50; ControlSubThread controlSubThread = new ControlSubThread(interval); controlSubThread.start(); // Give things a chance to get set up - Thread.sleep(100); + Thread.sleep(interval); assertTrue(controlSubThread.isRunning()); assertFalse(controlSubThread.isStopped()); @@ -48,6 +49,7 @@ public class StopThreadTest { // Wait less than the time we would normally sleep, and make sure we exited. Awaitility.await() + .pollDelay(2, TimeUnit.MILLISECONDS) .atMost(interval/ 10, TimeUnit.MILLISECONDS) .until(controlSubThread::isStopped); } diff --git a/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerTestOne.java b/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerLiveTest.java similarity index 90% rename from ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerTestOne.java rename to ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerLiveTest.java index 9298c34ec2..f62d229261 100644 --- a/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerTestOne.java +++ b/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerLiveTest.java @@ -1,25 +1,30 @@ package com.baeldung.ethereumj.controllers; -import com.baeldung.ethereumj.ApplicationMain; -import com.baeldung.ethereumj.Constants; -import com.baeldung.ethereumj.transfer.EthResponse; +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertNotNull; + 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.http.*; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertNotNull; +import com.baeldung.ethereumj.ApplicationMain; +import com.baeldung.ethereumj.Constants; +import com.baeldung.ethereumj.transfer.EthResponse; @RunWith(SpringRunner.class) @SpringBootTest(classes = ApplicationMain.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @TestPropertySource(properties = "server.port=8080") -public class EthControllerTestOne { +public class EthControllerLiveTest { @LocalServerPort int port; diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCacheUnitTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCacheUnitTest.java index eb67d8af44..49ce6b1a09 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaCacheUnitTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaCacheUnitTest.java @@ -89,7 +89,7 @@ public class GuavaCacheUnitTest { cache.getUnchecked("hello"); assertEquals(1, cache.size()); cache.getUnchecked("hello"); - Thread.sleep(300); + Thread.sleep(3); cache.getUnchecked("test"); assertEquals(1, cache.size()); assertNull(cache.getIfPresent("hello")); @@ -106,7 +106,7 @@ public class GuavaCacheUnitTest { final LoadingCache cache = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.MILLISECONDS).build(loader); cache.getUnchecked("hello"); assertEquals(1, cache.size()); - Thread.sleep(300); + Thread.sleep(3); cache.getUnchecked("test"); assertEquals(1, cache.size()); assertNull(cache.getIfPresent("hello")); @@ -203,8 +203,9 @@ public class GuavaCacheUnitTest { private String getSuffix(final String str) { final int lastIndex = str.lastIndexOf('.'); - if (lastIndex == -1) + if (lastIndex == -1) { return null; + } return str.substring(lastIndex + 1); } diff --git a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java index 826e06d598..b76dc40ba0 100644 --- a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java @@ -1,27 +1,40 @@ package com.baeldung.metrics.micrometer; -import com.netflix.spectator.atlas.AtlasConfig; +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.collection.IsMapContaining.hasEntry; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; import io.micrometer.atlas.AtlasMeterRegistry; -import io.micrometer.core.instrument.*; +import io.micrometer.core.instrument.Clock; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.DistributionSummary; +import io.micrometer.core.instrument.Gauge; +import io.micrometer.core.instrument.LongTaskTimer; +import io.micrometer.core.instrument.Measurement; +import io.micrometer.core.instrument.Meter.Type; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.Metrics; +import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Timer; import io.micrometer.core.instrument.composite.CompositeMeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import io.micrometer.core.instrument.stats.hist.Histogram; import io.micrometer.core.instrument.stats.quantile.WindowSketchQuantiles; -import org.junit.Before; -import org.junit.Test; import java.time.Duration; -import java.util.*; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; -import static io.micrometer.core.instrument.Meter.Type; -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.collection.IsMapContaining.hasEntry; -import static org.hamcrest.core.IsCollectionContaining.hasItems; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import org.junit.Before; +import org.junit.Test; + +import com.netflix.spectator.atlas.AtlasConfig; /** * @author aiet @@ -135,15 +148,15 @@ public class MicrometerAtlasTest { Timer timer = registry.timer("app.event"); timer.record(() -> { try { - TimeUnit.MILLISECONDS.sleep(1500); + TimeUnit.MILLISECONDS.sleep(15); } catch (InterruptedException ignored) { } }); - timer.record(3000, TimeUnit.MILLISECONDS); + timer.record(30, TimeUnit.MILLISECONDS); assertTrue(2 == timer.count()); - assertTrue(4510 > timer.totalTime(TimeUnit.MILLISECONDS) && 4500 <= timer.totalTime(TimeUnit.MILLISECONDS)); + assertTrue(50 > timer.totalTime(TimeUnit.MILLISECONDS) && 45 <= timer.totalTime(TimeUnit.MILLISECONDS)); } @Test @@ -155,12 +168,12 @@ public class MicrometerAtlasTest { long currentTaskId = longTaskTimer.start(); try { - TimeUnit.SECONDS.sleep(2); + TimeUnit.MILLISECONDS.sleep(2); } catch (InterruptedException ignored) { } long timeElapsed = longTaskTimer.stop(currentTaskId); - assertTrue(timeElapsed / (int) 1e9 == 2); + assertTrue(timeElapsed / (int) 1e6 == 2); } @Test diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java index 99009f8d84..237092b1c3 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java @@ -1,5 +1,19 @@ package com.baeldung.metrics.servo; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; +import static java.util.stream.Collectors.toMap; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasEntry; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.util.Map; + +import org.junit.Ignore; +import org.junit.Test; + import com.netflix.servo.monitor.BasicCounter; import com.netflix.servo.monitor.BasicGauge; import com.netflix.servo.monitor.BasicInformational; @@ -17,18 +31,6 @@ import com.netflix.servo.monitor.StatsTimer; import com.netflix.servo.monitor.StepCounter; import com.netflix.servo.monitor.Stopwatch; import com.netflix.servo.stats.StatsConfig; -import org.junit.Ignore; -import org.junit.Test; - -import java.util.Map; - -import static java.util.concurrent.TimeUnit.SECONDS; -import static java.util.stream.Collectors.toMap; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; public class MetricTypeTest { @@ -104,17 +106,18 @@ public class MetricTypeTest { public void givenTimer_whenExecuteTask_thenTimerUpdated() throws Exception { BasicTimer timer = new BasicTimer(MonitorConfig .builder("test") - .build(), SECONDS); + .build(), MILLISECONDS); Stopwatch stopwatch = timer.start(); - SECONDS.sleep(1); - timer.record(2, SECONDS); + MILLISECONDS.sleep(1); + timer.record(2, MILLISECONDS); stopwatch.stop(); - assertEquals("timer should count 1 second", 1, timer + assertEquals("timer should count 1 millisecond", 1, timer .getValue() .intValue()); - assertEquals("timer should count 3 seconds in total", 3.0, timer.getTotalTime(), 0.01); + assertEquals("timer should count 3 millisecond in total", 3, timer.getTotalTime() + .intValue()); assertEquals("timer should record 2 updates", 2, timer .getCount() .intValue()); @@ -158,6 +161,7 @@ public class MetricTypeTest { } @Test + //== public void givenStatsTimer_whenExecuteTask_thenStatsCalculated() throws Exception { System.setProperty("netflix.servo", "1000"); StatsTimer timer = new StatsTimer(MonitorConfig @@ -171,20 +175,20 @@ public class MetricTypeTest { .withPublishMean(true) .withPublishStdDev(true) .withPublishVariance(true) - .build(), SECONDS); + .build(), MILLISECONDS); Stopwatch stopwatch = timer.start(); - SECONDS.sleep(1); - timer.record(3, SECONDS); + MILLISECONDS.sleep(1); + timer.record(3, MILLISECONDS); stopwatch.stop(); stopwatch = timer.start(); - timer.record(6, SECONDS); - SECONDS.sleep(2); + timer.record(6, MILLISECONDS); + MILLISECONDS.sleep(2); stopwatch.stop(); - assertEquals("timer should count 12 seconds in total", 12, timer.getTotalTime()); - assertEquals("timer should count 12 seconds in total", 12, timer.getTotalMeasurement()); + assertEquals("timer should count 12 milliseconds in total", 12, timer.getTotalTime()); + assertEquals("timer should count 12 milliseconds in total", 12, timer.getTotalMeasurement()); assertEquals("timer should record 4 updates", 4, timer.getCount()); assertEquals("stats timer value time-cost/update should be 2", 3, timer .getValue() diff --git a/spring-remoting/remoting-hessian-burlap/client/src/test/java/com/baeldung/client/CabBookingServiceTest.java b/spring-remoting/remoting-hessian-burlap/client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java similarity index 97% rename from spring-remoting/remoting-hessian-burlap/client/src/test/java/com/baeldung/client/CabBookingServiceTest.java rename to spring-remoting/remoting-hessian-burlap/client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java index 373701f714..a1fed9637f 100644 --- a/spring-remoting/remoting-hessian-burlap/client/src/test/java/com/baeldung/client/CabBookingServiceTest.java +++ b/spring-remoting/remoting-hessian-burlap/client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java @@ -18,9 +18,9 @@ import static java.lang.Thread.sleep; @SpringBootTest(classes = {BurlapClient.class, HessianClient.class}) @RunWith(SpringRunner.class) -public class CabBookingServiceTest { +public class CabBookingServiceIntegrationTest { - static Logger log = LoggerFactory.getLogger(CabBookingServiceTest.class); + static Logger log = LoggerFactory.getLogger(CabBookingServiceIntegrationTest.class); @Autowired @Qualifier("burlapInvoker") CabBookingService burlapClient; @Autowired @Qualifier("hessianInvoker") CabBookingService hessianClient; static Thread serverThread; From 2b5a125440c16a45d464e4a80bd7111e6c495f52 Mon Sep 17 00:00:00 2001 From: Ahmed Tawila Date: Tue, 9 Jan 2018 13:31:45 +0200 Subject: [PATCH 50/58] BAEL-1080 Introduction to Future in Vavr (#3372) * Add missing features * Add missing features --- .../com/baeldung/vavr/future/FutureTest.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) 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 002919a937..d5345cad55 100644 --- a/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java @@ -58,6 +58,14 @@ public class FutureTest { assertThat(result) .isEqualTo(HELLO); } + + @Test + public void whenTransform_thenCorrect() { + Future future = Future.of(() -> 5) + .transformValue(result -> Try.of(() -> HELLO + result.get())); + + assertThat(future.get()).isEqualTo(HELLO + 5); + } @Test public void whenChainingCallbacks_thenCorrect() { @@ -139,6 +147,14 @@ public class FutureTest { assertThat(futureResult.get()) .isEqualTo("Hello from Baeldung"); } + + @Test + public void whenCallFlatMap_thenCorrect() { + Future futureMap = Future.of(() -> 1) + .flatMap((i) -> Future.of(() -> "Hello: " + i)); + + assertThat(futureMap.get()).isEqualTo("Hello: 1"); + } @Test public void whenFutureFails_thenGetErrorMessage() { From 92e8b0b8b0e595eeb3358bb9a9b289b9c58926d2 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Tue, 9 Jan 2018 09:03:02 -0600 Subject: [PATCH 51/58] 1297 README (#3383) * BAEL-973: updated README * BAEL-1069: Updated README * BAEL-817: add README file * BAEL-1084: README update * BAEL-960: Update README * BAEL-1155: updated README * BAEL-1041: updated README * BAEL-973: Updated README * BAEL-1187: updated README * BAEL-1183: Update README * BAEL-1133: Updated README * BAEL-1098: README update * BAEL-719: add README.md * BAEL-1272: README update * BAEL-1272: README update * BAEL-1196: Update README * BAEL-1328: Updated README * BAEL-1371: Update README.md * BAEL-1371: Update README.md * BAEL-1278: Update README * BAEL-1326: Update README * BAEL-399: Update README * BAEL-1297: Update README --- algorithms/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/algorithms/README.md b/algorithms/README.md index 5f101c296c..3401b6d935 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -15,3 +15,4 @@ - [Introduction to JGraphT](http://www.baeldung.com/jgrapht) - [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm) - [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance) +- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element) From 8aa6842c73f660a3aa36dfc80b72ac3319a531a2 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 9 Jan 2018 20:56:30 +0200 Subject: [PATCH 52/58] Update README.md --- vavr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/vavr/README.md b/vavr/README.md index 4361363fbd..35e97656d3 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -8,3 +8,4 @@ - [Introduction to Vavr’s Validation API](http://www.baeldung.com/vavr-validation-api) - [Guide to Collections API in Vavr](http://www.baeldung.com/vavr-collections) - [Collection Factory Methods for Vavr](http://www.baeldung.com/vavr-collection-factory-methods) +- [Introduction to Future in Vavr](http://www.baeldung.com/vavr-future) From c18ed68935b113b5cc87fb34592cb53d252a755b Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 9 Jan 2018 22:56:53 +0200 Subject: [PATCH 53/58] Update README.md --- vavr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/vavr/README.md b/vavr/README.md index 35e97656d3..d39c9f36a1 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -9,3 +9,4 @@ - [Guide to Collections API in Vavr](http://www.baeldung.com/vavr-collections) - [Collection Factory Methods for Vavr](http://www.baeldung.com/vavr-collection-factory-methods) - [Introduction to Future in Vavr](http://www.baeldung.com/vavr-future) + From 298225c6bd1aeb891feb96976497e99b20618506 Mon Sep 17 00:00:00 2001 From: k0l0ssus Date: Tue, 9 Jan 2018 20:27:52 -0500 Subject: [PATCH 54/58] Add files via upload --- java-vavr-stream/pom.xml | 20 ++++ .../samples/java/vavr/VavrSampler.java | 98 +++++++++++++++++++ 2 files changed, 118 insertions(+) create mode 100644 java-vavr-stream/pom.xml create mode 100644 java-vavr-stream/src/main/java/com/baeldung/samples/java/vavr/VavrSampler.java diff --git a/java-vavr-stream/pom.xml b/java-vavr-stream/pom.xml new file mode 100644 index 0000000000..ca3807cd15 --- /dev/null +++ b/java-vavr-stream/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + com.baeldung.samples + java-vavr-stream + 1.0 + jar + + UTF-8 + 1.8 + 1.8 + + + + io.vavr + vavr + 0.9.2 + + + \ No newline at end of file diff --git a/java-vavr-stream/src/main/java/com/baeldung/samples/java/vavr/VavrSampler.java b/java-vavr-stream/src/main/java/com/baeldung/samples/java/vavr/VavrSampler.java new file mode 100644 index 0000000000..d539342f69 --- /dev/null +++ b/java-vavr-stream/src/main/java/com/baeldung/samples/java/vavr/VavrSampler.java @@ -0,0 +1,98 @@ +package com.baeldung.samples.java.vavr; + +import io.vavr.collection.Stream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.IntStream; + +/** + * + * @author baeldung + */ +public class VavrSampler { + + static int[] intArray = new int[]{1, 2, 4}; + static List intList = new ArrayList(); + static int[][] intOfInts = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + + public static void main(String[] args) { + vavrStreamElementAccess(); + System.out.println("===================================="); + vavrParallelStreamAccess(); + System.out.println("===================================="); + jdkFlatMapping(); + System.out.println("===================================="); + vavrStreamManipulation(); + System.out.println("===================================="); + vavrStreamDistinct(); + } + + public static void vavrStreamElementAccess() { + System.out.println("Vavr Element Access"); + System.out.println("===================================="); + Stream vavredStream = Stream.ofAll(intArray); + System.out.println("Vavr index access: " + vavredStream.get(2)); + System.out.println("Vavr head element access: " + vavredStream.get()); + + Stream vavredStringStream = Stream.of("foo", "bar", "baz"); + System.out.println("Find foo " + vavredStringStream.indexOf("foo")); + } + + public static void vavrParallelStreamAccess() { + try { + System.out.println("Vavr Stream Concurrent Modification"); + System.out.println("===================================="); + Stream vavrStream = Stream.ofAll(intList); + intList.add(5); + vavrStream.forEach(i -> System.out.println("in a Vavr Stream: " + i)); + } catch (Exception ex) { + ex.printStackTrace(); + } + + Stream wrapped = Stream.ofAll(intArray); + intArray[2] = 5; + wrapped.forEach(i -> System.out.println("Vavr looped " + i)); + } + + public static void jdkFlatMapping() { + System.out.println("JDK FlatMap -> Uncomment line 68 to test"); + System.out.println("===================================="); + int[][] intOfInts = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + + IntStream mapToInt = Arrays.stream(intOfInts) + .map(intArr -> Arrays.stream(intArr)) + .flatMapToInt(val -> val.map(n -> { + return n * n; + })) + .peek(n -> System.out.println("Peeking at " + n)); + //Uncomment to execute pipeline + //mapToInt.forEach(n -> System.out.println("FlatMapped Result "+n)); + } + + public static void vavrStreamManipulation() { + System.out.println("Vavr Stream Manipulation"); + System.out.println("===================================="); + List stringList = new ArrayList<>(); + stringList.add("foo"); + stringList.add("bar"); + stringList.add("baz"); + Stream vavredStream = Stream.ofAll(stringList); + vavredStream.forEach(item -> System.out.println("Vavr Stream item: " + item)); + Stream vavredStream2 = vavredStream.insert(2, "buzz"); + vavredStream2.forEach(item -> System.out.println("Vavr Stream item after stream addition: " + item)); + stringList.forEach(item -> System.out.println("List item after stream addition: " + item)); + Stream deletionStream = vavredStream.remove("bar"); + deletionStream.forEach(item -> System.out.println("Vavr Stream item after stream item deletion: " + item)); + + } + + public static void vavrStreamDistinct() { + Stream vavredStream = Stream.of("foo", "bar", "baz", "buxx", "bar", "bar", "foo"); + Stream distinctVavrStream = vavredStream.distinctBy((y, z) -> { + return y.compareTo(z); + }); + distinctVavrStream.forEach(item -> System.out.println("Vavr Stream item after distinct query " + item)); + + } +} From 08f58c5f456d6d902f9874e93bbe8217ccb19c29 Mon Sep 17 00:00:00 2001 From: k0l0ssus Date: Tue, 9 Jan 2018 20:28:35 -0500 Subject: [PATCH 55/58] Update pom.xml --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 1c6a692705..73f1b27f7e 100644 --- a/pom.xml +++ b/pom.xml @@ -87,6 +87,7 @@ vavr java-lite + java-vavr-stream javax-servlets javaxval jaxb From ade2a3ef97132bd18036b9bb1576b6af8c703cf4 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 10 Jan 2018 10:31:43 +0200 Subject: [PATCH 56/58] Update README.md --- spring-5/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-5/README.md b/spring-5/README.md index 400e343263..8249fe3813 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -12,4 +12,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans) - [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) - [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) -- [Spring 5 Testing with @EnabledIf Annotation](https://github.com/eugenp/tutorials/tree/master/spring-5) +- [Spring 5 Testing with @EnabledIf Annotation](http://www.baeldung.com/sring-5-enabledif) +- [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs) From f7edd9b5945b652fdc6892f8434001cdc8dc7c39 Mon Sep 17 00:00:00 2001 From: Sirish Renukumar Date: Wed, 10 Jan 2018 19:27:36 +0530 Subject: [PATCH 57/58] Static class example (review comments addressed) --- .../java/com/baeldung/staticclass/Pizza.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/staticclass/Pizza.java diff --git a/core-java/src/main/java/com/baeldung/staticclass/Pizza.java b/core-java/src/main/java/com/baeldung/staticclass/Pizza.java new file mode 100644 index 0000000000..ee6283cee1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/staticclass/Pizza.java @@ -0,0 +1,33 @@ +package com.baeldung.staticclass; + +public class Pizza { + + private static String cookedCount; + private boolean isThinCrust; + + // Accessible globally + public static class PizzaSalesCounter { + + private static String orderedCount; + public static String deliveredCount; + + PizzaSalesCounter() { + System.out.println("Static field of enclosing class is " + + Pizza.cookedCount); + System.out.println("Non-static field of enclosing class is " + + new Pizza().isThinCrust); + } + } + + Pizza() { + System.out.println("Non private static field of static class is " + + PizzaSalesCounter.deliveredCount); + System.out.println("Private static field of static class is " + + PizzaSalesCounter.orderedCount); + } + + public static void main(String[] a) { + // Create instance of the static class without an instance of enclosing class + new Pizza.PizzaSalesCounter(); + } +} From 08594451789b2b5a91a7bdeb775e015a3da1b3da Mon Sep 17 00:00:00 2001 From: Dassi orleando Date: Thu, 11 Jan 2018 06:18:47 +0100 Subject: [PATCH 58/58] BAEL-1318: Add Maven Wrapper to spring-boot module (#3390) * BAEL-1216: improve tests * BAEL-1448: Update Spring 5 articles to use the release version * Setting up the Maven Wrapper on a maven project * Add Maven Wrapper on spring-boot module * simple add --- .../.mvn/wrapper/maven-wrapper.properties | 1 + spring-boot/mvnw | 227 ++++++++++++++++++ spring-boot/mvnw.cmd | 145 +++++++++++ 3 files changed, 373 insertions(+) create mode 100755 spring-boot/.mvn/wrapper/maven-wrapper.properties create mode 100755 spring-boot/mvnw create mode 100755 spring-boot/mvnw.cmd diff --git a/spring-boot/.mvn/wrapper/maven-wrapper.properties b/spring-boot/.mvn/wrapper/maven-wrapper.properties new file mode 100755 index 0000000000..a447c9fa81 --- /dev/null +++ b/spring-boot/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip \ No newline at end of file diff --git a/spring-boot/mvnw b/spring-boot/mvnw new file mode 100755 index 0000000000..e96ccd5fbb --- /dev/null +++ b/spring-boot/mvnw @@ -0,0 +1,227 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/spring-boot/mvnw.cmd b/spring-boot/mvnw.cmd new file mode 100755 index 0000000000..4f0b068a03 --- /dev/null +++ b/spring-boot/mvnw.cmd @@ -0,0 +1,145 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE%