From 897e24552410ce51683c081c2c8640e43c115f42 Mon Sep 17 00:00:00 2001 From: "nguyenminhtuanfit@gmail.com" Date: Sat, 3 Sep 2016 11:32:42 +0700 Subject: [PATCH 001/193] BAEL-221 - Guide to Hazelcast --- hazelcast/pom.xml | 72 +++++++++++++++++++ .../hazelcast/cluster/NativeClient.java | 26 +++++++ .../hazelcast/cluster/ServerNode.java | 23 ++++++ .../listener/CountryEntryListener.java | 41 +++++++++++ hazelcast/src/main/resources/hazelcast.xml | 16 +++++ hazelcast/src/main/resources/logback.xml | 18 +++++ 6 files changed, 196 insertions(+) create mode 100644 hazelcast/pom.xml create mode 100644 hazelcast/src/main/java/com/baeldung/hazelcast/cluster/NativeClient.java create mode 100644 hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java create mode 100644 hazelcast/src/main/java/com/baeldung/hazelcast/listener/CountryEntryListener.java create mode 100644 hazelcast/src/main/resources/hazelcast.xml create mode 100644 hazelcast/src/main/resources/logback.xml diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml new file mode 100644 index 0000000000..62cfa89c0f --- /dev/null +++ b/hazelcast/pom.xml @@ -0,0 +1,72 @@ + + 4.0.0 + com.baeldung + hazelcast + 0.0.1-SNAPSHOT + hazelcast + + + + + com.hazelcast + hazelcast-all + ${hazelcast.version} + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + ch.qos.logback + logback-classic + ${logback.version} + + + + ch.qos.logback + logback-core + ${logback.version} + + + + + + hazelcast + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + + + 3.7 + + + 1.7.21 + 1.1.7 + + + 3.5.1 + + + \ No newline at end of file diff --git a/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/NativeClient.java b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/NativeClient.java new file mode 100644 index 0000000000..bda4b94733 --- /dev/null +++ b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/NativeClient.java @@ -0,0 +1,26 @@ +package com.baeldung.hazelcast.cluster; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.hazelcast.listener.CountryEntryListener; +import com.hazelcast.client.HazelcastClient; +import com.hazelcast.client.config.ClientConfig; +import com.hazelcast.config.GroupConfig; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; + +public class NativeClient { + private static final Logger logger = LoggerFactory.getLogger(NativeClient.class); + + public static void main(String[] args) throws InterruptedException { + ClientConfig config = new ClientConfig(); + GroupConfig groupConfig = config.getGroupConfig(); + groupConfig.setName("dev"); + groupConfig.setPassword("dev-pass"); + HazelcastInstance hazelcastInstanceClient = HazelcastClient.newHazelcastClient(config); + IMap countryMap = hazelcastInstanceClient.getMap("country"); + countryMap.addEntryListener(new CountryEntryListener(), true); + logger.info("Country map size: " + countryMap.size()); + } +} diff --git a/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java new file mode 100644 index 0000000000..8680180399 --- /dev/null +++ b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java @@ -0,0 +1,23 @@ +package com.baeldung.hazelcast.cluster; + +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IdGenerator; + +public class ServerNode { + private static final Logger logger = LoggerFactory.getLogger(ServerNode.class); + + public static void main(String[] args) { + HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(); + Map countryMap = hazelcastInstance.getMap("country"); + IdGenerator idGenerator = hazelcastInstance.getIdGenerator("newid"); + Long countryIdGenerator = idGenerator.newId() == 0L ? 1L : idGenerator.newId(); + countryMap.put(countryIdGenerator, "Country1"); + logger.info("Country map size: " + countryMap.size()); + } +} diff --git a/hazelcast/src/main/java/com/baeldung/hazelcast/listener/CountryEntryListener.java b/hazelcast/src/main/java/com/baeldung/hazelcast/listener/CountryEntryListener.java new file mode 100644 index 0000000000..1f95dcd9f3 --- /dev/null +++ b/hazelcast/src/main/java/com/baeldung/hazelcast/listener/CountryEntryListener.java @@ -0,0 +1,41 @@ +package com.baeldung.hazelcast.listener; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.hazelcast.core.EntryEvent; +import com.hazelcast.core.MapEvent; +import com.hazelcast.map.listener.EntryAddedListener; +import com.hazelcast.map.listener.EntryEvictedListener; +import com.hazelcast.map.listener.EntryRemovedListener; +import com.hazelcast.map.listener.EntryUpdatedListener; +import com.hazelcast.map.listener.MapClearedListener; +import com.hazelcast.map.listener.MapEvictedListener; + +public class CountryEntryListener implements EntryAddedListener, EntryRemovedListener, EntryUpdatedListener, EntryEvictedListener, MapEvictedListener, MapClearedListener { + private static final Logger logger = LoggerFactory.getLogger(CountryEntryListener.class); + + public void entryAdded(EntryEvent event) { + logger.info("entryAdded:" + event); + } + + public void entryUpdated(EntryEvent event) { + logger.info("entryUpdated:" + event); + } + + public void entryRemoved(EntryEvent event) { + logger.info("entryRemoved:" + event); + } + + public void entryEvicted(EntryEvent event) { + logger.info("entryEvicted:" + event); + } + + public void mapCleared(MapEvent event) { + logger.info("mapCleared:" + event); + } + + public void mapEvicted(MapEvent event) { + logger.info("mapEvicted:" + event); + } +} diff --git a/hazelcast/src/main/resources/hazelcast.xml b/hazelcast/src/main/resources/hazelcast.xml new file mode 100644 index 0000000000..f29dc532b8 --- /dev/null +++ b/hazelcast/src/main/resources/hazelcast.xml @@ -0,0 +1,16 @@ + + + + 5701 + + + + + machine1 + localhost + + + + \ No newline at end of file diff --git a/hazelcast/src/main/resources/logback.xml b/hazelcast/src/main/resources/logback.xml new file mode 100644 index 0000000000..8b566286b8 --- /dev/null +++ b/hazelcast/src/main/resources/logback.xml @@ -0,0 +1,18 @@ + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg %n + + + + + + + + + + + + \ No newline at end of file From 03dbd93be250f1bc2bdb9dd8709828a1ae9adef1 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 5 Oct 2016 22:35:11 +0300 Subject: [PATCH 002/193] custom user repository and test --- .../WebContent/META-INF/MANIFEST.MF | 3 + spring-security-custom-permission/derby.log | 13 ++ spring-security-custom-permission/pom.xml | 42 +++++ .../baeldung/config/PersistenceConfig.java | 87 +++++++++++ .../org/baeldung/config/SecurityConfig.java | 19 +++ .../persistence/dao/MyUserRepository.java | 146 ++++++++++++++++++ .../persistence/dao/UserRepository.java | 2 + .../org/baeldung/persistence/model/User.java | 2 + .../resources/persistence-derby.properties | 12 ++ .../web/CustomUserDetailsServiceTest.java | 83 ++++++++++ 10 files changed, 409 insertions(+) create mode 100644 spring-security-custom-permission/WebContent/META-INF/MANIFEST.MF create mode 100644 spring-security-custom-permission/derby.log create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java create mode 100644 spring-security-custom-permission/src/main/resources/persistence-derby.properties create mode 100644 spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java diff --git a/spring-security-custom-permission/WebContent/META-INF/MANIFEST.MF b/spring-security-custom-permission/WebContent/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..254272e1c0 --- /dev/null +++ b/spring-security-custom-permission/WebContent/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/spring-security-custom-permission/derby.log b/spring-security-custom-permission/derby.log new file mode 100644 index 0000000000..3c0968fa9c --- /dev/null +++ b/spring-security-custom-permission/derby.log @@ -0,0 +1,13 @@ +---------------------------------------------------------------- +Wed Oct 05 21:59:32 EEST 2016: +Booting Derby version The Apache Software Foundation - Apache Derby - 10.12.1.1 - (1704137): instance a816c00e-0157-9637-0b63-000000c038f0 +on database directory memory:C:\Users\lore\Documents\workspace-articles\spring-security-custom-permission\spring_custom_user_service with class loader sun.misc.Launcher$AppClassLoader@6433a2 +Loaded from file:/C:/Users/lore/.m2/repository/org/apache/derby/derby/10.12.1.1/derby-10.12.1.1.jar +java.vendor=Oracle Corporation +java.runtime.version=1.8.0_77-b03 +user.dir=C:\Users\lore\Documents\workspace-articles\spring-security-custom-permission +os.name=Windows 7 +os.arch=x86 +os.version=6.1 +derby.system.home=null +Database Class Loader started - derby.database.classpath='' diff --git a/spring-security-custom-permission/pom.xml b/spring-security-custom-permission/pom.xml index 6f460f1751..d036975107 100644 --- a/spring-security-custom-permission/pom.xml +++ b/spring-security-custom-permission/pom.xml @@ -86,6 +86,48 @@ + + + org.springframework + spring-test + test + + + + org.apache.derby + derby + 10.12.1.1 + + + org.apache.derby + derbyclient + 10.12.1.1 + + + org.apache.derby + derbynet + 10.12.1.1 + + + org.apache.derby + derbytools + 10.12.1.1 + + + taglibs + standard + 1.1.2 + + + org.springframework.security + spring-security-taglibs + 4.1.3.RELEASE + + + javax.servlet.jsp.jstl + jstl-api + 1.2 + diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java new file mode 100644 index 0000000000..cd7caa5fd1 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java @@ -0,0 +1,87 @@ +package org.baeldung.config; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.baeldung.persistence.dao.MyUserRepository; +import org.baeldung.persistence.dao.UserRepository; +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.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-derby.properties" }) +public class PersistenceConfig { + + @Autowired + private Environment env; + + public PersistenceConfig() { + super(); + } + + // beans + + @Bean + public LocalContainerEntityManagerFactoryBean myEmf() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); + dataSource.setUrl(env.getProperty("jdbc.url")); + dataSource.setUsername(env.getProperty("jdbc.user")); + dataSource.setPassword(env.getProperty("jdbc.pass")); + + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(emf); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); + hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + + @Bean + public UserRepository userRepository(){ + return new MyUserRepository(); + } +} \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java index b365744bea..21b81741ee 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java @@ -1,14 +1,20 @@ package org.baeldung.config; +import org.baeldung.persistence.dao.MyUserRepository; +import org.baeldung.persistence.dao.UserRepository; import org.baeldung.security.MyUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; 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.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity @@ -40,4 +46,17 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { ; // @formatter:on } + + @Bean + public DaoAuthenticationProvider authenticationProvider() { + final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); + authProvider.setUserDetailsService(userDetailsService); + authProvider.setPasswordEncoder(encoder()); + return authProvider; + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(11); + } } \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java new file mode 100644 index 0000000000..ee290a0c35 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java @@ -0,0 +1,146 @@ +package org.baeldung.persistence.dao; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import org.baeldung.persistence.model.User; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class MyUserRepository implements UserRepository { + + @PersistenceContext + private EntityManager entityManager; + + @Override + public List findAll() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List findAll(Sort sort) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List findAll(Iterable ids) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List save(Iterable entities) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void flush() { + // TODO Auto-generated method stub + + } + + @Override + public S saveAndFlush(S entity) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void deleteInBatch(Iterable entities) { + // TODO Auto-generated method stub + + } + + @Override + public void deleteAllInBatch() { + // TODO Auto-generated method stub + + } + + @Override + public User getOne(Long id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Page findAll(Pageable arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public long count() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public void delete(Long arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void delete(User arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void delete(Iterable arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void deleteAll() { + // TODO Auto-generated method stub + + } + + @Override + public boolean exists(Long arg0) { + // TODO Auto-generated method stub + return false; + } + + @Override + public User findOne(Long arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public S save(S user) { + entityManager.persist(user); + return user; + } + + @Override + public User findByUsername(String username) { + Query query = entityManager.createQuery("from User where username=:username", User.class); + query.setParameter("username", username); + List result = query.getResultList(); + if (result != null && result.size() > 0) { + return result.get(0); + } else + return null; + } + + public void removeUserByUsername(String username) { + final Query query = entityManager.createQuery("delete from User where username=:username"); + query.setParameter("username", username); + query.executeUpdate(); + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java index 679dd6c363..8b4e20d146 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java @@ -6,5 +6,7 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { User findByUsername(final String username); + + void removeUserByUsername(String username); } diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java index 112d502105..67f18c1398 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java @@ -12,8 +12,10 @@ import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; +import javax.persistence.Table; @Entity +@Table(name="user_table") public class User { @Id diff --git a/spring-security-custom-permission/src/main/resources/persistence-derby.properties b/spring-security-custom-permission/src/main/resources/persistence-derby.properties new file mode 100644 index 0000000000..e808fdc288 --- /dev/null +++ b/spring-security-custom-permission/src/main/resources/persistence-derby.properties @@ -0,0 +1,12 @@ +# jdbc.X +jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver +jdbc.url=jdbc:derby:memory:spring_custom_user_service;create=true +jdbc.user=tutorialuser +jdbc.pass=tutorialpass + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.DerbyDialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java new file mode 100644 index 0000000000..390bd7c96c --- /dev/null +++ b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java @@ -0,0 +1,83 @@ +package org.baeldung.web; + +import org.baeldung.config.MvcConfig; +import org.baeldung.config.PersistenceConfig; +import org.baeldung.config.SecurityConfig; +import org.baeldung.persistence.dao.UserRepository; +import org.baeldung.persistence.model.User; +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.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import static org.junit.Assert.*; + +import java.util.logging.Level; +import java.util.logging.Logger; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = { MvcConfig.class, SecurityConfig.class, PersistenceConfig.class }) +@WebAppConfiguration +public class CustomUserDetailsServiceTest { + + private static final Logger LOG = Logger.getLogger("CustomUserDetailsServiceTest"); + + public static final String USERNAME = "user"; + public static final String PASSWORD = "pass"; + public static final String USERNAME2 = "user2"; + + @Autowired + UserRepository myUserRepository; + + @Autowired + AuthenticationProvider authenticationProvider; + + @Test + public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { + try { + User user = new User(); + user.setUsername(USERNAME); + user.setPassword(PASSWORD); + + myUserRepository.save(user); + + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); + Authentication authentication = authenticationProvider.authenticate(auth); + + assertEquals(authentication.getName(), USERNAME); + + } catch (Exception exc) { + LOG.log(Level.SEVERE, "Error creating account"); + } finally { + myUserRepository.removeUserByUsername(USERNAME); + } + } + + @Test (expected = BadCredentialsException.class) + public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { + try { + User user = new User(); + user.setUsername(USERNAME); + user.setPassword(PASSWORD); + + try { + myUserRepository.save(user); + } + catch (Exception exc) { + LOG.log(Level.SEVERE, "Error creating account"); + } + + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); + Authentication authentication = authenticationProvider.authenticate(auth); + } + finally { + myUserRepository.removeUserByUsername(USERNAME); + } + } + +} From 4639d467053417321836b30a43903a7f501ba103 Mon Sep 17 00:00:00 2001 From: Sandeep Kumar Date: Fri, 7 Oct 2016 18:16:04 +0530 Subject: [PATCH 003/193] Modify test cases for About Page --- selenium-junit-testng/pom.xml | 4 +- .../baeldung/selenium/SeleniumExample.java | 39 ++++++++++++++++++- .../selenium/junit/TestSeleniumWithJUnit.java | 34 ++++++++++------ .../testng/TestSeleniumWithTestNG.java | 19 ++++++--- 4 files changed, 76 insertions(+), 20 deletions(-) diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml index bf5a082fba..c6461816af 100644 --- a/selenium-junit-testng/pom.xml +++ b/selenium-junit-testng/pom.xml @@ -37,12 +37,12 @@ junit junit - 4.8.1 + 4.12 org.testng testng - 6.9.10 + 6.9.13.6 \ No newline at end of file diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java index d8b248df81..7661354aab 100644 --- a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java +++ b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java @@ -1,15 +1,22 @@ package main.java.com.baeldung.selenium; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class SeleniumExample { private WebDriver webDriver; private String url = "http://www.baeldung.com/"; - + public SeleniumExample() { webDriver = new FirefoxDriver(); + webDriver.manage().window().maximize(); + webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); webDriver.get(url); } @@ -21,4 +28,34 @@ public class SeleniumExample { return webDriver.getTitle(); } + public void getAboutBaeldungPage() { + closeOverlay(); + clickAboutLink(); + clickAboutUsLink(); + } + + private void closeOverlay() { + List webElementList = webDriver.findElements(By.tagName("a")); + if (webElementList != null && !webElementList.isEmpty()) { + for (WebElement webElement : webElementList) { + if (webElement.getAttribute("title").equalsIgnoreCase("Close")) { + webElement.click(); + } + } + } + } + + private void clickAboutLink() { + webDriver.findElement(By.partialLinkText("About")).click(); + } + + private void clickAboutUsLink() { + webDriver.findElement(By.partialLinkText("About Baeldung.")).click(); + } + + public boolean isAuthorInformationAvailable() { + return webDriver + .findElement(By.xpath("//*[contains(text(), 'Eugen – an engineer')]")) + .isDisplayed(); + } } diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java index dabb1e1988..85c20f62a5 100644 --- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java @@ -1,31 +1,41 @@ package test.java.com.baeldung.selenium.junit; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; import main.java.com.baeldung.selenium.SeleniumExample; -import org.junit.After; -import org.junit.Before; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; public class TestSeleniumWithJUnit { - private SeleniumExample seleniumExample; - private String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials"; + private static SeleniumExample seleniumExample; + private String expecteTilteAboutBaeldungPage = "About Baeldung | Baeldung"; - @Before - public void setUp() { + @BeforeClass + public static void setUp() { seleniumExample = new SeleniumExample(); } - @After - public void tearDown() { + @AfterClass + public static void tearDown() { seleniumExample.closeWindow(); } @Test - public void whenPageIsLoaded_thenTitleIsAsPerExpectation() { - String actualTitle = seleniumExample.getTitle(); - assertNotNull(actualTitle); - assertEquals(actualTitle, expectedTitle); + public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() { + try { + seleniumExample.getAboutBaeldungPage(); + String actualTitle = seleniumExample.getTitle(); + assertNotNull(actualTitle); + assertEquals(actualTitle, expecteTilteAboutBaeldungPage); + assertTrue(seleniumExample.isAuthorInformationAvailable()); + } catch (Exception exception) { + exception.printStackTrace(); + seleniumExample.closeWindow(); + } } + } diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java index 78ef8b8dfb..40b0424820 100644 --- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java @@ -1,6 +1,8 @@ package test.java.com.baeldung.selenium.testng; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; import main.java.com.baeldung.selenium.SeleniumExample; import org.testng.annotations.AfterSuite; @@ -10,7 +12,7 @@ import org.testng.annotations.Test; public class TestSeleniumWithTestNG { private SeleniumExample seleniumExample; - private String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials"; + private String expecteTilteAboutBaeldungPage = "About Baeldung | Baeldung"; @BeforeSuite public void setUp() { @@ -23,9 +25,16 @@ public class TestSeleniumWithTestNG { } @Test - public void whenPageIsLoaded_thenTitleIsAsPerExpectation() { - String actualTitle = seleniumExample.getTitle(); - assertNotNull(actualTitle); - assertEquals(actualTitle, expectedTitle); + public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() { + try { + seleniumExample.getAboutBaeldungPage(); + String actualTitle = seleniumExample.getTitle(); + assertNotNull(actualTitle); + assertEquals(actualTitle, expecteTilteAboutBaeldungPage); + assertTrue(seleniumExample.isAuthorInformationAvailable()); + } catch (Exception exception) { + exception.printStackTrace(); + seleniumExample.closeWindow(); + } } } From a8b3f44a2fd25918d25d0237c27d2c77080f67e5 Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Fri, 7 Oct 2016 17:31:28 +0200 Subject: [PATCH 004/193] Code improvement --- okhttp/pom.xml | 98 ++++++++++++------- .../okhttp/ProgressRequestWrapper.java | 10 +- .../okhttp/OkHttpFileUploadingTest.java | 4 +- .../org/baeldung/okhttp/OkHttpGetTest.java | 6 +- .../org/baeldung/okhttp/OkHttpHeaderTest.java | 4 +- .../org/baeldung/okhttp/OkHttpMiscTest.java | 54 +++++----- .../baeldung/okhttp/OkHttpPostingTest.java | 8 +- .../baeldung/okhttp/OkHttpRedirectTest.java | 2 +- 8 files changed, 111 insertions(+), 75 deletions(-) diff --git a/okhttp/pom.xml b/okhttp/pom.xml index ba5bcf9725..4d371f40b0 100644 --- a/okhttp/pom.xml +++ b/okhttp/pom.xml @@ -1,44 +1,76 @@ - - 4.0.0 - org.baeldung.okhttp - okhttp - 0.0.1-SNAPSHOT + + 4.0.0 + org.baeldung.okhttp + okhttp + 0.0.1-SNAPSHOT - + - - - com.squareup.okhttp3 - okhttp - ${com.squareup.okhttp3.version} - + - - - junit - junit - ${junit.version} - test - + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + - + + org.slf4j + slf4j-api + ${org.slf4j.version} + - + + ch.qos.logback + logback-classic + ${logback.version} + - - 3.4.1 + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + - - 1.3 - 4.12 - + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + junit + junit + ${junit.version} + test + + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + + + + + 3.4.1 + + + 1.7.13 + 1.1.3 + + + 1.3 + 4.12 + + diff --git a/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java b/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java index 6a98f8d20a..255d10b98a 100644 --- a/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java +++ b/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java @@ -1,11 +1,16 @@ package org.baeldung.okhttp; -import okhttp3.MediaType; import okhttp3.RequestBody; -import okio.*; +import okhttp3.MediaType; import java.io.IOException; +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + public class ProgressRequestWrapper extends RequestBody { protected RequestBody delegate; @@ -61,6 +66,7 @@ public class ProgressRequestWrapper extends RequestBody { } public interface ProgressListener { + void onRequestProgress(long bytesWritten, long contentLength); } diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java index 32457fc11b..77219b8e22 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java @@ -23,7 +23,7 @@ public class OkHttpFileUploadingTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; @Test - public void whenUploadFileUsingOkHttp_thenCorrect() throws IOException { + public void whenUploadFile_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -45,7 +45,7 @@ public class OkHttpFileUploadingTest { } @Test - public void whenGetUploadFileProgressUsingOkHttp_thenCorrect() throws IOException { + public void whenGetUploadFileProgress_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java index e8edff92df..de954e3dd7 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java @@ -19,7 +19,7 @@ public class OkHttpGetTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; @Test - public void whenGetRequestUsingOkHttp_thenCorrect() throws IOException { + public void whenGetRequest_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -34,7 +34,7 @@ public class OkHttpGetTest { } @Test - public void whenGetRequestWithQueryParameterUsingOkHttp_thenCorrect() throws IOException { + public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -54,7 +54,7 @@ public class OkHttpGetTest { } @Test - public void whenAsynchronousGetRequestUsingOkHttp_thenCorrect() { + public void whenAsynchronousGetRequest_thenCorrect() { OkHttpClient client = new OkHttpClient(); diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java index 5b2e89eca8..958eeb51ce 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java @@ -14,7 +14,7 @@ public class OkHttpHeaderTest { private static final String SAMPLE_URL = "http://www.github.com"; @Test - public void whenSetHeaderUsingOkHttp_thenCorrect() throws IOException { + public void whenSetHeader_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -29,7 +29,7 @@ public class OkHttpHeaderTest { } @Test - public void whenSetDefaultHeaderUsingOkHttp_thenCorrect() throws IOException { + public void whenSetDefaultHeader_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new DefaultContentTypeInterceptor("application/json")) diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java index 829bafe8ef..b72b461158 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java @@ -7,6 +7,8 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import okhttp3.Cache; import okhttp3.Call; @@ -17,13 +19,12 @@ import okhttp3.Response; public class OkHttpMiscTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static Logger logger = LoggerFactory.getLogger(OkHttpMiscTest.class); //@Test - public void whenSetRequestTimeoutUsingOkHttp_thenFail() throws IOException { + public void whenSetRequestTimeout_thenFail() throws IOException { OkHttpClient client = new OkHttpClient.Builder() - //.connectTimeout(10, TimeUnit.SECONDS) - //.writeTimeout(10, TimeUnit.SECONDS) .readTimeout(1, TimeUnit.SECONDS) .build(); @@ -36,8 +37,8 @@ public class OkHttpMiscTest { response.close(); } - //@Test - public void whenCancelRequestUsingOkHttp_thenCorrect() throws IOException { + @Test + public void whenCancelRequest_thenCorrect() throws IOException { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); @@ -48,7 +49,6 @@ public class OkHttpMiscTest { .build(); final int seconds = 1; - //final int seconds = 3; final long startNanos = System.nanoTime(); final Call call = client.newCall(request); @@ -57,57 +57,55 @@ public class OkHttpMiscTest { executor.schedule(new Runnable() { public void run() { - System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f); + logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f); call.cancel(); - System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f); + logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f); } }, seconds, TimeUnit.SECONDS); try { - System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f); - Response response = call.execute(); - System.out.printf("%.2f Call was expected to fail, but completed: %s%n", (System.nanoTime() - startNanos) / 1e9f, response); + logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f); + Response response = call.execute(); + logger.debug("Call was expected to fail, but completed: " + (System.nanoTime() - startNanos) / 1e9f, response); } catch (IOException e) { - System.out.printf("%.2f Call failed as expected: %s%n", (System.nanoTime() - startNanos) / 1e9f, e); + logger.debug("Call failed as expected: " + (System.nanoTime() - startNanos) / 1e9f, e); } } - @Test - public void whenSetResponseCacheUsingOkHttp_thenCorrect() throws IOException { + //@Test + public void whenSetResponseCache_thenCorrect() throws IOException { int cacheSize = 10 * 1024 * 1024; // 10 MiB File cacheDirectory = new File("src/test/resources/cache"); Cache cache = new Cache(cacheDirectory, cacheSize); OkHttpClient client = new OkHttpClient.Builder() - .cache(cache) - .build(); + .cache(cache) + .build(); Request request = new Request.Builder() - .url("http://publicobject.com/helloworld.txt") - //.cacheControl(CacheControl.FORCE_NETWORK) - //.cacheControl(CacheControl.FORCE_CACHE) - .build(); + .url("http://publicobject.com/helloworld.txt") + .build(); Response response1 = client.newCall(request).execute(); String responseBody1 = response1.body().string(); - System.out.println("Response 1 response: " + response1); - System.out.println("Response 1 cache response: " + response1.cacheResponse()); - System.out.println("Response 1 network response: " + response1.networkResponse()); - System.out.println("Response 1 responseBody: " + responseBody1); + logger.debug("Response 1 response: " + response1); + logger.debug("Response 1 cache response: " + response1.cacheResponse()); + logger.debug("Response 1 network response: " + response1.networkResponse()); + logger.debug("Response 1 responseBody: " + responseBody1); Response response2 = client.newCall(request).execute(); String responseBody2 = response2.body().string(); - System.out.println("Response 2 response: " + response2); - System.out.println("Response 2 cache response: " + response2.cacheResponse()); - System.out.println("Response 2 network response: " + response2.networkResponse()); - System.out.println("Response 2 responseBody: " + responseBody2); + logger.debug("Response 2 response: " + response2); + logger.debug("Response 2 cache response: " + response2.cacheResponse()); + logger.debug("Response 2 network response: " + response2.networkResponse()); + logger.debug("Response 2 responseBody: " + responseBody2); } } diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java index 1ba2d517c5..41a024d2ee 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java @@ -24,7 +24,7 @@ public class OkHttpPostingTest { private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; @Test - public void whenSendPostRequestUsingOkHttp_thenCorrect() throws IOException { + public void whenSendPostRequest_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -45,7 +45,7 @@ public class OkHttpPostingTest { } @Test - public void whenSendPostRequestWithAuthorizationUsingOkHttp_thenCorrect() throws IOException { + public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException { String postBody = "test post"; @@ -64,7 +64,7 @@ public class OkHttpPostingTest { } @Test - public void whenPostJsonUsingOkHttp_thenCorrect() throws IOException { + public void whenPostJson_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -84,7 +84,7 @@ public class OkHttpPostingTest { } @Test - public void whenSendMultipartRequestUsingOkHttp_thenCorrect() throws IOException { + public void whenSendMultipartRequest_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java index 1582a5ff7f..c709253478 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java @@ -15,7 +15,7 @@ import okhttp3.Response; public class OkHttpRedirectTest { @Test - public void whenSetFollowRedirectsUsingOkHttp_thenNotRedirected() throws IOException { + public void whenSetFollowRedirects_thenNotRedirected() throws IOException { OkHttpClient client = new OkHttpClient().newBuilder() .followRedirects(false) From 8692cad3282d0d8e72170bfa8720bb57ea98dd95 Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Fri, 7 Oct 2016 17:47:58 +0200 Subject: [PATCH 005/193] Code improvement --- .../org/baeldung/okhttp/OkHttpMiscTest.java | 24 ++++++++----------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java index b72b461158..fe15a76200 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java @@ -21,7 +21,7 @@ public class OkHttpMiscTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; private static Logger logger = LoggerFactory.getLogger(OkHttpMiscTest.class); - //@Test + @Test public void whenSetRequestTimeout_thenFail() throws IOException { OkHttpClient client = new OkHttpClient.Builder() @@ -75,7 +75,7 @@ public class OkHttpMiscTest { } } - //@Test + @Test public void whenSetResponseCache_thenCorrect() throws IOException { int cacheSize = 10 * 1024 * 1024; // 10 MiB @@ -91,21 +91,17 @@ public class OkHttpMiscTest { .build(); Response response1 = client.newCall(request).execute(); - - String responseBody1 = response1.body().string(); - - logger.debug("Response 1 response: " + response1); - logger.debug("Response 1 cache response: " + response1.cacheResponse()); - logger.debug("Response 1 network response: " + response1.networkResponse()); - logger.debug("Response 1 responseBody: " + responseBody1); + logResponse(response1); Response response2 = client.newCall(request).execute(); + logResponse(response2); + } - String responseBody2 = response2.body().string(); + private void logResponse(Response response) throws IOException { - logger.debug("Response 2 response: " + response2); - logger.debug("Response 2 cache response: " + response2.cacheResponse()); - logger.debug("Response 2 network response: " + response2.networkResponse()); - logger.debug("Response 2 responseBody: " + responseBody2); + logger.debug("Response response: " + response); + logger.debug("Response cache response: " + response.cacheResponse()); + logger.debug("Response network response: " + response.networkResponse()); + logger.debug("Response responseBody: " + response.body().string()); } } From 877706d2e17df91e5bb4a82b2d48faf0ecbfd4bd Mon Sep 17 00:00:00 2001 From: "nguyenminhtuanfit@gmail.com" Date: Fri, 7 Oct 2016 23:04:36 +0700 Subject: [PATCH 006/193] added hazelcast client, removed id generator --- hazelcast/pom.xml | 131 +++++++++--------- .../hazelcast/cluster/ServerNode.java | 5 +- 2 files changed, 71 insertions(+), 65 deletions(-) diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml index 62cfa89c0f..00960eadd2 100644 --- a/hazelcast/pom.xml +++ b/hazelcast/pom.xml @@ -1,72 +1,77 @@ - 4.0.0 - com.baeldung - hazelcast - 0.0.1-SNAPSHOT - hazelcast + 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 + hazelcast + 0.0.1-SNAPSHOT + hazelcast - - - - com.hazelcast - hazelcast-all - ${hazelcast.version} - - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - - ch.qos.logback - logback-classic - ${logback.version} - - - - ch.qos.logback - logback-core - ${logback.version} - + + + com.hazelcast + hazelcast + ${hazelcast.version} + + + + com.hazelcast + hazelcast-client + 3.7.2 + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + ch.qos.logback + logback-classic + ${logback.version} + + + + ch.qos.logback + logback-core + ${logback.version} + - + - - hazelcast - - - src/main/resources - true - - + + hazelcast + + + src/main/resources + true + + - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - - + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + - - - 3.7 - - - 1.7.21 - 1.1.7 + + + 3.7.2 + + + 1.7.21 + 1.1.7 - - 3.5.1 - + + 3.5.1 + \ No newline at end of file diff --git a/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java index 8680180399..01043cf712 100644 --- a/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java +++ b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java @@ -16,8 +16,9 @@ public class ServerNode { HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(); Map countryMap = hazelcastInstance.getMap("country"); IdGenerator idGenerator = hazelcastInstance.getIdGenerator("newid"); - Long countryIdGenerator = idGenerator.newId() == 0L ? 1L : idGenerator.newId(); - countryMap.put(countryIdGenerator, "Country1"); + for (int i = 0; i < 10; i++) { + countryMap.put(idGenerator.newId(), "message" + 1); + } logger.info("Country map size: " + countryMap.size()); } } From b3b7ac888c0d66601440651fd755b3dc97f37b3b Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 8 Oct 2016 11:11:20 +0300 Subject: [PATCH 007/193] update test, remove user repository implementation --- spring-security-custom-permission/derby.log | 13 -- .../baeldung/config/PersistenceConfig.java | 10 +- .../org/baeldung/config/SecurityConfig.java | 1 - .../persistence/dao/MyUserRepository.java | 146 ------------------ .../persistence/dao/UserRepository.java | 2 + .../security/MyUserDetailsService.java | 1 + .../web/CustomUserDetailsServiceTest.java | 29 ++-- 7 files changed, 19 insertions(+), 183 deletions(-) delete mode 100644 spring-security-custom-permission/derby.log delete mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java diff --git a/spring-security-custom-permission/derby.log b/spring-security-custom-permission/derby.log deleted file mode 100644 index 3c0968fa9c..0000000000 --- a/spring-security-custom-permission/derby.log +++ /dev/null @@ -1,13 +0,0 @@ ----------------------------------------------------------------- -Wed Oct 05 21:59:32 EEST 2016: -Booting Derby version The Apache Software Foundation - Apache Derby - 10.12.1.1 - (1704137): instance a816c00e-0157-9637-0b63-000000c038f0 -on database directory memory:C:\Users\lore\Documents\workspace-articles\spring-security-custom-permission\spring_custom_user_service with class loader sun.misc.Launcher$AppClassLoader@6433a2 -Loaded from file:/C:/Users/lore/.m2/repository/org/apache/derby/derby/10.12.1.1/derby-10.12.1.1.jar -java.vendor=Oracle Corporation -java.runtime.version=1.8.0_77-b03 -user.dir=C:\Users\lore\Documents\workspace-articles\spring-security-custom-permission -os.name=Windows 7 -os.arch=x86 -os.version=6.1 -derby.system.home=null -Database Class Loader started - derby.database.classpath='' diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java index cd7caa5fd1..ad19db9e3a 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java @@ -5,7 +5,6 @@ import java.util.Properties; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; -import org.baeldung.persistence.dao.MyUserRepository; import org.baeldung.persistence.dao.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -13,6 +12,7 @@ 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.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; @@ -23,6 +23,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-derby.properties" }) +@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") public class PersistenceConfig { @Autowired @@ -35,7 +36,7 @@ public class PersistenceConfig { // beans @Bean - public LocalContainerEntityManagerFactoryBean myEmf() { + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); @@ -79,9 +80,4 @@ public class PersistenceConfig { // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); return hibernateProperties; } - - @Bean - public UserRepository userRepository(){ - return new MyUserRepository(); - } } \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java index 21b81741ee..463ce9a8ca 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java @@ -1,6 +1,5 @@ package org.baeldung.config; -import org.baeldung.persistence.dao.MyUserRepository; import org.baeldung.persistence.dao.UserRepository; import org.baeldung.security.MyUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java deleted file mode 100644 index ee290a0c35..0000000000 --- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java +++ /dev/null @@ -1,146 +0,0 @@ -package org.baeldung.persistence.dao; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; - -import org.baeldung.persistence.model.User; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class MyUserRepository implements UserRepository { - - @PersistenceContext - private EntityManager entityManager; - - @Override - public List findAll() { - // TODO Auto-generated method stub - return null; - } - - @Override - public List findAll(Sort sort) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List findAll(Iterable ids) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List save(Iterable entities) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void flush() { - // TODO Auto-generated method stub - - } - - @Override - public S saveAndFlush(S entity) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void deleteInBatch(Iterable entities) { - // TODO Auto-generated method stub - - } - - @Override - public void deleteAllInBatch() { - // TODO Auto-generated method stub - - } - - @Override - public User getOne(Long id) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Page findAll(Pageable arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public long count() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public void delete(Long arg0) { - // TODO Auto-generated method stub - - } - - @Override - public void delete(User arg0) { - // TODO Auto-generated method stub - - } - - @Override - public void delete(Iterable arg0) { - // TODO Auto-generated method stub - - } - - @Override - public void deleteAll() { - // TODO Auto-generated method stub - - } - - @Override - public boolean exists(Long arg0) { - // TODO Auto-generated method stub - return false; - } - - @Override - public User findOne(Long arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public S save(S user) { - entityManager.persist(user); - return user; - } - - @Override - public User findByUsername(String username) { - Query query = entityManager.createQuery("from User where username=:username", User.class); - query.setParameter("username", username); - List result = query.getResultList(); - if (result != null && result.size() > 0) { - return result.get(0); - } else - return null; - } - - public void removeUserByUsername(String username) { - final Query query = entityManager.createQuery("delete from User where username=:username"); - query.setParameter("username", username); - query.executeUpdate(); - } - -} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java index 8b4e20d146..f0c3afdf0b 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java @@ -2,11 +2,13 @@ package org.baeldung.persistence.dao; import org.baeldung.persistence.model.User; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.transaction.annotation.Transactional; public interface UserRepository extends JpaRepository { User findByUsername(final String username); + @Transactional void removeUserByUsername(String username); } diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java index 685219728f..3c0024c4b9 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -23,6 +23,7 @@ public class MyUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(final String username) { final User user = userRepository.findByUsername(username); + System.out.println("load user from repo"+user); if (user == null) { throw new UsernameNotFoundException(username); } diff --git a/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java index 390bd7c96c..bdf9c32ca8 100644 --- a/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java +++ b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java @@ -9,9 +9,11 @@ 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.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.core.Authentication; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @@ -36,13 +38,16 @@ public class CustomUserDetailsServiceTest { @Autowired AuthenticationProvider authenticationProvider; + + @Autowired + PasswordEncoder passwordEncoder; @Test public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { try { User user = new User(); user.setUsername(USERNAME); - user.setPassword(PASSWORD); + user.setPassword(passwordEncoder.encode(PASSWORD)); myUserRepository.save(user); @@ -51,31 +56,23 @@ public class CustomUserDetailsServiceTest { assertEquals(authentication.getName(), USERNAME); - } catch (Exception exc) { - LOG.log(Level.SEVERE, "Error creating account"); } finally { myUserRepository.removeUserByUsername(USERNAME); } } - - @Test (expected = BadCredentialsException.class) + + @Test(expected = BadCredentialsException.class) public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { try { User user = new User(); user.setUsername(USERNAME); - user.setPassword(PASSWORD); + user.setPassword(passwordEncoder.encode(PASSWORD)); + + myUserRepository.save(user); - try { - myUserRepository.save(user); - } - catch (Exception exc) { - LOG.log(Level.SEVERE, "Error creating account"); - } - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); - Authentication authentication = authenticationProvider.authenticate(auth); - } - finally { + authenticationProvider.authenticate(auth); + } finally { myUserRepository.removeUserByUsername(USERNAME); } } From 78f8591937a7e44f253d907183b09c644d31f6c3 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 8 Oct 2016 11:14:09 +0300 Subject: [PATCH 008/193] remove unused imports --- .../src/main/java/org/baeldung/config/PersistenceConfig.java | 1 - .../src/main/java/org/baeldung/config/SecurityConfig.java | 1 - .../main/java/org/baeldung/security/MyUserDetailsService.java | 1 - .../java/org/baeldung/web/CustomUserDetailsServiceTest.java | 4 ---- 4 files changed, 7 deletions(-) diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java index ad19db9e3a..1c4cb0124a 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java @@ -5,7 +5,6 @@ import java.util.Properties; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; -import org.baeldung.persistence.dao.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java index 463ce9a8ca..8cc9d45823 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java @@ -1,6 +1,5 @@ package org.baeldung.config; -import org.baeldung.persistence.dao.UserRepository; import org.baeldung.security.MyUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java index 3c0024c4b9..685219728f 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -23,7 +23,6 @@ public class MyUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(final String username) { final User user = userRepository.findByUsername(username); - System.out.println("load user from repo"+user); if (user == null) { throw new UsernameNotFoundException(username); } diff --git a/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java index bdf9c32ca8..19603a499c 100644 --- a/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java +++ b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java @@ -9,7 +9,6 @@ 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.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -19,7 +18,6 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import static org.junit.Assert.*; -import java.util.logging.Level; import java.util.logging.Logger; @RunWith(SpringJUnit4ClassRunner.class) @@ -27,8 +25,6 @@ import java.util.logging.Logger; @WebAppConfiguration public class CustomUserDetailsServiceTest { - private static final Logger LOG = Logger.getLogger("CustomUserDetailsServiceTest"); - public static final String USERNAME = "user"; public static final String PASSWORD = "pass"; public static final String USERNAME2 = "user2"; From 0d2e13392bb352a14b9f5e2a3168202e7b6cc6fe Mon Sep 17 00:00:00 2001 From: Sandeep Kumar Date: Sun, 9 Oct 2016 08:15:55 +0530 Subject: [PATCH 009/193] Implementing Java 8 streaming API for-next loop --- .../main/java/com/baeldung/selenium/SeleniumExample.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java index 7661354aab..1007bf7503 100644 --- a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java +++ b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java @@ -37,11 +37,7 @@ public class SeleniumExample { private void closeOverlay() { List webElementList = webDriver.findElements(By.tagName("a")); if (webElementList != null && !webElementList.isEmpty()) { - for (WebElement webElement : webElementList) { - if (webElement.getAttribute("title").equalsIgnoreCase("Close")) { - webElement.click(); - } - } + webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().get().click(); } } From b66c42d0f613efa540db0cfb67f72068d67e301a Mon Sep 17 00:00:00 2001 From: Thai Nguyen Date: Sun, 9 Oct 2016 10:45:25 +0700 Subject: [PATCH 010/193] Apache CXF support for RESTful web services --- apache-cxf/jaxrs-implementation/pom.xml | 54 +++++++++++ .../cxf/jaxrs/implementation/Baeldung.java | 68 ++++++++++++++ .../cxf/jaxrs/implementation/Course.java | 73 +++++++++++++++ .../jaxrs/implementation/RestfulServer.java | 21 +++++ .../cxf/jaxrs/implementation/Student.java | 25 +++++ .../src/main/resources/course.xml | 4 + .../src/main/resources/student.xml | 5 + .../cxf/jaxrs/implementation/ServiceTest.java | 93 +++++++++++++++++++ apache-cxf/pom.xml | 1 + 9 files changed, 344 insertions(+) create mode 100644 apache-cxf/jaxrs-implementation/pom.xml create mode 100644 apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java create mode 100644 apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java create mode 100644 apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java create mode 100644 apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java create mode 100644 apache-cxf/jaxrs-implementation/src/main/resources/course.xml create mode 100644 apache-cxf/jaxrs-implementation/src/main/resources/student.xml create mode 100644 apache-cxf/jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java diff --git a/apache-cxf/jaxrs-implementation/pom.xml b/apache-cxf/jaxrs-implementation/pom.xml new file mode 100644 index 0000000000..1f83ecf934 --- /dev/null +++ b/apache-cxf/jaxrs-implementation/pom.xml @@ -0,0 +1,54 @@ + + + + 4.0.0 + cxf-jaxrs-implementation + + com.baeldung + apache-cxf + 0.0.1-SNAPSHOT + + + UTF-8 + 3.1.7 + 4.5.2 + + + + + org.codehaus.mojo + exec-maven-plugin + + com.baeldung.cxf.jaxrs.implementation.RestfulServer + + + + maven-surefire-plugin + 2.19.1 + + + **/ServiceTest + + + + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf.version} + + + org.apache.cxf + cxf-rt-transports-http-jetty + ${cxf.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + diff --git a/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java b/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java new file mode 100644 index 0000000000..5617f482f8 --- /dev/null +++ b/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java @@ -0,0 +1,68 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +@Path("baeldung") +@Produces("text/xml") +public class Baeldung { + private Map courses = new HashMap<>(); + + { + Student student1 = new Student(); + Student student2 = new Student(); + student1.setId(1); + student1.setName("Student A"); + student2.setId(2); + student2.setName("Student B"); + + List course1Students = new ArrayList<>(); + course1Students.add(student1); + course1Students.add(student2); + + Course course1 = new Course(); + Course course2 = new Course(); + course1.setId(1); + course1.setName("REST with Spring"); + course1.setStudents(course1Students); + course2.setId(2); + course2.setName("Learn Spring Security"); + + courses.put(1, course1); + courses.put(2, course2); + } + + @GET + @Path("courses/{courseOrder}") + public Course getCourse(@PathParam("courseOrder") int courseOrder) { + return courses.get(courseOrder); + } + + @PUT + @Path("courses/{courseOrder}") + public Response putCourse(@PathParam("courseOrder") int courseOrder, Course course) { + Course existingCourse = courses.get(courseOrder); + Response response; + if (existingCourse == null || existingCourse.getId() != course.getId() || !(existingCourse.getName().equals(course.getName()))) { + courses.put(courseOrder, course); + response = Response.ok().build(); + } else { + response = Response.notModified().build(); + } + return response; + } + + @Path("courses/{courseOrder}/students") + public Course pathToStudent(@PathParam("courseOrder") int courseOrder) { + return courses.get(courseOrder); + } +} \ No newline at end of file diff --git a/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java new file mode 100644 index 0000000000..9ab74bea58 --- /dev/null +++ b/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java @@ -0,0 +1,73 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Response; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "Course") +public class Course { + private int id; + private String name; + private List students; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getStudents() { + return students; + } + + public void setStudents(List students) { + this.students = students; + } + + @GET + @Path("{studentOrder}") + public Student getStudent(@PathParam("studentOrder")int studentOrder) { + return students.get(studentOrder); + } + + @POST + public Response postStudent(Student student) { + if (students == null) { + students = new ArrayList(); + } + students.add(student); + return Response.ok(student).build(); + } + + @DELETE + @Path("{studentOrder}") + public Response deleteStudent(@PathParam("studentOrder") int studentOrder) { + Student student = students.get(studentOrder); + Response response; + if (student != null) { + students.remove(studentOrder); + response = Response.ok().build(); + } else { + response = Response.notModified().build(); + } + return response; + } +} \ No newline at end of file diff --git a/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java b/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java new file mode 100644 index 0000000000..bb35bab3f8 --- /dev/null +++ b/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java @@ -0,0 +1,21 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import org.apache.cxf.endpoint.Server; +import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; +import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider; + +public class RestfulServer { + public static void main(String args[]) throws Exception { + JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean(); + factoryBean.setResourceClasses(Baeldung.class); + factoryBean.setResourceProvider(new SingletonResourceProvider(new Baeldung())); + factoryBean.setAddress("http://localhost:8080/"); + Server server = factoryBean.create(); + + System.out.println("Server ready..."); + Thread.sleep(60 * 1000); + System.out.println("Server exiting"); + server.destroy(); + System.exit(0); + } +} \ No newline at end of file diff --git a/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java b/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java new file mode 100644 index 0000000000..de782e4edb --- /dev/null +++ b/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java @@ -0,0 +1,25 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "Student") +public class Student { + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/apache-cxf/jaxrs-implementation/src/main/resources/course.xml b/apache-cxf/jaxrs-implementation/src/main/resources/course.xml new file mode 100644 index 0000000000..465c337745 --- /dev/null +++ b/apache-cxf/jaxrs-implementation/src/main/resources/course.xml @@ -0,0 +1,4 @@ + + 3 + Apache CXF Support for RESTful + \ No newline at end of file diff --git a/apache-cxf/jaxrs-implementation/src/main/resources/student.xml b/apache-cxf/jaxrs-implementation/src/main/resources/student.xml new file mode 100644 index 0000000000..7fb6189815 --- /dev/null +++ b/apache-cxf/jaxrs-implementation/src/main/resources/student.xml @@ -0,0 +1,5 @@ + + + 3 + Student C + \ No newline at end of file diff --git a/apache-cxf/jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java b/apache-cxf/jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java new file mode 100644 index 0000000000..48749a568e --- /dev/null +++ b/apache-cxf/jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java @@ -0,0 +1,93 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import static org.junit.Assert.assertEquals; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; + +import javax.xml.bind.JAXB; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; + +public class ServiceTest { + private static final String BASE_URL = "http://localhost:8080/baeldung/courses/"; + private static CloseableHttpClient client; + + @BeforeClass + public static void createClient() { + client = HttpClients.createDefault(); + } + + @AfterClass + public static void closeClient() throws IOException { + client.close(); + } + + @Test + public void whenPutCourse_thenCorrect() throws IOException { + HttpPut httpPut = new HttpPut(BASE_URL + "3"); + InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("course.xml"); + httpPut.setEntity(new InputStreamEntity(resourceStream)); + httpPut.setHeader("Content-Type", "text/xml"); + + HttpResponse response = client.execute(httpPut); + assertEquals(200, response.getStatusLine().getStatusCode()); + + Course course = getCourse(3); + assertEquals(3, course.getId()); + assertEquals("Apache CXF Support for RESTful", course.getName()); + } + + @Test + public void whenPostStudent_thenCorrect() throws IOException { + HttpPost httpPost = new HttpPost(BASE_URL + "2/students"); + InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("student.xml"); + httpPost.setEntity(new InputStreamEntity(resourceStream)); + httpPost.setHeader("Content-Type", "text/xml"); + + HttpResponse response = client.execute(httpPost); + assertEquals(200, response.getStatusLine().getStatusCode()); + + Student student = getStudent(2, 0); + assertEquals(3, student.getId()); + assertEquals("Student C", student.getName()); + } + + @Test + public void whenDeleteStudent_thenCorrect() throws IOException { + HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/0"); + HttpResponse response = client.execute(httpDelete); + assertEquals(200, response.getStatusLine().getStatusCode()); + + Course course = getCourse(1); + assertEquals(1, course.getStudents().size()); + assertEquals(2, course.getStudents().get(0).getId()); + assertEquals("Student B", course.getStudents().get(0).getName()); + } + + private Course getCourse(int courseOrder) throws IOException { + URL url = new URL(BASE_URL + courseOrder); + InputStream input = url.openStream(); + Course course = JAXB.unmarshal(new InputStreamReader(input), Course.class); + return course; + } + + private Student getStudent(int courseOrder, int studentOrder) throws IOException { + URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder); + InputStream input = url.openStream(); + Student student = JAXB.unmarshal(new InputStreamReader(input), Student.class); + return student; + } +} \ No newline at end of file diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml index 022fc59f9b..af7949bb6c 100644 --- a/apache-cxf/pom.xml +++ b/apache-cxf/pom.xml @@ -8,6 +8,7 @@ cxf-introduction cxf-spring + cxf-jaxrs-implementation From 4f64784e841d255323d2c76f3be7289615ee9f72 Mon Sep 17 00:00:00 2001 From: sanketmeghani Date: Sun, 9 Oct 2016 11:17:22 +0530 Subject: [PATCH 011/193] Mocking current time for JUnits --- .../baeldung/util/CurrentDateTimeTest.java | 42 ++++++++++++------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java index 06d9394a5e..599d5a5894 100644 --- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java +++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java @@ -1,47 +1,57 @@ package com.baeldung.util; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import java.time.Clock; import java.time.Instant; import java.time.LocalDate; import java.time.LocalTime; +import java.time.ZoneId; import java.time.temporal.ChronoField; -import java.util.Calendar; -import java.util.GregorianCalendar; +import org.junit.BeforeClass; import org.junit.Test; +import org.mockito.Mockito; public class CurrentDateTimeTest { + private static Clock clock; + + @BeforeClass + public static void setup() { + final Instant currentTime = Instant.parse("2016-10-09T15:10:30.00Z"); + + clock = Mockito.mock(Clock.class); + when(clock.instant()).thenAnswer((invocation) -> currentTime); + when(clock.getZone()).thenAnswer((invocation) -> ZoneId.of("UTC")); + } + @Test public void shouldReturnCurrentDate() { - final LocalDate now = LocalDate.now(); - final Calendar calendar = GregorianCalendar.getInstance(); + final LocalDate now = LocalDate.now(clock); - assertEquals("10-10-2010".length(), now.toString().length()); - assertEquals(calendar.get(Calendar.DATE), now.get(ChronoField.DAY_OF_MONTH)); - assertEquals(calendar.get(Calendar.MONTH), now.get(ChronoField.MONTH_OF_YEAR) - 1); - assertEquals(calendar.get(Calendar.YEAR), now.get(ChronoField.YEAR)); + assertEquals(9, now.get(ChronoField.DAY_OF_MONTH)); + assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(2016, now.get(ChronoField.YEAR)); } @Test public void shouldReturnCurrentTime() { - final LocalTime now = LocalTime.now(); - final Calendar calendar = GregorianCalendar.getInstance(); + final LocalTime now = LocalTime.now(clock); - assertEquals(calendar.get(Calendar.HOUR_OF_DAY), now.get(ChronoField.HOUR_OF_DAY)); - assertEquals(calendar.get(Calendar.MINUTE), now.get(ChronoField.MINUTE_OF_HOUR)); - assertEquals(calendar.get(Calendar.SECOND), now.get(ChronoField.SECOND_OF_MINUTE)); + assertEquals(15, now.get(ChronoField.HOUR_OF_DAY)); + assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR)); + assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE)); } @Test public void shouldReturnCurrentTimestamp() { - final Instant now = Instant.now(); - final Calendar calendar = GregorianCalendar.getInstance(); + final Instant now = Instant.now(clock); - assertEquals(calendar.getTimeInMillis() / 1000, now.getEpochSecond()); + assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond()); } } From d98924b39db3405cdf32eb4856f3b3c5b20b5734 Mon Sep 17 00:00:00 2001 From: Kiran Date: Sun, 9 Oct 2016 13:52:52 -0400 Subject: [PATCH 012/193] Updated indentation and refactored code --- spring-jms/src/com/baeldung/spring/jms/Employee.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-jms/src/com/baeldung/spring/jms/Employee.java b/spring-jms/src/com/baeldung/spring/jms/Employee.java index a0346c4291..36783ebf46 100644 --- a/spring-jms/src/com/baeldung/spring/jms/Employee.java +++ b/spring-jms/src/com/baeldung/spring/jms/Employee.java @@ -18,6 +18,6 @@ public class Employee { } public String toString() { - return "Person: name(" + name + "), age(" + age + ")"; + return "Employee: name(" + name + "), age(" + age + ")"; } } From 94f258f90c16c326979cc8efdab1eefb53cae893 Mon Sep 17 00:00:00 2001 From: Kiran Date: Sun, 9 Oct 2016 13:53:20 -0400 Subject: [PATCH 013/193] Updated indentation and refactored code --- .../spring/jms/SampleJmsMessageSender.java | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/spring-jms/src/com/baeldung/spring/jms/SampleJmsMessageSender.java b/spring-jms/src/com/baeldung/spring/jms/SampleJmsMessageSender.java index e3eccea03e..123edccb4d 100644 --- a/spring-jms/src/com/baeldung/spring/jms/SampleJmsMessageSender.java +++ b/spring-jms/src/com/baeldung/spring/jms/SampleJmsMessageSender.java @@ -1,6 +1,8 @@ package com.baeldung.spring.jms; -import javax.jms.ConnectionFactory; +import java.util.HashMap; +import java.util.Map; + import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Queue; @@ -14,8 +16,8 @@ public class SampleJmsMessageSender { private JmsTemplate jmsTemplate; private Queue queue; - public void setConnectionFactory(ConnectionFactory cf) { - this.jmsTemplate = new JmsTemplate(cf); + public void setJmsTemplate(JmsTemplate jmsTemplate) { + this.jmsTemplate = jmsTemplate; } public void setQueue(Queue queue) { @@ -29,4 +31,12 @@ public class SampleJmsMessageSender { } }); } -} \ No newline at end of file + + public void sendMessage(final Employee employee) { + System.out.println("Jms Message Sender : " + employee); + Map map = new HashMap(); + map.put("name", employee.getName()); + map.put("age", employee.getAge()); + this.jmsTemplate.convertAndSend(map); + } +} From 53a353916b1bf91653c8df6907e630b3751582e1 Mon Sep 17 00:00:00 2001 From: Kiran Date: Sun, 9 Oct 2016 13:55:01 -0400 Subject: [PATCH 014/193] Updated indentation and refactored code Added a a new method receiveMessage() to receive custom converted messages --- .../baeldung/spring/jms/SampleListener.java | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/spring-jms/src/com/baeldung/spring/jms/SampleListener.java b/spring-jms/src/com/baeldung/spring/jms/SampleListener.java index 466cac44a0..8c28ab3e35 100644 --- a/spring-jms/src/com/baeldung/spring/jms/SampleListener.java +++ b/spring-jms/src/com/baeldung/spring/jms/SampleListener.java @@ -1,18 +1,26 @@ package com.baeldung.spring.jms; +import java.util.Map; + import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; +import org.springframework.jms.core.JmsTemplate; + public class SampleListener implements MessageListener { - private String textMessage; + public JmsTemplate getJmsTemplate() { + return getJmsTemplate(); + } public void onMessage(Message message) { if (message instanceof TextMessage) { try { - textMessage = ((TextMessage) message).getText(); + + String msg = ((TextMessage) message).getText(); + System.out.println("Message has been consumed : " + msg); } catch (JMSException ex) { throw new RuntimeException(ex); } @@ -20,4 +28,10 @@ public class SampleListener implements MessageListener { throw new IllegalArgumentException("Message Error"); } } -} \ No newline at end of file + + public Employee receiveMessage() throws JMSException { + Map map = (Map) getJmsTemplate().receiveAndConvert(); + Employee employee = new Employee((String) map.get("name"), (Integer) map.get("age")); + return employee; + } +} From fe9c63560d12e51a9ca7318639d9fa3a79da90f2 Mon Sep 17 00:00:00 2001 From: Kiran Date: Sun, 9 Oct 2016 13:55:26 -0400 Subject: [PATCH 015/193] Updated indentation --- .../baeldung/spring/jms/SampleMessageConverter.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/spring-jms/src/com/baeldung/spring/jms/SampleMessageConverter.java b/spring-jms/src/com/baeldung/spring/jms/SampleMessageConverter.java index 856e0e9e49..2142461a5f 100644 --- a/spring-jms/src/com/baeldung/spring/jms/SampleMessageConverter.java +++ b/spring-jms/src/com/baeldung/spring/jms/SampleMessageConverter.java @@ -11,17 +11,17 @@ import org.springframework.jms.support.converter.MessageConverter; public class SampleMessageConverter implements MessageConverter { public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException { - Employee person = (Employee) object; + Employee employee = (Employee) object; MapMessage message = session.createMapMessage(); - message.setString("name", person.getName()); - message.setInt("age", person.getAge()); + message.setString("name", employee.getName()); + message.setInt("age", employee.getAge()); return message; } public Object fromMessage(Message message) throws JMSException, MessageConversionException { MapMessage mapMessage = (MapMessage) message; - Employee person = new Employee(mapMessage.getString("name"), mapMessage.getInt("age")); - return person; + Employee employee = new Employee(mapMessage.getString("name"), mapMessage.getInt("age")); + return employee; } } From d1bdfb5234c94c4c99fbd1eba6ea7f3adde80387 Mon Sep 17 00:00:00 2001 From: Kiran Date: Sun, 9 Oct 2016 13:56:37 -0400 Subject: [PATCH 016/193] This class is not required Embedded ActiveMq is created from XML now. --- .../baeldung/spring/jms/SampleJMSExample.java | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 spring-jms/src/com/baeldung/spring/jms/SampleJMSExample.java diff --git a/spring-jms/src/com/baeldung/spring/jms/SampleJMSExample.java b/spring-jms/src/com/baeldung/spring/jms/SampleJMSExample.java deleted file mode 100644 index bdde97b82d..0000000000 --- a/spring-jms/src/com/baeldung/spring/jms/SampleJMSExample.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.spring.jms; - -import java.net.URI; -import java.net.URISyntaxException; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class SampleJMSExample { - public static void main(String[] args) throws URISyntaxException, Exception { - BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:61616)")); - broker.start(); - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); - - } -} From 0af6fbea16c2ed7f1aee6154a06713bee3794c1b Mon Sep 17 00:00:00 2001 From: Kiran Date: Sun, 9 Oct 2016 13:58:30 -0400 Subject: [PATCH 017/193] Updated ApplicationContext.xml --- .../src/main/resources/applicationContext.xml | 34 ++++++++++++------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/spring-jms/src/main/resources/applicationContext.xml b/spring-jms/src/main/resources/applicationContext.xml index c15289763f..d94eb4c371 100644 --- a/spring-jms/src/main/resources/applicationContext.xml +++ b/spring-jms/src/main/resources/applicationContext.xml @@ -3,16 +3,27 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - - - - - - - - + + + + + + + + + + + + + + + + + + - + @@ -23,8 +34,7 @@ - + - - \ No newline at end of file + From 147e1bfe107eed1dcabca36fa7a27847cd4d9d7d Mon Sep 17 00:00:00 2001 From: Kiran Date: Sun, 9 Oct 2016 13:59:25 -0400 Subject: [PATCH 018/193] Embedded activemq is configured in this file --- .../src/main/resources/EmbeddedActiveMQ.xml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 spring-jms/src/main/resources/EmbeddedActiveMQ.xml diff --git a/spring-jms/src/main/resources/EmbeddedActiveMQ.xml b/spring-jms/src/main/resources/EmbeddedActiveMQ.xml new file mode 100644 index 0000000000..5e956144fd --- /dev/null +++ b/spring-jms/src/main/resources/EmbeddedActiveMQ.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + \ No newline at end of file From 4240e34c376b670ad44df0ce19af55d47eda3329 Mon Sep 17 00:00:00 2001 From: Kiran Date: Sun, 9 Oct 2016 14:01:42 -0400 Subject: [PATCH 019/193] Junit tests JUnit tests for testing default text message as well as custom messages --- .../src/DefaultTextMessageSenderTest.java | 26 ++++++++++++++++++ .../src/MapMessageConvertAndSendTest.java | 27 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 spring-jms/src/DefaultTextMessageSenderTest.java create mode 100644 spring-jms/src/MapMessageConvertAndSendTest.java diff --git a/spring-jms/src/DefaultTextMessageSenderTest.java b/spring-jms/src/DefaultTextMessageSenderTest.java new file mode 100644 index 0000000000..8806f4d1ba --- /dev/null +++ b/spring-jms/src/DefaultTextMessageSenderTest.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.jms.test; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.spring.jms.SampleJmsMessageSender; + +public class DefaultTextMessageSenderTest { + + private SampleJmsMessageSender messageProducer; + + @SuppressWarnings("resource") + @Before + public void setUp() { + ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml" }); + messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); + } + + @Test + public void testSimpleSend() { + messageProducer.simpleSend(); + } + +} \ No newline at end of file diff --git a/spring-jms/src/MapMessageConvertAndSendTest.java b/spring-jms/src/MapMessageConvertAndSendTest.java new file mode 100644 index 0000000000..d2a3867679 --- /dev/null +++ b/spring-jms/src/MapMessageConvertAndSendTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.jms.test; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.spring.jms.Employee; +import com.baeldung.spring.jms.SampleJmsMessageSender; + +public class MapMessageConvertAndSendTest { + + private SampleJmsMessageSender messageProducer; + + @SuppressWarnings("resource") + @Before + public void setUp() { + ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml" }); + messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); + } + + @Test + public void testSendMessage() { + messageProducer.sendMessage(new Employee("JavaDeveloper2", 22)); + } + +} From 528e3b1ef59ee883deabbda34f204c01efbda578 Mon Sep 17 00:00:00 2001 From: Kiran Date: Sun, 9 Oct 2016 14:02:38 -0400 Subject: [PATCH 020/193] Uploaded in wrong location --- .../src/DefaultTextMessageSenderTest.java | 26 ------------------- 1 file changed, 26 deletions(-) delete mode 100644 spring-jms/src/DefaultTextMessageSenderTest.java diff --git a/spring-jms/src/DefaultTextMessageSenderTest.java b/spring-jms/src/DefaultTextMessageSenderTest.java deleted file mode 100644 index 8806f4d1ba..0000000000 --- a/spring-jms/src/DefaultTextMessageSenderTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.spring.jms.test; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.baeldung.spring.jms.SampleJmsMessageSender; - -public class DefaultTextMessageSenderTest { - - private SampleJmsMessageSender messageProducer; - - @SuppressWarnings("resource") - @Before - public void setUp() { - ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml" }); - messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); - } - - @Test - public void testSimpleSend() { - messageProducer.simpleSend(); - } - -} \ No newline at end of file From d640b9818d91615e6594f159226b0b4b87bb0920 Mon Sep 17 00:00:00 2001 From: Kiran Date: Sun, 9 Oct 2016 14:02:46 -0400 Subject: [PATCH 021/193] Uploaded in wrong location --- .../src/MapMessageConvertAndSendTest.java | 27 ------------------- 1 file changed, 27 deletions(-) delete mode 100644 spring-jms/src/MapMessageConvertAndSendTest.java diff --git a/spring-jms/src/MapMessageConvertAndSendTest.java b/spring-jms/src/MapMessageConvertAndSendTest.java deleted file mode 100644 index d2a3867679..0000000000 --- a/spring-jms/src/MapMessageConvertAndSendTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.spring.jms.test; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.baeldung.spring.jms.Employee; -import com.baeldung.spring.jms.SampleJmsMessageSender; - -public class MapMessageConvertAndSendTest { - - private SampleJmsMessageSender messageProducer; - - @SuppressWarnings("resource") - @Before - public void setUp() { - ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml" }); - messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); - } - - @Test - public void testSendMessage() { - messageProducer.sendMessage(new Employee("JavaDeveloper2", 22)); - } - -} From b253563e676013443ec0ead0445e28ae6a8552b9 Mon Sep 17 00:00:00 2001 From: Kiran Date: Sun, 9 Oct 2016 14:06:40 -0400 Subject: [PATCH 022/193] Junit tests JUnit Tests for default text messages and custom converted messages --- .../jms/DefaultTextMessageSenderTest.java | 26 ++++++++++++++++++ .../jms/MapMessageConvertAndSendTest.java | 27 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java create mode 100644 spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java diff --git a/spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java b/spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java new file mode 100644 index 0000000000..5176d79386 --- /dev/null +++ b/spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.jms; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.spring.jms.SampleJmsMessageSender; + +public class DefaultTextMessageSenderTest { + + private SampleJmsMessageSender messageProducer; + + @SuppressWarnings("resource") + @Before + public void setUp() { + ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml" }); + messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); + } + + @Test + public void testSimpleSend() { + messageProducer.simpleSend(); + } + +} \ No newline at end of file diff --git a/spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java b/spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java new file mode 100644 index 0000000000..4bd9827c60 --- /dev/null +++ b/spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.jms; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.spring.jms.Employee; +import com.baeldung.spring.jms.SampleJmsMessageSender; + +public class MapMessageConvertAndSendTest { + + private SampleJmsMessageSender messageProducer; + + @SuppressWarnings("resource") + @Before + public void setUp() { + ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml" }); + messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); + } + + @Test + public void testSendMessage() { + messageProducer.sendMessage(new Employee("JavaDeveloper2", 22)); + } + +} From ca3e67fcd8da6a5ce90a34b1819e92159eaa2f3d Mon Sep 17 00:00:00 2001 From: Kiran Date: Sun, 9 Oct 2016 14:21:43 -0400 Subject: [PATCH 023/193] Changed @Before to @BeforeClass accordingly made the necessary methods staic --- .../spring/jms/DefaultTextMessageSenderTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java b/spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java index 5176d79386..2016122105 100644 --- a/spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java +++ b/spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java @@ -1,6 +1,6 @@ package com.baeldung.spring.jms; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -9,11 +9,11 @@ import com.baeldung.spring.jms.SampleJmsMessageSender; public class DefaultTextMessageSenderTest { - private SampleJmsMessageSender messageProducer; + private static SampleJmsMessageSender messageProducer; @SuppressWarnings("resource") - @Before - public void setUp() { + @BeforeClass + public static void setUp() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml" }); messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); } @@ -23,4 +23,4 @@ public class DefaultTextMessageSenderTest { messageProducer.simpleSend(); } -} \ No newline at end of file +} From 872654d54cbfd0768e7c36dcc8ab2634df5ec8aa Mon Sep 17 00:00:00 2001 From: Kiran Date: Sun, 9 Oct 2016 14:22:20 -0400 Subject: [PATCH 024/193] Changed @Before to @BeforeClass accordingly made the necessary methods staic --- .../baeldung/spring/jms/MapMessageConvertAndSendTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java b/spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java index 4bd9827c60..19b9097601 100644 --- a/spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java +++ b/spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java @@ -1,6 +1,6 @@ package com.baeldung.spring.jms; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -10,11 +10,11 @@ import com.baeldung.spring.jms.SampleJmsMessageSender; public class MapMessageConvertAndSendTest { - private SampleJmsMessageSender messageProducer; + private static SampleJmsMessageSender messageProducer; @SuppressWarnings("resource") - @Before - public void setUp() { + @BeforeClass + public static void setUp() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml" }); messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); } From 02a1c2d114f43604baaeeb0a52efabd063ea934f Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 9 Oct 2016 20:36:41 +0200 Subject: [PATCH 025/193] Merge fix --- .../baeldung/spring/jms/DefaultTextMessageSenderTest.java | 3 +-- .../baeldung/spring/jms/MapMessageConvertAndSendTest.java | 5 ++--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java b/spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java index 2016122105..aceb551563 100644 --- a/spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java +++ b/spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java @@ -1,12 +1,11 @@ package com.baeldung.spring.jms; +import com.baeldung.spring.jms.SampleJmsMessageSender; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import com.baeldung.spring.jms.SampleJmsMessageSender; - public class DefaultTextMessageSenderTest { private static SampleJmsMessageSender messageProducer; diff --git a/spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java b/spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java index 19b9097601..d649938533 100644 --- a/spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java +++ b/spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java @@ -1,13 +1,12 @@ package com.baeldung.spring.jms; +import com.baeldung.spring.jms.Employee; +import com.baeldung.spring.jms.SampleJmsMessageSender; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import com.baeldung.spring.jms.Employee; -import com.baeldung.spring.jms.SampleJmsMessageSender; - public class MapMessageConvertAndSendTest { private static SampleJmsMessageSender messageProducer; From dd360db0605c335f0169817d94bfa59ff7641ddc Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 9 Oct 2016 21:21:09 +0200 Subject: [PATCH 026/193] Refactor JMS examples --- spring-jms/pom.xml | 22 ++++++-- .../spring/jms/SampleJmsMessageSender.java | 19 ++----- .../baeldung/spring/jms/SampleListener.java | 8 ++- .../spring/jms/SampleMessageConverter.java | 9 ++-- .../jms/DefaultTextMessageSenderTest.java | 50 +++++++++--------- .../jms/MapMessageConvertAndSendTest.java | 51 +++++++++---------- 6 files changed, 81 insertions(+), 78 deletions(-) rename spring-jms/src/test/{ => java}/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java (78%) rename spring-jms/src/test/{ => java}/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java (75%) diff --git a/spring-jms/pom.xml b/spring-jms/pom.xml index 8f78469989..b15c18f991 100644 --- a/spring-jms/pom.xml +++ b/spring-jms/pom.xml @@ -26,6 +26,12 @@ activemq-all ${activemq.version} + + junit + junit + 4.12 + test + @@ -36,8 +42,8 @@ maven-compiler-plugin 3.2 - 1.7 - 1.7 + 1.8 + 1.8 @@ -52,6 +58,16 @@ - spring-jms + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + spring-jms \ No newline at end of file diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java index 8751b42ff8..1ef3902a31 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java @@ -1,16 +1,11 @@ package com.baeldung.spring.jms; +import org.springframework.jms.core.JmsTemplate; + +import javax.jms.Queue; import java.util.HashMap; import java.util.Map; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Queue; -import javax.jms.Session; - -import org.springframework.jms.core.JmsTemplate; -import org.springframework.jms.core.MessageCreator; - public class SampleJmsMessageSender { private JmsTemplate jmsTemplate; @@ -25,16 +20,12 @@ public class SampleJmsMessageSender { } public void simpleSend() { - this.jmsTemplate.send(this.queue, new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - return session.createTextMessage("hello queue world"); - } - }); + jmsTemplate.send(queue, s -> s.createTextMessage("hello queue world")); } public void sendMessage(final Employee employee) { System.out.println("Jms Message Sender : " + employee); - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("name", employee.getName()); map.put("age", employee.getAge()); this.jmsTemplate.convertAndSend(map); diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java index 3ad4d70829..eb9d51160d 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java @@ -1,13 +1,12 @@ package com.baeldung.spring.jms; -import java.util.Map; +import org.springframework.jms.core.JmsTemplate; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; - -import org.springframework.jms.core.JmsTemplate; +import java.util.Map; public class SampleListener implements MessageListener { @@ -31,7 +30,6 @@ public class SampleListener implements MessageListener { public Employee receiveMessage() throws JMSException { Map map = (Map) getJmsTemplate().receiveAndConvert(); - Employee employee = new Employee((String) map.get("name"), (Integer) map.get("age")); - return employee; + return new Employee((String) map.get("name"), (Integer) map.get("age")); } } diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java index c61cd5bc89..368a62841f 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java @@ -1,13 +1,13 @@ package com.baeldung.spring.jms; +import org.springframework.jms.support.converter.MessageConversionException; +import org.springframework.jms.support.converter.MessageConverter; + import javax.jms.JMSException; import javax.jms.MapMessage; import javax.jms.Message; import javax.jms.Session; -import org.springframework.jms.support.converter.MessageConversionException; -import org.springframework.jms.support.converter.MessageConverter; - public class SampleMessageConverter implements MessageConverter { public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException { @@ -20,8 +20,7 @@ public class SampleMessageConverter implements MessageConverter { public Object fromMessage(Message message) throws JMSException, MessageConversionException { MapMessage mapMessage = (MapMessage) message; - Employee employee = new Employee(mapMessage.getString("name"), mapMessage.getInt("age")); - return employee; + return new Employee(mapMessage.getString("name"), mapMessage.getInt("age")); } } diff --git a/spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java b/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java similarity index 78% rename from spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java rename to spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java index aceb551563..439bc6caad 100644 --- a/spring-jms/src/test/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java +++ b/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java @@ -1,25 +1,25 @@ -package com.baeldung.spring.jms; - -import com.baeldung.spring.jms.SampleJmsMessageSender; -import org.junit.BeforeClass; -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class DefaultTextMessageSenderTest { - - private static SampleJmsMessageSender messageProducer; - - @SuppressWarnings("resource") - @BeforeClass - public static void setUp() { - ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml" }); - messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); - } - - @Test - public void testSimpleSend() { - messageProducer.simpleSend(); - } - -} +package com.baeldung.spring.jms; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class DefaultTextMessageSenderTest { + + private static SampleJmsMessageSender messageProducer; + + @SuppressWarnings("resource") + @BeforeClass + public static void setUp() { + ApplicationContext applicationContext = new ClassPathXmlApplicationContext( + "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); + messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); + } + + @Test + public void testSimpleSend() { + messageProducer.simpleSend(); + } + +} diff --git a/spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java b/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java similarity index 75% rename from spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java rename to spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java index d649938533..da9bb0294d 100644 --- a/spring-jms/src/test/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java +++ b/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java @@ -1,26 +1,25 @@ -package com.baeldung.spring.jms; - -import com.baeldung.spring.jms.Employee; -import com.baeldung.spring.jms.SampleJmsMessageSender; -import org.junit.BeforeClass; -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class MapMessageConvertAndSendTest { - - private static SampleJmsMessageSender messageProducer; - - @SuppressWarnings("resource") - @BeforeClass - public static void setUp() { - ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml" }); - messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); - } - - @Test - public void testSendMessage() { - messageProducer.sendMessage(new Employee("JavaDeveloper2", 22)); - } - -} +package com.baeldung.spring.jms; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class MapMessageConvertAndSendTest { + + private static SampleJmsMessageSender messageProducer; + + @SuppressWarnings("resource") + @BeforeClass + public static void setUp() { + ApplicationContext applicationContext = new ClassPathXmlApplicationContext( + "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); + messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); + } + + @Test + public void testSendMessage() { + messageProducer.sendMessage(new Employee("JavaDeveloper2", 22)); + } + +} From 423dc63cdd0f3f5bb214f04432abf2fda5b2f2d0 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Mon, 10 Oct 2016 00:34:11 +0200 Subject: [PATCH 027/193] BAEL-226 - Source code for wicket --- .../wicket/examples/{Examples.html => HelloWorld.html} | 0 .../wicket/examples/{Examples.java => HelloWorld.java} | 2 +- ...{ExamplesApplication.java => HelloWorldApplication.java} | 5 ++--- .../java/com/baeldung/wicket/examples/TestHomePage.java | 6 +++--- wicket/src/main/webapp/WEB-INF/web.xml | 2 +- 5 files changed, 7 insertions(+), 8 deletions(-) rename wicket/src/main/java/com/baeldung/wicket/examples/{Examples.html => HelloWorld.html} (100%) rename wicket/src/main/java/com/baeldung/wicket/examples/{Examples.java => HelloWorld.java} (77%) rename wicket/src/main/java/com/baeldung/wicket/examples/{ExamplesApplication.java => HelloWorldApplication.java} (80%) diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/Examples.html b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.html similarity index 100% rename from wicket/src/main/java/com/baeldung/wicket/examples/Examples.html rename to wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.html diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/Examples.java b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.java similarity index 77% rename from wicket/src/main/java/com/baeldung/wicket/examples/Examples.java rename to wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.java index 358e4f7b19..ceb0836467 100644 --- a/wicket/src/main/java/com/baeldung/wicket/examples/Examples.java +++ b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.java @@ -2,7 +2,7 @@ package com.baeldung.wicket.examples; import org.apache.wicket.markup.html.WebPage; -public class Examples extends WebPage { +public class HelloWorld extends WebPage { private static final long serialVersionUID = 1L; diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/ExamplesApplication.java b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorldApplication.java similarity index 80% rename from wicket/src/main/java/com/baeldung/wicket/examples/ExamplesApplication.java rename to wicket/src/main/java/com/baeldung/wicket/examples/HelloWorldApplication.java index 711e8f01fd..079280adce 100644 --- a/wicket/src/main/java/com/baeldung/wicket/examples/ExamplesApplication.java +++ b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorldApplication.java @@ -4,15 +4,14 @@ import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.protocol.http.WebApplication; import com.baeldung.wicket.examples.cafeaddress.CafeAddress; -import com.baeldung.wicket.examples.helloworld.HelloWorld; -public class ExamplesApplication extends WebApplication { +public class HelloWorldApplication extends WebApplication { /** * @see org.apache.wicket.Application#getHomePage() */ @Override public Class getHomePage() { - return Examples.class; + return HelloWorld.class; } /** diff --git a/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java b/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java index a393f1d178..7015ffd255 100644 --- a/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java +++ b/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java @@ -9,15 +9,15 @@ public class TestHomePage { @Before public void setUp() { - tester = new WicketTester(new ExamplesApplication()); + tester = new WicketTester(new HelloWorldApplication()); } @Test public void whenPageInvoked_thanRenderedOK() { //start and render the test page - tester.startPage(Examples.class); + tester.startPage(HelloWorld.class); //assert rendered page class - tester.assertRenderedPage(Examples.class); + tester.assertRenderedPage(HelloWorld.class); } } diff --git a/wicket/src/main/webapp/WEB-INF/web.xml b/wicket/src/main/webapp/WEB-INF/web.xml index 8a4451c80e..8fc1b1aa95 100644 --- a/wicket/src/main/webapp/WEB-INF/web.xml +++ b/wicket/src/main/webapp/WEB-INF/web.xml @@ -21,7 +21,7 @@ org.apache.wicket.protocol.http.WicketFilter applicationClassName - com.baeldung.wicket.examples.ExamplesApplication + com.baeldung.wicket.examples.HelloWorldApplication From b8161aca1a5a9b46931c11b1dabaa5ebb0a009af Mon Sep 17 00:00:00 2001 From: maverick Date: Mon, 10 Oct 2016 08:14:51 +0530 Subject: [PATCH 028/193] Java sorting. Adding required files. This is commit for starting from new fork due to conflicts in PR. --- .../org/baeldung/java/sorting/Employee.java | 58 +++++ .../baeldung/java/sorting/JavaSorting.java | 211 ++++++++++++++++++ 2 files changed, 269 insertions(+) create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/Employee.java create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java diff --git a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java new file mode 100644 index 0000000000..c48cdd91a8 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java @@ -0,0 +1,58 @@ +package org.baeldung.java.sorting; + +public class Employee implements Comparable { + private String name; + private int age; + private double salary; + + public Employee() { + } + + public Employee(String name, int age, double salary) { + super(); + this.name = name; + this.age = age; + this.salary = salary; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + + @Override + public String toString() { + return "(" + name + "," + age + "," + salary + ")"; + + } + + @Override + public boolean equals(Object obj) { + return ((Employee) obj).getName().equals(getName()); + } + + @Override + public int compareTo(Object o) { + Employee e = (Employee) o; + return getName().compareTo(e.getName()); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java b/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java new file mode 100644 index 0000000000..54d58dc87c --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java @@ -0,0 +1,211 @@ +package org.baeldung.java.sorting; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.junit.Test; + +public class JavaSorting { + + @Test + public void givenIntArray_whenUsingSort_thenSortedArray() { + int [] numbers = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }, + sortedInts = {1, 5, 7, 66, 88, 89, 123, 200, 255}; + + Arrays.sort(numbers); + + assertTrue(Arrays.equals(numbers, sortedInts)); + } + + @Test + public void givenIntegerArray_whenUsingSort_thenSortedArray() { + Integer[] integers = new Integer[] + { 5, 1, 89, 255, 7, 88, 200, 123, 66 }, + sortedIntegers = {1, 5, 7, 66, 88, 89, 123, 200, 255}; + + + Arrays.sort(integers, new Comparator() { + @Override + public int compare(Integer a, Integer b) { + return a - b; + } + }); + + assertTrue(Arrays.equals(integers, sortedIntegers)); + } + + @Test + public void givenArray_whenUsingSortWithLambdas_thenSortedArray() { + Integer[] integers = new Integer[] + { 5, 1, 89, 255, 7, 88, 200, 123, 66 }, + sortedIntegers = {1, 5, 7, 66, 88, 89, 123, 200, 255}; + + Arrays.sort(integers, (a, b) -> { + return a - b; + }); + + assertTrue(Arrays.equals(integers, sortedIntegers)); + } + + @Test + public void givenEmpArray_SortEmpArray_thenSortedArrayinNaturalOrder() { + Employee[] employees = new Employee[] { + new Employee("John", 23, 5000), + new Employee("Steve", 26, 6000), + new Employee("Frank", 33, 7000), + new Employee("Earl", 43, 10000), + new Employee("Jessica", 23, 4000), + new Employee("Pearl", 33, 6000)}; + Employee[] employeesSorted = new Employee[] { + new Employee("Earl", 43, 10000), + new Employee("Frank", 33, 70000), + new Employee("Jessica", 23, 4000), + new Employee("John", 23, 5000), + new Employee("Pearl", 33, 4000), + new Employee("Steve", 26, 6000)}; + + Arrays.sort(employees); + + assertTrue(Arrays.equals(employees, employeesSorted)); + } + + + @Test + public void givenIntArray_whenUsingRangeSort_thenRangeSortedArray() { + int [] numbers = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }, + sortedRangeInts = {5, 1, 89, 7, 88, 200, 255, 123, 66}; + + Arrays.sort(numbers, 3, 7); + + assertTrue(Arrays.equals(numbers, sortedRangeInts)); + } + + @Test + public void givenIntArray_whenUsingParallelSort_thenParallelSortedArray() { + int [] numbers = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }, + sortedInts = {1, 5, 7, 66, 88, 89, 123, 200, 255}; + + Arrays.parallelSort(numbers); + + assertTrue(Arrays.equals(numbers, sortedInts)); + } + + + + @Test + public void givenArrayObjects_whenUsingComparing_thenSortedArrayObjects() { + List employees = Arrays.asList(new Employee[] { new Employee("John", 23, 5000), + new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), + new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), + new Employee("Pearl", 33, 6000) }); + Employee[] employeesSorted = new Employee[] { + new Employee("John", 23, 5000), + new Employee("Jessica", 23, 4000), + new Employee("Steve", 26, 6000), + new Employee("Frank", 33, 70000), + new Employee("Pearl", 33, 4000), + new Employee("Earl", 43, 10000)}; + + employees.sort(Comparator.comparing(Employee::getAge));//.thenComparing(Employee::getName)); + + assertTrue(Arrays.equals(employees.toArray(), employeesSorted)); + } + + @Test + public void givenList_whenUsingSort_thenSortedList() { + List integers = Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }), + sortedIntegers = Arrays.asList(new Integer[] {1, 5, 7, 66, 88, 89, 123, 200, 255}); + + Collections.sort(integers); + + assertTrue(Arrays.equals(integers.toArray(), sortedIntegers.toArray())); + } + + @Test + public void givenMap_whenSortingByKeys_thenSortedMap() { + HashMap map = new HashMap<>(); + map.put(55, "John"); + map.put(22, "Apple"); + map.put(66, "Earl"); + map.put(77, "Pearl"); + map.put(12, "George"); + map.put(6, "Rocky"); + Integer[] sortedKeys = new Integer[] { 6, 12, 22, 55, 66, 77 }; + + List> entries = new ArrayList<>(map.entrySet()); + Collections.sort(entries, new Comparator>() { + @Override + public int compare(Entry o1, Entry o2) { + return o1.getKey().compareTo(o2.getKey()); + } + }); + HashMap sortedMap = new LinkedHashMap<>(); + for (Map.Entry entry : entries) { + sortedMap.put(entry.getKey(), entry.getValue()); + } + + assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys)); + } + + @Test + public void givenMap_whenSortingByValues_thenSortedMap() { + HashMap map = new HashMap<>(); + map.put(55, "John"); + map.put(22, "Apple"); + map.put(66, "Earl"); + map.put(77, "Pearl"); + map.put(12, "George"); + map.put(6, "Rocky"); + String[] sortedValues = new String[] + { "Apple", "Earl", "George", "John", "Pearl", "Rocky" }; + + List> entries = new ArrayList<>(map.entrySet()); + Collections.sort(entries, new Comparator>() { + @Override + public int compare(Entry o1, Entry o2) { + return o1.getValue().compareTo(o2.getValue()); + } + }); + HashMap sortedMap = new LinkedHashMap<>(); + for (Map.Entry entry : entries) { + sortedMap.put(entry.getKey(), entry.getValue()); + } + + assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues)); + } + + + + + + + @Test + public void givenSet_whenUsingSort_thenSortedSet() { + HashSet integers = new LinkedHashSet<>(Arrays.asList(new Integer[] + { 5, 1, 89, 255, 7, 88, 200, 123, 66 })), + sortedIntegers = new LinkedHashSet<>(Arrays.asList(new Integer[] + {255, 200, 123, 89, 88, 66, 7, 5, 1})); + + ArrayList list = new ArrayList(integers); + Collections.sort(list, (i1, i2) -> { + return i2 - i1; + }); + integers = new LinkedHashSet<>(list); + + assertTrue(Arrays.equals(integers.toArray(), sortedIntegers.toArray())); + } + + + +} From 9f3c791d99dc3550f8330fc1f5fcbd9f7dfb9883 Mon Sep 17 00:00:00 2001 From: maverick Date: Mon, 10 Oct 2016 08:30:54 +0530 Subject: [PATCH 029/193] Added files missed in earlier PR --- core-java/src/test/resources/test_md5.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 core-java/src/test/resources/test_md5.txt diff --git a/core-java/src/test/resources/test_md5.txt b/core-java/src/test/resources/test_md5.txt new file mode 100644 index 0000000000..95d09f2b10 --- /dev/null +++ b/core-java/src/test/resources/test_md5.txt @@ -0,0 +1 @@ +hello world \ No newline at end of file From 6df151a3f98950940ea4a8de491eb09fb6f976ab Mon Sep 17 00:00:00 2001 From: maverick Date: Mon, 10 Oct 2016 08:32:51 +0530 Subject: [PATCH 030/193] Removes Sorting changes for this PR --- .../org/baeldung/java/sorting/Employee.java | 58 ----- .../baeldung/java/sorting/JavaSorting.java | 211 ------------------ 2 files changed, 269 deletions(-) delete mode 100644 core-java/src/test/java/org/baeldung/java/sorting/Employee.java delete mode 100644 core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java diff --git a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java deleted file mode 100644 index c48cdd91a8..0000000000 --- a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.baeldung.java.sorting; - -public class Employee implements Comparable { - private String name; - private int age; - private double salary; - - public Employee() { - } - - public Employee(String name, int age, double salary) { - super(); - this.name = name; - this.age = age; - this.salary = salary; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public double getSalary() { - return salary; - } - - public void setSalary(double salary) { - this.salary = salary; - } - - @Override - public String toString() { - return "(" + name + "," + age + "," + salary + ")"; - - } - - @Override - public boolean equals(Object obj) { - return ((Employee) obj).getName().equals(getName()); - } - - @Override - public int compareTo(Object o) { - Employee e = (Employee) o; - return getName().compareTo(e.getName()); - } -} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java b/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java deleted file mode 100644 index 54d58dc87c..0000000000 --- a/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java +++ /dev/null @@ -1,211 +0,0 @@ -package org.baeldung.java.sorting; - -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.junit.Test; - -public class JavaSorting { - - @Test - public void givenIntArray_whenUsingSort_thenSortedArray() { - int [] numbers = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }, - sortedInts = {1, 5, 7, 66, 88, 89, 123, 200, 255}; - - Arrays.sort(numbers); - - assertTrue(Arrays.equals(numbers, sortedInts)); - } - - @Test - public void givenIntegerArray_whenUsingSort_thenSortedArray() { - Integer[] integers = new Integer[] - { 5, 1, 89, 255, 7, 88, 200, 123, 66 }, - sortedIntegers = {1, 5, 7, 66, 88, 89, 123, 200, 255}; - - - Arrays.sort(integers, new Comparator() { - @Override - public int compare(Integer a, Integer b) { - return a - b; - } - }); - - assertTrue(Arrays.equals(integers, sortedIntegers)); - } - - @Test - public void givenArray_whenUsingSortWithLambdas_thenSortedArray() { - Integer[] integers = new Integer[] - { 5, 1, 89, 255, 7, 88, 200, 123, 66 }, - sortedIntegers = {1, 5, 7, 66, 88, 89, 123, 200, 255}; - - Arrays.sort(integers, (a, b) -> { - return a - b; - }); - - assertTrue(Arrays.equals(integers, sortedIntegers)); - } - - @Test - public void givenEmpArray_SortEmpArray_thenSortedArrayinNaturalOrder() { - Employee[] employees = new Employee[] { - new Employee("John", 23, 5000), - new Employee("Steve", 26, 6000), - new Employee("Frank", 33, 7000), - new Employee("Earl", 43, 10000), - new Employee("Jessica", 23, 4000), - new Employee("Pearl", 33, 6000)}; - Employee[] employeesSorted = new Employee[] { - new Employee("Earl", 43, 10000), - new Employee("Frank", 33, 70000), - new Employee("Jessica", 23, 4000), - new Employee("John", 23, 5000), - new Employee("Pearl", 33, 4000), - new Employee("Steve", 26, 6000)}; - - Arrays.sort(employees); - - assertTrue(Arrays.equals(employees, employeesSorted)); - } - - - @Test - public void givenIntArray_whenUsingRangeSort_thenRangeSortedArray() { - int [] numbers = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }, - sortedRangeInts = {5, 1, 89, 7, 88, 200, 255, 123, 66}; - - Arrays.sort(numbers, 3, 7); - - assertTrue(Arrays.equals(numbers, sortedRangeInts)); - } - - @Test - public void givenIntArray_whenUsingParallelSort_thenParallelSortedArray() { - int [] numbers = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }, - sortedInts = {1, 5, 7, 66, 88, 89, 123, 200, 255}; - - Arrays.parallelSort(numbers); - - assertTrue(Arrays.equals(numbers, sortedInts)); - } - - - - @Test - public void givenArrayObjects_whenUsingComparing_thenSortedArrayObjects() { - List employees = Arrays.asList(new Employee[] { new Employee("John", 23, 5000), - new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), - new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), - new Employee("Pearl", 33, 6000) }); - Employee[] employeesSorted = new Employee[] { - new Employee("John", 23, 5000), - new Employee("Jessica", 23, 4000), - new Employee("Steve", 26, 6000), - new Employee("Frank", 33, 70000), - new Employee("Pearl", 33, 4000), - new Employee("Earl", 43, 10000)}; - - employees.sort(Comparator.comparing(Employee::getAge));//.thenComparing(Employee::getName)); - - assertTrue(Arrays.equals(employees.toArray(), employeesSorted)); - } - - @Test - public void givenList_whenUsingSort_thenSortedList() { - List integers = Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }), - sortedIntegers = Arrays.asList(new Integer[] {1, 5, 7, 66, 88, 89, 123, 200, 255}); - - Collections.sort(integers); - - assertTrue(Arrays.equals(integers.toArray(), sortedIntegers.toArray())); - } - - @Test - public void givenMap_whenSortingByKeys_thenSortedMap() { - HashMap map = new HashMap<>(); - map.put(55, "John"); - map.put(22, "Apple"); - map.put(66, "Earl"); - map.put(77, "Pearl"); - map.put(12, "George"); - map.put(6, "Rocky"); - Integer[] sortedKeys = new Integer[] { 6, 12, 22, 55, 66, 77 }; - - List> entries = new ArrayList<>(map.entrySet()); - Collections.sort(entries, new Comparator>() { - @Override - public int compare(Entry o1, Entry o2) { - return o1.getKey().compareTo(o2.getKey()); - } - }); - HashMap sortedMap = new LinkedHashMap<>(); - for (Map.Entry entry : entries) { - sortedMap.put(entry.getKey(), entry.getValue()); - } - - assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys)); - } - - @Test - public void givenMap_whenSortingByValues_thenSortedMap() { - HashMap map = new HashMap<>(); - map.put(55, "John"); - map.put(22, "Apple"); - map.put(66, "Earl"); - map.put(77, "Pearl"); - map.put(12, "George"); - map.put(6, "Rocky"); - String[] sortedValues = new String[] - { "Apple", "Earl", "George", "John", "Pearl", "Rocky" }; - - List> entries = new ArrayList<>(map.entrySet()); - Collections.sort(entries, new Comparator>() { - @Override - public int compare(Entry o1, Entry o2) { - return o1.getValue().compareTo(o2.getValue()); - } - }); - HashMap sortedMap = new LinkedHashMap<>(); - for (Map.Entry entry : entries) { - sortedMap.put(entry.getKey(), entry.getValue()); - } - - assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues)); - } - - - - - - - @Test - public void givenSet_whenUsingSort_thenSortedSet() { - HashSet integers = new LinkedHashSet<>(Arrays.asList(new Integer[] - { 5, 1, 89, 255, 7, 88, 200, 123, 66 })), - sortedIntegers = new LinkedHashSet<>(Arrays.asList(new Integer[] - {255, 200, 123, 89, 88, 66, 7, 5, 1})); - - ArrayList list = new ArrayList(integers); - Collections.sort(list, (i1, i2) -> { - return i2 - i1; - }); - integers = new LinkedHashSet<>(list); - - assertTrue(Arrays.equals(integers.toArray(), sortedIntegers.toArray())); - } - - - -} From 687b7e0044d3ec8ace6921e5ccdac3a84a8e6362 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 10 Oct 2016 06:46:31 +0200 Subject: [PATCH 031/193] Refactor Wicket examples --- .../examples/cafeaddress/CafeAddress.java | 33 ++++++++----------- .../examples/helloworld/HelloWorld.java | 3 -- 2 files changed, 14 insertions(+), 22 deletions(-) diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java b/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java index ce26c5a1ad..86820393c7 100644 --- a/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java +++ b/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java @@ -1,10 +1,5 @@ package com.baeldung.wicket.examples.cafeaddress; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.markup.html.WebPage; @@ -13,29 +8,29 @@ import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.mapper.parameter.PageParameters; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + public class CafeAddress extends WebPage { - - private static final long serialVersionUID = 1L; - - String selectedCafe; - Address address; - Map cafeNamesAndAddresses = new HashMap<>(); + private String selectedCafe; + private Address address; + private Map cafeNamesAndAddresses = new HashMap<>(); public CafeAddress(final PageParameters parameters) { super(parameters); initCafes(); - ArrayList cafeNames = new ArrayList<>(this.cafeNamesAndAddresses.keySet()); - this.selectedCafe = cafeNames.get(0); - this.address = new Address(this.cafeNamesAndAddresses.get(this.selectedCafe).getAddress()); + ArrayList cafeNames = new ArrayList<>(cafeNamesAndAddresses.keySet()); + selectedCafe = cafeNames.get(0); + address = new Address(cafeNamesAndAddresses.get(selectedCafe).getAddress()); final Label addressLabel = new Label("address", new PropertyModel(this.address, "address")); addressLabel.setOutputMarkupId(true); - final DropDownChoice cafeDropdown = new DropDownChoice<>("cafes", new PropertyModel(this, "selectedCafe"), cafeNames); + final DropDownChoice cafeDropdown = new DropDownChoice<>("cafes", new PropertyModel<>(this, "selectedCafe"), cafeNames); cafeDropdown.add(new AjaxFormComponentUpdatingBehavior("onchange") { - private static final long serialVersionUID = 1L; - @Override protected void onUpdate(AjaxRequestTarget target) { String name = (String) cafeDropdown.getDefaultModel().getObject(); @@ -61,11 +56,11 @@ public class CafeAddress extends WebPage { this.sAddress = address; } - public String getAddress() { + String getAddress() { return this.sAddress; } - public void setAddress(String address) { + void setAddress(String address) { this.sAddress = address; } } diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java b/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java index f819e05be6..6dc7295798 100644 --- a/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java +++ b/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java @@ -4,9 +4,6 @@ import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; public class HelloWorld extends WebPage { - - private static final long serialVersionUID = 1L; - public HelloWorld() { add(new Label("hello", "Hello World!")); } From 9da1680d0f618f1f788d0d8e5fb5006d7b843fab Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 10 Oct 2016 07:09:47 +0200 Subject: [PATCH 032/193] Refactor readFromInputStream --- .../com/baeldung/file/FileOperationsTest.java | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java index 3752fc5b7f..1e4f23745c 100644 --- a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java +++ b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java @@ -107,17 +107,14 @@ public class FileOperationsTest { } private String readFromInputStream(InputStream inputStream) throws IOException { - InputStreamReader inputStreamReader = new InputStreamReader(inputStream); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder resultStringBuilder = new StringBuilder(); - String line; - while ((line = bufferedReader.readLine()) != null) { - resultStringBuilder.append(line); - resultStringBuilder.append("\n"); + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + resultStringBuilder.append(line); + resultStringBuilder.append("\n"); + } } - bufferedReader.close(); - inputStreamReader.close(); - inputStream.close(); return resultStringBuilder.toString(); } } \ No newline at end of file From fa1fc3cbe7b5509a7147ea8d1c210d6eb8c3c187 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 10 Oct 2016 07:11:06 +0200 Subject: [PATCH 033/193] Refactor readFromInputStream --- .../src/test/java/com/baeldung/file/FileOperationsTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java index 1e4f23745c..30f6fc713f 100644 --- a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java +++ b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java @@ -111,8 +111,7 @@ public class FileOperationsTest { try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = bufferedReader.readLine()) != null) { - resultStringBuilder.append(line); - resultStringBuilder.append("\n"); + resultStringBuilder.append(line).append("\n"); } } return resultStringBuilder.toString(); From 94fd47d9bb96fe7cb69f5db3b3222a1df049b397 Mon Sep 17 00:00:00 2001 From: Egima profile Date: Mon, 10 Oct 2016 11:14:19 +0300 Subject: [PATCH 034/193] Added test suite, removed bad names (#732) * made changes to java reflection * removed redundant method makeSound in Animal abstract class * added project for play-framework article * added project for regex * changed regex project from own model to core-java * added project for routing in play * made changes to regex project * refactored code for REST API with Play project * refactored student store indexing to zero base * added unit tests, removed bad names --- .../student-api/test/ApplicationTest.java | 203 ++++++++++++++---- .../student-api/test/IntegrationTest.java | 25 --- 2 files changed, 165 insertions(+), 63 deletions(-) delete mode 100644 play-framework/student-api/test/IntegrationTest.java diff --git a/play-framework/student-api/test/ApplicationTest.java b/play-framework/student-api/test/ApplicationTest.java index 3d7c4875aa..1133978e9a 100644 --- a/play-framework/student-api/test/ApplicationTest.java +++ b/play-framework/student-api/test/ApplicationTest.java @@ -1,45 +1,172 @@ -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import com.fasterxml.jackson.databind.JsonNode; -import org.junit.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -import play.mvc.*; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Arrays; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import model.Student; import play.test.*; -import play.data.DynamicForm; -import play.data.validation.ValidationError; -import play.data.validation.Constraints.RequiredValidator; -import play.i18n.Lang; -import play.libs.F; -import play.libs.F.*; -import play.twirl.api.Content; - import static play.test.Helpers.*; -import static org.junit.Assert.*; - - -/** - * - * Simple (JUnit) tests that can call all parts of a play app. - * If you are interested in mocking a whole application, see the wiki for more details. - * - */ -public class ApplicationTest { - - @Test - public void simpleCheck() { - int a = 1 + 1; - assertEquals(2, a); - } - - @Test - public void renderTemplate() { - Content html = views.html.index.render("Your new application is ready."); - assertEquals("text/html", html.contentType()); - assertTrue(html.body().contains("Your new application is ready.")); - } +public class ApplicationTest{ + private static final String BASE_URL = "http://localhost:9000"; + @Test +public void testInServer() throws Exception { + TestServer server = testServer(3333); + running(server, () -> { + try { + WSClient ws = play.libs.ws.WS.newClient(3333); + CompletionStage completionStage = ws.url("/").get(); + WSResponse response = completionStage.toCompletableFuture().get(); + ws.close(); + assertEquals(OK, response.getStatus()); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }); +} + @Test + public void whenCreatesRecord_thenCorrect() { + Student student = new Student("jody", "west", 50); + JSONObject obj = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))); + assertTrue(obj.getBoolean("isSuccessfull")); + JSONObject body = obj.getJSONObject("body"); + assertEquals(student.getAge(), body.getInt("age")); + assertEquals(student.getFirstName(), body.getString("firstName")); + assertEquals(student.getLastName(), body.getString("lastName")); + } + + @Test + public void whenDeletesCreatedRecord_thenCorrect() { + Student student = new Student("Usain", "Bolt", 25); + JSONObject ob1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body"); + int id = ob1.getInt("id"); + JSONObject obj1 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject())); + assertTrue(obj1.getBoolean("isSuccessfull")); + makeRequest(BASE_URL + "/" + id, "DELETE", null); + JSONObject obj2 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject())); + assertFalse(obj2.getBoolean("isSuccessfull")); + } + + @Test + public void whenUpdatesCreatedRecord_thenCorrect() { + Student student = new Student("john", "doe", 50); + JSONObject body1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body"); + assertEquals(student.getAge(), body1.getInt("age")); + int newAge = 60; + body1.put("age", newAge); + JSONObject body2 = new JSONObject(makeRequest(BASE_URL, "PUT", body1)).getJSONObject("body"); + assertFalse(student.getAge() == body2.getInt("age")); + assertTrue(newAge == body2.getInt("age")); + } + + @Test + public void whenGetsAllRecords_thenCorrect() { + Student student1 = new Student("jane", "daisy", 50); + Student student2 = new Student("john", "daniel", 60); + Student student3 = new Student("don", "mason", 55); + Student student4 = new Student("scarlet", "ohara", 90); + + makeRequest(BASE_URL, "POST", new JSONObject(student1)); + makeRequest(BASE_URL, "POST", new JSONObject(student2)); + makeRequest(BASE_URL, "POST", new JSONObject(student3)); + makeRequest(BASE_URL, "POST", new JSONObject(student4)); + + JSONObject objects = new JSONObject(makeRequest(BASE_URL, "GET", null)); + assertTrue(objects.getBoolean("isSuccessfull")); + JSONArray array = objects.getJSONArray("body"); + assertTrue(array.length() >= 4); + } + + public static String makeRequest(String myUrl, String httpMethod, JSONObject parameters) { + + URL url = null; + try { + url = new URL(myUrl); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + HttpURLConnection conn = null; + try { + + conn = (HttpURLConnection) url.openConnection(); + } catch (IOException e) { + e.printStackTrace(); + } + conn.setDoInput(true); + + conn.setReadTimeout(10000); + + conn.setRequestProperty("Content-Type", "application/json"); + DataOutputStream dos = null; + int respCode = 0; + String inputString = null; + try { + conn.setRequestMethod(httpMethod); + + if (Arrays.asList("POST", "PUT").contains(httpMethod)) { + String params = parameters.toString(); + + conn.setDoOutput(true); + + dos = new DataOutputStream(conn.getOutputStream()); + dos.writeBytes(params); + dos.flush(); + dos.close(); + } + respCode = conn.getResponseCode(); + if (respCode != 200 && respCode != 201) { + String error = inputStreamToString(conn.getErrorStream()); + return error; + } + inputString = inputStreamToString(conn.getInputStream()); + + } catch (IOException e) { + + e.printStackTrace(); + } + return inputString; + } + + public static String inputStreamToString(InputStream is) { + BufferedReader br = null; + StringBuilder sb = new StringBuilder(); + + String line; + try { + + br = new BufferedReader(new InputStreamReader(is)); + while ((line = br.readLine()) != null) { + sb.append(line); + } + + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return sb.toString(); + + } } diff --git a/play-framework/student-api/test/IntegrationTest.java b/play-framework/student-api/test/IntegrationTest.java deleted file mode 100644 index c53c71e124..0000000000 --- a/play-framework/student-api/test/IntegrationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -import org.junit.*; - -import play.mvc.*; -import play.test.*; - -import static play.test.Helpers.*; -import static org.junit.Assert.*; - -import static org.fluentlenium.core.filter.FilterConstructor.*; - -public class IntegrationTest { - - /** - * add your integration test here - * in this example we just check if the welcome page is being shown - */ - @Test - public void test() { - running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, browser -> { - browser.goTo("http://localhost:3333"); - assertTrue(browser.pageSource().contains("Your new application is ready.")); - }); - } - -} From 24e560a1dda6c2a89a67238628c7e5cad0456dbb Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Mon, 10 Oct 2016 11:58:44 +0200 Subject: [PATCH 035/193] BAEL-39 - upgrading versions --- log4j/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/log4j/pom.xml b/log4j/pom.xml index 1081513dcf..ab384d4dd1 100644 --- a/log4j/pom.xml +++ b/log4j/pom.xml @@ -20,12 +20,12 @@ org.apache.logging.log4j log4j-api - 2.6 + 2.7 org.apache.logging.log4j log4j-core - 2.6 + 2.7 From 798b624a90caaac73819d075cfc9f7067a97bc02 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 10 Oct 2016 18:54:01 +0200 Subject: [PATCH 036/193] Refactor CurrentDateTimeTest --- .../com/baeldung/file/FileOperationsTest.java | 1 + .../baeldung/util/CurrentDateTimeTest.java | 24 ++++--------------- 2 files changed, 5 insertions(+), 20 deletions(-) diff --git a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java index 30f6fc713f..12143c3c19 100644 --- a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java +++ b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java @@ -114,6 +114,7 @@ public class FileOperationsTest { resultStringBuilder.append(line).append("\n"); } } + return resultStringBuilder.toString(); } } \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java index 599d5a5894..da9027060e 100644 --- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java +++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java @@ -1,31 +1,15 @@ package com.baeldung.util; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; +import org.junit.Test; -import java.time.Clock; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalTime; -import java.time.ZoneId; +import java.time.*; import java.time.temporal.ChronoField; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mockito.Mockito; +import static org.junit.Assert.assertEquals; public class CurrentDateTimeTest { - private static Clock clock; - - @BeforeClass - public static void setup() { - final Instant currentTime = Instant.parse("2016-10-09T15:10:30.00Z"); - - clock = Mockito.mock(Clock.class); - when(clock.instant()).thenAnswer((invocation) -> currentTime); - when(clock.getZone()).thenAnswer((invocation) -> ZoneId.of("UTC")); - } + private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC")); @Test public void shouldReturnCurrentDate() { From f2bbe6341f5aa40eff70f987534377eb7649a1a7 Mon Sep 17 00:00:00 2001 From: Thai Nguyen Date: Tue, 11 Oct 2016 00:00:28 +0700 Subject: [PATCH 037/193] Renames a sub-directory of Apache CXF --- .../{jaxrs-implementation => cxf-jaxrs-implementation}/pom.xml | 0 .../main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java | 0 .../main/java/com/baeldung/cxf/jaxrs/implementation/Course.java | 0 .../java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java | 0 .../main/java/com/baeldung/cxf/jaxrs/implementation/Student.java | 0 .../src/main/resources/course.xml | 0 .../src/main/resources/student.xml | 0 .../java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java | 0 8 files changed, 0 insertions(+), 0 deletions(-) rename apache-cxf/{jaxrs-implementation => cxf-jaxrs-implementation}/pom.xml (100%) rename apache-cxf/{jaxrs-implementation => cxf-jaxrs-implementation}/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java (100%) rename apache-cxf/{jaxrs-implementation => cxf-jaxrs-implementation}/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java (100%) rename apache-cxf/{jaxrs-implementation => cxf-jaxrs-implementation}/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java (100%) rename apache-cxf/{jaxrs-implementation => cxf-jaxrs-implementation}/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java (100%) rename apache-cxf/{jaxrs-implementation => cxf-jaxrs-implementation}/src/main/resources/course.xml (100%) rename apache-cxf/{jaxrs-implementation => cxf-jaxrs-implementation}/src/main/resources/student.xml (100%) rename apache-cxf/{jaxrs-implementation => cxf-jaxrs-implementation}/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java (100%) diff --git a/apache-cxf/jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml similarity index 100% rename from apache-cxf/jaxrs-implementation/pom.xml rename to apache-cxf/cxf-jaxrs-implementation/pom.xml diff --git a/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java similarity index 100% rename from apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java rename to apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java diff --git a/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java similarity index 100% rename from apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java rename to apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java diff --git a/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java similarity index 100% rename from apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java rename to apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java diff --git a/apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java similarity index 100% rename from apache-cxf/jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java rename to apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java diff --git a/apache-cxf/jaxrs-implementation/src/main/resources/course.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/course.xml similarity index 100% rename from apache-cxf/jaxrs-implementation/src/main/resources/course.xml rename to apache-cxf/cxf-jaxrs-implementation/src/main/resources/course.xml diff --git a/apache-cxf/jaxrs-implementation/src/main/resources/student.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/student.xml similarity index 100% rename from apache-cxf/jaxrs-implementation/src/main/resources/student.xml rename to apache-cxf/cxf-jaxrs-implementation/src/main/resources/student.xml diff --git a/apache-cxf/jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java similarity index 100% rename from apache-cxf/jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java rename to apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java From 9c5a0ff10f913b466216d9e938b31561846b81e6 Mon Sep 17 00:00:00 2001 From: Kiran Date: Tue, 11 Oct 2016 03:30:54 -0400 Subject: [PATCH 038/193] Removed unnecessary code and SOP statements (#736) --- .../java/com/baeldung/spring/jms/SampleJmsMessageSender.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java index 1ef3902a31..cfbfc77a75 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java @@ -24,10 +24,6 @@ public class SampleJmsMessageSender { } public void sendMessage(final Employee employee) { - System.out.println("Jms Message Sender : " + employee); - Map map = new HashMap<>(); - map.put("name", employee.getName()); - map.put("age", employee.getAge()); this.jmsTemplate.convertAndSend(map); } } From 805c472ed6e57cfe18769e0db71f41b85534601a Mon Sep 17 00:00:00 2001 From: Kiran Date: Tue, 11 Oct 2016 03:31:10 -0400 Subject: [PATCH 039/193] Added useShutdownHook="false" (#735) Set the property useShutdownHook to false --- spring-jms/src/main/resources/EmbeddedActiveMQ.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-jms/src/main/resources/EmbeddedActiveMQ.xml b/spring-jms/src/main/resources/EmbeddedActiveMQ.xml index 5e956144fd..1db20b8f0f 100644 --- a/spring-jms/src/main/resources/EmbeddedActiveMQ.xml +++ b/spring-jms/src/main/resources/EmbeddedActiveMQ.xml @@ -9,10 +9,10 @@ http://activemq.apache.org/schema/core/activemq-core-5.2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> - + - \ No newline at end of file + From ea37b3e51af32964312cb10b30bf4ddf1eba647f Mon Sep 17 00:00:00 2001 From: Egima profile Date: Tue, 11 Oct 2016 10:33:14 +0300 Subject: [PATCH 040/193] Added NIO Selector project under core-java (#738) * made changes to java reflection * removed redundant method makeSound in Animal abstract class * added project for play-framework article * added project for regex * changed regex project from own model to core-java * added project for routing in play * made changes to regex project * refactored code for REST API with Play project * refactored student store indexing to zero base * added unit tests, removed bad names * added NIO Selector project under core-java module --- .../java/nio/selector/EchoClient.java | 46 +++++++++++++++++ .../java/nio/selector/EchoServer.java | 50 +++++++++++++++++++ .../baeldung/java/nio/selector/EchoTest.java | 18 +++++++ 3 files changed, 114 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java create mode 100644 core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java create mode 100644 core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java new file mode 100644 index 0000000000..188db21641 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java @@ -0,0 +1,46 @@ +package com.baeldung.java.nio.selector; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; + +public class EchoClient { + private static SocketChannel client = null; + private static ByteBuffer buffer; + private static EchoClient instance = null; + + public static EchoClient start() { + if (instance == null) + instance = new EchoClient(); + + return instance; + } + + private EchoClient() { + try { + client = SocketChannel.open(new InetSocketAddress("localhost", 5454)); + buffer = ByteBuffer.allocate(256); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public String sendMessage(String msg) { + buffer = ByteBuffer.wrap(msg.getBytes()); + String response = null; + try { + client.write(buffer); + buffer.clear(); + client.read(buffer); + response = new String(buffer.array()).trim(); + System.out.println("response=" + response); + buffer.clear(); + } catch (IOException e) { + e.printStackTrace(); + } + return response; + + } + +} diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java new file mode 100644 index 0000000000..aedcbb319b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java @@ -0,0 +1,50 @@ +package com.baeldung.java.nio.selector; + +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.channels.Selector; +import java.nio.channels.SelectionKey; +import java.nio.ByteBuffer; +import java.io.IOException; +import java.util.Set; +import java.util.Iterator; +import java.net.InetSocketAddress; + +public class EchoServer { + + public static void main(String[] args) + + throws IOException { + Selector selector = Selector.open(); + ServerSocketChannel serverSocket = ServerSocketChannel.open(); + serverSocket.bind(new InetSocketAddress("localhost", 5454)); + serverSocket.configureBlocking(false); + serverSocket.register(selector, SelectionKey.OP_ACCEPT); + ByteBuffer buffer = ByteBuffer.allocate(256); + + while (true) { + selector.select(); + Set selectedKeys = selector.selectedKeys(); + Iterator iter = selectedKeys.iterator(); + while (iter.hasNext()) { + + SelectionKey key = iter.next(); + + if (key.isAcceptable()) { + SocketChannel client = serverSocket.accept(); + client.configureBlocking(false); + client.register(selector, SelectionKey.OP_READ); + } + + if (key.isReadable()) { + SocketChannel client = (SocketChannel) key.channel(); + client.read(buffer); + buffer.flip(); + client.write(buffer); + buffer.clear(); + } + iter.remove(); + } + } + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java b/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java new file mode 100644 index 0000000000..63da2fe2bf --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java @@ -0,0 +1,18 @@ +package com.baeldung.java.nio.selector; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class EchoTest { + + @Test + public void givenClient_whenServerEchosMessage_thenCorrect() { + EchoClient client = EchoClient.start(); + String resp1 = client.sendMessage("hello"); + String resp2 = client.sendMessage("world"); + assertEquals("hello", resp1); + assertEquals("world", resp2); + } + +} From e7ea2e1d2b0a81c15c2d7adf3164b4490bf839f5 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Tue, 11 Oct 2016 09:54:18 +0200 Subject: [PATCH 041/193] Fix spring-jms --- .../baeldung/spring/jms/SampleJmsMessageSender.java | 4 ++++ spring-jms/src/main/resources/EmbeddedActiveMQ.xml | 13 +++++-------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java index cfbfc77a75..1ef3902a31 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java @@ -24,6 +24,10 @@ public class SampleJmsMessageSender { } public void sendMessage(final Employee employee) { + System.out.println("Jms Message Sender : " + employee); + Map map = new HashMap<>(); + map.put("name", employee.getName()); + map.put("age", employee.getAge()); this.jmsTemplate.convertAndSend(map); } } diff --git a/spring-jms/src/main/resources/EmbeddedActiveMQ.xml b/spring-jms/src/main/resources/EmbeddedActiveMQ.xml index 1db20b8f0f..6b419c3270 100644 --- a/spring-jms/src/main/resources/EmbeddedActiveMQ.xml +++ b/spring-jms/src/main/resources/EmbeddedActiveMQ.xml @@ -1,15 +1,12 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" + xmlns:amq="http://activemq.apache.org/schema/core" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://activemq.apache.org/schema/core + http://activemq.apache.org/schema/core/activemq-core-5.2.0.xsd"> - + From 453b739f6c11cf7c28102f810ac734d956a02f2f Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Tue, 11 Oct 2016 10:38:51 +0200 Subject: [PATCH 042/193] Add OkHttp example --- spring-rest/pom.xml | 23 +++- .../okhttp/DefaultContentTypeInterceptor.java | 26 +++++ .../okhttp/OkHttpFileUploadingTest.java | 81 +++++++++++++ .../org/baeldung/okhttp/OkHttpGetTest.java | 78 +++++++++++++ .../org/baeldung/okhttp/OkHttpHeaderTest.java | 48 ++++++++ .../org/baeldung/okhttp/OkHttpMiscTest.java | 107 +++++++++++++++++ .../baeldung/okhttp/OkHttpPostingTest.java | 109 ++++++++++++++++++ .../baeldung/okhttp/OkHttpRedirectTest.java | 33 ++++++ .../okhttp/ProgressRequestWrapper.java | 74 ++++++++++++ spring-rest/src/test/resources/test.txt | 1 + 10 files changed, 574 insertions(+), 6 deletions(-) create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java create mode 100644 spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java create mode 100644 spring-rest/src/test/resources/test.txt diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 18cb1dc72a..69ab4ed361 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -15,7 +15,7 @@ - + org.springframework.boot spring-boot-starter-thymeleaf @@ -71,7 +71,7 @@ com.fasterxml.jackson.core jackson-databind - + com.fasterxml.jackson.dataformat jackson-dataformat-xml @@ -118,6 +118,14 @@ log4j-over-slf4j + + + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + + @@ -153,14 +161,14 @@ rest-assured ${rest-assured.version} - + com.google.protobuf protobuf-java 2.6.1 - + com.esotericsoftware kryo @@ -198,7 +206,7 @@ maven-surefire-plugin - **/*LiveTest.java + **/*LiveTest.java @@ -285,7 +293,7 @@ - + @@ -320,6 +328,9 @@ 2.19.1 1.6.0 + + 3.4.1 + diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java b/spring-rest/src/test/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java new file mode 100644 index 0000000000..2a33a1febd --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java @@ -0,0 +1,26 @@ +package org.baeldung.okhttp; + +import java.io.IOException; + +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +public class DefaultContentTypeInterceptor implements Interceptor { + + private final String contentType; + + public DefaultContentTypeInterceptor(String contentType) { + this.contentType = contentType; + } + + public Response intercept(Interceptor.Chain chain) throws IOException { + + Request originalRequest = chain.request(); + Request requestWithUserAgent = originalRequest.newBuilder() + .header("Content-Type", contentType) + .build(); + + return chain.proceed(requestWithUserAgent); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java new file mode 100644 index 0000000000..77219b8e22 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java @@ -0,0 +1,81 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.IOException; + +import org.baeldung.okhttp.ProgressRequestWrapper; +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +public class OkHttpFileUploadingTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + + @Test + public void whenUploadFile_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("file", "file.txt", + RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/upload") + .post(requestBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenGetUploadFileProgress_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("file", "file.txt", + RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) + .build(); + + + ProgressRequestWrapper.ProgressListener listener = new ProgressRequestWrapper.ProgressListener() { + + public void onRequestProgress(long bytesWritten, long contentLength) { + + float percentage = 100f * bytesWritten / contentLength; + assertFalse(Float.compare(percentage, 100) > 0); + } + }; + + ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, listener); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/upload") + .post(countingBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + + } +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java new file mode 100644 index 0000000000..de954e3dd7 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java @@ -0,0 +1,78 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpGetTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + + @Test + public void whenGetRequest_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(BASE_URL + "/date") + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); + urlBuilder.addQueryParameter("id", "1"); + + String url = urlBuilder.build().toString(); + + Request request = new Request.Builder() + .url(url) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenAsynchronousGetRequest_thenCorrect() { + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(BASE_URL + "/date") + .build(); + + Call call = client.newCall(request); + + call.enqueue(new Callback() { + + public void onResponse(Call call, Response response) throws IOException { + assertThat(response.code(), equalTo(200)); + } + + public void onFailure(Call call, IOException e) { + + } + }); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java new file mode 100644 index 0000000000..958eeb51ce --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java @@ -0,0 +1,48 @@ +package org.baeldung.okhttp; + +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpHeaderTest { + + private static final String SAMPLE_URL = "http://www.github.com"; + + @Test + public void whenSetHeader_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(SAMPLE_URL) + .addHeader("Content-Type", "application/json") + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + response.close(); + } + + @Test + public void whenSetDefaultHeader_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient.Builder() + .addInterceptor(new DefaultContentTypeInterceptor("application/json")) + .build(); + + Request request = new Request.Builder() + .url(SAMPLE_URL) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + response.close(); + } + + +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java new file mode 100644 index 0000000000..fe15a76200 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java @@ -0,0 +1,107 @@ +package org.baeldung.okhttp; + +import java.io.File; +import java.io.IOException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import okhttp3.Cache; +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpMiscTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static Logger logger = LoggerFactory.getLogger(OkHttpMiscTest.class); + + @Test + public void whenSetRequestTimeout_thenFail() throws IOException { + + OkHttpClient client = new OkHttpClient.Builder() + .readTimeout(1, TimeUnit.SECONDS) + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + response.close(); + } + + @Test + public void whenCancelRequest_thenCorrect() throws IOException { + + ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. + .build(); + + final int seconds = 1; + + final long startNanos = System.nanoTime(); + final Call call = client.newCall(request); + + // Schedule a job to cancel the call in 1 second. + executor.schedule(new Runnable() { + public void run() { + + logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f); + call.cancel(); + logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f); + } + }, seconds, TimeUnit.SECONDS); + + try { + + logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f); + Response response = call.execute(); + logger.debug("Call was expected to fail, but completed: " + (System.nanoTime() - startNanos) / 1e9f, response); + + } catch (IOException e) { + + logger.debug("Call failed as expected: " + (System.nanoTime() - startNanos) / 1e9f, e); + } + } + + @Test + public void whenSetResponseCache_thenCorrect() throws IOException { + + int cacheSize = 10 * 1024 * 1024; // 10 MiB + File cacheDirectory = new File("src/test/resources/cache"); + Cache cache = new Cache(cacheDirectory, cacheSize); + + OkHttpClient client = new OkHttpClient.Builder() + .cache(cache) + .build(); + + Request request = new Request.Builder() + .url("http://publicobject.com/helloworld.txt") + .build(); + + Response response1 = client.newCall(request).execute(); + logResponse(response1); + + Response response2 = client.newCall(request).execute(); + logResponse(response2); + } + + private void logResponse(Response response) throws IOException { + + logger.debug("Response response: " + response); + logger.debug("Response cache response: " + response.cacheResponse()); + logger.debug("Response network response: " + response.networkResponse()); + logger.debug("Response responseBody: " + response.body().string()); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java new file mode 100644 index 0000000000..41a024d2ee --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java @@ -0,0 +1,109 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.Credentials; +import okhttp3.FormBody; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +public class OkHttpPostingTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; + + @Test + public void whenSendPostRequest_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody formBody = new FormBody.Builder() + .add("username", "test") + .add("password", "test") + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/users") + .post(formBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException { + + String postBody = "test post"; + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(URL_SECURED_BY_BASIC_AUTHENTICATION) + .addHeader("Authorization", Credentials.basic("test", "test")) + .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody)) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenPostJson_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + String json = "{\"id\":1,\"name\":\"John\"}"; + + RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/detail") + .post(body) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenSendMultipartRequest_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("username", "test") + .addFormDataPart("password", "test") + .addFormDataPart("file", "file.txt", + RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/multipart") + .post(requestBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java new file mode 100644 index 0000000000..c709253478 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java @@ -0,0 +1,33 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpRedirectTest { + + @Test + public void whenSetFollowRedirects_thenNotRedirected() throws IOException { + + OkHttpClient client = new OkHttpClient().newBuilder() + .followRedirects(false) + .build(); + + Request request = new Request.Builder() + .url("http://t.co/I5YYd9tddw") + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(301)); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java b/spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java new file mode 100644 index 0000000000..255d10b98a --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java @@ -0,0 +1,74 @@ +package org.baeldung.okhttp; + +import okhttp3.RequestBody; +import okhttp3.MediaType; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestWrapper extends RequestBody { + + protected RequestBody delegate; + protected ProgressListener listener; + + protected CountingSink countingSink; + + public ProgressRequestWrapper(RequestBody delegate, ProgressListener listener) { + this.delegate = delegate; + this.listener = listener; + } + + @Override + public MediaType contentType() { + return delegate.contentType(); + } + + @Override + public long contentLength() throws IOException { + return delegate.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + + BufferedSink bufferedSink; + + countingSink = new CountingSink(sink); + bufferedSink = Okio.buffer(countingSink); + + delegate.writeTo(bufferedSink); + + bufferedSink.flush(); + } + + protected final class CountingSink extends ForwardingSink { + + private long bytesWritten = 0; + + public CountingSink(Sink delegate) { + super(delegate); + } + + @Override + public void write(Buffer source, long byteCount) throws IOException { + + super.write(source, byteCount); + + bytesWritten += byteCount; + listener.onRequestProgress(bytesWritten, contentLength()); + } + + } + + public interface ProgressListener { + + void onRequestProgress(long bytesWritten, long contentLength); + + } +} + diff --git a/spring-rest/src/test/resources/test.txt b/spring-rest/src/test/resources/test.txt new file mode 100644 index 0000000000..95d09f2b10 --- /dev/null +++ b/spring-rest/src/test/resources/test.txt @@ -0,0 +1 @@ +hello world \ No newline at end of file From ebc1c54bea85af32ef238f1128a46ba6a84c85dc Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Tue, 11 Oct 2016 10:42:45 +0200 Subject: [PATCH 043/193] Add OkHttp example --- spring-rest/src/test/resources/.gitignore | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 spring-rest/src/test/resources/.gitignore diff --git a/spring-rest/src/test/resources/.gitignore b/spring-rest/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/spring-rest/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file From 5b09ae527551228177ea62fa2b8b75859b2de262 Mon Sep 17 00:00:00 2001 From: Sunil Gulabani Date: Tue, 11 Oct 2016 14:14:11 +0530 Subject: [PATCH 044/193] Added stream close snippet --- .../src/test/java/com/baeldung/file/FileOperationsTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java index 3752fc5b7f..90f5ded1cb 100644 --- a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java +++ b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java @@ -102,6 +102,7 @@ public class FileOperationsTest { StringBuilder data = new StringBuilder(); Stream lines = Files.lines(path); lines.forEach(line -> data.append(line).append("\n")); + lines.close(); Assert.assertEquals(expectedData, data.toString().trim()); } From 774b2610504f7c74f6888c89f5687c94d6a94699 Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Tue, 11 Oct 2016 10:44:47 +0200 Subject: [PATCH 045/193] Add OkHttp example --- spring-rest/src/test/resources/.gitignore | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 spring-rest/src/test/resources/.gitignore diff --git a/spring-rest/src/test/resources/.gitignore b/spring-rest/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-rest/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file From 7279e62e448547684e973ac8e19dae847fd1989f Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 11 Oct 2016 13:10:56 +0200 Subject: [PATCH 046/193] add live profile --- spring-security-rest-digest-auth/pom.xml | 55 +++++++++++++++++++ .../client/ClientNoSpringLiveTest.java | 8 +-- .../client/ClientWithSpringLiveTest.java | 2 +- .../baeldung/client/RawClientLiveTest.java | 2 +- 4 files changed, 61 insertions(+), 6 deletions(-) diff --git a/spring-security-rest-digest-auth/pom.xml b/spring-security-rest-digest-auth/pom.xml index bfb4a7223a..1eddbc17f8 100644 --- a/spring-security-rest-digest-auth/pom.xml +++ b/spring-security-rest-digest-auth/pom.xml @@ -278,6 +278,61 @@ + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + 4.2.5.RELEASE diff --git a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientNoSpringLiveTest.java b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientNoSpringLiveTest.java index 245d5d0a41..cbf6a12ff7 100644 --- a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientNoSpringLiveTest.java +++ b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientNoSpringLiveTest.java @@ -22,16 +22,16 @@ public class ClientNoSpringLiveTest { @Test public final void givenUsingCustomHttpRequestFactory_whenSecuredRestApiIsConsumed_then200OK() { - final HttpHost host = new HttpHost("localhost", 8080, "http"); + final HttpHost host = new HttpHost("localhost", 8082, "http"); final CredentialsProvider credentialsProvider = provider(); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).useSystemProperties().build(); final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryDigestAuth(host, client); final RestTemplate restTemplate = new RestTemplate(requestFactory); - // credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); + // credentialsProvider.setCredentials(new AuthScope("localhost", 8082, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); - final String uri = "http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"; + final String uri = "http://localhost:8082/spring-security-rest-digest-auth/api/foos/1"; final ResponseEntity responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, Foo.class); System.out.println(responseEntity.getStatusCode()); @@ -46,7 +46,7 @@ public class ClientNoSpringLiveTest { // credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); - final String uri = "http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"; + final String uri = "http://localhost:8082/spring-security-rest-digest-auth/api/foos/1"; final ResponseEntity responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, Foo.class); System.out.println(responseEntity.getStatusCode()); diff --git a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientWithSpringLiveTest.java b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientWithSpringLiveTest.java index b40f9ef472..d673b2633b 100644 --- a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientWithSpringLiveTest.java +++ b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientWithSpringLiveTest.java @@ -23,7 +23,7 @@ public class ClientWithSpringLiveTest { @Test public final void whenSecuredRestApiIsConsumed_then200OK() { - final String uri = "http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"; + final String uri = "http://localhost:8082/spring-security-rest-digest-auth/api/foos/1"; final ResponseEntity responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, Foo.class); System.out.println(responseEntity.getStatusCode()); diff --git a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java index 93c3af3876..83e888e793 100644 --- a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java +++ b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java @@ -29,7 +29,7 @@ public class RawClientLiveTest { final int timeout = 20; // seconds final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout).setConnectTimeout(timeout).setSocketTimeout(timeout).build(); - final HttpGet getMethod = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/bars/1"); + final HttpGet getMethod = new HttpGet("http://localhost:8082/spring-security-rest-basic-auth/api/bars/1"); getMethod.setConfig(requestConfig); final int hardTimeout = 5; // seconds From a063b93de01b6bc9533b23ab99947a9860cd6231 Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 11 Oct 2016 13:24:45 +0200 Subject: [PATCH 047/193] add live profile --- spring-security-rest-basic-auth/pom.xml | 55 +++++++++++++++++++ .../baeldung/client/RestTemplateFactory.java | 2 +- .../org/baeldung/client/ClientLiveTest.java | 2 +- .../client/RestClientLiveManualTest.java | 2 +- 4 files changed, 58 insertions(+), 3 deletions(-) diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index 854bbb70be..d3f4de9914 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -285,6 +285,61 @@ + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + 4.2.5.RELEASE diff --git a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java index f369e96ca9..0cec0dc5c3 100644 --- a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java @@ -45,7 +45,7 @@ public class RestTemplateFactory implements FactoryBean, Initializ final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); + credentialsProvider.setCredentials(new AuthScope("localhost", 8082, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).setDefaultCredentialsProvider(credentialsProvider).build(); final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client); diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java index 817e818b58..2a668f827a 100644 --- a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java @@ -33,7 +33,7 @@ public class ClientLiveTest { @Test public final void whenSecuredRestApiIsConsumed_then200OK() { - final ResponseEntity responseEntity = secureRestTemplate.exchange("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1", HttpMethod.GET, null, Foo.class); + final ResponseEntity responseEntity = secureRestTemplate.exchange("http://localhost:8082/spring-security-rest-basic-auth/api/foos/1", HttpMethod.GET, null, Foo.class); assertThat(responseEntity.getStatusCode().value(), is(200)); } diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java index 44c5c0cbb1..c27e306c08 100644 --- a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java @@ -30,7 +30,7 @@ import org.springframework.web.client.RestTemplate; * */ public class RestClientLiveManualTest { - final String urlOverHttps = "http://localhost:8080/spring-security-rest-basic-auth/api/bars/1"; + final String urlOverHttps = "http://localhost:8082/spring-security-rest-basic-auth/api/bars/1"; // tests From 0d22ab4a44dd1db96e46a2bfa02c47f9654de15e Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 11 Oct 2016 13:32:28 +0200 Subject: [PATCH 048/193] add live profile --- spring-security-rest/pom.xml | 58 ++++++++++++++++++- .../java/org/baeldung/web/FooLiveTest.java | 6 +- .../org/baeldung/web/SwaggerLiveTest.java | 2 +- 3 files changed, 62 insertions(+), 4 deletions(-) diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 6d492863b4..255cf25308 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -257,7 +257,7 @@ ${maven-surefire-plugin.version} - + **/*LiveTest.java @@ -289,6 +289,62 @@ + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + + 4.2.5.RELEASE diff --git a/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java b/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java index dc3a576b7b..0ef50f745a 100644 --- a/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java +++ b/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java @@ -17,14 +17,16 @@ import com.jayway.restassured.specification.RequestSpecification; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) public class FooLiveTest { - private static final String URL_PREFIX = "http://localhost:8080/spring-security-rest"; + private static final String URL_PREFIX = "http://localhost:8082/spring-security-rest"; // private FormAuthConfig formConfig = new FormAuthConfig(URL_PREFIX + "/login", "temporary", "temporary"); private String cookie; + private RequestSpecification givenAuth() { // return RestAssured.given().auth().form("user", "userPass", formConfig); - if (cookie == null) + if (cookie == null) { cookie = RestAssured.given().contentType("application/x-www-form-urlencoded").formParam("password", "userPass").formParam("username", "user").post(URL_PREFIX + "/login").getCookie("JSESSIONID"); + } return RestAssured.given().cookie("JSESSIONID", cookie); } diff --git a/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java b/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java index 792b3e28ce..cf1516f8e1 100644 --- a/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java +++ b/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java @@ -8,7 +8,7 @@ import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; public class SwaggerLiveTest { - private static final String URL_PREFIX = "http://localhost:8080/spring-security-rest/api"; + private static final String URL_PREFIX = "http://localhost:8082/spring-security-rest/api"; @Test public void whenVerifySpringFoxIsWorking_thenOK() { From 9c252d8cc8d09185ca4eb62930352636dc77ce8b Mon Sep 17 00:00:00 2001 From: Anil Bhaskar Date: Tue, 11 Oct 2016 19:03:40 +0530 Subject: [PATCH 049/193] updating latest versions for webjars (#740) --- spring-boot/src/main/resources/templates/index.html | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/spring-boot/src/main/resources/templates/index.html b/spring-boot/src/main/resources/templates/index.html index 046d21600a..2c4387ed10 100644 --- a/spring-boot/src/main/resources/templates/index.html +++ b/spring-boot/src/main/resources/templates/index.html @@ -1,19 +1,19 @@ WebJars Demo - +

- × + × Success! It is working as we expected.
- - + + - \ No newline at end of file + From 9c8ef99ed3bb532f4d88961b583107cd9d4faf3c Mon Sep 17 00:00:00 2001 From: Anil Bhaskar Date: Tue, 11 Oct 2016 19:03:49 +0530 Subject: [PATCH 050/193] updating latest versions for webjars (#741) --- spring-boot/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 5a20ff5602..5281b9b2c0 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -88,12 +88,12 @@ org.webjars bootstrap - 3.3.4 + 3.3.7-1 org.webjars jquery - 2.1.4 + 3.1.1
From b36a7e00cc954ecf862796915a14e7ee8dd32b4f Mon Sep 17 00:00:00 2001 From: Ante Pocedulic Date: Tue, 11 Oct 2016 17:15:13 +0200 Subject: [PATCH 051/193] Ehcache code (#734) * - created packages for each logical part of application - created validator for WebsiteUser rest API - created ValidatorEventRegister class which fixes known bug for not detecting generated events - created custom Exception Handler which creates better response messages * Code formatting * formated pom.xml replaced for loops with streams fixed bug while getting all beans * removed unnecessary code changed repository type * - added test for Spring Data REST APIs - changed bad request return code - formated code * - added source code for ehcache article - added ehcache dependency to pom.xml --- spring-all/pom.xml | 496 +++++++++--------- .../java/org/baeldung/ehcache/app/App.java | 24 + .../ehcache/calculator/SquaredCalculator.java | 24 + .../baeldung/ehcache/config/CacheHelper.java | 25 + 4 files changed, 324 insertions(+), 245 deletions(-) create mode 100755 spring-all/src/main/java/org/baeldung/ehcache/app/App.java create mode 100755 spring-all/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java create mode 100755 spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java diff --git a/spring-all/pom.xml b/spring-all/pom.xml index c70d9d75fc..003cdacc2c 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -1,295 +1,301 @@ - - 4.0.0 - com.baeldung - spring-all - 0.1-SNAPSHOT + + 4.0.0 + com.baeldung + spring-all + 0.1-SNAPSHOT - spring-all - war + spring-all + war - - org.springframework.boot - spring-boot-starter-parent - 1.3.6.RELEASE - + + org.springframework.boot + spring-boot-starter-parent + 1.3.6.RELEASE + - - - com.fasterxml.jackson.core - jackson-databind - + + + com.fasterxml.jackson.core + jackson-databind + - + - - org.springframework - spring-web - - - org.springframework - spring-webmvc - - - org.springframework - spring-orm - - - org.springframework - spring-context - + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.springframework + spring-orm + + + org.springframework + spring-context + - + - - org.springframework - spring-aspects - + + org.springframework + spring-aspects + - + - - org.hibernate - hibernate-core - ${hibernate.version} - - - org.javassist - javassist - - - mysql - mysql-connector-java - runtime - - - org.hsqldb - hsqldb - - - + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.javassist + javassist + + + mysql + mysql-connector-java + runtime + + + org.hsqldb + hsqldb + - - org.hibernate - hibernate-validator - + - + + org.hibernate + hibernate-validator + - - javax.servlet - javax.servlet-api - provided - + - - javax.servlet - jstl - runtime - + + javax.servlet + javax.servlet-api + provided + - + + javax.servlet + jstl + runtime + - - com.google.guava - guava - ${guava.version} - - - + - - org.slf4j - slf4j-api - - - ch.qos.logback - logback-classic - - - - org.slf4j - jcl-over-slf4j - - - - org.slf4j - log4j-over-slf4j - + + com.google.guava + guava + ${guava.version} + - + - - org.springframework - spring-test - test - + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + org.slf4j + jcl-over-slf4j + + + + org.slf4j + log4j-over-slf4j + - - junit - junit - test - + - - org.assertj - assertj-core - 3.5.1 - test - + + org.springframework + spring-test + test + - - org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library - test - + + junit + junit + test + - - org.mockito - mockito-core - test - + + org.assertj + assertj-core + 3.5.1 + test + - - org.easymock - easymock - 3.4 - test - + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + - + + org.mockito + mockito-core + test + - + + org.easymock + easymock + 3.4 + test + + + org.ehcache + ehcache + 3.1.3 + - + - - org.springframework - spring-framework-bom - ${org.springframework.version} - pom - import - + - - org.springframework - spring-core - ${org.springframework.version} - + - + + org.springframework + spring-framework-bom + ${org.springframework.version} + pom + import + - + + org.springframework + spring-core + ${org.springframework.version} + - - spring-all - - - src/main/resources - true - - + - + - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - + + spring-all + + + src/main/resources + true + + - - org.apache.maven.plugins - maven-war-plugin - - false - - + - - org.apache.maven.plugins - maven-surefire-plugin - - - - - - - - - + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - + + org.apache.maven.plugins + maven-war-plugin + + false + + - + + org.apache.maven.plugins + maven-surefire-plugin + + + + + + + + + - + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + - - - 4.3.1.RELEASE - 4.0.4.RELEASE - 3.20.0-GA - 1.2 + - - 4.3.11.Final - 5.1.38 + - - 1.7.13 - 1.1.3 + + + 4.3.1.RELEASE + 4.0.4.RELEASE + 3.20.0-GA + 1.2 - - 5.2.2.Final + + 4.3.11.Final + 5.1.38 - - 19.0 - 3.4 + + 1.7.13 + 1.1.3 - - 1.3 - 4.12 - 1.10.19 + + 5.2.2.Final - 4.4.1 - 4.5 + + 19.0 + 3.4 - 2.9.0 + + 1.3 + 4.12 + 1.10.19 - - 3.5.1 - 2.6 - 2.19.1 - 2.7 - 1.4.18 + 4.4.1 + 4.5 - + 2.9.0 + + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 + + \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/ehcache/app/App.java b/spring-all/src/main/java/org/baeldung/ehcache/app/App.java new file mode 100755 index 0000000000..99370186a3 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/ehcache/app/App.java @@ -0,0 +1,24 @@ +package org.baeldung.ehcache.app; + +import org.baeldung.ehcache.calculator.SquaredCalculator; +import org.baeldung.ehcache.config.CacheHelper; + +public class App { + + public static void main(String[] args) { + + SquaredCalculator squaredCalculator = new SquaredCalculator(); + CacheHelper cacheHelper = new CacheHelper(); + + squaredCalculator.setCache(cacheHelper); + + calculate(squaredCalculator); + calculate(squaredCalculator); + } + + private static void calculate(SquaredCalculator squaredCalculator) { + for (int i = 10; i < 15; i++) { + System.out.println("Square value of " + i + " is: " + squaredCalculator.getSquareValueOfNumber(i) + "\n"); + } + } +} diff --git a/spring-all/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java b/spring-all/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java new file mode 100755 index 0000000000..25957539df --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java @@ -0,0 +1,24 @@ +package org.baeldung.ehcache.calculator; + +import org.baeldung.ehcache.config.CacheHelper; + +public class SquaredCalculator { + private CacheHelper cache; + + public int getSquareValueOfNumber(int input) { + if (cache.getSquareNumberCache().containsKey(input)) { + return cache.getSquareNumberCache().get(input); + } + + System.out.println("Calculating square value of " + input + " and caching result."); + + int squaredValue = (int) Math.pow(input, 2); + cache.getSquareNumberCache().put(input, squaredValue); + + return squaredValue; + } + + public void setCache(CacheHelper cache) { + this.cache = cache; + } +} diff --git a/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java b/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java new file mode 100755 index 0000000000..387a57880b --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java @@ -0,0 +1,25 @@ +package org.baeldung.ehcache.config; + +import org.ehcache.Cache; +import org.ehcache.CacheManager; +import org.ehcache.config.builders.CacheConfigurationBuilder; +import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ResourcePoolsBuilder; + +public class CacheHelper { + + private CacheManager cacheManager; + private Cache squareNumberCache; + + public CacheHelper() { + cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("squaredNumber", CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Integer.class, ResourcePoolsBuilder.heap(10))).build(); + cacheManager.init(); + + squareNumberCache = cacheManager.getCache("squaredNumber", Integer.class, Integer.class); + } + + public Cache getSquareNumberCache() { + return squareNumberCache; + } + +} From 9e5d795bd4af5e02860223f82618c7f67379fe1a Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Tue, 11 Oct 2016 17:51:49 +0200 Subject: [PATCH 052/193] BAEL-225 - Upgrading version --- core-java-8/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 566eb4e43a..22e3bab595 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -15,7 +15,7 @@ commons-io commons-io - 2.4 + 2.5 From f8bbbea88cdfce9e65abe75494f9c636a1ea67df Mon Sep 17 00:00:00 2001 From: Prashant Khanal Date: Tue, 11 Oct 2016 14:39:43 -0700 Subject: [PATCH 053/193] Code cleanup --- .../org/baeldung/web/CustomUserDetailsServiceTest.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java index 19603a499c..6917cea99a 100644 --- a/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java +++ b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java @@ -1,5 +1,7 @@ package org.baeldung.web; +import static org.junit.Assert.assertEquals; + import org.baeldung.config.MvcConfig; import org.baeldung.config.PersistenceConfig; import org.baeldung.config.SecurityConfig; @@ -12,13 +14,10 @@ import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.core.Authentication; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; -import static org.junit.Assert.*; - -import java.util.logging.Logger; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = { MvcConfig.class, SecurityConfig.class, PersistenceConfig.class }) From 564bb18344e1146d9d7d3b50740596262033dca5 Mon Sep 17 00:00:00 2001 From: Prashant Khanal Date: Tue, 11 Oct 2016 14:42:09 -0700 Subject: [PATCH 054/193] Indentation issue fixed --- spring-security-custom-permission/pom.xml | 41 ++++++++++++----------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/spring-security-custom-permission/pom.xml b/spring-security-custom-permission/pom.xml index d036975107..166f0b43c0 100644 --- a/spring-security-custom-permission/pom.xml +++ b/spring-security-custom-permission/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 com.baeldung @@ -31,7 +32,7 @@ spring-boot-starter-tomcat provided - + org.springframework.boot spring-boot-starter-thymeleaf @@ -41,39 +42,39 @@ org.thymeleaf.extras thymeleaf-extras-springsecurity4 - - - - org.springframework.boot - spring-boot-starter-data-jpa - - + + + + org.springframework.boot + spring-boot-starter-data-jpa + + com.h2database h2 - - - + + + junit junit test - + org.hamcrest hamcrest-core test - + org.hamcrest hamcrest-library test - + com.jayway.restassured rest-assured @@ -86,14 +87,14 @@ - - + + org.springframework spring-test test - - + + org.apache.derby derby 10.12.1.1 @@ -145,5 +146,5 @@ 1.8 2.4.0 - + From 2aa2f43c6e9da11f4d862da40a1aed8f52c74492 Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 12 Oct 2016 07:44:40 +0300 Subject: [PATCH 055/193] maven cleanup --- assertj/pom.xml | 25 +- core-java/pom.xml | 2 +- gson-jackson-performance/README.md | 3 - gson-jackson-performance/pom.xml | 72 --- .../data/complex/ComplexDataGeneration.java | 63 --- .../data/complex/ComplexDataGson.java | 91 ---- .../data/complex/ComplexDataJackson.java | 95 ---- .../data/simple/SimpleDataGeneration.java | 35 -- .../baeldung/data/simple/SimpleDataGson.java | 91 ---- .../data/simple/SimpleDataJackson.java | 95 ---- .../com/baeldung/data/utility/Utility.java | 90 ---- .../baeldung/pojo/complex/AddressDetails.java | 37 -- .../baeldung/pojo/complex/ContactDetails.java | 25 - .../pojo/complex/CustomerAddressDetails.java | 18 - .../complex/CustomerPortfolioComplex.java | 17 - .../com/baeldung/pojo/simple/Customer.java | 36 -- .../pojo/simple/CustomerPortfolioSimple.java | 16 - .../src/main/resources/log4j.properties | 16 - gson/pom.xml | 2 +- guava18/pom.xml | 10 +- guava19/pom.xml | 14 +- handling-spring-static-resources/pom.xml | 4 +- jackson/pom.xml | 2 +- java-cassandra/pom.xml | 85 ++-- rest-assured/pom.xml | 435 ++++++++---------- rest-testing/pom.xml | 2 +- spring-mvc-java/pom.xml | 27 +- spring-mvc-xml/pom.xml | 19 +- spring-rest-angular/pom.xml | 187 ++++---- spring-security-rest-digest-auth/pom.xml | 2 +- spring-security-rest-full/pom.xml | 2 +- spring-security-rest/pom.xml | 6 +- 32 files changed, 403 insertions(+), 1221 deletions(-) delete mode 100644 gson-jackson-performance/README.md delete mode 100644 gson-jackson-performance/pom.xml delete mode 100644 gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java delete mode 100644 gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java delete mode 100644 gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java delete mode 100644 gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java delete mode 100644 gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java delete mode 100644 gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java delete mode 100644 gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java delete mode 100644 gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java delete mode 100644 gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java delete mode 100644 gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java delete mode 100644 gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java delete mode 100644 gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java delete mode 100644 gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java delete mode 100644 gson-jackson-performance/src/main/resources/log4j.properties diff --git a/assertj/pom.xml b/assertj/pom.xml index 421afd40a5..df55ebba4b 100644 --- a/assertj/pom.xml +++ b/assertj/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung @@ -9,11 +8,18 @@ 1.0.0-SNAPSHOT + com.google.guava guava - 19.0 + ${guava.version} + + org.assertj + assertj-guava + 3.0.0 + + junit junit @@ -26,11 +32,7 @@ 3.5.1 test - - org.assertj - assertj-guava - 3.0.0 - + @@ -46,4 +48,9 @@ + + + 19.0 + + \ No newline at end of file diff --git a/core-java/pom.xml b/core-java/pom.xml index bce97d1148..a5e89d2a76 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -174,7 +174,7 @@ 5.1.38 - 2.7.2 + 2.7.8 1.7.13 diff --git a/gson-jackson-performance/README.md b/gson-jackson-performance/README.md deleted file mode 100644 index 5b08f6cdec..0000000000 --- a/gson-jackson-performance/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Performance of Gson and Jackson - -Standalone java programs to measure the performance of both JSON APIs based on file size and object graph complexity. diff --git a/gson-jackson-performance/pom.xml b/gson-jackson-performance/pom.xml deleted file mode 100644 index 1ea43bd7fa..0000000000 --- a/gson-jackson-performance/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - 4.0.0 - - com.baeldung - gson-jackson-performance - 0.0.1-SNAPSHOT - jar - - gson-jackson-performance - http://maven.apache.org - - - UTF-8 - - - - gson-jackson-performance - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - - - - - - - - com.google.code.gson - gson - 2.5 - - - - com.fasterxml.jackson.core - jackson-databind - 2.7.1-1 - - - - junit - junit - 3.8.1 - test - - - - log4j - log4j - 1.2.17 - - - - - - - diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java deleted file mode 100644 index b69d306edf..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.data.complex; - -import java.util.ArrayList; -import java.util.List; - -import com.baeldung.data.utility.Utility; -import com.baeldung.pojo.complex.AddressDetails; -import com.baeldung.pojo.complex.ContactDetails; -import com.baeldung.pojo.complex.CustomerAddressDetails; -import com.baeldung.pojo.complex.CustomerPortfolioComplex; - -/** - * - * This class is responsible for generating data for complex type object - */ - -public class ComplexDataGeneration { - - public static CustomerPortfolioComplex generateData() { - List customerAddressDetailsList = new ArrayList(); - for (int i = 0; i < 600000; i++) { - CustomerAddressDetails customerAddressDetails = new CustomerAddressDetails(); - customerAddressDetails.setAge(20); - customerAddressDetails.setFirstName(Utility.generateRandomName()); - customerAddressDetails.setLastName(Utility.generateRandomName()); - - List addressDetailsList = new ArrayList(); - customerAddressDetails.setAddressDetails(addressDetailsList); - - for (int j = 0; j < 2; j++) { - AddressDetails addressDetails = new AddressDetails(); - addressDetails.setZipcode(Utility.generateRandomZip()); - addressDetails.setAddress(Utility.generateRandomAddress()); - - List contactDetailsList = new ArrayList(); - addressDetails.setContactDetails(contactDetailsList); - - for (int k = 0; k < 2; k++) { - ContactDetails contactDetails = new ContactDetails(); - contactDetails.setLandline(Utility.generateRandomPhone()); - contactDetails.setMobile(Utility.generateRandomPhone()); - contactDetailsList.add(contactDetails); - contactDetails = null; - } - - addressDetailsList.add(addressDetails); - addressDetails = null; - contactDetailsList = null; - } - customerAddressDetailsList.add(customerAddressDetails); - customerAddressDetails = null; - - if (i % 6000 == 0) { - Runtime.getRuntime().gc(); - } - } - - CustomerPortfolioComplex customerPortfolioComplex = new CustomerPortfolioComplex(); - customerPortfolioComplex.setCustomerAddressDetailsList(customerAddressDetailsList); - customerAddressDetailsList = null; - return customerPortfolioComplex; - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java deleted file mode 100644 index b97893e8f1..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.data.complex; - -import java.util.Map; - -import org.apache.log4j.Logger; -import com.baeldung.data.utility.Utility; -import com.baeldung.pojo.complex.CustomerPortfolioComplex; - -import com.google.gson.Gson; - -/** - * - * This class is responsible for performing functions for Complex type - * GSON like - * Java to Json - * Json to Map - * Json to Java Object - */ - -public class ComplexDataGson { - - private static final Logger logger = Logger.getLogger(ComplexDataGson.class); - - static Gson gson = new Gson(); - - static long generateJsonAvgTime = 0L; - - static long parseJsonToMapAvgTime = 0L; - - static long parseJsonToActualObjectAvgTime = 0L; - - public static void main(String[] args) { - CustomerPortfolioComplex customerPortfolioComplex = ComplexDataGeneration.generateData(); - int j = 50; - for (int i = 0; i < j; i++) { - logger.info("-------Round " + (i + 1)); - String jsonStr = generateJson(customerPortfolioComplex); - logger.info("Size of Complex content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length)); - logger.info("--------------------------------------------------------------------------"); - parseJsonToMap(jsonStr); - parseJsonToActualObject(jsonStr); - jsonStr = null; - } - - generateJsonAvgTime = generateJsonAvgTime / j; - parseJsonToMapAvgTime = parseJsonToMapAvgTime / j; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j; - - logger.info("--------------------------------------------------------------------------"); - logger.info("Average Time to Generate JSON : " + generateJsonAvgTime); - logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime); - logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime); - logger.info("--------------------------------------------------------------------------"); - } - - private static String generateJson(CustomerPortfolioComplex customerPortfolioComplex) { - Runtime.getRuntime().gc(); - long startParsTime = System.nanoTime(); - String json = gson.toJson(customerPortfolioComplex); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - generateJsonAvgTime = generateJsonAvgTime + elapsedTime; - logger.info("Json Generation Time(ms):: " + elapsedTime); - return json; - } - - private static void parseJsonToMap(String jsonStr) { - long startParsTime = System.nanoTime(); - Map parsedMap = gson.fromJson(jsonStr , Map.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime; - logger.info("Generating Map from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - parsedMap = null; - Runtime.getRuntime().gc(); - } - - private static void parseJsonToActualObject(String jsonStr) { - long startParsTime = System.nanoTime(); - CustomerPortfolioComplex customerPortfolioComplex = gson.fromJson(jsonStr , CustomerPortfolioComplex.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime; - logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - customerPortfolioComplex = null; - Runtime.getRuntime().gc(); - - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java deleted file mode 100644 index 07a210fb37..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.baeldung.data.complex; - -import java.io.IOException; -import java.util.Map; - -import com.baeldung.data.utility.Utility; -import org.apache.log4j.Logger; -import com.baeldung.pojo.complex.CustomerPortfolioComplex; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * - * This class is responsible for performing functions for Complex type - * Jackson like - * Java to Json - * Json to Map - * Json to Java Object - */ - -public class ComplexDataJackson { - - private static final Logger logger = Logger.getLogger(ComplexDataJackson.class); - - static ObjectMapper mapper = new ObjectMapper(); - - static long generateJsonAvgTime = 0L; - - static long parseJsonToMapAvgTime = 0L; - - static long parseJsonToActualObjectAvgTime = 0L; - - public static void main(String[] args) throws IOException { - CustomerPortfolioComplex customerPortfolioComplex = ComplexDataGeneration.generateData(); - int j = 50; - for (int i = 0; i < j; i++) { - logger.info("-------Round " + (i + 1)); - String jsonStr = generateJson(customerPortfolioComplex); - logger.info("Size of Complex content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length)); - logger.info("--------------------------------------------------------------------------"); - parseJsonToMap(jsonStr); - parseJsonToActualObject(jsonStr); - jsonStr = null; - } - - generateJsonAvgTime = generateJsonAvgTime / j; - parseJsonToMapAvgTime = parseJsonToMapAvgTime / j; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j; - - logger.info("--------------------------------------------------------------------------"); - logger.info("Average Time to Generate JSON : " + generateJsonAvgTime); - logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime); - logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime); - logger.info("--------------------------------------------------------------------------"); - } - - private static String generateJson(CustomerPortfolioComplex customerPortfolioComplex) - throws JsonProcessingException { - Runtime.getRuntime().gc(); - long startParsTime = System.nanoTime(); - String json = mapper.writeValueAsString(customerPortfolioComplex); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - generateJsonAvgTime = generateJsonAvgTime + elapsedTime; - logger.info("Json Generation Time(ms):: " + elapsedTime); - return json; - } - - private static void parseJsonToMap(String jsonStr) throws JsonParseException , JsonMappingException , IOException { - long startParsTime = System.nanoTime(); - Map parsedMap = mapper.readValue(jsonStr , Map.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime; - logger.info("Generating Map from json Time(ms):: " + elapsedTime); - parsedMap = null; - Runtime.getRuntime().gc(); - - } - - private static void parseJsonToActualObject(String jsonStr) throws JsonParseException , JsonMappingException , - IOException { - long startParsTime = System.nanoTime(); - CustomerPortfolioComplex customerPortfolioComplex = mapper.readValue(jsonStr , CustomerPortfolioComplex.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime; - logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime); - customerPortfolioComplex = null; - Runtime.getRuntime().gc(); - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java deleted file mode 100644 index 1e186adc72..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.data.simple; - -import java.util.ArrayList; -import java.util.List; - -import com.baeldung.data.utility.Utility; -import com.baeldung.pojo.simple.Customer; -import com.baeldung.pojo.simple.CustomerPortfolioSimple; - -/** - * - * This class is responsible for generating data for simple type object - */ - -public class SimpleDataGeneration { - - public static CustomerPortfolioSimple generateData() { - List customerList = new ArrayList(); - for (int i = 0; i < 1; i++) { - Customer customer = new Customer(); - customer.setAge(20); - customer.setFirstName(Utility.generateRandomName()); - customer.setLastName(Utility.generateRandomName()); - - customerList.add(customer); - customer = null; - - } - - CustomerPortfolioSimple customerPortfolioSimple = new CustomerPortfolioSimple(); - customerPortfolioSimple.setCustomerLists(customerList); - customerList = null; - return customerPortfolioSimple; - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java deleted file mode 100644 index b190313462..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.data.simple; - -import java.util.Map; - -import org.apache.log4j.Logger; -import com.baeldung.data.utility.Utility; -import com.baeldung.pojo.simple.CustomerPortfolioSimple; - -import com.google.gson.Gson; - -/** - * - * This class is responsible for performing functions for Simple type - * GSON like - * Java to Json - * Json to Map - * Json to Java Object - */ - -public class SimpleDataGson { - - private static final Logger logger = Logger.getLogger(SimpleDataGson.class); - - static Gson gson = new Gson(); - - static long generateJsonAvgTime = 0L; - - static long parseJsonToMapAvgTime = 0L; - - static long parseJsonToActualObjectAvgTime = 0L; - - public static void main(String[] args) { - CustomerPortfolioSimple customerPortfolioSimple = SimpleDataGeneration.generateData(); - String jsonStr = null; - int j = 5; - for (int i = 0; i < j; i++) { - logger.info("-------Round " + (i + 1)); - jsonStr = generateJson(customerPortfolioSimple); - logger.info("Size of Simple content Gson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length)); - logger.info("--------------------------------------------------------------------------"); - parseJsonToMap(jsonStr); - parseJsonToActualObject(jsonStr); - jsonStr = null; - } - generateJsonAvgTime = generateJsonAvgTime / j; - parseJsonToMapAvgTime = parseJsonToMapAvgTime / j; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j; - - logger.info("--------------------------------------------------------------------------"); - logger.info("Average Time to Generate JSON : " + generateJsonAvgTime); - logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime); - logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime); - logger.info("--------------------------------------------------------------------------"); - } - - private static String generateJson(CustomerPortfolioSimple customerPortfolioSimple) { - Runtime.getRuntime().gc(); - long startParsTime = System.nanoTime(); - String json = gson.toJson(customerPortfolioSimple); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - generateJsonAvgTime = generateJsonAvgTime + elapsedTime; - logger.info("Json Generation Time(ms):: " + elapsedTime); - return json; - } - - private static void parseJsonToMap(String jsonStr) { - long startParsTime = System.nanoTime(); - Map parsedMap = gson.fromJson(jsonStr , Map.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime; - logger.info("Generating Map from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - parsedMap = null; - Runtime.getRuntime().gc(); - - } - - private static void parseJsonToActualObject(String jsonStr) { - long startParsTime = System.nanoTime(); - CustomerPortfolioSimple customerPortfolioSimple = gson.fromJson(jsonStr , CustomerPortfolioSimple.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime; - logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - customerPortfolioSimple = null; - Runtime.getRuntime().gc(); - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java deleted file mode 100644 index 9330333604..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.baeldung.data.simple; - -import java.io.IOException; -import java.util.Map; - -import com.baeldung.data.utility.Utility; -import org.apache.log4j.Logger; -import com.baeldung.pojo.simple.CustomerPortfolioSimple; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * - * This class is responsible for performing functions for Simple type - * Jackson like - * Java to Json - * Json to Map - * Json to Java Object - */ - -public class SimpleDataJackson { - - private static final Logger logger = Logger.getLogger(SimpleDataJackson.class); - - static ObjectMapper mapper = new ObjectMapper(); - - static long generateJsonAvgTime = 0L; - - static long parseJsonToMapAvgTime = 0L; - - static long parseJsonToActualObjectAvgTime = 0L; - - public static void main(String[] args) throws IOException { - CustomerPortfolioSimple customerPortfolioSimple = SimpleDataGeneration.generateData(); - int j = 50; - for (int i = 0; i < j; i++) { - logger.info("-------Round " + (i + 1)); - String jsonStr = generateJson(customerPortfolioSimple); - logger.info("Size of Simple content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length)); - logger.info("--------------------------------------------------------------------------"); - - parseJsonToMap(jsonStr); - parseJsonToActualObject(jsonStr); - jsonStr = null; - } - - generateJsonAvgTime = generateJsonAvgTime / j; - parseJsonToMapAvgTime = parseJsonToMapAvgTime / j; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j; - - logger.info("--------------------------------------------------------------------------"); - logger.info("Average Time to Generate JSON : " + generateJsonAvgTime); - logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime); - logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime); - logger.info("--------------------------------------------------------------------------"); - } - - private static String generateJson(CustomerPortfolioSimple customerPortfolioSimple) throws JsonProcessingException { - Runtime.getRuntime().gc(); - long startParsTime = System.nanoTime(); - String json = mapper.writeValueAsString(customerPortfolioSimple); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - generateJsonAvgTime = generateJsonAvgTime + elapsedTime; - logger.info("Json Generation Time(ms):: " + elapsedTime); - return json; - } - - private static void parseJsonToMap(String jsonStr) throws JsonParseException , JsonMappingException , IOException { - long startParsTime = System.nanoTime(); - Map parsedMap = mapper.readValue(jsonStr , Map.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime; - logger.info("Generating Map from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - parsedMap = null; - Runtime.getRuntime().gc(); - } - - private static void parseJsonToActualObject(String jsonStr) throws JsonParseException , JsonMappingException , - IOException { - long startParsTime = System.nanoTime(); - CustomerPortfolioSimple customerPortfolioSimple = mapper.readValue(jsonStr , CustomerPortfolioSimple.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime; - logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime); - customerPortfolioSimple = null; - Runtime.getRuntime().gc(); - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java b/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java deleted file mode 100644 index 8b0c402e47..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.baeldung.data.utility; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.util.Random; - -public class Utility { - - public static String generateRandomName() { - char[] chars = "abcdefghijklmnopqrstuvwxyz ".toCharArray(); - StringBuilder sb = new StringBuilder(); - Random random = new Random(); - for (int i = 0; i < 8; i++) { - char c = chars[random.nextInt(chars.length)]; - sb.append(c); - } - return sb.toString(); - } - - public static String generateRandomAddress() { - char[] chars = "abcdefghijklmnopqrstuvwxyz ".toCharArray(); - StringBuilder sb = new StringBuilder(); - Random random = new Random(); - for (int i = 0; i < 30; i++) { - char c = chars[random.nextInt(chars.length)]; - sb.append(c); - } - return sb.toString(); - } - - public static String generateRandomZip() { - char[] chars = "1234567890".toCharArray(); - StringBuilder sb = new StringBuilder(); - Random random = new Random(); - for (int i = 0; i < 8; i++) { - char c = chars[random.nextInt(chars.length)]; - sb.append(c); - } - return sb.toString(); - } - - public static String generateRandomPhone() { - char[] chars = "1234567890".toCharArray(); - StringBuilder sb = new StringBuilder(); - Random random = new Random(); - for (int i = 0; i < 10; i++) { - char c = chars[random.nextInt(chars.length)]; - sb.append(c); - } - return sb.toString(); - } - - public static String readFile(String fileName , Class clazz) throws IOException { - String dir = clazz.getResource("/").getFile(); - dir = dir + "/" + fileName; - - BufferedReader br = new BufferedReader(new FileReader(dir)); - try { - StringBuilder sb = new StringBuilder(); - String line = br.readLine(); - - while (line != null) { - sb.append(line); - sb.append(System.lineSeparator()); - line = br.readLine(); - } - return sb.toString(); - } finally { - br.close(); - } - } - - public static String bytesIntoMB(long bytes) { - long kilobyte = 1024; - long megabyte = kilobyte * 1024; - - if ((bytes >= 0) && (bytes < kilobyte)) { - return bytes + " B"; - - } else if ((bytes >= kilobyte) && (bytes < megabyte)) { - return (bytes / kilobyte) + " KB"; - - } else if ((bytes >= megabyte)) { - return (bytes / megabyte) + " MB"; - } - - return null; - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java deleted file mode 100644 index 79725a97bd..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.pojo.complex; - -import java.util.List; - -public class AddressDetails { - - private String address; - - private String zipcode; - - private List contactDetails; - - public String getZipcode() { - return zipcode; - } - - public void setZipcode(String zipcode) { - this.zipcode = zipcode; - } - - public List getContactDetails() { - return contactDetails; - } - - public void setContactDetails(List contactDetails) { - this.contactDetails = contactDetails; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java deleted file mode 100644 index 164fe3f470..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.pojo.complex; - -public class ContactDetails { - - private String mobile; - - private String landline; - - public String getMobile() { - return mobile; - } - - public void setMobile(String mobile) { - this.mobile = mobile; - } - - public String getLandline() { - return landline; - } - - public void setLandline(String landline) { - this.landline = landline; - } - -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java deleted file mode 100644 index 9bc5951716..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.pojo.complex; - -import java.util.List; - -import com.baeldung.pojo.simple.Customer; - -public class CustomerAddressDetails extends Customer { - - private List addressDetails; - - public List getAddressDetails() { - return addressDetails; - } - - public void setAddressDetails(List addressDetails) { - this.addressDetails = addressDetails; - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java deleted file mode 100644 index 13f9d240b8..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.pojo.complex; - -import java.util.List; - -public class CustomerPortfolioComplex { - - private List customerAddressDetailsList; - - public List getCustomerAddressDetailsList() { - return customerAddressDetailsList; - } - - public void setCustomerAddressDetailsList(List customerAddressDetailsList) { - this.customerAddressDetailsList = customerAddressDetailsList; - } - -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java deleted file mode 100644 index 3d5668f85a..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.pojo.simple; - - -public class Customer { - - private String firstName; - - private String lastName; - - private int age; - - 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; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java deleted file mode 100644 index 7cb684813c..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.pojo.simple; - -import java.util.List; - -public class CustomerPortfolioSimple { - - private List customerLists; - - public List getCustomerLists() { - return customerLists; - } - - public void setCustomerLists(List customerLists) { - this.customerLists = customerLists; - } -} diff --git a/gson-jackson-performance/src/main/resources/log4j.properties b/gson-jackson-performance/src/main/resources/log4j.properties deleted file mode 100644 index 371cbc9048..0000000000 --- a/gson-jackson-performance/src/main/resources/log4j.properties +++ /dev/null @@ -1,16 +0,0 @@ -# Root logger option -log4j.rootLogger=DEBUG, file - -# Redirect log messages to console -# log4j.appender.stdout=org.apache.log4j.ConsoleAppender -# log4j.appender.stdout.Target=System.out -# log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n - -# Redirect log messages to a log file, support file rolling. -log4j.appender.file=org.apache.log4j.RollingFileAppender -log4j.appender.file.File=log4j-application.log -log4j.appender.file.MaxFileSize=5MB -log4j.appender.file.MaxBackupIndex=10 -log4j.appender.file.layout=org.apache.log4j.PatternLayout -log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/gson/pom.xml b/gson/pom.xml index 4f331f6fd9..d864c289c2 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -19,7 +19,7 @@ com.google.guava guava - 18.0 + ${guava.version} commons-io diff --git a/guava18/pom.xml b/guava18/pom.xml index 6002b37d74..e26eb7313e 100644 --- a/guava18/pom.xml +++ b/guava18/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung @@ -14,12 +13,15 @@ guava 18.0 + junit junit - 4.12 + 4.13 + test + diff --git a/guava19/pom.xml b/guava19/pom.xml index 13f3b471f1..61fbf38575 100644 --- a/guava19/pom.xml +++ b/guava19/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 com.baeldung @@ -10,20 +11,23 @@ com.google.guava guava - 19.0 + ${guava.version} + junit junit 4.12 + test org.hamcrest hamcrest-all 1.3 + test - + @@ -42,4 +46,8 @@ + + 19.0 + + \ No newline at end of file diff --git a/handling-spring-static-resources/pom.xml b/handling-spring-static-resources/pom.xml index aca069e300..6dd0c95026 100644 --- a/handling-spring-static-resources/pom.xml +++ b/handling-spring-static-resources/pom.xml @@ -115,6 +115,7 @@ jackson-databind ${jackson.version}
+ org.hibernate hibernate-validator @@ -221,8 +222,7 @@ 1.9.2.RELEASE - - 2.7.2 + 2.7.8 1.7.13 diff --git a/jackson/pom.xml b/jackson/pom.xml index 17b0ac507e..e795ad11a2 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -174,7 +174,7 @@ 5.1.38 - 2.7.2 + 2.7.8 1.7.13 diff --git a/java-cassandra/pom.xml b/java-cassandra/pom.xml index 265a230eb4..a91c3b9b62 100644 --- a/java-cassandra/pom.xml +++ b/java-cassandra/pom.xml @@ -1,56 +1,36 @@ - + 4.0.0 com.baeldung cassandra-java-client 1.0.0-SNAPSHOT - - cassandra-java-client - - - UTF-8 - - - 1.7.21 - 1.1.7 - - - 1.3 - 4.12 - 1.10.19 - 6.8 - 3.5.1 - - - 3.5.1 - + + cassandra-java-client + + - 3.1.0 - - - - - + com.datastax.cassandra cassandra-driver-core ${cassandra-driver-core.version} true - + org.cassandraunit cassandra-unit 3.0.0.1 - + com.google.guava guava - 19.0 + ${guava.version} - - + + org.slf4j @@ -74,16 +54,16 @@ log4j-over-slf4j ${org.slf4j.version} - + - junit - junit - ${junit.version} - test + junit + junit + ${junit.version} + test - - - + + + java-cassandra @@ -97,6 +77,29 @@ - + + + UTF-8 + + 19.0 + + + 1.7.21 + 1.1.7 + + + 1.3 + 4.12 + 1.10.19 + 6.8 + 3.5.1 + + + 3.5.1 + + + 3.1.0 + + diff --git a/rest-assured/pom.xml b/rest-assured/pom.xml index 47241b18bd..e2a2af9cd9 100644 --- a/rest-assured/pom.xml +++ b/rest-assured/pom.xml @@ -1,257 +1,226 @@ - 4.0.0 - com.baeldung - rest-assured - 1.0 - rest-assured - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 8 - 8 - - - - - - - - javax.servlet - javax.servlet-api - 3.1-b06 - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + com.baeldung + rest-assured + 1.0 + rest-assured - - - javax.servlet - servlet-api - 2.5 - + + + javax.servlet + javax.servlet-api + 3.1-b06 + + + javax.servlet + servlet-api + 2.5 + + + org.eclipse.jetty + jetty-security + 9.2.0.M1 + + + org.eclipse.jetty + jetty-servlet + 9.2.0.M1 + + + org.eclipse.jetty + jetty-servlets + 9.2.0.M1 + + + org.eclipse.jetty + jetty-io + 9.2.0.M1 + + + org.eclipse.jetty + jetty-http + 9.2.0.M1 + + + org.eclipse.jetty + jetty-server + 9.2.0.M1 + + + org.eclipse.jetty + jetty-util + 9.2.0.M1 + - - - org.eclipse.jetty - jetty-security - 9.2.0.M1 - + + org.slf4j + slf4j-api + 1.7.21 + - - - org.eclipse.jetty - jetty-servlet - 9.2.0.M1 - + + log4j + log4j + 1.2.17 + + + org.slf4j + slf4j-log4j12 + 1.7.21 + - - - org.eclipse.jetty - jetty-servlets - 9.2.0.M1 - + + commons-logging + commons-logging + 1.2 + - - - org.eclipse.jetty - jetty-io - 9.2.0.M1 - + + org.apache.httpcomponents + httpcore + 4.4.5 + - - - org.eclipse.jetty - jetty-http - 9.2.0.M1 - + + org.apache.commons + commons-lang3 + 3.4 + + + com.github.fge + uri-template + 0.9 + + + com.googlecode.libphonenumber + libphonenumber + 7.4.5 + - - - org.eclipse.jetty - jetty-server - 9.2.0.M1 - + + javax.mail + mail + 1.4.7 + - - - org.eclipse.jetty - jetty-util - 9.2.0.M1 - + + joda-time + joda-time + 2.9.4 + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + - - - org.slf4j - slf4j-api - 1.7.21 - + + com.github.fge + msg-simple + 1.1 + - - - log4j - log4j - 1.2.17 - - - - org.slf4j - slf4j-log4j12 - 1.7.21 - + + com.github.fge + jackson-coreutils + 1.8 + - - - - commons-logging - commons-logging - 1.2 - + + com.google.guava + guava + ${guava.version} + + + com.github.fge + btf + 1.2 + - - org.apache.httpcomponents - httpcore - 4.4.5 - + + org.apache.httpcomponents + httpclient + 4.5.2 + - - - org.apache.commons - commons-lang3 - 3.4 - + + org.codehaus.groovy + groovy-all + 2.4.7 + - - - - com.github.fge - uri-template - 0.9 - + + com.github.tomakehurst + wiremock + 2.1.7 + + + io.rest-assured + rest-assured + 3.0.0 + test + + + io.rest-assured + json-schema-validator + 3.0.0 + + + com.github.fge + json-schema-validator + 2.2.6 + + + com.github.fge + json-schema-core + 1.2.5 + + + junit + junit + 4.3 + test + - - - com.googlecode.libphonenumber - libphonenumber - 7.4.5 - + + org.hamcrest + hamcrest-all + 1.3 + + + commons-collections + commons-collections + 3.2.2 + - - javax.mail - mail - 1.4.7 - + - - joda-time - joda-time - 2.9.4 - + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 8 + 8 + + + + - - com.fasterxml.jackson.core - jackson-annotations - 2.8.0 - + + 2.8.3 + 19.0 + - - com.fasterxml.jackson.core - jackson-databind - 2.8.0 - - - - com.fasterxml.jackson.core - jackson-core - 2.8.0 - - - - com.github.fge - msg-simple - 1.1 - - - - com.github.fge - jackson-coreutils - 1.8 - - - - - - com.google.guava - guava - 18.0 - - - com.github.fge - btf - 1.2 - - - - org.apache.httpcomponents - httpclient - 4.5.2 - - - - org.codehaus.groovy - groovy-all - 2.4.7 - - - - com.github.tomakehurst - wiremock - 2.1.7 - - - io.rest-assured - rest-assured - 3.0.0 - test - - - io.rest-assured - json-schema-validator - 3.0.0 - - - com.github.fge - json-schema-validator - 2.2.6 - - - com.github.fge - json-schema-core - 1.2.5 - - - junit - junit - 4.3 - test - - - - org.hamcrest - hamcrest-all - 1.3 - - - - commons-collections - commons-collections - 3.2.2 - - - diff --git a/rest-testing/pom.xml b/rest-testing/pom.xml index 652f2ab601..819e8de8a5 100644 --- a/rest-testing/pom.xml +++ b/rest-testing/pom.xml @@ -156,7 +156,7 @@ - 2.7.2 + 2.7.8 1.7.13 diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 7361d16b33..54d6eee01a 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -6,6 +6,7 @@ 0.1-SNAPSHOT spring-mvc-java war + @@ -34,16 +35,12 @@ spring-messaging ${org.springframework.version} + - - com.fasterxml.jackson.core - jackson-core - 2.7.3 - com.fasterxml.jackson.core jackson-databind - 2.7.3 + ${jackson.version} @@ -59,6 +56,7 @@ 1.2 runtime + org.springframework @@ -95,18 +93,6 @@ ${thymeleaf.version} - - - com.fasterxml.jackson.core - jackson-core - 2.1.2 - - - com.fasterxml.jackson.core - jackson-databind - 2.1.2 - - org.slf4j @@ -244,18 +230,23 @@ 4.2.5.RELEASE 4.0.4.RELEASE 2.1.4.RELEASE + 2.7.8 + 4.3.11.Final 5.1.38 + 1.7.21 1.1.5 5.2.2.Final + 19.0 3.4 + 1.3 4.12 diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 9c65ccdadd..849699cfae 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung 0.1-SNAPSHOT @@ -99,16 +100,11 @@ - - com.fasterxml.jackson.core - jackson-core - 2.7.2 - - - com.fasterxml.jackson.core - jackson-databind - 2.7.2 - + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + @@ -165,6 +161,7 @@ 4.2.5.RELEASE + 2.7.8 1.7.13 diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 331c9a644c..981ee9dabc 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -1,95 +1,102 @@ - - 4.0.0 - spring-rest-angular - spring-rest-angular - com.baeldung - 1.0 - war - - org.springframework.boot - spring-boot-starter-parent - 1.3.3.RELEASE - - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.data - spring-data-commons - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.hsqldb - hsqldb - runtime - - - org.springframework - spring-test - test - - - org.apache.commons - commons-lang3 - 3.3 - - - com.google.guava - guava - 19.0 - - - junit - junit - test - - - io.rest-assured - rest-assured - 3.0.0 - test - - - io.rest-assured - spring-mock-mvc - 3.0.0 - test - - - - angular-spring-rest-sample - + + 4.0.0 + spring-rest-angular + spring-rest-angular + com.baeldung + 1.0 + war - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + - - org.apache.maven.plugins - maven-war-plugin - - false - - + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.data + spring-data-commons + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hsqldb + hsqldb + runtime + + + org.springframework + spring-test + test + + + org.apache.commons + commons-lang3 + 3.3 + + + com.google.guava + guava + ${guava.version} + + + junit + junit + test + + + io.rest-assured + rest-assured + 3.0.0 + test + + + io.rest-assured + spring-mock-mvc + 3.0.0 + test + + + + + angular-spring-rest-sample + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + + + + + 19.0 + - - diff --git a/spring-security-rest-digest-auth/pom.xml b/spring-security-rest-digest-auth/pom.xml index 1eddbc17f8..1880e12a74 100644 --- a/spring-security-rest-digest-auth/pom.xml +++ b/spring-security-rest-digest-auth/pom.xml @@ -351,7 +351,7 @@ 1.1.3 - 2.7.2 + 2.7.8 5.2.2.Final diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index 77b11f1cb1..dff9f7ed4f 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -439,7 +439,7 @@ 3.6.2 - 2.7.2 + 2.7.8 1.4.01 diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 255cf25308..60f3ed41d1 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -109,7 +109,6 @@ - com.fasterxml.jackson.core jackson-databind @@ -117,7 +116,6 @@ - com.google.guava guava @@ -128,8 +126,8 @@ commons-lang3 ${commons-lang3.version} + - org.slf4j slf4j-api @@ -364,7 +362,7 @@ 3.0.1 1.1.0.Final 1.2 - 2.2.2 + 2.7.8 19.0 From eb7650eeadfa45961d9699f8620d78ab9c3e6ce0 Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 12 Oct 2016 08:00:02 +0300 Subject: [PATCH 056/193] cleanup and testing work --- guava18/pom.xml | 2 +- pom.xml | 1 - spring-mvc-java/pom.xml | 22 +++-- .../main/java/com/baeldung/model/Message.java | 16 ++-- .../com/baeldung/model/OutputMessage.java | 34 +++---- .../spring/web/config/WebSocketConfig.java | 18 ++-- .../web/controller/CompanyController.java | 88 +++++++++---------- .../web/controller/EmployeeController.java | 6 +- .../web/controller/MessageController.java | 18 ++-- .../advice/JsonpControllerAdvice.java | 6 +- ...st.java => AopLoggingIntegrationTest.java} | 2 +- ...ava => AopPerformanceIntegrationTest.java} | 2 +- ...java => AopPublishingIntegrationTest.java} | 2 +- ...pXmlConfigPerformanceIntegrationTest.java} | 2 +- .../htmlunit/HtmlUnitAndJUnitTest.java | 22 ----- .../HtmlUnitAndSpringIntegrationTest.java | 70 +++++++++++++++ .../htmlunit/HtmlUnitAndSpringTest.java | 79 ----------------- .../com/baeldung/htmlunit/HtmlUnitTest.java | 21 +++++ .../htmlunit/HtmlUnitWebScraping.java | 36 ++++---- .../com/baeldung/htmlunit/TestConfig.java | 42 ++++----- ...t.java => EmployeeMvcIntegrationTest.java} | 2 +- ...java => EmployeeNoMvcIntegrationTest.java} | 7 +- .../GreetControllerIntegrationTest.java | 8 +- ...Test.java => GreetControllerUnitTest.java} | 24 ++--- 24 files changed, 259 insertions(+), 271 deletions(-) rename spring-mvc-java/src/test/java/com/baeldung/aop/{AopLoggingTest.java => AopLoggingIntegrationTest.java} (98%) rename spring-mvc-java/src/test/java/com/baeldung/aop/{AopPerformanceTest.java => AopPerformanceIntegrationTest.java} (97%) rename spring-mvc-java/src/test/java/com/baeldung/aop/{AopPublishingTest.java => AopPublishingIntegrationTest.java} (97%) rename spring-mvc-java/src/test/java/com/baeldung/aop/{AopXmlConfigPerformanceTest.java => AopXmlConfigPerformanceIntegrationTest.java} (97%) delete mode 100644 spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java create mode 100644 spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java delete mode 100644 spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java create mode 100644 spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java rename spring-mvc-java/src/test/java/com/baeldung/web/controller/{EmployeeTest.java => EmployeeMvcIntegrationTest.java} (97%) rename spring-mvc-java/src/test/java/com/baeldung/web/controller/{EmployeeTestWithoutMockMvc.java => EmployeeNoMvcIntegrationTest.java} (97%) rename spring-mvc-java/src/test/java/com/baeldung/web/controller/{GreetControllerTest.java => GreetControllerUnitTest.java} (77%) diff --git a/guava18/pom.xml b/guava18/pom.xml index e26eb7313e..413e9c35b8 100644 --- a/guava18/pom.xml +++ b/guava18/pom.xml @@ -17,7 +17,7 @@ junit junit - 4.13 + 4.12 test diff --git a/pom.xml b/pom.xml index 5526c1e2a3..709c3e4e00 100644 --- a/pom.xml +++ b/pom.xml @@ -34,7 +34,6 @@ gson - gson-jackson-performance guava guava18 guava19 diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 54d6eee01a..8248343105 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -6,7 +6,7 @@ 0.1-SNAPSHOT spring-mvc-java war - + @@ -35,7 +35,7 @@ spring-messaging ${org.springframework.version} - + com.fasterxml.jackson.core @@ -56,7 +56,7 @@ 1.2 runtime - + org.springframework @@ -80,6 +80,11 @@ commons-fileupload 1.3.1 + + net.sourceforge.htmlunit + htmlunit + ${net.sourceforge.htmlunit} + @@ -196,7 +201,7 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java @@ -231,22 +236,22 @@ 4.0.4.RELEASE 2.1.4.RELEASE 2.7.8 - + 4.3.11.Final 5.1.38 - + 1.7.21 1.1.5 5.2.2.Final - + 19.0 3.4 - + 1.3 4.12 @@ -255,6 +260,7 @@ 4.5 2.9.0 2.23 + 3.5.1 2.6 diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/Message.java b/spring-mvc-java/src/main/java/com/baeldung/model/Message.java index c1f7f52215..76d53e132a 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/Message.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/Message.java @@ -2,14 +2,14 @@ package com.baeldung.model; public class Message { - private String from; - private String text; + private String from; + private String text; - public String getText() { - return text; - } + public String getText() { + return text; + } - public String getFrom() { - return from; - } + public String getFrom() { + return from; + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java b/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java index fc201ed016..9aad564b1e 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java @@ -2,26 +2,26 @@ package com.baeldung.model; public class OutputMessage { - private String from; - private String text; - private String time; + private String from; + private String text; + private String time; - public OutputMessage(final String from, final String text, final String time) { + public OutputMessage(final String from, final String text, final String time) { - this.from = from; - this.text = text; - this.time = time; - } + this.from = from; + this.text = text; + this.time = time; + } - public String getText() { - return text; - } + public String getText() { + return text; + } - public String getTime() { - return time; - } + public String getTime() { + return time; + } - public String getFrom() { - return from; - } + public String getFrom() { + return from; + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java index 6330041c60..5f3eb1312d 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java @@ -10,15 +10,15 @@ import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { - @Override - public void configureMessageBroker(final MessageBrokerRegistry config) { - config.enableSimpleBroker("/topic"); - config.setApplicationDestinationPrefixes("/app"); - } + @Override + public void configureMessageBroker(final MessageBrokerRegistry config) { + config.enableSimpleBroker("/topic"); + config.setApplicationDestinationPrefixes("/app"); + } - @Override - public void registerStompEndpoints(final StompEndpointRegistry registry) { - registry.addEndpoint("/chat").withSockJS(); - } + @Override + public void registerStompEndpoints(final StompEndpointRegistry registry) { + registry.addEndpoint("/chat").withSockJS(); + } } \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java index 8dcfe68a84..e92abfdc47 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java @@ -22,59 +22,55 @@ import com.baeldung.model.Company; @Controller public class CompanyController { - Map companyMap = new HashMap<>(); + Map companyMap = new HashMap<>(); - @RequestMapping(value = "/company", method = RequestMethod.GET) - public ModelAndView showForm() { - return new ModelAndView("companyHome", "company", new Company()); - } + @RequestMapping(value = "/company", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("companyHome", "company", new Company()); + } - @RequestMapping(value = "/company/{Id}", produces = { "application/json", - "application/xml" }, method = RequestMethod.GET) - public @ResponseBody Company getCompanyById(@PathVariable final long Id) { - return companyMap.get(Id); - } + @RequestMapping(value = "/company/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Company getCompanyById(@PathVariable final long Id) { + return companyMap.get(Id); + } - @RequestMapping(value = "/addCompany", method = RequestMethod.POST) - public String submit(@ModelAttribute("company") final Company company, - final BindingResult result, final ModelMap model) { - if (result.hasErrors()) { - return "error"; - } - model.addAttribute("name", company.getName()); - model.addAttribute("id", company.getId()); + @RequestMapping(value = "/addCompany", method = RequestMethod.POST) + public String submit(@ModelAttribute("company") final Company company, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", company.getName()); + model.addAttribute("id", company.getId()); - companyMap.put(company.getId(), company); + companyMap.put(company.getId(), company); - return "companyView"; - } + return "companyView"; + } - @RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET) - @ResponseBody - public ResponseEntity> getEmployeeDataFromCompany( - @MatrixVariable(pathVar = "employee") final Map matrixVars) { - return new ResponseEntity<>(matrixVars, HttpStatus.OK); - } + @RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity> getEmployeeDataFromCompany(@MatrixVariable(pathVar = "employee") final Map matrixVars) { + return new ResponseEntity<>(matrixVars, HttpStatus.OK); + } - @RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET) - @ResponseBody - public ResponseEntity> getCompanyName( - @MatrixVariable(value = "name", pathVar = "company") final String name) { - final Map result = new HashMap(); - result.put("name", name); - return new ResponseEntity<>(result, HttpStatus.OK); - } + @RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity> getCompanyName(@MatrixVariable(value = "name", pathVar = "company") final String name) { + final Map result = new HashMap(); + result.put("name", name); + return new ResponseEntity<>(result, HttpStatus.OK); + } - @RequestMapping(value = "/companyResponseBody", produces = MediaType.APPLICATION_JSON_VALUE) - @ResponseBody - public Company getCompanyResponseBody() { - final Company company = new Company(2, "ABC"); - return company; - } + @RequestMapping(value = "/companyResponseBody", produces = MediaType.APPLICATION_JSON_VALUE) + @ResponseBody + public Company getCompanyResponseBody() { + final Company company = new Company(2, "ABC"); + return company; + } - @RequestMapping(value = "/companyResponseEntity", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getCompanyResponseEntity() { - final Company company = new Company(3, "123"); - return new ResponseEntity(company, HttpStatus.OK); - } + @RequestMapping(value = "/companyResponseEntity", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity getCompanyResponseEntity() { + final Company company = new Company(3, "123"); + return new ResponseEntity(company, HttpStatus.OK); + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java index fd5fa6bc27..ef76059567 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -31,10 +31,8 @@ public class EmployeeController { return new ModelAndView("employeeHome", "employee", new Employee()); } - @RequestMapping(value = "/employee/{Id}", produces = {"application/json", "application/xml"}, method = RequestMethod.GET) - public - @ResponseBody - Employee getEmployeeById(@PathVariable final long Id) { + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { return employeeMap.get(Id); } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java index cfc73aeabe..111bf023f7 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java @@ -10,15 +10,15 @@ import org.springframework.web.bind.annotation.RequestParam; @RequestMapping("/message") public class MessageController { - @RequestMapping(value = "/showForm", method = RequestMethod.GET) - public String showForm() { - return "message"; - } + @RequestMapping(value = "/showForm", method = RequestMethod.GET) + public String showForm() { + return "message"; + } - @RequestMapping(value = "/processForm", method = RequestMethod.POST) - public String processForm(@RequestParam("message") final String message, final Model model) { - model.addAttribute("message", message); - return "message"; - } + @RequestMapping(value = "/processForm", method = RequestMethod.POST) + public String processForm(@RequestParam("message") final String message, final Model model) { + model.addAttribute("message", message); + return "message"; + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java index 8557b15492..7b2c6870df 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java @@ -6,8 +6,8 @@ import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpRespon @ControllerAdvice public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice { - public JsonpControllerAdvice() { - super("callback"); - } + public JsonpControllerAdvice() { + super("callback"); + } } diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingIntegrationTest.java similarity index 98% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingIntegrationTest.java index 19bf4d0fac..0837100bfa 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingIntegrationTest.java @@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class AopLoggingTest { +public class AopLoggingIntegrationTest { @Before public void setUp() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceIntegrationTest.java index 4ad5a3e1a6..c9ab2fb4bb 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceIntegrationTest.java @@ -24,7 +24,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class AopPerformanceTest { +public class AopPerformanceIntegrationTest { @Before public void setUp() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java index c075db9fc6..cf9c83a93d 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java @@ -23,7 +23,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class AopPublishingTest { +public class AopPublishingIntegrationTest { @Before public void setUp() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceIntegrationTest.java index 4d2df50d18..3b380315e8 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceIntegrationTest.java @@ -22,7 +22,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/com/baeldung/aop/beans.xml") -public class AopXmlConfigPerformanceTest { +public class AopXmlConfigPerformanceIntegrationTest { @Before public void setUp() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java deleted file mode 100644 index 58e5f9829b..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.htmlunit; - -import org.junit.Assert; -import org.junit.Test; - -import com.gargoylesoftware.htmlunit.WebClient; -import com.gargoylesoftware.htmlunit.html.HtmlPage; - -public class HtmlUnitAndJUnitTest { - - @Test - public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { - try (final WebClient webClient = new WebClient()) { - - webClient.getOptions().setThrowExceptionOnScriptError(false); - - final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); - Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); - } - } - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java new file mode 100644 index 0000000000..7a23908fe5 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java @@ -0,0 +1,70 @@ +package com.baeldung.htmlunit; + +import java.io.IOException; +import java.net.MalformedURLException; + +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.web.WebAppConfiguration; +import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; +import org.springframework.web.context.WebApplicationContext; + +import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlForm; +import com.gargoylesoftware.htmlunit.html.HtmlPage; +import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; +import com.gargoylesoftware.htmlunit.html.HtmlTextInput; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { TestConfig.class }) +public class HtmlUnitAndSpringIntegrationTest { + + @Autowired + private WebApplicationContext wac; + + private WebClient webClient; + + @Before + public void setup() { + webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build(); + } + + // + + @Test + public void givenAMessage_whenSent_thenItShows() throws FailingHttpStatusCodeException, MalformedURLException, IOException { + final String text = "Hello world!"; + HtmlPage page = webClient.getPage("http://localhost/message/showForm"); + System.out.println(page.asXml()); + + final HtmlTextInput messageText = page.getHtmlElementById("message"); + messageText.setValueAttribute(text); + + final HtmlForm form = page.getForms().get(0); + final HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit"); + final HtmlPage newPage = submit.click(); + + final String receivedText = newPage.getHtmlElementById("received").getTextContent(); + + Assert.assertEquals(receivedText, text); + System.out.println(newPage.asXml()); + } + + @Test + public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { + try (final WebClient client = new WebClient()) { + webClient.getOptions().setThrowExceptionOnScriptError(false); + + final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); + Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); + } + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java deleted file mode 100644 index dcc7555ae2..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.baeldung.htmlunit; - -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -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.web.WebAppConfiguration; -import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; -import org.springframework.web.context.WebApplicationContext; - -import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; -import com.gargoylesoftware.htmlunit.WebClient; -import com.gargoylesoftware.htmlunit.html.HtmlForm; -import com.gargoylesoftware.htmlunit.html.HtmlPage; -import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; -import com.gargoylesoftware.htmlunit.html.HtmlTextInput; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { TestConfig.class }) -public class HtmlUnitAndSpringTest { - - @Autowired - private WebApplicationContext wac; - - private WebClient webClient; - - @Before - public void setup() { - webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build(); - } - - @Test - @Ignore - public void givenAMessage_whenSent_thenItShows() { - final String text = "Hello world!"; - HtmlPage page; - - try { - - page = webClient.getPage("http://localhost/message/showForm"); - System.out.println(page.asXml()); - - final HtmlTextInput messageText = page.getHtmlElementById("message"); - messageText.setValueAttribute(text); - - final HtmlForm form = page.getForms().get(0); - final HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit"); - final HtmlPage newPage = submit.click(); - - final String receivedText = newPage.getHtmlElementById("received").getTextContent(); - - Assert.assertEquals(receivedText, text); - System.out.println(newPage.asXml()); - - } catch (FailingHttpStatusCodeException | IOException e) { - e.printStackTrace(); - } - - } - - @Test - public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { - try (final WebClient client = new WebClient()) { - - webClient.getOptions().setThrowExceptionOnScriptError(false); - - final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); - Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); - } - } - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java new file mode 100644 index 0000000000..6a7e961eb1 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.htmlunit; + +import org.junit.Assert; +import org.junit.Test; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlPage; + +public class HtmlUnitTest { + + @Test + public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { + try (final WebClient webClient = new WebClient()) { + webClient.getOptions().setThrowExceptionOnScriptError(false); + + final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); + Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); + } + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java index 16d18717e6..9919d7571d 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java @@ -10,31 +10,31 @@ import com.gargoylesoftware.htmlunit.html.HtmlPage; public class HtmlUnitWebScraping { - public static void main(final String[] args) throws Exception { - try (final WebClient webClient = new WebClient()) { + public static void main(final String[] args) throws Exception { + try (final WebClient webClient = new WebClient()) { - webClient.getOptions().setCssEnabled(false); - webClient.getOptions().setJavaScriptEnabled(false); + webClient.getOptions().setCssEnabled(false); + webClient.getOptions().setJavaScriptEnabled(false); - final HtmlPage page = webClient.getPage("http://www.baeldung.com/full_archive"); - final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath("(//ul[@class='car-monthlisting']/li)[1]/a").get(0); + final HtmlPage page = webClient.getPage("http://www.baeldung.com/full_archive"); + final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath("(//ul[@class='car-monthlisting']/li)[1]/a").get(0); - System.out.println("Entering: " + latestPostLink.getHrefAttribute()); + System.out.println("Entering: " + latestPostLink.getHrefAttribute()); - final HtmlPage postPage = latestPostLink.click(); + final HtmlPage postPage = latestPostLink.click(); - final HtmlHeading1 heading1 = (HtmlHeading1) postPage.getByXPath("//h1").get(0); - System.out.println("Title: " + heading1.getTextContent()); + final HtmlHeading1 heading1 = (HtmlHeading1) postPage.getByXPath("//h1").get(0); + System.out.println("Title: " + heading1.getTextContent()); - final List headings2 = (List) postPage.getByXPath("//h2"); + final List headings2 = (List) postPage.getByXPath("//h2"); - final StringBuilder sb = new StringBuilder(heading1.getTextContent()); - for (final HtmlHeading2 h2 : headings2) { - sb.append("\n").append(h2.getTextContent()); - } + final StringBuilder sb = new StringBuilder(heading1.getTextContent()); + for (final HtmlHeading2 h2 : headings2) { + sb.append("\n").append(h2.getTextContent()); + } - System.out.println(sb.toString()); - } - } + System.out.println(sb.toString()); + } + } } diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java index 1357310b1f..17a68d67a5 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -15,28 +15,28 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @ComponentScan(basePackages = { "com.baeldung.web.controller" }) public class TestConfig extends WebMvcConfigurerAdapter { - @Bean - public ViewResolver thymeleafViewResolver() { - final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); - viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setOrder(1); - return viewResolver; - } + @Bean + public ViewResolver thymeleafViewResolver() { + final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; + } - @Bean - public ServletContextTemplateResolver templateResolver() { - final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); - templateResolver.setPrefix("/WEB-INF/templates/"); - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); - return templateResolver; - } + @Bean + public ServletContextTemplateResolver templateResolver() { + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/templates/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } - @Bean - public SpringTemplateEngine templateEngine() { - final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); - templateEngine.setTemplateResolver(templateResolver()); - return templateEngine; - } + @Bean + public SpringTemplateEngine templateEngine() { + final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + return templateEngine; + } } diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeMvcIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeMvcIntegrationTest.java index c1e79a2a63..86420a5fbd 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeMvcIntegrationTest.java @@ -23,7 +23,7 @@ import com.baeldung.spring.web.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = WebConfig.class) -public class EmployeeTest { +public class EmployeeMvcIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeNoMvcIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeNoMvcIntegrationTest.java index 19806e0559..e84c20c973 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeNoMvcIntegrationTest.java @@ -1,7 +1,7 @@ package com.baeldung.web.controller; -import org.junit.Before; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -15,7 +15,7 @@ import com.baeldung.spring.web.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = WebConfig.class) -public class EmployeeTestWithoutMockMvc { +public class EmployeeNoMvcIntegrationTest { @Autowired private EmployeeController employeeController; @@ -25,9 +25,10 @@ public class EmployeeTestWithoutMockMvc { employeeController.initEmployees(); } + // + @Test public void whenInitEmployees_thenVerifyValuesInitiation() { - Employee employee1 = employeeController.employeeMap.get(1L); Employee employee2 = employeeController.employeeMap.get(2L); Employee employee3 = employeeController.employeeMap.get(3L); diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java index d1d1167369..db984eadfb 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.web.controller; - import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import javax.servlet.ServletContext; @@ -25,7 +24,7 @@ import com.baeldung.spring.web.config.ApplicationConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes = {ApplicationConfig.class}) +@ContextConfiguration(classes = { ApplicationConfig.class }) public class GreetControllerIntegrationTest { @Autowired @@ -35,7 +34,6 @@ public class GreetControllerIntegrationTest { private static final String CONTENT_TYPE = "application/json"; - @Before public void setup() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); @@ -74,8 +72,8 @@ public class GreetControllerIntegrationTest { @Test public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); + this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); } @Test diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerUnitTest.java similarity index 77% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerUnitTest.java index 0fd71a46dd..eacd256438 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerUnitTest.java @@ -1,17 +1,19 @@ package com.baeldung.web.controller; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + import org.junit.Before; import org.junit.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -public class GreetControllerTest { +public class GreetControllerUnitTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json"; @@ -43,19 +45,17 @@ public class GreetControllerTest { @Test public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()) - .andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")); + this.mockMvc.perform(get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")); } @Test public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)) - .andExpect(jsonPath("$.message").value("Hello World!!!")); + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World!!!")); } @Test public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()) - .andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(jsonPath("$.id").value(1)); + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)) + .andExpect(jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(jsonPath("$.id").value(1)); } } From 856be0a08a5ab123c82ead8a7a4db0dbd49bf0c7 Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 12 Oct 2016 08:02:05 +0300 Subject: [PATCH 057/193] formatting work --- .../org/baeldung/akka/SpringExtension.java | 1 - .../org/baeldung/akka/SpringAkkaTest.java | 4 +- .../caching/example/AbstractService.java | 2 +- .../config/StudentControllerConfig.java | 26 +- .../baeldung/controller/config/WebConfig.java | 4 +- .../controller/controller/RestController.java | 16 +- .../baeldung/controller/student/Student.java | 50 +- .../PropertiesWithPlaceHolderConfigurer.java | 1 - .../scopes/HelloMessageGenerator.java | 14 +- .../main/java/org/baeldung/scopes/Person.java | 34 +- .../org/baeldung/scopes/ScopesController.java | 30 +- .../baeldung/spring/config/ScopesConfig.java | 66 +- .../java/org/baeldung/spring43/cache/Foo.java | 1 - .../controller/ControllerAnnotationTest.java | 21 +- .../baeldung/controller/ControllerTest.java | 14 +- .../java/org/baeldung/scopes/ScopesTest.java | 44 +- .../AttributeAnnotationTest.java | 10 +- .../composedmapping/ComposedMappingTest.java | 7 +- ...ConfigurationConstructorInjectionTest.java | 2 +- .../TransactionalTestConfiguration.java | 1 - .../ScopeAnnotationsTest.java | 52 +- .../com/baeldung/autowire/sample/App.java | 10 +- .../autowire/sample/BarFormatter.java | 2 +- .../autowire/sample/FooFormatter.java | 2 +- .../baeldung/autowire/sample/FooService.java | 8 +- .../baeldung/autowire/sample/Formatter.java | 2 +- .../autowire/sample/FormatterType.java | 4 +- .../autowire/sample/FooServiceTest.java | 8 +- .../java/com/baeldung/TestController.java | 10 +- .../com/baeldung/WebjarsdemoApplication.java | 6 +- .../com/baeldung/git/CommitIdApplication.java | 5 +- .../baeldung/git/CommitInfoController.java | 2 +- .../baeldung/WebjarsdemoApplicationTests.java | 6 +- .../java/com/baeldung/git/CommitIdTest.java | 9 +- .../baeldung/SpringBootApplicationTest.java | 13 +- .../java/org/baeldung/SpringBootMailTest.java | 1 - .../client/DetailsServiceClientTest.java | 3 +- .../com/baeldung/SpringDemoApplication.java | 6 +- .../spring/data/couchbase/model/Campus.java | 34 +- .../spring/data/couchbase/model/Person.java | 25 +- .../spring/data/couchbase/model/Student.java | 38 +- .../repos/CustomStudentRepositoryImpl.java | 5 +- .../couchbase/repos/PersonRepository.java | 1 + .../couchbase/repos/StudentRepository.java | 1 + .../service/PersonRepositoryService.java | 5 +- .../service/PersonTemplateService.java | 7 +- .../service/StudentRepositoryService.java | 5 +- .../service/StudentTemplateService.java | 7 +- .../couchbase2b/repos/CampusRepository.java | 4 +- .../couchbase2b/repos/PersonRepository.java | 1 + .../couchbase2b/repos/StudentRepository.java | 1 + .../couchbase2b/service/CampusService.java | 6 +- .../service/CampusServiceImpl.java | 9 +- .../service/PersonServiceImpl.java | 3 +- .../service/StudentServiceImpl.java | 3 +- .../data/couchbase/MyCouchbaseConfig.java | 4 +- .../couchbase/service/StudentServiceTest.java | 38 +- .../MultiBucketCouchbaseConfig.java | 14 +- .../service/CampusServiceImplTest.java | 70 +- .../service/StudentServiceImplTest.java | 38 +- .../elasticsearch/ElasticSearchUnitTests.java | 40 +- .../gridfs/GridFSIntegrationTest.java | 2 +- .../MovieDatabaseNeo4jConfiguration.java | 8 +- .../MovieDatabaseNeo4jTestConfiguration.java | 9 +- .../spring/data/neo4j/domain/Movie.java | 11 +- .../spring/data/neo4j/domain/Person.java | 8 +- .../spring/data/neo4j/domain/Role.java | 3 +- .../data/neo4j/repostory/MovieRepository.java | 4 +- .../neo4j/repostory/PersonRepository.java | 3 +- .../data/neo4j/services/MovieService.java | 20 +- .../data/neo4j/MovieRepositoryTest.java | 9 +- .../data/redis/queue/MessagePublisher.java | 1 - .../redis/queue/RedisMessagePublisher.java | 3 +- .../InvalidResourceUsageExceptionTest.java | 26 +- .../hibernate/criteria/model/Item.java | 122 +- .../criteria/util/HibernateUtil.java | 11 +- .../criteria/view/ApplicationView.java | 406 +++--- .../hibernate/fetching/model/OrderDetail.java | 96 +- .../hibernate/fetching/model/UserEager.java | 104 +- .../hibernate/fetching/model/UserLazy.java | 105 +- .../fetching/util/HibernateUtil.java | 35 +- .../com/baeldung/persistence/model/Foo.java | 134 +- .../criteria/HibernateCriteriaTest.java | 306 +++-- .../criteria/HibernateCriteriaTestRunner.java | 12 +- .../criteria/HibernateCriteriaTestSuite.java | 2 +- .../fetching/HibernateFetchingTest.java | 51 +- .../persistence/save/SaveMethodsTest.java | 16 +- .../FooStoredProceduresIntegrationTest.java | 17 +- .../jms/DefaultTextMessageSenderTest.java | 3 +- .../jms/MapMessageConvertAndSendTest.java | 3 +- .../SecondLevelCacheIntegrationTest.java | 13 +- .../org/baeldung/persistence/model/User.java | 2 +- .../java/com/baeldung/MocksApplication.java | 6 +- .../velocity/controller/MainController.java | 12 +- .../velocity/service/ITutorialsService.java | 2 +- .../velocity/service/TutorialsService.java | 5 +- .../mvc/velocity/spring/config/WebConfig.java | 2 +- .../test/DataContentControllerTest.java | 5 +- .../mvc/velocity/test/config/TestConfig.java | 5 +- .../com/baeldung/spring/ClientWebConfig.java | 8 +- .../baeldung/spring/ClientWebConfigJava.java | 54 +- .../spring/controller/EmployeeController.java | 40 +- .../spring/controller/HelloController.java | 3 +- .../controller/HelloGuestController.java | 3 +- .../controller/HelloWorldController.java | 3 +- .../spring/controller/PersonController.java | 89 +- .../spring/controller/WelcomeController.java | 3 +- .../java/com/baeldung/spring/form/Person.java | 218 ++-- .../spring/validator/PersonValidator.java | 16 +- .../springquartz/SpringQuartzApp.java | 3 +- .../basics/scheduler/QrtzScheduler.java | 13 +- .../basics/scheduler/SampleJob.java | 3 +- .../AutoWiringSpringBeanJobFactory.java | 10 +- .../web/controller/CompanyController.java | 10 +- .../web/controller/ItemController.java | 36 +- .../advice/JsonpControllerAdvice.java | 6 +- .../controller/status/ForbiddenException.java | 4 +- .../java/org/baeldung/web/dto/Company.java | 50 +- .../java/org/baeldung/web/dto/FooProtos.java | 1153 ++++++++--------- .../status/ExampleControllerTest.java | 6 +- .../service/MyUserDetailsService.java | 4 +- .../config/parent/SecurityConfig.java | 1 - .../org/baeldung/spring/ListenerConfig.java | 10 +- .../java/org/baeldung/spring/WebConfig.java | 14 +- .../interceptor/SessionTimerInterceptor.java | 69 +- .../web/interceptor/UserInterceptor.java | 3 +- .../SessionTimerInterceptorTest.java | 37 +- .../web/interceptor/UserInterceptorTest.java | 7 +- 128 files changed, 2039 insertions(+), 2275 deletions(-) diff --git a/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java b/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java index 624e289812..aa5941c763 100644 --- a/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java +++ b/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java @@ -29,5 +29,4 @@ public class SpringExtension extends AbstractExtensionId getCommitId() { Map result = new HashMap<>(); - result.put("Commit message",commitMessage); + result.put("Commit message", commitMessage); result.put("Commit branch", branch); result.put("Commit id", commitId); return result; diff --git a/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java b/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java index 284cda5d31..c43b13ea0b 100644 --- a/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java +++ b/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java @@ -11,8 +11,8 @@ import org.springframework.test.context.web.WebAppConfiguration; @WebAppConfiguration public class WebjarsdemoApplicationTests { - @Test - public void contextLoads() { - } + @Test + public void contextLoads() { + } } diff --git a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java index e16791881e..c0fc1befd3 100644 --- a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java +++ b/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java @@ -32,13 +32,10 @@ public class CommitIdTest { LOG.info(commitMessage); LOG.info(branch); - assertThat(commitMessage) - .isNotEqualTo("UNKNOWN"); + assertThat(commitMessage).isNotEqualTo("UNKNOWN"); - assertThat(branch) - .isNotEqualTo("UNKNOWN"); + assertThat(branch).isNotEqualTo("UNKNOWN"); - assertThat(commitId) - .isNotEqualTo("UNKNOWN"); + assertThat(commitId).isNotEqualTo("UNKNOWN"); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java index ac7bcd62a9..1255180e44 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java @@ -31,22 +31,15 @@ public class SpringBootApplicationTest { private WebApplicationContext webApplicationContext; private MockMvc mockMvc; - @Before public void setupMockMvc() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) - .build(); + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception { - MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), - MediaType.APPLICATION_JSON.getSubtype(), - Charset.forName("utf8")); + MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")). - andExpect(MockMvcResultMatchers.status().isOk()). - andExpect(MockMvcResultMatchers.content().contentType(contentType)). - andExpect(jsonPath("$", hasSize(4))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4))); } } diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java index d36a7906a3..f4ce158661 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java @@ -69,7 +69,6 @@ public class SpringBootMailTest { return wiserMessage.getMimeMessage().getSubject(); } - private SimpleMailMessage composeEmailMessage() { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo(userTo); diff --git a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java index c594610be2..ba0da968ad 100644 --- a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java +++ b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java @@ -30,8 +30,7 @@ public class DetailsServiceClientTest { @Before public void setUp() throws Exception { String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john")); - this.server.expect(requestTo("/john/details")) - .andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); + this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); } @Test diff --git a/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java index 60548dd6e3..820e7e8004 100644 --- a/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java +++ b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java @@ -18,9 +18,9 @@ public class SpringDemoApplication extends SpringBootServletInitializer { protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SpringDemoApplication.class); } - + @Bean - public RestTemplate getRestTemplate(){ - return new RestTemplate(); + public RestTemplate getRestTemplate() { + return new RestTemplate(); } } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java index 201b14cf0b..c357ab8596 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java @@ -19,22 +19,27 @@ public class Campus { @Field @NotNull private Point location; - + public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public Point getLocation() { return location; } + public void setLocation(Point location) { this.location = location; } @@ -42,13 +47,13 @@ public class Campus { @Override public int hashCode() { int hash = 1; - if(id != null) { + if (id != null) { hash = hash * 31 + id.hashCode(); } - if(name != null) { + if (name != null) { hash = hash * 31 + name.hashCode(); } - if(location != null) { + if (location != null) { hash = hash * 31 + location.hashCode(); } return hash; @@ -56,30 +61,33 @@ public class Campus { @Override public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; Campus other = (Campus) obj; return this.hashCode() == other.hashCode(); } - + @SuppressWarnings("unused") - private Campus() {} - + private Campus() { + } + public Campus(Builder b) { this.id = b.id; this.name = b.name; this.location = b.location; } - + public static class Builder { private String id; private String name; private Point location; - + public static Builder newInstance() { return new Builder(); } - + public Campus build() { return new Campus(this); } @@ -93,7 +101,7 @@ public class Campus { this.name = name; return this; } - + public Builder location(Point location) { this.location = location; return this; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java index 9220e157ed..fd41427d20 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java @@ -24,7 +24,7 @@ public class Person { private DateTime created; @Field private DateTime updated; - + public Person(String id, String firstName, String lastName) { this.id = id; this.firstName = firstName; @@ -34,44 +34,53 @@ public class Person { public String getId() { return id; } + public void setId(String id) { this.id = id; } + 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; } + public DateTime getCreated() { return created; } + public void setCreated(DateTime created) { this.created = created; } + public DateTime getUpdated() { return updated; } + public void setUpdated(DateTime updated) { this.updated = updated; } - + @Override public int hashCode() { int hash = 1; - if(id != null) { + if (id != null) { hash = hash * 31 + id.hashCode(); } - if(firstName != null) { + if (firstName != null) { hash = hash * 31 + firstName.hashCode(); } - if(lastName != null) { + if (lastName != null) { hash = hash * 31 + lastName.hashCode(); } return hash; @@ -79,8 +88,10 @@ public class Person { @Override public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; Person other = (Person) obj; return this.hashCode() == other.hashCode(); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java index 9c266c2c62..726ed2347e 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java @@ -20,13 +20,13 @@ public class Student { private String id; @Field @NotNull - @Size(min=1, max=20) - @Pattern(regexp=NAME_REGEX) + @Size(min = 1, max = 20) + @Pattern(regexp = NAME_REGEX) private String firstName; @Field @NotNull - @Size(min=1, max=20) - @Pattern(regexp=NAME_REGEX) + @Size(min = 1, max = 20) + @Pattern(regexp = NAME_REGEX) private String lastName; @Field @Past @@ -38,8 +38,9 @@ public class Student { private DateTime updated; @Version private long version; - - public Student() {} + + public Student() { + } public Student(String id, String firstName, String lastName, DateTime dateOfBirth) { this.id = id; @@ -51,36 +52,47 @@ public class Student { public String getId() { return id; } + public void setId(String id) { this.id = id; } + 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; } + public DateTime getDateOfBirth() { return dateOfBirth; } + public void setDateOfBirth(DateTime dateOfBirth) { this.dateOfBirth = dateOfBirth; } + public DateTime getCreated() { return created; } + public void setCreated(DateTime created) { this.created = created; } + public DateTime getUpdated() { return updated; } + public void setUpdated(DateTime updated) { this.updated = updated; } @@ -88,16 +100,16 @@ public class Student { @Override public int hashCode() { int hash = 1; - if(id != null) { + if (id != null) { hash = hash * 31 + id.hashCode(); } - if(firstName != null) { + if (firstName != null) { hash = hash * 31 + firstName.hashCode(); } - if(lastName != null) { + if (lastName != null) { hash = hash * 31 + lastName.hashCode(); } - if(dateOfBirth != null) { + if (dateOfBirth != null) { hash = hash * 31 + dateOfBirth.hashCode(); } return hash; @@ -105,8 +117,10 @@ public class Student { @Override public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; Student other = (Student) obj; return this.hashCode() == other.hashCode(); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java index 66b672a4fd..751895502c 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java @@ -17,9 +17,6 @@ public class CustomStudentRepositoryImpl implements CustomStudentRepository { private CouchbaseTemplate template; public List findByFirstNameStartsWith(String s) { - return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName") - .startKey(s) - .stale(Stale.FALSE), - Student.class); + return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName").startKey(s).stale(Stale.FALSE), Student.class); } } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java index 14b77759e3..717feb858f 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface PersonRepository extends CrudRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java index 331ddc553d..9bbdeec642 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface StudentRepository extends CrudRepository, CustomStudentRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java index 90cc36780a..49548bdbfb 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java @@ -14,8 +14,9 @@ import org.springframework.stereotype.Service; @Service @Qualifier("PersonRepositoryService") public class PersonRepositoryService implements PersonService { - + private PersonRepository repo; + @Autowired public void setPersonRepository(PersonRepository repo) { this.repo = repo; @@ -28,7 +29,7 @@ public class PersonRepositoryService implements PersonService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java index 45e9b90a19..8398847f65 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java @@ -14,17 +14,18 @@ import com.couchbase.client.java.view.ViewQuery; @Service @Qualifier("PersonTemplateService") public class PersonTemplateService implements PersonService { - + private static final String DESIGN_DOC = "person"; private CouchbaseTemplate template; + @Autowired public void setCouchbaseTemplate(CouchbaseTemplate template) { this.template = template; } - public Person findOne(String id) { - return template.findById(id, Person.class); + public Person findOne(String id) { + return template.findById(id, Person.class); } public List findAll() { diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java index 58304afc1c..65f5a6e78e 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java @@ -14,8 +14,9 @@ import org.springframework.stereotype.Service; @Service @Qualifier("StudentRepositoryService") public class StudentRepositoryService implements StudentService { - + private StudentRepository repo; + @Autowired public void setStudentRepository(StudentRepository repo) { this.repo = repo; @@ -28,7 +29,7 @@ public class StudentRepositoryService implements StudentService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java index c3808e0015..8d1292b5e4 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java @@ -14,17 +14,18 @@ import com.couchbase.client.java.view.ViewQuery; @Service @Qualifier("StudentTemplateService") public class StudentTemplateService implements StudentService { - + private static final String DESIGN_DOC = "student"; private CouchbaseTemplate template; + @Autowired public void setCouchbaseTemplate(CouchbaseTemplate template) { this.template = template; } - public Student findOne(String id) { - return template.findById(id, Student.class); + public Student findOne(String id) { + return template.findById(id, Student.class); } public List findAll() { diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java index 2cf388f518..b1857222c5 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java @@ -11,9 +11,9 @@ import org.springframework.data.repository.CrudRepository; public interface CampusRepository extends CrudRepository { - @View(designDocument="campus", viewName="byName") + @View(designDocument = "campus", viewName = "byName") Set findByName(String name); - @Dimensional(dimensions=2, designDocument="campus_spatial", spatialViewName="byLocation") + @Dimensional(dimensions = 2, designDocument = "campus_spatial", spatialViewName = "byLocation") Set findByLocationNear(Point point, Distance distance); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java index e441bec6e4..ef37106c6d 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface PersonRepository extends CrudRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java index 2a960d37de..0d790d2f39 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface StudentRepository extends CrudRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java index d098c39011..58f00dda25 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java @@ -7,14 +7,14 @@ import org.springframework.data.geo.Distance; import org.springframework.data.geo.Point; public interface CampusService { - + Campus find(String id); Set findByName(String name); Set findByLocationNear(Point point, Distance distance); - + Set findAll(); - + void save(Campus campus); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java index 612774fec9..586f5f0dc1 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java @@ -15,21 +15,22 @@ import org.springframework.stereotype.Service; public class CampusServiceImpl implements CampusService { private CampusRepository repo; + @Autowired public void setCampusRepository(CampusRepository repo) { this.repo = repo; } - + @Override public Campus find(String id) { return repo.findOne(id); } - + @Override public Set findByName(String name) { return repo.findByName(name); } - + @Override public Set findByLocationNear(Point point, Distance distance) { return repo.findByLocationNear(point, distance); @@ -39,7 +40,7 @@ public class CampusServiceImpl implements CampusService { public Set findAll() { Set campuses = new HashSet<>(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { campuses.add(it.next()); } return campuses; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java index f1ff513bff..fe0a9e48cd 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java @@ -14,6 +14,7 @@ import org.springframework.stereotype.Service; public class PersonServiceImpl implements PersonService { private PersonRepository repo; + @Autowired public void setPersonRepository(PersonRepository repo) { this.repo = repo; @@ -26,7 +27,7 @@ public class PersonServiceImpl implements PersonService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java index 65400636cf..248d824081 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java @@ -14,6 +14,7 @@ import org.springframework.stereotype.Service; public class StudentServiceImpl implements StudentService { private StudentRepository repo; + @Autowired public void setStudentRepository(StudentRepository repo) { this.repo = repo; @@ -26,7 +27,7 @@ public class StudentServiceImpl implements StudentService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java index 8e6b971dbf..a37e918101 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java @@ -12,9 +12,9 @@ import org.springframework.data.couchbase.repository.config.EnableCouchbaseRepos import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; @Configuration -@EnableCouchbaseRepositories(basePackages={"org.baeldung.spring.data.couchbase"}) +@EnableCouchbaseRepositories(basePackages = { "org.baeldung.spring.data.couchbase" }) public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration { - + public static final List NODE_LIST = Arrays.asList("localhost"); public static final String BUCKET_NAME = "baeldung"; public static final String BUCKET_PASSWORD = ""; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java index 79948cbedf..0bf2c5d673 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java @@ -30,27 +30,17 @@ public abstract class StudentServiceTest extends IntegrationTest { static final String joeCollegeId = "student:" + joe + ":" + college; static final DateTime joeCollegeDob = DateTime.now().minusYears(21); static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob); - static final JsonObject jsonJoeCollege = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", joe) - .put("lastName", college) - .put("created", DateTime.now().getMillis()) - .put("version", 1); + static final JsonObject jsonJoeCollege = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1); static final String judy = "Judy"; static final String jetson = "Jetson"; static final String judyJetsonId = "student:" + judy + ":" + jetson; static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3); static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob); - static final JsonObject jsonJudyJetson = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", judy) - .put("lastName", jetson) - .put("created", DateTime.now().getMillis()) - .put("version", 1); - + static final JsonObject jsonJudyJetson = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1); + StudentService studentService; - + @BeforeClass public static void setupBeforeClass() { Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST); @@ -60,7 +50,7 @@ public abstract class StudentServiceTest extends IntegrationTest { bucket.close(); cluster.disconnect(); } - + @Test public void whenCreatingStudent_thenDocumentIsPersisted() { String firstName = "Eric"; @@ -75,7 +65,7 @@ public abstract class StudentServiceTest extends IntegrationTest { assertEquals(expectedStudent.getId(), actualStudent.getId()); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() { String firstName = "Er+ic"; String lastName = "Stratton"; @@ -85,7 +75,7 @@ public abstract class StudentServiceTest extends IntegrationTest { studentService.create(student); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() { String firstName = "Jane"; String lastName = "Doe"; @@ -130,11 +120,11 @@ public abstract class StudentServiceTest extends IntegrationTest { assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName)); } - + private boolean resultContains(List resultList, Student student) { boolean found = false; - for(Student p : resultList) { - if(p.getId().equals(student.getId())) { + for (Student p : resultList) { + if (p.getId().equals(student.getId())) { found = true; break; } @@ -144,8 +134,8 @@ public abstract class StudentServiceTest extends IntegrationTest { private boolean allResultsContainExpectedFirstName(List resultList, String firstName) { boolean found = false; - for(Student p : resultList) { - if(p.getFirstName().equals(firstName)) { + for (Student p : resultList) { + if (p.getFirstName().equals(firstName)) { found = true; break; } @@ -155,8 +145,8 @@ public abstract class StudentServiceTest extends IntegrationTest { private boolean allResultsContainExpectedLastName(List resultList, String lastName) { boolean found = false; - for(Student p : resultList) { - if(p.getLastName().equals(lastName)) { + for (Student p : resultList) { + if (p.getLastName().equals(lastName)) { found = true; break; } diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java index f419ba3499..fe32305feb 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java @@ -38,29 +38,25 @@ public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration { protected String getBucketPassword() { return DEFAULT_BUCKET_PASSWORD; } - + @Bean public Bucket campusBucket() throws Exception { return couchbaseCluster().openBucket("baeldung2", ""); } - + @Bean(name = "campusTemplate") public CouchbaseTemplate campusTemplate() throws Exception { - CouchbaseTemplate template = new CouchbaseTemplate( - couchbaseClusterInfo(), - campusBucket(), - mappingCouchbaseConverter(), - translationService()); + CouchbaseTemplate template = new CouchbaseTemplate(couchbaseClusterInfo(), campusBucket(), mappingCouchbaseConverter(), translationService()); template.setDefaultConsistency(getDefaultConsistency()); return template; } - + @Override public void configureRepositoryOperationsMapping(RepositoryOperationsMapping baseMapping) { try { baseMapping.mapEntity(Campus.class, campusTemplate()); } catch (Exception e) { - //custom Exception handling + // custom Exception handling } } diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java index 7e24952e32..d3982e1ecc 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java @@ -19,61 +19,29 @@ import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Point; public class CampusServiceImplTest extends MultiBucketIntegationTest { - + @Autowired private CampusServiceImpl campusService; - + @Autowired private CampusRepository campusRepo; - - private final Campus Brown = Campus.Builder.newInstance() - .id("campus:Brown") - .name("Brown") - .location(new Point(71.4025, 51.8268)) - .build(); - private final Campus Cornell = Campus.Builder.newInstance() - .id("campus:Cornell") - .name("Cornell") - .location(new Point(76.4833, 42.4459)) - .build(); - - private final Campus Columbia = Campus.Builder.newInstance() - .id("campus:Columbia") - .name("Columbia") - .location(new Point(73.9626, 40.8075)) - .build(); - - private final Campus Dartmouth = Campus.Builder.newInstance() - .id("campus:Dartmouth") - .name("Dartmouth") - .location(new Point(72.2887, 43.7044)) - .build(); + private final Campus Brown = Campus.Builder.newInstance().id("campus:Brown").name("Brown").location(new Point(71.4025, 51.8268)).build(); - private final Campus Harvard = Campus.Builder.newInstance() - .id("campus:Harvard") - .name("Harvard") - .location(new Point(71.1167, 42.3770)) - .build(); + private final Campus Cornell = Campus.Builder.newInstance().id("campus:Cornell").name("Cornell").location(new Point(76.4833, 42.4459)).build(); - private final Campus Penn = Campus.Builder.newInstance() - .id("campus:Penn") - .name("Penn") - .location(new Point(75.1932, 39.9522)) - .build(); + private final Campus Columbia = Campus.Builder.newInstance().id("campus:Columbia").name("Columbia").location(new Point(73.9626, 40.8075)).build(); + + private final Campus Dartmouth = Campus.Builder.newInstance().id("campus:Dartmouth").name("Dartmouth").location(new Point(72.2887, 43.7044)).build(); + + private final Campus Harvard = Campus.Builder.newInstance().id("campus:Harvard").name("Harvard").location(new Point(71.1167, 42.3770)).build(); + + private final Campus Penn = Campus.Builder.newInstance().id("campus:Penn").name("Penn").location(new Point(75.1932, 39.9522)).build(); + + private final Campus Princeton = Campus.Builder.newInstance().id("campus:Princeton").name("Princeton").location(new Point(74.6514, 40.3340)).build(); + + private final Campus Yale = Campus.Builder.newInstance().id("campus:Yale").name("Yale").location(new Point(72.9223, 41.3163)).build(); - private final Campus Princeton = Campus.Builder.newInstance() - .id("campus:Princeton") - .name("Princeton") - .location(new Point(74.6514, 40.3340)) - .build(); - - private final Campus Yale = Campus.Builder.newInstance() - .id("campus:Yale") - .name("Yale") - .location(new Point(72.9223, 41.3163)) - .build(); - private final Point Boston = new Point(71.0589, 42.3601); private final Point NewYorkCity = new Point(74.0059, 40.7128); @@ -88,7 +56,7 @@ public class CampusServiceImplTest extends MultiBucketIntegationTest { campusRepo.save(Princeton); campusRepo.save(Yale); } - + @Test public final void givenNameHarvard_whenFindByName_thenReturnsHarvard() throws Exception { Set campuses = campusService.findByName(Harvard.getName()); @@ -97,14 +65,14 @@ public class CampusServiceImplTest extends MultiBucketIntegationTest { assertTrue(campuses.size() == 1); assertTrue(campuses.contains(Harvard)); } - + @Test public final void givenHarvardId_whenFind_thenReturnsHarvard() throws Exception { Campus actual = campusService.find(Harvard.getId()); assertNotNull(actual); assertEquals(Harvard, actual); } - + @Test public final void whenFindAll_thenReturnsAll() throws Exception { Set campuses = campusService.findAll(); @@ -125,7 +93,7 @@ public class CampusServiceImplTest extends MultiBucketIntegationTest { assertTrue(campuses.contains(Harvard)); assertFalse(campuses.contains(Columbia)); } - + @Test public final void whenFindByLocationNearNewYorkCity_thenResultContainsColumbia() throws Exception { Set campuses = campusService.findByLocationNear(NewYorkCity, new Distance(1, Metrics.NEUTRAL)); diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java index 220c2c3b00..c503726377 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java @@ -31,28 +31,18 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { static final String joeCollegeId = "student:" + joe + ":" + college; static final DateTime joeCollegeDob = DateTime.now().minusYears(21); static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob); - static final JsonObject jsonJoeCollege = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", joe) - .put("lastName", college) - .put("created", DateTime.now().getMillis()) - .put("version", 1); + static final JsonObject jsonJoeCollege = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1); static final String judy = "Judy"; static final String jetson = "Jetson"; static final String judyJetsonId = "student:" + judy + ":" + jetson; static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3); static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob); - static final JsonObject jsonJudyJetson = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", judy) - .put("lastName", jetson) - .put("created", DateTime.now().getMillis()) - .put("version", 1); - + static final JsonObject jsonJudyJetson = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1); + @Autowired StudentServiceImpl studentService; - + @BeforeClass public static void setupBeforeClass() { Cluster cluster = CouchbaseCluster.create(MultiBucketCouchbaseConfig.NODE_LIST); @@ -62,7 +52,7 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { bucket.close(); cluster.disconnect(); } - + @Test public void whenCreatingStudent_thenDocumentIsPersisted() { String firstName = "Eric"; @@ -77,7 +67,7 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { assertEquals(expectedStudent.getId(), actualStudent.getId()); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() { String firstName = "Er+ic"; String lastName = "Stratton"; @@ -87,7 +77,7 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { studentService.create(student); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() { String firstName = "Jane"; String lastName = "Doe"; @@ -132,11 +122,11 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName)); } - + private boolean resultContains(List resultList, Student student) { boolean found = false; - for(Student p : resultList) { - if(p.getId().equals(student.getId())) { + for (Student p : resultList) { + if (p.getId().equals(student.getId())) { found = true; break; } @@ -146,8 +136,8 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { private boolean allResultsContainExpectedFirstName(List resultList, String firstName) { boolean found = false; - for(Student p : resultList) { - if(p.getFirstName().equals(firstName)) { + for (Student p : resultList) { + if (p.getFirstName().equals(firstName)) { found = true; break; } @@ -157,8 +147,8 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { private boolean allResultsContainExpectedLastName(List resultList, String lastName) { boolean found = false; - for(Student p : resultList) { - if(p.getLastName().equals(lastName)) { + for (Student p : resultList) { + if (p.getLastName().equals(lastName)) { found = true; break; } diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java index db304ee78d..4ab5d40788 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java @@ -43,8 +43,7 @@ public class ElasticSearchUnitTests { @Test public void givenJsonString_whenJavaObject_thenIndexDocument() { String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}"; - IndexResponse response = client.prepareIndex("people", "Doe") - .setSource(jsonObject).get(); + IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get(); String index = response.getIndex(); String type = response.getType(); assertTrue(response.isCreated()); @@ -55,8 +54,7 @@ public class ElasticSearchUnitTests { @Test public void givenDocumentId_whenJavaObject_thenDeleteDocument() { String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}"; - IndexResponse response = client.prepareIndex("people", "Doe") - .setSource(jsonObject).get(); + IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get(); String id = response.getId(); DeleteResponse deleteResponse = client.prepareDelete("people", "Doe", id).get(); assertTrue(deleteResponse.isFound()); @@ -77,29 +75,11 @@ public class ElasticSearchUnitTests { @Test public void givenSearchParamters_thenReturnResults() { boolean isExecutedSuccessfully = true; - SearchResponse response = client.prepareSearch() - .setTypes() - .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) - .setPostFilter(QueryBuilders.rangeQuery("age").from(5).to(15)) - .setFrom(0).setSize(60).setExplain(true) - .execute() - .actionGet(); + SearchResponse response = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.rangeQuery("age").from(5).to(15)).setFrom(0).setSize(60).setExplain(true).execute().actionGet(); - SearchResponse response2 = client.prepareSearch() - .setTypes() - .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) - .setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette")) - .setFrom(0).setSize(60).setExplain(true) - .execute() - .actionGet(); + SearchResponse response2 = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette")).setFrom(0).setSize(60).setExplain(true).execute().actionGet(); - SearchResponse response3 = client.prepareSearch() - .setTypes() - .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) - .setPostFilter(QueryBuilders.matchQuery("John", "Name*")) - .setFrom(0).setSize(60).setExplain(true) - .execute() - .actionGet(); + SearchResponse response3 = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.matchQuery("John", "Name*")).setFrom(0).setSize(60).setExplain(true).execute().actionGet(); try { response2.getHits(); response3.getHits(); @@ -114,14 +94,8 @@ public class ElasticSearchUnitTests { @Test public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException { - XContentBuilder builder = XContentFactory.jsonBuilder() - .startObject() - .field("fullName", "Test") - .field("salary", "11500") - .field("age", "10") - .endObject(); - IndexResponse response = client.prepareIndex("people", "Doe") - .setSource(builder).get(); + XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("fullName", "Test").field("salary", "11500").field("age", "10").endObject(); + IndexResponse response = client.prepareIndex("people", "Doe").setSource(builder).get(); assertTrue(response.isCreated()); } } diff --git a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java index 06ad21647b..bb4b268ca7 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java @@ -140,7 +140,7 @@ public class GridFSIntegrationTest { assertNotNull(gridFSDBFiles); assertThat(gridFSDBFiles.size(), is(2)); } - + @Test public void givenMetadataAndFilesExist_whenFindingAllFilesOnQuery_thenFilesWithMetadataAreFoundOnQuery() { DBObject metaDataUser1 = new BasicDBObject(); diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java index ac9a7260be..fb4fda1497 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java @@ -9,8 +9,7 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; - -@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"}) +@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) @Configuration @EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration { @@ -20,10 +19,7 @@ public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration(); - config - .driverConfiguration() - .setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver") - .setURI(URL); + config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver").setURI(URL); return config; } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java index 2b6394184d..81935b2293 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java @@ -10,20 +10,17 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; import org.springframework.data.neo4j.server.Neo4jServer; import org.springframework.transaction.annotation.EnableTransactionManagement; - @EnableTransactionManagement -@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"}) +@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) @Configuration @EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") -@Profile({"embedded", "test"}) +@Profile({ "embedded", "test" }) public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration(); - config - .driverConfiguration() - .setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); + config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); return config; } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java index e48dfaf276..029754c0fc 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java @@ -9,7 +9,7 @@ import org.neo4j.ogm.annotation.Relationship; import java.util.Collection; import java.util.List; -@JsonIdentityInfo(generator=JSOGGenerator.class) +@JsonIdentityInfo(generator = JSOGGenerator.class) @NodeEntity public class Movie { @@ -21,9 +21,11 @@ public class Movie { private int released; private String tagline; - @Relationship(type="ACTED_IN", direction = Relationship.INCOMING) private List roles; + @Relationship(type = "ACTED_IN", direction = Relationship.INCOMING) + private List roles; - public Movie() { } + public Movie() { + } public String getTitle() { return title; @@ -56,6 +58,5 @@ public class Movie { public void setRoles(List roles) { this.roles = roles; } - - + } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java index d96dc07530..dc5a850f29 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java @@ -1,6 +1,5 @@ package com.baeldung.spring.data.neo4j.domain; - import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; import org.neo4j.ogm.annotation.GraphId; @@ -9,7 +8,7 @@ import org.neo4j.ogm.annotation.Relationship; import java.util.List; -@JsonIdentityInfo(generator=JSOGGenerator.class) +@JsonIdentityInfo(generator = JSOGGenerator.class) @NodeEntity public class Person { @GraphId @@ -21,7 +20,8 @@ public class Person { @Relationship(type = "ACTED_IN") private List movies; - public Person() { } + public Person() { + } public String getName() { return name; @@ -46,5 +46,5 @@ public class Person { public void setMovies(List movies) { this.movies = movies; } - + } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java index 20512a10ad..40dabb054b 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java @@ -1,6 +1,5 @@ package com.baeldung.spring.data.neo4j.domain; - import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; import org.neo4j.ogm.annotation.EndNode; @@ -10,7 +9,7 @@ import org.neo4j.ogm.annotation.StartNode; import java.util.Collection; -@JsonIdentityInfo(generator=JSOGGenerator.class) +@JsonIdentityInfo(generator = JSOGGenerator.class) @RelationshipEntity(type = "ACTED_IN") public class Role { @GraphId diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java index 850d2336ba..1bd605a7bc 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java @@ -18,7 +18,5 @@ public interface MovieRepository extends GraphRepository { Collection findByTitleContaining(@Param("title") String title); @Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title as movie, collect(a.name) as cast LIMIT {limit}") - List> graph(@Param("limit") int limit); + List> graph(@Param("limit") int limit); } - - diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java index 4c287f99a4..f7f694c07f 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java @@ -4,8 +4,7 @@ import com.baeldung.spring.data.neo4j.domain.Person; import org.springframework.data.neo4j.repository.GraphRepository; import org.springframework.stereotype.Repository; - @Repository public interface PersonRepository extends GraphRepository { - + } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java index 532cc79091..d760d19066 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java @@ -15,31 +15,31 @@ public class MovieService { MovieRepository movieRepository; private Map toD3Format(Iterator> result) { - List> nodes = new ArrayList>(); - List> rels= new ArrayList>(); - int i=0; + List> nodes = new ArrayList>(); + List> rels = new ArrayList>(); + int i = 0; while (result.hasNext()) { Map row = result.next(); - nodes.add(map("title",row.get("movie"),"label","movie")); - int target=i; + nodes.add(map("title", row.get("movie"), "label", "movie")); + int target = i; i++; for (Object name : (Collection) row.get("cast")) { - Map actor = map("title", name,"label","actor"); + Map actor = map("title", name, "label", "actor"); int source = nodes.indexOf(actor); if (source == -1) { nodes.add(actor); source = i++; } - rels.add(map("source",source,"target",target)); + rels.add(map("source", source, "target", target)); } } return map("nodes", nodes, "links", rels); } private Map map(String key1, Object value1, String key2, Object value2) { - Map result = new HashMap(2); - result.put(key1,value1); - result.put(key2,value2); + Map result = new HashMap(2); + result.put(key1, value1); + result.put(key2, value2); return result; } diff --git a/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java b/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java index 8061b3c2a7..0e54208c31 100644 --- a/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java +++ b/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java @@ -82,8 +82,7 @@ public class MovieRepositoryTest { @DirtiesContext public void testFindAll() { System.out.println("findAll"); - Collection result = - (Collection) movieRepository.findAll(); + Collection result = (Collection) movieRepository.findAll(); assertNotNull(result); assertEquals(1, result.size()); } @@ -93,8 +92,7 @@ public class MovieRepositoryTest { public void testFindByTitleContaining() { System.out.println("findByTitleContaining"); String title = "Italian"; - Collection result = - movieRepository.findByTitleContaining(title); + Collection result = movieRepository.findByTitleContaining(title); assertNotNull(result); assertEquals(1, result.size()); } @@ -126,8 +124,7 @@ public class MovieRepositoryTest { public void testDeleteAll() { System.out.println("deleteAll"); movieRepository.deleteAll(); - Collection result = - (Collection) movieRepository.findAll(); + Collection result = (Collection) movieRepository.findAll(); assertEquals(0, result.size()); } } diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java index 9a42545d6c..4c55fc3179 100644 --- a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java @@ -1,6 +1,5 @@ package com.baeldung.spring.data.redis.queue; - public interface MessagePublisher { void publish(final String message); diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java index f4b3180a37..2a595305bd 100644 --- a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java @@ -16,8 +16,7 @@ public class RedisMessagePublisher implements MessagePublisher { public RedisMessagePublisher() { } - public RedisMessagePublisher(final RedisTemplate redisTemplate, - final ChannelTopic topic) { + public RedisMessagePublisher(final RedisTemplate redisTemplate, final ChannelTopic topic) { this.redisTemplate = redisTemplate; this.topic = topic; } diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java index 9c4fd55fa4..64f12e82e9 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java @@ -18,16 +18,16 @@ import javax.sql.DataSource; @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) public class InvalidResourceUsageExceptionTest { - @Autowired - private IFooService fooService; + @Autowired + private IFooService fooService; - @Autowired - private DataSource restDataSource; + @Autowired + private DataSource restDataSource; - @Test(expected = InvalidDataAccessResourceUsageException.class) - public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() { - final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); - jdbcTemplate.execute("revoke select from tutorialuser"); + @Test(expected = InvalidDataAccessResourceUsageException.class) + public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + jdbcTemplate.execute("revoke select from tutorialuser"); try { fooService.findAll(); @@ -36,11 +36,11 @@ public class InvalidResourceUsageExceptionTest { } } - @Test(expected = BadSqlGrammarException.class) - public void whenIncorrectSql_thenBadSqlGrammarException() { - final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + @Test(expected = BadSqlGrammarException.class) + public void whenIncorrectSql_thenBadSqlGrammarException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); - jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class); - } + jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class); + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java index b8b012c061..957207b7e6 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java @@ -4,78 +4,78 @@ import java.io.Serializable; public class Item implements Serializable { - private static final long serialVersionUID = 1L; - private Integer itemId; - private String itemName; - private String itemDescription; - private Integer itemPrice; + private static final long serialVersionUID = 1L; + private Integer itemId; + private String itemName; + private String itemDescription; + private Integer itemPrice; - // constructors - public Item() { + // constructors + public Item() { - } + } - public Item(final Integer itemId, final String itemName, final String itemDescription) { - super(); - this.itemId = itemId; - this.itemName = itemName; - this.itemDescription = itemDescription; - } + public Item(final Integer itemId, final String itemName, final String itemDescription) { + super(); + this.itemId = itemId; + this.itemName = itemName; + this.itemDescription = itemDescription; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((itemId == null) ? 0 : itemId.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((itemId == null) ? 0 : itemId.hashCode()); + return result; + } - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Item other = (Item) obj; - if (itemId == null) { - if (other.itemId != null) - return false; - } else if (!itemId.equals(other.itemId)) - return false; - return true; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Item other = (Item) obj; + if (itemId == null) { + if (other.itemId != null) + return false; + } else if (!itemId.equals(other.itemId)) + return false; + return true; + } - public Integer getItemId() { - return itemId; - } + public Integer getItemId() { + return itemId; + } - public void setItemId(final Integer itemId) { - this.itemId = itemId; - } + public void setItemId(final Integer itemId) { + this.itemId = itemId; + } - public String getItemName() { - return itemName; - } + public String getItemName() { + return itemName; + } - public void setItemName(final String itemName) { - this.itemName = itemName; - } + public void setItemName(final String itemName) { + this.itemName = itemName; + } - public String getItemDescription() { - return itemDescription; - } + public String getItemDescription() { + return itemDescription; + } - public Integer getItemPrice() { - return itemPrice; - } + public Integer getItemPrice() { + return itemPrice; + } - public void setItemPrice(final Integer itemPrice) { - this.itemPrice = itemPrice; - } + public void setItemPrice(final Integer itemPrice) { + this.itemPrice = itemPrice; + } - public void setItemDescription(final String itemDescription) { - this.itemDescription = itemDescription; - } + public void setItemDescription(final String itemDescription) { + this.itemDescription = itemDescription; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java index 57f32cfe50..ff9ccb017b 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java @@ -5,16 +5,15 @@ import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { - + @SuppressWarnings("deprecation") public static Session getHibernateSession() { - final SessionFactory sf = new Configuration() - .configure("criteria.cfg.xml").buildSessionFactory(); + final SessionFactory sf = new Configuration().configure("criteria.cfg.xml").buildSessionFactory(); - // factory = new Configuration().configure().buildSessionFactory(); - final Session session = sf.openSession(); - return session; + // factory = new Configuration().configure().buildSessionFactory(); + final Session session = sf.openSession(); + return session; } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java index 4db94f2ad7..83e3c2f9a5 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java @@ -26,228 +26,226 @@ import com.baeldung.hibernate.criteria.util.HibernateUtil; public class ApplicationView { - // default Constructor - public ApplicationView() { + // default Constructor + public ApplicationView() { - } + } - public boolean checkIfCriteriaTimeLower() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - Transaction tx = null; - - // calculate the time taken by criteria - final long startTimeCriteria = System.nanoTime(); - cr.add(Restrictions.like("itemName", "%item One%")); - final List results = cr.list(); - final long endTimeCriteria = System.nanoTime(); - final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000; + public boolean checkIfCriteriaTimeLower() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + Transaction tx = null; - // calculate the time taken by HQL - final long startTimeHQL = System.nanoTime(); - tx = session.beginTransaction(); - final List items = session.createQuery("FROM Item where itemName like '%item One%'").list(); - final long endTimeHQL = System.nanoTime(); - final long durationHQL = (endTimeHQL - startTimeHQL) / 1000; + // calculate the time taken by criteria + final long startTimeCriteria = System.nanoTime(); + cr.add(Restrictions.like("itemName", "%item One%")); + final List results = cr.list(); + final long endTimeCriteria = System.nanoTime(); + final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000; - if (durationCriteria > durationHQL) { - return false; - } else { - return true; - } - } + // calculate the time taken by HQL + final long startTimeHQL = System.nanoTime(); + tx = session.beginTransaction(); + final List items = session.createQuery("FROM Item where itemName like '%item One%'").list(); + final long endTimeHQL = System.nanoTime(); + final long durationHQL = (endTimeHQL - startTimeHQL) / 1000; - // To get items having price more than 1000 - public String[] greaterThanCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.gt("itemPrice", 1000)); - final List greaterThanItemsList = cr.list(); - final String greaterThanItems[] = new String[greaterThanItemsList.size()]; - for (int i = 0; i < greaterThanItemsList.size(); i++) { - greaterThanItems[i] = greaterThanItemsList.get(i).getItemName(); - } - session.close(); - return greaterThanItems; - } + if (durationCriteria > durationHQL) { + return false; + } else { + return true; + } + } - // To get items having price less than 1000 - public String[] lessThanCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.lt("itemPrice", 1000)); - final List lessThanItemsList = cr.list(); - final String lessThanItems[] = new String[lessThanItemsList.size()]; - for (int i = 0; i < lessThanItemsList.size(); i++) { - lessThanItems[i] = lessThanItemsList.get(i).getItemName(); - } - session.close(); - return lessThanItems; - } + // To get items having price more than 1000 + public String[] greaterThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.gt("itemPrice", 1000)); + final List greaterThanItemsList = cr.list(); + final String greaterThanItems[] = new String[greaterThanItemsList.size()]; + for (int i = 0; i < greaterThanItemsList.size(); i++) { + greaterThanItems[i] = greaterThanItemsList.get(i).getItemName(); + } + session.close(); + return greaterThanItems; + } - // To get items whose Name start with Chair - public String[] likeCriteria() { - final Session session = HibernateUtil.getHibernateSession(); + // To get items having price less than 1000 + public String[] lessThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.lt("itemPrice", 1000)); + final List lessThanItemsList = cr.list(); + final String lessThanItems[] = new String[lessThanItemsList.size()]; + for (int i = 0; i < lessThanItemsList.size(); i++) { + lessThanItems[i] = lessThanItemsList.get(i).getItemName(); + } + session.close(); + return lessThanItems; + } - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.like("itemName", "%chair%")); - final List likeItemsList = cr.list(); - final String likeItems[] = new String[likeItemsList.size()]; - for (int i = 0; i < likeItemsList.size(); i++) { - likeItems[i] = likeItemsList.get(i).getItemName(); - } - session.close(); - return likeItems; - } + // To get items whose Name start with Chair + public String[] likeCriteria() { + final Session session = HibernateUtil.getHibernateSession(); - // Case sensitive search - public String[] likeCaseCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.ilike("itemName", "%Chair%")); - final List ilikeItemsList = cr.list(); - final String ilikeItems[] = new String[ilikeItemsList.size()]; - for (int i = 0; i < ilikeItemsList.size(); i++) { - ilikeItems[i] = ilikeItemsList.get(i).getItemName(); - } - session.close(); - return ilikeItems; - } + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.like("itemName", "%chair%")); + final List likeItemsList = cr.list(); + final String likeItems[] = new String[likeItemsList.size()]; + for (int i = 0; i < likeItemsList.size(); i++) { + likeItems[i] = likeItemsList.get(i).getItemName(); + } + session.close(); + return likeItems; + } - // To get records having itemPrice in between 100 and 200 - public String[] betweenCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - // To get items having price more than 1000 - cr.add(Restrictions.between("itemPrice", 100, 200)); - final List betweenItemsList = cr.list(); - final String betweenItems[] = new String[betweenItemsList.size()]; - for (int i = 0; i < betweenItemsList.size(); i++) { - betweenItems[i] = betweenItemsList.get(i).getItemName(); - } - session.close(); - return betweenItems; - } + // Case sensitive search + public String[] likeCaseCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.ilike("itemName", "%Chair%")); + final List ilikeItemsList = cr.list(); + final String ilikeItems[] = new String[ilikeItemsList.size()]; + for (int i = 0; i < ilikeItemsList.size(); i++) { + ilikeItems[i] = ilikeItemsList.get(i).getItemName(); + } + session.close(); + return ilikeItems; + } - // To check if the given property is null - public String[] nullCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNull("itemDescription")); - final List nullItemsList = cr.list(); - final String nullDescItems[] = new String[nullItemsList.size()]; - for (int i = 0; i < nullItemsList.size(); i++) { - nullDescItems[i] = nullItemsList.get(i).getItemName(); - } - session.close(); - return nullDescItems; - } + // To get records having itemPrice in between 100 and 200 + public String[] betweenCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + // To get items having price more than 1000 + cr.add(Restrictions.between("itemPrice", 100, 200)); + final List betweenItemsList = cr.list(); + final String betweenItems[] = new String[betweenItemsList.size()]; + for (int i = 0; i < betweenItemsList.size(); i++) { + betweenItems[i] = betweenItemsList.get(i).getItemName(); + } + session.close(); + return betweenItems; + } - // To check if the given property is not null - public String[] notNullCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNotNull("itemDescription")); - final List notNullItemsList = cr.list(); - final String notNullDescItems[] = new String[notNullItemsList.size()]; - for (int i = 0; i < notNullItemsList.size(); i++) { - notNullDescItems[i] = notNullItemsList.get(i).getItemName(); - } - session.close(); - return notNullDescItems; - } + // To check if the given property is null + public String[] nullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNull("itemDescription")); + final List nullItemsList = cr.list(); + final String nullDescItems[] = new String[nullItemsList.size()]; + for (int i = 0; i < nullItemsList.size(); i++) { + nullDescItems[i] = nullItemsList.get(i).getItemName(); + } + session.close(); + return nullDescItems; + } - // Adding more than one expression in one cr - public String[] twoCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNull("itemDescription")); - cr.add(Restrictions.like("itemName", "chair%")); - final List notNullItemsList = cr.list(); - final String notNullDescItems[] = new String[notNullItemsList.size()]; - for (int i = 0; i < notNullItemsList.size(); i++) { - notNullDescItems[i] = notNullItemsList.get(i).getItemName(); - } - session.close(); - return notNullDescItems; - } + // To check if the given property is not null + public String[] notNullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNotNull("itemDescription")); + final List notNullItemsList = cr.list(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i).getItemName(); + } + session.close(); + return notNullDescItems; + } - // To get items matching with the above defined conditions joined - // with Logical AND - public String[] andLogicalCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); - final Criterion chairItems = Restrictions.like("itemName", "Chair%"); - final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems); - cr.add(andExample); - final List andItemsList = cr.list(); - final String andItems[] = new String[andItemsList.size()]; - for (int i = 0; i < andItemsList.size(); i++) { - andItems[i] = andItemsList.get(i).getItemName(); - } - session.close(); - return andItems; - } + // Adding more than one expression in one cr + public String[] twoCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNull("itemDescription")); + cr.add(Restrictions.like("itemName", "chair%")); + final List notNullItemsList = cr.list(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i).getItemName(); + } + session.close(); + return notNullDescItems; + } - // To get items matching with the above defined conditions joined - // with Logical OR - public String[] orLogicalCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); - final Criterion chairItems = Restrictions.like("itemName", "Chair%"); - final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems); - cr.add(orExample); - final List orItemsList = cr.list(); - final String orItems[] = new String[orItemsList.size()]; - for (int i = 0; i < orItemsList.size(); i++) { - orItems[i] = orItemsList.get(i).getItemName(); - } - session.close(); - return orItems; - } + // To get items matching with the above defined conditions joined + // with Logical AND + public String[] andLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); + final Criterion chairItems = Restrictions.like("itemName", "Chair%"); + final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems); + cr.add(andExample); + final List andItemsList = cr.list(); + final String andItems[] = new String[andItemsList.size()]; + for (int i = 0; i < andItemsList.size(); i++) { + andItems[i] = andItemsList.get(i).getItemName(); + } + session.close(); + return andItems; + } - // Sorting example - public String[] sortingCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.addOrder(Order.asc("itemName")); - cr.addOrder(Order.desc("itemPrice")).list(); - final List sortedItemsList = cr.list(); - final String sortedItems[] = new String[sortedItemsList.size()]; - for (int i = 0; i < sortedItemsList.size(); i++) { - sortedItems[i] = sortedItemsList.get(i).getItemName(); - } - session.close(); - return sortedItems; - } + // To get items matching with the above defined conditions joined + // with Logical OR + public String[] orLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); + final Criterion chairItems = Restrictions.like("itemName", "Chair%"); + final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems); + cr.add(orExample); + final List orItemsList = cr.list(); + final String orItems[] = new String[orItemsList.size()]; + for (int i = 0; i < orItemsList.size(); i++) { + orItems[i] = orItemsList.get(i).getItemName(); + } + session.close(); + return orItems; + } - // Set projections Row Count - public Long[] projectionRowCount() { - final Session session = HibernateUtil.getHibernateSession(); - final List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()) - .list(); - final Long projectedRowCount[] = new Long[itemProjected.size()]; - for (int i = 0; i < itemProjected.size(); i++) { - projectedRowCount[i] = itemProjected.get(i); - } - session.close(); - return projectedRowCount; - } + // Sorting example + public String[] sortingCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.addOrder(Order.asc("itemName")); + cr.addOrder(Order.desc("itemPrice")).list(); + final List sortedItemsList = cr.list(); + final String sortedItems[] = new String[sortedItemsList.size()]; + for (int i = 0; i < sortedItemsList.size(); i++) { + sortedItems[i] = sortedItemsList.get(i).getItemName(); + } + session.close(); + return sortedItems; + } - // Set projections average of itemPrice - public Double[] projectionAverage() { - final Session session = HibernateUtil.getHibernateSession(); - final List avgItemPriceList = session.createCriteria(Item.class) - .setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); + // Set projections Row Count + public Long[] projectionRowCount() { + final Session session = HibernateUtil.getHibernateSession(); + final List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()).list(); + final Long projectedRowCount[] = new Long[itemProjected.size()]; + for (int i = 0; i < itemProjected.size(); i++) { + projectedRowCount[i] = itemProjected.get(i); + } + session.close(); + return projectedRowCount; + } - final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; - for (int i = 0; i < avgItemPriceList.size(); i++) { - avgItemPrice[i] = (Double) avgItemPriceList.get(i); - } - session.close(); - return avgItemPrice; - } + // Set projections average of itemPrice + public Double[] projectionAverage() { + final Session session = HibernateUtil.getHibernateSession(); + final List avgItemPriceList = session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); + + final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; + for (int i = 0; i < avgItemPriceList.size(); i++) { + avgItemPrice[i] = (Double) avgItemPriceList.get(i); + } + session.close(); + return avgItemPrice; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java index ec8dc32200..f4a9b8a678 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java @@ -5,54 +5,54 @@ import java.io.Serializable; import java.sql.Date; @Entity -@Table (name = "USER_ORDER") -public class OrderDetail implements Serializable{ +@Table(name = "USER_ORDER") +public class OrderDetail implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name="ORDER_ID") - private Long orderId; - - public OrderDetail(){ - } - - public OrderDetail(Date orderDate, String orderDesc) { - super(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OrderDetail other = (OrderDetail) obj; - if (orderId == null) { - if (other.orderId != null) - return false; - } else if (!orderId.equals(other.orderId)) - return false; - - return true; - } + private static final long serialVersionUID = 1L; - public Long getOrderId() { - return orderId; - } - public void setOrderId(Long orderId) { - this.orderId = orderId; - } + @Id + @GeneratedValue + @Column(name = "ORDER_ID") + private Long orderId; + + public OrderDetail() { + } + + public OrderDetail(Date orderDate, String orderDesc) { + super(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OrderDetail other = (OrderDetail) obj; + if (orderId == null) { + if (other.orderId != null) + return false; + } else if (!orderId.equals(other.orderId)) + return false; + + return true; + } + + public Long getOrderId() { + return orderId; + } + + public void setOrderId(Long orderId) { + this.orderId = orderId; + } } - - diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java index 22b4fdc76c..2559d5f048 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java @@ -6,66 +6,66 @@ import java.util.HashSet; import java.util.Set; @Entity -@Table (name = "USER") +@Table(name = "USER") public class UserEager implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name="USER_ID") - private Long userId; - - @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") - private Set orderDetail = new HashSet(); - public UserEager() { - } + private static final long serialVersionUID = 1L; - public UserEager(final Long userId) { - super(); - this.userId = userId; - } + @Id + @GeneratedValue + @Column(name = "USER_ID") + private Long userId; - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((userId == null) ? 0 : userId.hashCode()); - return result; - } + @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") + private Set orderDetail = new HashSet(); - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final UserEager other = (UserEager) obj; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; - } + public UserEager() { + } - public Long getUserId() { - return userId; - } + public UserEager(final Long userId) { + super(); + this.userId = userId; + } - public void setUserId(final Long userId) { - this.userId = userId; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } - public Set getOrderDetail() { - return orderDetail; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final UserEager other = (UserEager) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } - public void setOrderDetail(Set orderDetail) { - this.orderDetail = orderDetail; - } + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java index 5038fb90ef..5852e74418 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java @@ -6,67 +6,66 @@ import java.util.HashSet; import java.util.Set; @Entity -@Table (name = "USER") +@Table(name = "USER") public class UserLazy implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name="USER_ID") - private Long userId; - - @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") - private Set orderDetail = new HashSet(); - public UserLazy() { - } + private static final long serialVersionUID = 1L; - public UserLazy(final Long userId) { - super(); - this.userId = userId; - } + @Id + @GeneratedValue + @Column(name = "USER_ID") + private Long userId; - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((userId == null) ? 0 : userId.hashCode()); - return result; - } + @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") + private Set orderDetail = new HashSet(); - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final UserLazy other = (UserLazy) obj; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; - } + public UserLazy() { + } - public Long getUserId() { - return userId; - } + public UserLazy(final Long userId) { + super(); + this.userId = userId; + } - public void setUserId(final Long userId) { - this.userId = userId; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } - - public Set getOrderDetail() { - return orderDetail; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final UserLazy other = (UserLazy) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } - public void setOrderDetail(Set orderDetail) { - this.orderDetail = orderDetail; - } + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java index bbd7729232..c7be96abb7 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java @@ -6,27 +6,24 @@ import org.hibernate.cfg.Configuration; public class HibernateUtil { - @SuppressWarnings("deprecation") - public static Session getHibernateSession(String fetchMethod) { - //two config files are there - //one with lazy loading enabled - //another lazy = false - SessionFactory sf; - if ("lazy".equals(fetchMethod)) { - sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); - } else { - sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); - } - - // fetching.cfg.xml is used for this example - return sf.openSession(); - } + @SuppressWarnings("deprecation") + public static Session getHibernateSession(String fetchMethod) { + // two config files are there + // one with lazy loading enabled + // another lazy = false + SessionFactory sf; + if ("lazy".equals(fetchMethod)) { + sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); + } else { + sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); + } + + // fetching.cfg.xml is used for this example + return sf.openSession(); + } public static Session getHibernateSession() { - return new Configuration() - .configure("fetching.cfg.xml") - .buildSessionFactory() - .openSession(); + return new Configuration().configure("fetching.cfg.xml").buildSessionFactory().openSession(); } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java index bdd48d6aa6..d36a1e58cf 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java +++ b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java @@ -16,92 +16,90 @@ import javax.persistence.NamedNativeQuery; import org.hibernate.envers.Audited; -@NamedNativeQueries({ - @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), - @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) }) +@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) }) @Entity @Audited // @Proxy(lazy = false) public class Foo implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private long id; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private long id; - @Column(name = "name") - private String name; + @Column(name = "name") + private String name; - @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "BAR_ID") - private Bar bar = new Bar(); + @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "BAR_ID") + private Bar bar = new Bar(); - public Foo() { - super(); - } + public Foo() { + super(); + } - public Foo(final String name) { - super(); - this.name = name; - } + public Foo(final String name) { + super(); + this.name = name; + } - // + // - public Bar getBar() { - return bar; - } + public Bar getBar() { + return bar; + } - public void setBar(final Bar bar) { - this.bar = bar; - } + public void setBar(final Bar bar) { + this.bar = bar; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(final String name) { - this.name = name; - } + public void setName(final String name) { + this.name = name; + } - // + // - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Foo other = (Foo) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Foo [name=").append(name).append("]"); - return builder.toString(); - } + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java index 3bd8c5ee00..88186098cc 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java @@ -14,178 +14,170 @@ import com.baeldung.hibernate.criteria.view.ApplicationView; public class HibernateCriteriaTest { - final private ApplicationView av = new ApplicationView(); + final private ApplicationView av = new ApplicationView(); - @Test - public void testPerformanceOfCriteria() { - assertTrue(av.checkIfCriteriaTimeLower()); - } - - @Test - public void testLikeCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list(); - final String expectedLikeItems[] = new String[expectedLikeList.size()]; - for (int i = 0; i < expectedLikeList.size(); i++) { - expectedLikeItems[i] = expectedLikeList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedLikeItems, av.likeCriteria()); - } + @Test + public void testPerformanceOfCriteria() { + assertTrue(av.checkIfCriteriaTimeLower()); + } - @Test - public void testILikeCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list(); - final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()]; - for (int i = 0; i < expectedChairCaseList.size(); i++) { - expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria()); + @Test + public void testLikeCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list(); + final String expectedLikeItems[] = new String[expectedLikeList.size()]; + for (int i = 0; i < expectedLikeList.size(); i++) { + expectedLikeItems[i] = expectedLikeList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedLikeItems, av.likeCriteria()); + } - } + @Test + public void testILikeCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list(); + final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()]; + for (int i = 0; i < expectedChairCaseList.size(); i++) { + expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria()); - @Test - public void testNullCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null") - .list(); - final String expectedIsNullDescItems[] = new String[expectedIsNullDescItemsList.size()]; - for (int i = 0; i < expectedIsNullDescItemsList.size(); i++) { - expectedIsNullDescItems[i] = expectedIsNullDescItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedIsNullDescItems, av.nullCriteria()); - } + } - @Test - public void testIsNotNullCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedIsNotNullDescItemsList = session - .createQuery("From Item where itemDescription is not null").list(); - final String expectedIsNotNullDescItems[] = new String[expectedIsNotNullDescItemsList.size()]; - for (int i = 0; i < expectedIsNotNullDescItemsList.size(); i++) { - expectedIsNotNullDescItems[i] = expectedIsNotNullDescItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedIsNotNullDescItems, av.notNullCriteria()); + @Test + public void testNullCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null").list(); + final String expectedIsNullDescItems[] = new String[expectedIsNullDescItemsList.size()]; + for (int i = 0; i < expectedIsNullDescItemsList.size(); i++) { + expectedIsNullDescItems[i] = expectedIsNullDescItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedIsNullDescItems, av.nullCriteria()); + } - } + @Test + public void testIsNotNullCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedIsNotNullDescItemsList = session.createQuery("From Item where itemDescription is not null").list(); + final String expectedIsNotNullDescItems[] = new String[expectedIsNotNullDescItemsList.size()]; + for (int i = 0; i < expectedIsNotNullDescItemsList.size(); i++) { + expectedIsNotNullDescItems[i] = expectedIsNotNullDescItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedIsNotNullDescItems, av.notNullCriteria()); - @Test - public void testAverageProjection() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item") - .list(); + } - final Double expectedAvgProjItems[] = new Double[expectedAvgProjItemsList.size()]; - for (int i = 0; i < expectedAvgProjItemsList.size(); i++) { - expectedAvgProjItems[i] = expectedAvgProjItemsList.get(i); - } - session.close(); - assertArrayEquals(expectedAvgProjItems, av.projectionAverage()); + @Test + public void testAverageProjection() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item").list(); - } + final Double expectedAvgProjItems[] = new Double[expectedAvgProjItemsList.size()]; + for (int i = 0; i < expectedAvgProjItemsList.size(); i++) { + expectedAvgProjItems[i] = expectedAvgProjItemsList.get(i); + } + session.close(); + assertArrayEquals(expectedAvgProjItems, av.projectionAverage()); - @Test - public void testRowCountProjection() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedCountProjItemsList = session.createQuery("Select count(*) from Item").list(); - final Long expectedCountProjItems[] = new Long[expectedCountProjItemsList.size()]; - for (int i = 0; i < expectedCountProjItemsList.size(); i++) { - expectedCountProjItems[i] = expectedCountProjItemsList.get(i); - } - session.close(); - assertArrayEquals(expectedCountProjItems, av.projectionRowCount()); - } + } - @Test - public void testOrCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedOrCritItemsList = session - .createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list(); - final String expectedOrCritItems[] = new String[expectedOrCritItemsList.size()]; - for (int i = 0; i < expectedOrCritItemsList.size(); i++) { - expectedOrCritItems[i] = expectedOrCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedOrCritItems, av.orLogicalCriteria()); - } + @Test + public void testRowCountProjection() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedCountProjItemsList = session.createQuery("Select count(*) from Item").list(); + final Long expectedCountProjItems[] = new Long[expectedCountProjItemsList.size()]; + for (int i = 0; i < expectedCountProjItemsList.size(); i++) { + expectedCountProjItems[i] = expectedCountProjItemsList.get(i); + } + session.close(); + assertArrayEquals(expectedCountProjItems, av.projectionRowCount()); + } - @Test - public void testAndCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedAndCritItemsList = session - .createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list(); - final String expectedAndCritItems[] = new String[expectedAndCritItemsList.size()]; - for (int i = 0; i < expectedAndCritItemsList.size(); i++) { - expectedAndCritItems[i] = expectedAndCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedAndCritItems, av.andLogicalCriteria()); - } + @Test + public void testOrCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedOrCritItemsList = session.createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list(); + final String expectedOrCritItems[] = new String[expectedOrCritItemsList.size()]; + for (int i = 0; i < expectedOrCritItemsList.size(); i++) { + expectedOrCritItems[i] = expectedOrCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedOrCritItems, av.orLogicalCriteria()); + } - @Test - public void testMultiCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedMultiCritItemsList = session - .createQuery("From Item where itemDescription is null and itemName like'chair%'").list(); - final String expectedMultiCritItems[] = new String[expectedMultiCritItemsList.size()]; - for (int i = 0; i < expectedMultiCritItemsList.size(); i++) { - expectedMultiCritItems[i] = expectedMultiCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedMultiCritItems, av.twoCriteria()); - } + @Test + public void testAndCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedAndCritItemsList = session.createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list(); + final String expectedAndCritItems[] = new String[expectedAndCritItemsList.size()]; + for (int i = 0; i < expectedAndCritItemsList.size(); i++) { + expectedAndCritItems[i] = expectedAndCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedAndCritItems, av.andLogicalCriteria()); + } - @Test - public void testSortCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedSortCritItemsList = session - .createQuery("From Item order by itemName asc, itemPrice desc").list(); - final String expectedSortCritItems[] = new String[expectedSortCritItemsList.size()]; - for (int i = 0; i < expectedSortCritItemsList.size(); i++) { - expectedSortCritItems[i] = expectedSortCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedSortCritItems, av.sortingCriteria()); - } + @Test + public void testMultiCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedMultiCritItemsList = session.createQuery("From Item where itemDescription is null and itemName like'chair%'").list(); + final String expectedMultiCritItems[] = new String[expectedMultiCritItemsList.size()]; + for (int i = 0; i < expectedMultiCritItemsList.size(); i++) { + expectedMultiCritItems[i] = expectedMultiCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedMultiCritItems, av.twoCriteria()); + } - @Test - public void testGreaterThanCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list(); - final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()]; - for (int i = 0; i < expectedGreaterThanList.size(); i++) { - expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedGreaterThanItems, av.greaterThanCriteria()); - } + @Test + public void testSortCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedSortCritItemsList = session.createQuery("From Item order by itemName asc, itemPrice desc").list(); + final String expectedSortCritItems[] = new String[expectedSortCritItemsList.size()]; + for (int i = 0; i < expectedSortCritItemsList.size(); i++) { + expectedSortCritItems[i] = expectedSortCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedSortCritItems, av.sortingCriteria()); + } - @Test - public void testLessThanCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedLessList = session.createQuery("From Item where itemPrice<1000").list(); - final String expectedLessThanItems[] = new String[expectedLessList.size()]; - for (int i = 0; i < expectedLessList.size(); i++) { - expectedLessThanItems[i] = expectedLessList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedLessThanItems, av.lessThanCriteria()); - } + @Test + public void testGreaterThanCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list(); + final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()]; + for (int i = 0; i < expectedGreaterThanList.size(); i++) { + expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedGreaterThanItems, av.greaterThanCriteria()); + } - @Test - public void betweenCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200") - .list(); - final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()]; - for (int i = 0; i < expectedBetweenList.size(); i++) { - expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria()); - } + @Test + public void testLessThanCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedLessList = session.createQuery("From Item where itemPrice<1000").list(); + final String expectedLessThanItems[] = new String[expectedLessList.size()]; + for (int i = 0; i < expectedLessList.size(); i++) { + expectedLessThanItems[i] = expectedLessList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedLessThanItems, av.lessThanCriteria()); + } + + @Test + public void betweenCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200").list(); + final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()]; + for (int i = 0; i < expectedBetweenList.size(); i++) { + expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria()); + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java index 8341df9fcb..99164efb7a 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java @@ -6,10 +6,10 @@ import org.junit.runner.notification.Failure; public class HibernateCriteriaTestRunner { - public static void main(final String[] args) { - Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class); - for (Failure failure : result.getFailures()) { - - } - } + public static void main(final String[] args) { + Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class); + for (Failure failure : result.getFailures()) { + + } + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java index ab27a6ba82..2911fb4725 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java @@ -7,5 +7,5 @@ import org.junit.runners.Suite; @Suite.SuiteClasses({ HibernateCriteriaTest.class }) public class HibernateCriteriaTestSuite { - + } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java index a650f8eb37..42245ca89e 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java @@ -13,31 +13,30 @@ import static org.junit.Assert.assertTrue; public class HibernateFetchingTest { + // this loads sample data in the database + @Before + public void addFecthingTestData() { + FetchingAppView fav = new FetchingAppView(); + fav.createTestData(); + } - //this loads sample data in the database - @Before - public void addFecthingTestData(){ - FetchingAppView fav = new FetchingAppView(); - fav.createTestData(); - } - - //testLazyFetching() tests the lazy loading - //Since it lazily loaded so orderDetalSetLazy won't - //be initialized - @Test - public void testLazyFetching() { - FetchingAppView fav = new FetchingAppView(); - Set orderDetalSetLazy = fav.lazyLoaded(); - assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); - } - - //testEagerFetching() tests the eager loading - //Since it eagerly loaded so orderDetalSetLazy would - //be initialized - @Test - public void testEagerFetching() { - FetchingAppView fav = new FetchingAppView(); - Set orderDetalSetEager = fav.eagerLoaded(); - assertTrue(Hibernate.isInitialized(orderDetalSetEager)); - } + // testLazyFetching() tests the lazy loading + // Since it lazily loaded so orderDetalSetLazy won't + // be initialized + @Test + public void testLazyFetching() { + FetchingAppView fav = new FetchingAppView(); + Set orderDetalSetLazy = fav.lazyLoaded(); + assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); + } + + // testEagerFetching() tests the eager loading + // Since it eagerly loaded so orderDetalSetLazy would + // be initialized + @Test + public void testEagerFetching() { + FetchingAppView fav = new FetchingAppView(); + Set orderDetalSetEager = fav.eagerLoaded(); + assertTrue(Hibernate.isInitialized(orderDetalSetEager)); + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java index aadaefbe44..2e729c5680 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java @@ -1,6 +1,5 @@ package com.baeldung.persistence.save; - import com.baeldung.persistence.model.Person; import org.hibernate.HibernateException; import org.hibernate.Session; @@ -25,16 +24,9 @@ public class SaveMethodsTest { @BeforeClass public static void beforeTests() { - Configuration configuration = new Configuration() - .addAnnotatedClass(Person.class) - .setProperty("hibernate.dialect", HSQLDialect.class.getName()) - .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test") - .setProperty("hibernate.connection.username", "sa") - .setProperty("hibernate.connection.password", "") - .setProperty("hibernate.hbm2ddl.auto", "update"); - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings( - configuration.getProperties()).build(); + Configuration configuration = new Configuration().addAnnotatedClass(Person.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()).setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update"); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } @@ -44,7 +36,6 @@ public class SaveMethodsTest { session.beginTransaction(); } - @Test public void whenPersistTransient_thenSavedToDatabaseOnCommit() { @@ -244,7 +235,6 @@ public class SaveMethodsTest { assertNotNull(session.get(Person.class, person.getId())); - } @Test diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java index 238b228101..db64107405 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java @@ -25,7 +25,7 @@ import com.baeldung.persistence.model.Foo; import com.baeldung.spring.PersistenceConfig; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {PersistenceConfig.class}, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) public class FooStoredProceduresIntegrationTest { private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresIntegrationTest.class); @@ -47,8 +47,7 @@ public class FooStoredProceduresIntegrationTest { private boolean getFoosByNameExists() { try { - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()") - .addEntity(Foo.class); + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); sqlQuery.list(); return true; } catch (SQLGrammarException e) { @@ -59,8 +58,7 @@ public class FooStoredProceduresIntegrationTest { private boolean getAllFoosExists() { try { - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()") - .addEntity(Foo.class); + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); sqlQuery.list(); return true; } catch (SQLGrammarException e) { @@ -80,8 +78,7 @@ public class FooStoredProceduresIntegrationTest { fooService.create(new Foo(randomAlphabetic(6))); // Stored procedure getAllFoos using createSQLQuery - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity( - Foo.class); + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); @SuppressWarnings("unchecked") List allFoos = sqlQuery.list(); for (Foo foo : allFoos) { @@ -105,8 +102,7 @@ public class FooStoredProceduresIntegrationTest { fooService.create(new Foo("NewFooName")); // Stored procedure getFoosByName using createSQLQuery() - Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)") - .addEntity(Foo.class).setParameter("fooName", "NewFooName"); + Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName"); @SuppressWarnings("unchecked") List allFoosByName = sqlQuery.list(); for (Foo foo : allFoosByName) { @@ -114,8 +110,7 @@ public class FooStoredProceduresIntegrationTest { } // Stored procedure getFoosByName using getNamedQuery() - Query namedQuery = session.getNamedQuery("callGetFoosByName") - .setParameter("fooName", "NewFooName"); + Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName"); @SuppressWarnings("unchecked") List allFoosByName2 = namedQuery.list(); for (Foo foo : allFoosByName2) { diff --git a/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java b/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java index 439bc6caad..c0761939ad 100644 --- a/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java +++ b/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java @@ -12,8 +12,7 @@ public class DefaultTextMessageSenderTest { @SuppressWarnings("resource") @BeforeClass public static void setUp() { - ApplicationContext applicationContext = new ClassPathXmlApplicationContext( - "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); + ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); } diff --git a/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java b/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java index da9bb0294d..117f8bed82 100644 --- a/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java +++ b/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java @@ -12,8 +12,7 @@ public class MapMessageConvertAndSendTest { @SuppressWarnings("resource") @BeforeClass public static void setUp() { - ApplicationContext applicationContext = new ClassPathXmlApplicationContext( - "classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); + ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); } diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java index f97f53b82c..907043b8ce 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java @@ -43,8 +43,7 @@ public class SecondLevelCacheIntegrationTest { final Foo foo = new Foo(randomAlphabetic(6)); fooService.create(foo); fooService.findOne(foo.getId()); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) - .getCache("org.baeldung.persistence.model.Foo").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize(); assertThat(size, greaterThan(0)); } @@ -64,21 +63,17 @@ public class SecondLevelCacheIntegrationTest { return nativeQuery.executeUpdate(); }); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) - .getCache("org.baeldung.persistence.model.Foo").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize(); assertThat(size, greaterThan(0)); } @Test public final void givenCacheableQueryIsExecuted_thenItIsCached() { new TransactionTemplate(platformTransactionManager).execute(status -> { - return entityManager.createQuery("select f from Foo f") - .setHint("org.hibernate.cacheable", true) - .getResultList(); + return entityManager.createQuery("select f from Foo f").setHint("org.hibernate.cacheable", true).getResultList(); }); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) - .getCache("org.hibernate.cache.internal.StandardQueryCache").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.hibernate.cache.internal.StandardQueryCache").getSize(); assertThat(size, greaterThan(0)); } } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java index 67e4c6ae1d..58a92002c8 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java @@ -30,7 +30,7 @@ public class User { private String email; @ManyToMany(fetch = FetchType.EAGER) - @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) + @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) @JsonApiToMany @JsonApiIncludeByDefault private Set roles; diff --git a/spring-mockito/src/main/java/com/baeldung/MocksApplication.java b/spring-mockito/src/main/java/com/baeldung/MocksApplication.java index 32be4c6a0a..94309cf1a6 100644 --- a/spring-mockito/src/main/java/com/baeldung/MocksApplication.java +++ b/spring-mockito/src/main/java/com/baeldung/MocksApplication.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MocksApplication { - public static void main(String[] args) { - SpringApplication.run(MocksApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(MocksApplication.class, args); + } } diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java index 679a455f3f..10b54e345c 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java @@ -17,13 +17,12 @@ public class MainController { @Autowired private ITutorialsService tutService; - @RequestMapping(value ="/", method = RequestMethod.GET) + @RequestMapping(value = "/", method = RequestMethod.GET) public String welcomePage() { - return "index"; + return "index"; } - - - @RequestMapping(value ="/list", method = RequestMethod.GET) + + @RequestMapping(value = "/list", method = RequestMethod.GET) public String listTutorialsPage(Model model) { List list = tutService.listTutorials(); model.addAttribute("tutorials", list); @@ -37,6 +36,5 @@ public class MainController { public void setTutService(ITutorialsService tutService) { this.tutService = tutService; } - - + } \ No newline at end of file diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java index 24059f2662..237b603590 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java @@ -6,5 +6,5 @@ import java.util.List; public interface ITutorialsService { - List listTutorials(); + List listTutorials(); } diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java index f67cc0824f..9d48e130c8 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java @@ -10,9 +10,6 @@ import java.util.List; public class TutorialsService implements ITutorialsService { public List listTutorials() { - return Arrays.asList( - new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), - new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor") - ); + return Arrays.asList(new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")); } } diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java index ce8ce1919a..17388b52b0 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java @@ -13,7 +13,7 @@ import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver; @Configuration @EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller", "com.baeldung.mvc.velocity.service"}) +@ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller", "com.baeldung.mvc.velocity.service" }) public class WebConfig extends WebMvcConfigurerAdapter { @Override diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java index a9fb242755..1f90b0fc67 100644 --- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java +++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java @@ -38,7 +38,6 @@ public class DataContentControllerTest { @Before public void setUp() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @@ -53,9 +52,9 @@ public class DataContentControllerTest { mockMvc.perform(get("/list")).andExpect(xpath("//table").exists()); mockMvc.perform(get("/list")).andExpect(xpath("//td[@id='tutId_1']").exists()); } - + @Test - public void whenCallingIndex_thenViewOK() throws Exception{ + public void whenCallingIndex_thenViewOK() throws Exception { mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("index")).andExpect(model().size(0)); } } diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java index 8b84bcdd23..a75cd1291a 100644 --- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java +++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java @@ -8,7 +8,6 @@ import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver; @Configuration public class TestConfig { - @Bean public ViewResolver viewResolver() { @@ -19,14 +18,12 @@ public class TestConfig { bean.setSuffix(".vm"); return bean; } - + @Bean public VelocityConfigurer velocityConfig() { VelocityConfigurer velocityConfigurer = new VelocityConfigurer(); velocityConfigurer.setResourceLoaderPath("/"); return velocityConfigurer; } - - } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java index 76351b96f7..b5238b04d5 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -8,10 +8,10 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration public class ClientWebConfig extends WebMvcConfigurerAdapter { - public ClientWebConfig() { - super(); - } + public ClientWebConfig() { + super(); + } - // API + // API } \ No newline at end of file diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java index bee09b742a..f299c46dbc 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java @@ -17,40 +17,40 @@ import org.springframework.web.servlet.view.JstlView; //@Configuration public class ClientWebConfigJava extends WebMvcConfigurerAdapter { - public ClientWebConfigJava() { - super(); - } + public ClientWebConfigJava() { + super(); + } - @Bean - public MessageSource messageSource() { + @Bean + public MessageSource messageSource() { - final ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); - ms.setBasenames("messages"); - return ms; - } + final ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); + ms.setBasenames("messages"); + return ms; + } - @Bean - public ResourceBundle getBeanResourceBundle() { + @Bean + public ResourceBundle getBeanResourceBundle() { - final Locale locale = Locale.getDefault(); - return new MessageSourceResourceBundle(messageSource(), locale); - } + final Locale locale = Locale.getDefault(); + return new MessageSourceResourceBundle(messageSource(), locale); + } - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } + registry.addViewController("/sample.html"); + } - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); - return bean; - } + return bean; + } } \ No newline at end of file diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java index aa25f47a2a..fa76933f8f 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java @@ -18,28 +18,28 @@ import com.baeldung.spring.form.Employee; @Controller public class EmployeeController { - Map employeeMap = new HashMap<>(); + Map employeeMap = new HashMap<>(); - @RequestMapping(value = "/employee", method = RequestMethod.GET) - public ModelAndView showForm() { - return new ModelAndView("employeeHome", "employee", new Employee()); - } + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } - @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { - return employeeMap.get(Id); - } + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { + return employeeMap.get(Id); + } - @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) - public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { - if (result.hasErrors()) { - return "error"; - } - model.addAttribute("name", employee.getName()); - model.addAttribute("contactNumber", employee.getContactNumber()); - model.addAttribute("id", employee.getId()); - employeeMap.put(employee.getId(), employee); - return "employeeView"; - } + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("id", employee.getId()); + employeeMap.put(employee.getId(), employee); + return "employeeView"; + } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java index cc9d66d4d4..17f0801a6e 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java @@ -11,8 +11,7 @@ public class HelloController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using SimpleUrlHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using SimpleUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java index 614888ae42..c7f3adb594 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java @@ -10,8 +10,7 @@ public class HelloGuestController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using ControllerClassNameHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using ControllerClassNameHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java index 6ed3d06ab7..a0be507125 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java @@ -10,8 +10,7 @@ public class HelloWorldController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using BeanNameUrlHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using BeanNameUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java index 39dabf86ed..71d9ad7845 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java @@ -22,63 +22,62 @@ import org.springframework.web.servlet.ModelAndView; @Controller public class PersonController { - @Autowired - PersonValidator validator; + @Autowired + PersonValidator validator; - @RequestMapping(value = "/person", method = RequestMethod.GET) - public ModelAndView showForm(final Model model) { + @RequestMapping(value = "/person", method = RequestMethod.GET) + public ModelAndView showForm(final Model model) { - initData(model); - return new ModelAndView("personForm", "person", new Person()); - } + initData(model); + return new ModelAndView("personForm", "person", new Person()); + } - @RequestMapping(value = "/addPerson", method = RequestMethod.POST) - public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, - final ModelMap modelMap, final Model model) { + @RequestMapping(value = "/addPerson", method = RequestMethod.POST) + public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, final ModelMap modelMap, final Model model) { - validator.validate(person, result); + validator.validate(person, result); - if (result.hasErrors()) { + if (result.hasErrors()) { - initData(model); - return "personForm"; - } + initData(model); + return "personForm"; + } - modelMap.addAttribute("person", person); + modelMap.addAttribute("person", person); - return "personView"; - } + return "personView"; + } - private void initData(final Model model) { + private void initData(final Model model) { - final List favouriteLanguageItem = new ArrayList(); - favouriteLanguageItem.add("Java"); - favouriteLanguageItem.add("C++"); - favouriteLanguageItem.add("Perl"); - model.addAttribute("favouriteLanguageItem", favouriteLanguageItem); + final List favouriteLanguageItem = new ArrayList(); + favouriteLanguageItem.add("Java"); + favouriteLanguageItem.add("C++"); + favouriteLanguageItem.add("Perl"); + model.addAttribute("favouriteLanguageItem", favouriteLanguageItem); - final List jobItem = new ArrayList(); - jobItem.add("Full time"); - jobItem.add("Part time"); - model.addAttribute("jobItem", jobItem); + final List jobItem = new ArrayList(); + jobItem.add("Full time"); + jobItem.add("Part time"); + model.addAttribute("jobItem", jobItem); - final Map countryItems = new LinkedHashMap(); - countryItems.put("US", "United Stated"); - countryItems.put("IT", "Italy"); - countryItems.put("UK", "United Kingdom"); - countryItems.put("FR", "Grance"); - model.addAttribute("countryItems", countryItems); + final Map countryItems = new LinkedHashMap(); + countryItems.put("US", "United Stated"); + countryItems.put("IT", "Italy"); + countryItems.put("UK", "United Kingdom"); + countryItems.put("FR", "Grance"); + model.addAttribute("countryItems", countryItems); - final List fruit = new ArrayList(); - fruit.add("Banana"); - fruit.add("Mango"); - fruit.add("Apple"); - model.addAttribute("fruit", fruit); + final List fruit = new ArrayList(); + fruit.add("Banana"); + fruit.add("Mango"); + fruit.add("Apple"); + model.addAttribute("fruit", fruit); - final List books = new ArrayList(); - books.add("The Great Gatsby"); - books.add("Nineteen Eighty-Four"); - books.add("The Lord of the Rings"); - model.addAttribute("books", books); - } + final List books = new ArrayList(); + books.add("The Great Gatsby"); + books.add("Nineteen Eighty-Four"); + books.add("The Lord of the Rings"); + model.addAttribute("books", books); + } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java index 5459481674..2760fb8f89 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java @@ -11,8 +11,7 @@ public class WelcomeController extends AbstractController { protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("welcome"); - model.addObject("msg", " Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using SimpleUrlHandlerMapping."); + model.addObject("msg", " Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using SimpleUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java index 88e4f9ff4c..01638fbe76 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java @@ -7,146 +7,146 @@ import org.springframework.web.multipart.MultipartFile; public class Person { - private long id; + private long id; - private String name; - private String email; - private String dateOfBirth; + private String name; + private String email; + private String dateOfBirth; - @NotEmpty - private String password; - private String sex; - private String country; - private String book; - private String job; - private boolean receiveNewsletter; - private String[] hobbies; - private List favouriteLanguage; - private List fruit; - private String notes; - private MultipartFile file; + @NotEmpty + private String password; + private String sex; + private String country; + private String book; + private String job; + private boolean receiveNewsletter; + private String[] hobbies; + private List favouriteLanguage; + private List fruit; + private String notes; + private MultipartFile file; - public Person() { - super(); - } + public Person() { + super(); + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(final String name) { - this.name = name; - } + public void setName(final String name) { + this.name = name; + } - public String getEmail() { - return email; - } + public String getEmail() { + return email; + } - public void setEmail(final String email) { - this.email = email; - } + public void setEmail(final String email) { + this.email = email; + } - public String getDateOfBirth() { - return dateOfBirth; - } + public String getDateOfBirth() { + return dateOfBirth; + } - public void setDateOfBirth(final String dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } + public void setDateOfBirth(final String dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(final String password) { - this.password = password; - } + public void setPassword(final String password) { + this.password = password; + } - public String getSex() { - return sex; - } + public String getSex() { + return sex; + } - public void setSex(final String sex) { - this.sex = sex; - } + public void setSex(final String sex) { + this.sex = sex; + } - public String getCountry() { - return country; - } + public String getCountry() { + return country; + } - public void setCountry(final String country) { - this.country = country; - } + public void setCountry(final String country) { + this.country = country; + } - public String getJob() { - return job; - } + public String getJob() { + return job; + } - public void setJob(final String job) { - this.job = job; - } + public void setJob(final String job) { + this.job = job; + } - public boolean isReceiveNewsletter() { - return receiveNewsletter; - } + public boolean isReceiveNewsletter() { + return receiveNewsletter; + } - public void setReceiveNewsletter(final boolean receiveNewsletter) { - this.receiveNewsletter = receiveNewsletter; - } + public void setReceiveNewsletter(final boolean receiveNewsletter) { + this.receiveNewsletter = receiveNewsletter; + } - public String[] getHobbies() { - return hobbies; - } + public String[] getHobbies() { + return hobbies; + } - public void setHobbies(final String[] hobbies) { - this.hobbies = hobbies; - } + public void setHobbies(final String[] hobbies) { + this.hobbies = hobbies; + } - public List getFavouriteLanguage() { - return favouriteLanguage; - } + public List getFavouriteLanguage() { + return favouriteLanguage; + } - public void setFavouriteLanguage(final List favouriteLanguage) { - this.favouriteLanguage = favouriteLanguage; - } + public void setFavouriteLanguage(final List favouriteLanguage) { + this.favouriteLanguage = favouriteLanguage; + } - public String getNotes() { - return notes; - } + public String getNotes() { + return notes; + } - public void setNotes(final String notes) { - this.notes = notes; - } + public void setNotes(final String notes) { + this.notes = notes; + } - public List getFruit() { - return fruit; - } + public List getFruit() { + return fruit; + } - public void setFruit(final List fruit) { - this.fruit = fruit; - } + public void setFruit(final List fruit) { + this.fruit = fruit; + } - public String getBook() { - return book; - } + public String getBook() { + return book; + } - public void setBook(final String book) { - this.book = book; - } + public void setBook(final String book) { + this.book = book; + } - public MultipartFile getFile() { - return file; - } + public MultipartFile getFile() { + return file; + } - public void setFile(final MultipartFile file) { - this.file = file; - } + public void setFile(final MultipartFile file) { + this.file = file; + } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java index 3a271f6545..f7625bacd9 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java @@ -9,14 +9,14 @@ import org.springframework.validation.Validator; @Component public class PersonValidator implements Validator { - @Override - public boolean supports(final Class calzz) { - return Person.class.isAssignableFrom(calzz); - } + @Override + public boolean supports(final Class calzz) { + return Person.class.isAssignableFrom(calzz); + } - @Override - public void validate(final Object obj, final Errors errors) { + @Override + public void validate(final Object obj, final Errors errors) { - ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required.name"); - } + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required.name"); + } } \ No newline at end of file diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java b/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java index e51e4ad43d..547ef78d84 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java @@ -10,7 +10,6 @@ import org.springframework.scheduling.annotation.EnableScheduling; public class SpringQuartzApp { public static void main(String[] args) { - new SpringApplicationBuilder(SpringQuartzApp.class) - .showBanner(false).run(args); + new SpringApplicationBuilder(SpringQuartzApp.class).showBanner(false).run(args); } } diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java index a944f8fe43..6601df6c94 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java @@ -45,8 +45,7 @@ public class QrtzScheduler { } @Bean - public Scheduler scheduler(Trigger trigger, JobDetail job) - throws SchedulerException, IOException { + public Scheduler scheduler(Trigger trigger, JobDetail job) throws SchedulerException, IOException { StdSchedulerFactory factory = new StdSchedulerFactory(); factory.initialize(new ClassPathResource("quartz.properties").getInputStream()); @@ -64,9 +63,7 @@ public class QrtzScheduler { @Bean public JobDetail jobDetail() { - return newJob().ofType(SampleJob.class).storeDurably() - .withIdentity(JobKey.jobKey("Qrtz_Job_Detail")) - .withDescription("Invoke Sample Job service...").build(); + return newJob().ofType(SampleJob.class).storeDurably().withIdentity(JobKey.jobKey("Qrtz_Job_Detail")).withDescription("Invoke Sample Job service...").build(); } @Bean @@ -75,10 +72,6 @@ public class QrtzScheduler { int frequencyInSec = 10; logger.info("Configuring trigger to fire every {} seconds", frequencyInSec); - return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")) - .withDescription("Sample trigger") - .withSchedule( - simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()) - .build(); + return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")).withDescription("Sample trigger").withSchedule(simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()).build(); } } diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java index 9474272a3c..7c50f9a231 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java @@ -19,8 +19,7 @@ public class SampleJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { - logger.info("Job ** {} ** fired @ {}", context.getJobDetail().getKey().getName(), - context.getFireTime()); + logger.info("Job ** {} ** fired @ {}", context.getJobDetail().getKey().getName(), context.getFireTime()); jobService.executeSampleJob(); diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java b/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java index 0e24238467..d3034ae7af 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java @@ -11,21 +11,17 @@ import org.springframework.scheduling.quartz.SpringBeanJobFactory; * Adds auto-wiring support to quartz jobs. * @see "https://gist.github.com/jelies/5085593" */ -public final class AutoWiringSpringBeanJobFactory extends SpringBeanJobFactory - implements ApplicationContextAware { +public final class AutoWiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware { private transient AutowireCapableBeanFactory beanFactory; - - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { beanFactory = applicationContext.getAutowireCapableBeanFactory(); } @Override - protected Object createJobInstance(final TriggerFiredBundle bundle) - throws Exception { + protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception { final Object job = super.createJobInstance(bundle); beanFactory.autowireBean(job); diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java b/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java index d640ac671d..aa694c08ed 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java @@ -8,9 +8,9 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class CompanyController { - @RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE) - public Company getCompanyRest() { - final Company company = new Company(1, "Xpto"); - return company; - } + @RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE) + public Company getCompanyRest() { + final Company company = new Company(1, "Xpto"); + return company; + } } diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java b/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java index f3e3738bfe..1cc3eae432 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java @@ -14,26 +14,26 @@ import com.fasterxml.jackson.annotation.JsonView; @RestController public class ItemController { - @JsonView(Views.Public.class) - @RequestMapping("/items/{id}") - public Item getItemPublic(@PathVariable final int id) { - return ItemManager.getById(id); - } + @JsonView(Views.Public.class) + @RequestMapping("/items/{id}") + public Item getItemPublic(@PathVariable final int id) { + return ItemManager.getById(id); + } - @JsonView(Views.Internal.class) - @RequestMapping("/items/internal/{id}") - public Item getItemInternal(@PathVariable final int id) { - return ItemManager.getById(id); - } + @JsonView(Views.Internal.class) + @RequestMapping("/items/internal/{id}") + public Item getItemInternal(@PathVariable final int id) { + return ItemManager.getById(id); + } - @RequestMapping("/date") - public Date getCurrentDate() throws Exception { - return new Date(); - } + @RequestMapping("/date") + public Date getCurrentDate() throws Exception { + return new Date(); + } - @RequestMapping("/delay/{seconds}") - public void getCurrentTime(@PathVariable final int seconds) throws Exception { + @RequestMapping("/delay/{seconds}") + public void getCurrentTime(@PathVariable final int seconds) throws Exception { - Thread.sleep(seconds * 1000); - } + Thread.sleep(seconds * 1000); + } } \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java index 7d62cc0c66..996f229128 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java @@ -6,8 +6,8 @@ import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpRespon @ControllerAdvice public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice { - public JsonpControllerAdvice() { - super("callback"); - } + public JsonpControllerAdvice() { + super("callback"); + } } diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java b/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java index 348ee6d596..458bdaf170 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java @@ -3,8 +3,8 @@ package org.baeldung.web.controller.status; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; -@ResponseStatus(value = HttpStatus.FORBIDDEN, reason="To show an example of a custom message") +@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "To show an example of a custom message") public class ForbiddenException extends RuntimeException { - private static final long serialVersionUID = 6826605655586311552L; + private static final long serialVersionUID = 6826605655586311552L; } diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java b/spring-rest/src/main/java/org/baeldung/web/dto/Company.java index c7d0718140..3164d604ad 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java +++ b/spring-rest/src/main/java/org/baeldung/web/dto/Company.java @@ -2,37 +2,37 @@ package org.baeldung.web.dto; public class Company { - private long id; - private String name; + private long id; + private String name; - public Company() { - super(); - } + public Company() { + super(); + } - public Company(final long id, final String name) { - this.id = id; - this.name = name; - } + public Company(final long id, final String name) { + this.id = id; + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(final String name) { - this.name = name; - } + public void setName(final String name) { + this.name = name; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } - @Override - public String toString() { - return "Company [id=" + id + ", name=" + name + "]"; - } + @Override + public String toString() { + return "Company [id=" + id + ", name=" + name + "]"; + } } diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java b/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java index 61251ea33a..8ca96c38fc 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java +++ b/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java @@ -4,617 +4,594 @@ package org.baeldung.web.dto; public final class FooProtos { - private FooProtos() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - } - public interface FooOrBuilder extends - // @@protoc_insertion_point(interface_extends:baeldung.Foo) - com.google.protobuf.MessageOrBuilder { - - /** - * required int64 id = 1; - */ - boolean hasId(); - /** - * required int64 id = 1; - */ - long getId(); - - /** - * required string name = 2; - */ - boolean hasName(); - /** - * required string name = 2; - */ - java.lang.String getName(); - /** - * required string name = 2; - */ - com.google.protobuf.ByteString - getNameBytes(); - } - /** - * Protobuf type {@code baeldung.Foo} - */ - public static final class Foo extends - com.google.protobuf.GeneratedMessage implements - // @@protoc_insertion_point(message_implements:baeldung.Foo) - FooOrBuilder { - // Use Foo.newBuilder() to construct. - private Foo(com.google.protobuf.GeneratedMessage.Builder builder) { - super(builder); - this.unknownFields = builder.getUnknownFields(); - } - private Foo(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } - - private static final Foo defaultInstance; - public static Foo getDefaultInstance() { - return defaultInstance; + private FooProtos() { } - public Foo getDefaultInstanceForType() { - return defaultInstance; + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { } - private final com.google.protobuf.UnknownFieldSet unknownFields; - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private Foo( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - initFields(); - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownField(input, unknownFields, - extensionRegistry, tag)) { - done = true; - } - break; - } - case 8: { - bitField0_ |= 0x00000001; - id_ = input.readInt64(); - break; - } - case 18: { - com.google.protobuf.ByteString bs = input.readBytes(); - bitField0_ |= 0x00000002; - name_ = bs; - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e.getMessage()).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + public interface FooOrBuilder extends + // @@protoc_insertion_point(interface_extends:baeldung.Foo) + com.google.protobuf.MessageOrBuilder { + + /** + * required int64 id = 1; + */ + boolean hasId(); + + /** + * required int64 id = 1; + */ + long getId(); + + /** + * required string name = 2; + */ + boolean hasName(); + + /** + * required string name = 2; + */ + java.lang.String getName(); + + /** + * required string name = 2; + */ + com.google.protobuf.ByteString getNameBytes(); } - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); - } - - public static com.google.protobuf.Parser PARSER = - new com.google.protobuf.AbstractParser() { - public Foo parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new Foo(input, extensionRegistry); - } - }; - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - private int bitField0_; - public static final int ID_FIELD_NUMBER = 1; - private long id_; - /** - * required int64 id = 1; - */ - public boolean hasId() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * required int64 id = 1; - */ - public long getId() { - return id_; - } - - public static final int NAME_FIELD_NUMBER = 2; - private java.lang.Object name_; - /** - * required string name = 2; - */ - public boolean hasName() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * required string name = 2; - */ - public java.lang.String getName() { - java.lang.Object ref = name_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - name_ = s; - } - return s; - } - } - /** - * required string name = 2; - */ - public com.google.protobuf.ByteString - getNameBytes() { - java.lang.Object ref = name_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - private void initFields() { - id_ = 0L; - name_ = ""; - } - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - if (!hasId()) { - memoizedIsInitialized = 0; - return false; - } - if (!hasName()) { - memoizedIsInitialized = 0; - return false; - } - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - getSerializedSize(); - if (((bitField0_ & 0x00000001) == 0x00000001)) { - output.writeInt64(1, id_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - output.writeBytes(2, getNameBytes()); - } - getUnknownFields().writeTo(output); - } - - private int memoizedSerializedSize = -1; - public int getSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (((bitField0_ & 0x00000001) == 0x00000001)) { - size += com.google.protobuf.CodedOutputStream - .computeInt64Size(1, id_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(2, getNameBytes()); - } - size += getUnknownFields().getSerializedSize(); - memoizedSerializedSize = size; - return size; - } - - private static final long serialVersionUID = 0L; - @java.lang.Override - protected java.lang.Object writeReplace() - throws java.io.ObjectStreamException { - return super.writeReplace(); - } - - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input); - } - public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input, extensionRegistry); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - - public static Builder newBuilder() { return Builder.create(); } - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder(org.baeldung.web.dto.FooProtos.Foo prototype) { - return newBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { return newBuilder(this); } - - @java.lang.Override - protected Builder newBuilderForType( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } /** * Protobuf type {@code baeldung.Foo} */ - public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder implements - // @@protoc_insertion_point(builder_implements:baeldung.Foo) - org.baeldung.web.dto.FooProtos.FooOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); - } - - // Construct using org.baeldung.web.dto.FooProtos.Foo.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + public static final class Foo extends com.google.protobuf.GeneratedMessage implements + // @@protoc_insertion_point(message_implements:baeldung.Foo) + FooOrBuilder { + // Use Foo.newBuilder() to construct. + private Foo(com.google.protobuf.GeneratedMessage.Builder builder) { + super(builder); + this.unknownFields = builder.getUnknownFields(); } - } - private static Builder create() { - return new Builder(); - } - public Builder clear() { - super.clear(); - id_ = 0L; - bitField0_ = (bitField0_ & ~0x00000001); - name_ = ""; - bitField0_ = (bitField0_ & ~0x00000002); - return this; - } - - public Builder clone() { - return create().mergeFrom(buildPartial()); - } - - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; - } - - public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { - return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); - } - - public org.baeldung.web.dto.FooProtos.Foo build() { - org.baeldung.web.dto.FooProtos.Foo result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); + private Foo(boolean noInit) { + this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } - return result; - } - public org.baeldung.web.dto.FooProtos.Foo buildPartial() { - org.baeldung.web.dto.FooProtos.Foo result = new org.baeldung.web.dto.FooProtos.Foo(this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if (((from_bitField0_ & 0x00000001) == 0x00000001)) { - to_bitField0_ |= 0x00000001; + private static final Foo defaultInstance; + + public static Foo getDefaultInstance() { + return defaultInstance; } - result.id_ = id_; - if (((from_bitField0_ & 0x00000002) == 0x00000002)) { - to_bitField0_ |= 0x00000002; + + public Foo getDefaultInstanceForType() { + return defaultInstance; } - result.name_ = name_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.baeldung.web.dto.FooProtos.Foo) { - return mergeFrom((org.baeldung.web.dto.FooProtos.Foo)other); - } else { - super.mergeFrom(other); - return this; + private final com.google.protobuf.UnknownFieldSet unknownFields; + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; } - } - public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) { - if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) return this; - if (other.hasId()) { - setId(other.getId()); + private Foo(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + id_ = input.readInt64(); + break; + } + case 18: { + com.google.protobuf.ByteString bs = input.readBytes(); + bitField0_ |= 0x00000002; + name_ = bs; + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e.getMessage()).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } } - if (other.hasName()) { - bitField0_ |= 0x00000002; - name_ = other.name_; - onChanged(); + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } - this.mergeUnknownFields(other.getUnknownFields()); - return this; - } - public final boolean isInitialized() { - if (!hasId()) { - - return false; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); } - if (!hasName()) { - - return false; - } - return true; - } - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - org.baeldung.web.dto.FooProtos.Foo parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); - throw e; - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - private int bitField0_; - - private long id_ ; - /** - * required int64 id = 1; - */ - public boolean hasId() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * required int64 id = 1; - */ - public long getId() { - return id_; - } - /** - * required int64 id = 1; - */ - public Builder setId(long value) { - bitField0_ |= 0x00000001; - id_ = value; - onChanged(); - return this; - } - /** - * required int64 id = 1; - */ - public Builder clearId() { - bitField0_ = (bitField0_ & ~0x00000001); - id_ = 0L; - onChanged(); - return this; - } - - private java.lang.Object name_ = ""; - /** - * required string name = 2; - */ - public boolean hasName() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * required string name = 2; - */ - public java.lang.String getName() { - java.lang.Object ref = name_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - name_ = s; - } - return s; - } else { - return (java.lang.String) ref; - } - } - /** - * required string name = 2; - */ - public com.google.protobuf.ByteString - getNameBytes() { - java.lang.Object ref = name_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * required string name = 2; - */ - public Builder setName( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000002; - name_ = value; - onChanged(); - return this; - } - /** - * required string name = 2; - */ - public Builder clearName() { - bitField0_ = (bitField0_ & ~0x00000002); - name_ = getDefaultInstance().getName(); - onChanged(); - return this; - } - /** - * required string name = 2; - */ - public Builder setNameBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000002; - name_ = value; - onChanged(); - return this; - } - - // @@protoc_insertion_point(builder_scope:baeldung.Foo) - } - - static { - defaultInstance = new Foo(true); - defaultInstance.initFields(); - } - - // @@protoc_insertion_point(class_scope:baeldung.Foo) - } - - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_baeldung_Foo_descriptor; - private static - com.google.protobuf.GeneratedMessage.FieldAccessorTable - internal_static_baeldung_Foo_fieldAccessorTable; - - public static com.google.protobuf.Descriptors.FileDescriptor - getDescriptor() { - return descriptor; - } - private static com.google.protobuf.Descriptors.FileDescriptor - descriptor; - static { - java.lang.String[] descriptorData = { - "\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" + - "\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024org.baeldung.web" + - ".dtoB\tFooProtos" - }; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = - new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } + public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { + public Foo parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return new Foo(input, extensionRegistry); + } }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[] { - }, assigner); - internal_static_baeldung_Foo_descriptor = - getDescriptor().getMessageTypes().get(0); - internal_static_baeldung_Foo_fieldAccessorTable = new - com.google.protobuf.GeneratedMessage.FieldAccessorTable( - internal_static_baeldung_Foo_descriptor, - new java.lang.String[] { "Id", "Name", }); - } - // @@protoc_insertion_point(outer_class_scope) + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + private int bitField0_; + public static final int ID_FIELD_NUMBER = 1; + private long id_; + + /** + * required int64 id = 1; + */ + public boolean hasId() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + + /** + * required int64 id = 1; + */ + public long getId() { + return id_; + } + + public static final int NAME_FIELD_NUMBER = 2; + private java.lang.Object name_; + + /** + * required string name = 2; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + + /** + * required string name = 2; + */ + public java.lang.String getName() { + java.lang.Object ref = name_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; + } + } + + /** + * required string name = 2; + */ + public com.google.protobuf.ByteString getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private void initFields() { + id_ = 0L; + name_ = ""; + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) + return true; + if (isInitialized == 0) + return false; + + if (!hasId()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasName()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt64(1, id_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, getNameBytes()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) + return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream.computeInt64Size(1, id_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream.computeBytesSize(2, getNameBytes()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + + @java.lang.Override + protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) throws java.io.IOException { + return PARSER.parseFrom(input); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return PARSER.parseFrom(input); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { + return Builder.create(); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder(org.baeldung.web.dto.FooProtos.Foo prototype) { + return newBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return newBuilder(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** + * Protobuf type {@code baeldung.Foo} + */ + public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements + // @@protoc_insertion_point(builder_implements:baeldung.Foo) + org.baeldung.web.dto.FooProtos.FooOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); + } + + // Construct using org.baeldung.web.dto.FooProtos.Foo.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + id_ = 0L; + bitField0_ = (bitField0_ & ~0x00000001); + name_ = ""; + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + } + + public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { + return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); + } + + public org.baeldung.web.dto.FooProtos.Foo build() { + org.baeldung.web.dto.FooProtos.Foo result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.baeldung.web.dto.FooProtos.Foo buildPartial() { + org.baeldung.web.dto.FooProtos.Foo result = new org.baeldung.web.dto.FooProtos.Foo(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.id_ = id_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.name_ = name_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof org.baeldung.web.dto.FooProtos.Foo) { + return mergeFrom((org.baeldung.web.dto.FooProtos.Foo) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) { + if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) + return this; + if (other.hasId()) { + setId(other.getId()); + } + if (other.hasName()) { + bitField0_ |= 0x00000002; + name_ = other.name_; + onChanged(); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + if (!hasId()) { + + return false; + } + if (!hasName()) { + + return false; + } + return true; + } + + public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + org.baeldung.web.dto.FooProtos.Foo parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private long id_; + + /** + * required int64 id = 1; + */ + public boolean hasId() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + + /** + * required int64 id = 1; + */ + public long getId() { + return id_; + } + + /** + * required int64 id = 1; + */ + public Builder setId(long value) { + bitField0_ |= 0x00000001; + id_ = value; + onChanged(); + return this; + } + + /** + * required int64 id = 1; + */ + public Builder clearId() { + bitField0_ = (bitField0_ & ~0x00000001); + id_ = 0L; + onChanged(); + return this; + } + + private java.lang.Object name_ = ""; + + /** + * required string name = 2; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + + /** + * required string name = 2; + */ + public java.lang.String getName() { + java.lang.Object ref = name_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; + } else { + return (java.lang.String) ref; + } + } + + /** + * required string name = 2; + */ + public com.google.protobuf.ByteString getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * required string name = 2; + */ + public Builder setName(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + name_ = value; + onChanged(); + return this; + } + + /** + * required string name = 2; + */ + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000002); + name_ = getDefaultInstance().getName(); + onChanged(); + return this; + } + + /** + * required string name = 2; + */ + public Builder setNameBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + name_ = value; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:baeldung.Foo) + } + + static { + defaultInstance = new Foo(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:baeldung.Foo) + } + + private static final com.google.protobuf.Descriptors.Descriptor internal_static_baeldung_Foo_descriptor; + private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_baeldung_Foo_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; + static { + java.lang.String[] descriptorData = { "\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" + "\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024org.baeldung.web" + ".dtoB\tFooProtos" }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors(com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + internal_static_baeldung_Foo_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_baeldung_Foo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable(internal_static_baeldung_Foo_descriptor, new java.lang.String[] { "Id", "Name", }); + } + + // @@protoc_insertion_point(outer_class_scope) } diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java index 1344d2d40e..c50e1b4f43 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java @@ -32,13 +32,11 @@ public class ExampleControllerTest { @Test public void whenGetRequestSentToController_thenReturnsStatusNotAcceptable() throws Exception { - mockMvc.perform(get("/controller")) - .andExpect(status().isNotAcceptable()); + mockMvc.perform(get("/controller")).andExpect(status().isNotAcceptable()); } @Test public void whenGetRequestSentToException_thenReturnsStatusForbidden() throws Exception { - mockMvc.perform(get("/exception")) - .andExpect(status().isForbidden()); + mockMvc.perform(get("/exception")).andExpect(status().isForbidden()); } } diff --git a/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java index c662c32738..e6c77110b3 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java +++ b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java @@ -51,9 +51,7 @@ public class MyUserDetailsService implements UserDetailsService { private User createUser(final String username, final String password, final List roles) { logger.info("Create user " + username); - final List authorities = roles.stream() - .map(role -> new SimpleGrantedAuthority(role.toString())) - .collect(Collectors.toList()); + final List authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.toString())).collect(Collectors.toList()); return new User(username, password, true, true, true, true, authorities); } diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java index 67d9abbae5..616c2a7684 100644 --- a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java +++ b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java @@ -37,5 +37,4 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { // @formatter:on } - } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java index 80af01aeeb..3d727fc19f 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java @@ -8,9 +8,9 @@ import org.springframework.web.context.request.RequestContextListener; public class ListenerConfig implements WebApplicationInitializer { - @Override - public void onStartup(ServletContext sc) throws ServletException { - // Manages the lifecycle of the root application context - sc.addListener(new RequestContextListener()); - } + @Override + public void onStartup(ServletContext sc) throws ServletException { + // Manages the lifecycle of the root application context + sc.addListener(new RequestContextListener()); + } } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java index 57e9b32a62..efdb2bc8d4 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java @@ -16,7 +16,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan("org.baeldung.web") @EnableWebMvc -public class WebConfig extends WebMvcConfigurerAdapter{ +public class WebConfig extends WebMvcConfigurerAdapter { public WebConfig() { super(); @@ -39,11 +39,11 @@ public class WebConfig extends WebMvcConfigurerAdapter{ registry.addViewController("/homepage.html"); } - @Override - public void addInterceptors(final InterceptorRegistry registry) { - registry.addInterceptor(new LoggerInterceptor()); - registry.addInterceptor(new UserInterceptor()); - registry.addInterceptor(new SessionTimerInterceptor()); - } + @Override + public void addInterceptors(final InterceptorRegistry registry) { + registry.addInterceptor(new LoggerInterceptor()); + registry.addInterceptor(new UserInterceptor()); + registry.addInterceptor(new SessionTimerInterceptor()); + } } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java index f5c1626989..90199347b4 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java @@ -13,44 +13,41 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class SessionTimerInterceptor extends HandlerInterceptorAdapter { - private static Logger log = LoggerFactory.getLogger(SessionTimerInterceptor.class); + private static Logger log = LoggerFactory.getLogger(SessionTimerInterceptor.class); - private static final long MAX_INACTIVE_SESSION_TIME = 5 * 10000; + private static final long MAX_INACTIVE_SESSION_TIME = 5 * 10000; - @Autowired - private HttpSession session; + @Autowired + private HttpSession session; - /** - * Executed before actual handler is executed - **/ - @Override - public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) - throws Exception { - log.info("Pre handle method - check handling start time"); - long startTime = System.currentTimeMillis(); - request.setAttribute("executionTime", startTime); - if (UserInterceptor.isUserLogged()) { - session = request.getSession(); - log.info("Time since last request in this session: {} ms", - System.currentTimeMillis() - request.getSession().getLastAccessedTime()); - if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) { - log.warn("Logging out, due to inactive session"); - SecurityContextHolder.clearContext(); - request.logout(); - response.sendRedirect("/spring-security-rest-full/logout"); - } - } - return true; - } + /** + * Executed before actual handler is executed + **/ + @Override + public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { + log.info("Pre handle method - check handling start time"); + long startTime = System.currentTimeMillis(); + request.setAttribute("executionTime", startTime); + if (UserInterceptor.isUserLogged()) { + session = request.getSession(); + log.info("Time since last request in this session: {} ms", System.currentTimeMillis() - request.getSession().getLastAccessedTime()); + if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) { + log.warn("Logging out, due to inactive session"); + SecurityContextHolder.clearContext(); + request.logout(); + response.sendRedirect("/spring-security-rest-full/logout"); + } + } + return true; + } - /** - * Executed before after handler is executed - **/ - @Override - public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, - final ModelAndView model) throws Exception { - log.info("Post handle method - check execution time of handling"); - long startTime = (Long) request.getAttribute("executionTime"); - log.info("Execution time for handling the request was: {} ms", System.currentTimeMillis() - startTime); - } + /** + * Executed before after handler is executed + **/ + @Override + public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView model) throws Exception { + log.info("Post handle method - check execution time of handling"); + long startTime = (Long) request.getAttribute("executionTime"); + log.info("Execution time for handling the request was: {} ms", System.currentTimeMillis() - startTime); + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java index 4ba12d0138..6b808d885e 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java @@ -31,8 +31,7 @@ public class UserInterceptor extends HandlerInterceptorAdapter { * Executed before after handler is executed. If view is a redirect view, we don't need to execute postHandle **/ @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model) - throws Exception { + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model) throws Exception { if (model != null && !isRedirectView(model)) { if (isUserLogged()) { addToModelUserDetails(model); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java index a29de04bb4..916a849c63 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java @@ -30,27 +30,26 @@ import org.springframework.web.context.WebApplicationContext; @WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) public class SessionTimerInterceptorTest { - @Autowired - WebApplicationContext wac; + @Autowired + WebApplicationContext wac; - private MockMvc mockMvc; + private MockMvc mockMvc; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); - } + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); + } - /** - * After execution of HTTP GET logs from interceptor will be displayed in - * the console - */ - @Test - public void testInterceptors() throws Exception { - HttpSession session = mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()).andReturn() - .getRequest().getSession(); - Thread.sleep(51000); - mockMvc.perform(get("/auth/admin").session((MockHttpSession) session)).andExpect(status().is2xxSuccessful()); - } + /** + * After execution of HTTP GET logs from interceptor will be displayed in + * the console + */ + @Test + public void testInterceptors() throws Exception { + HttpSession session = mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()).andReturn().getRequest().getSession(); + Thread.sleep(51000); + mockMvc.perform(get("/auth/admin").session((MockHttpSession) session)).andExpect(status().is2xxSuccessful()); + } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java index 0b65311203..ff40c86906 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java @@ -23,8 +23,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @Transactional -@ContextConfiguration(classes = {SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class}) -@WithMockUser(username = "admin", roles = {"USER", "ADMIN"}) +@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) +@WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) public class UserInterceptorTest { @Autowired @@ -46,8 +46,7 @@ public class UserInterceptorTest { */ @Test public void testInterceptors() throws Exception { - mockMvc.perform(get("/auth/admin")) - .andExpect(status().is2xxSuccessful()); + mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()); } } From 3a27d6b50e844626ad525d4a5363e5cb73ca3649 Mon Sep 17 00:00:00 2001 From: Sunil Gulabani Date: Wed, 12 Oct 2016 10:33:48 +0530 Subject: [PATCH 058/193] BAEL-255: Added encode-decode of url --- .../encoderdecoder/EncoderDecoder.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java diff --git a/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java b/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java new file mode 100644 index 0000000000..62d2663994 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java @@ -0,0 +1,38 @@ +package com.baeldung.encoderdecoder; + +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Test; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +public class EncoderDecoder { + + @Test + public void givenPlainURL_whenUsingUTF8EncodingScheme_thenEncodeURL() throws UnsupportedEncodingException { + String plainURL = "http://www.baeldung.com" ; + String encodedURL = URLEncoder.encode(plainURL, StandardCharsets.UTF_8.toString()); + + Assert.assertThat("http%3A%2F%2Fwww.baeldung.com", CoreMatchers.is(encodedURL)); + } + + @Test + public void givenEncodedURL_whenUsingUTF8EncodingScheme_thenDecodeURL() throws UnsupportedEncodingException { + String encodedURL = "http%3A%2F%2Fwww.baeldung.com" ; + String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_8.toString()); + + Assert.assertThat("http://www.baeldung.com", CoreMatchers.is(decodedURL)); + } + + @Test + public void givenEncodedURL_whenUsingWrongEncodingScheme_thenDecodeInvalidURL() throws UnsupportedEncodingException { + String encodedURL = "http%3A%2F%2Fwww.baeldung.com"; + + String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_16.toString()); + + Assert.assertFalse("http://www.baeldung.com".equals(decodedURL)); + } +} From 51729209ed21820bda42bae0ef4ee75f37d93c0f Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 12 Oct 2016 08:40:56 +0200 Subject: [PATCH 059/193] Remove unnecessary field initialization --- .../main/java/com/baeldung/java/nio/selector/EchoClient.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java index 188db21641..1c034051aa 100644 --- a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java @@ -6,9 +6,9 @@ import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class EchoClient { - private static SocketChannel client = null; + private static SocketChannel client; private static ByteBuffer buffer; - private static EchoClient instance = null; + private static EchoClient instance; public static EchoClient start() { if (instance == null) From 7ad97523318e247fd9dce8e3e23b8b5c65c414bc Mon Sep 17 00:00:00 2001 From: "lcrusoveanu@optaros.com" Date: Wed, 12 Oct 2016 12:32:19 +0300 Subject: [PATCH 060/193] update test with after method --- .../web/CustomUserDetailsServiceTest.java | 40 +++++++++---------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java index 6917cea99a..0c82a4e98b 100644 --- a/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java +++ b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java @@ -39,37 +39,33 @@ public class CustomUserDetailsServiceTest { @Test public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { - try { - User user = new User(); - user.setUsername(USERNAME); - user.setPassword(passwordEncoder.encode(PASSWORD)); + User user = new User(); + user.setUsername(USERNAME); + user.setPassword(passwordEncoder.encode(PASSWORD)); - myUserRepository.save(user); + myUserRepository.save(user); - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); - Authentication authentication = authenticationProvider.authenticate(auth); + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); + Authentication authentication = authenticationProvider.authenticate(auth); - assertEquals(authentication.getName(), USERNAME); - - } finally { - myUserRepository.removeUserByUsername(USERNAME); - } + assertEquals(authentication.getName(), USERNAME); } @Test(expected = BadCredentialsException.class) public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { - try { - User user = new User(); - user.setUsername(USERNAME); - user.setPassword(passwordEncoder.encode(PASSWORD)); + User user = new User(); + user.setUsername(USERNAME); + user.setPassword(passwordEncoder.encode(PASSWORD)); - myUserRepository.save(user); + myUserRepository.save(user); - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); - authenticationProvider.authenticate(auth); - } finally { - myUserRepository.removeUserByUsername(USERNAME); - } + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); + authenticationProvider.authenticate(auth); + } + + @After + public void tearDown() { + myUserRepository.removeUserByUsername(USERNAME); } } From c0d4eee6697575f0c5dd84845cb08283de90e4b1 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 12 Oct 2016 16:29:30 +0200 Subject: [PATCH 061/193] configure live tests --- spring-security-custom-permission/pom.xml | 48 ++++++++++++++++++- .../src/main/resources/application.properties | 2 +- .../test/java/org/baeldung/web/LiveTest.java | 24 +++++++--- 3 files changed, 65 insertions(+), 9 deletions(-) diff --git a/spring-security-custom-permission/pom.xml b/spring-security-custom-permission/pom.xml index 6f460f1751..b2854fe7c5 100644 --- a/spring-security-custom-permission/pom.xml +++ b/spring-security-custom-permission/pom.xml @@ -55,7 +55,12 @@
- + + org.springframework.boot + spring-boot-starter-test + test + + junit junit @@ -95,13 +100,54 @@ org.springframework.boot spring-boot-maven-plugin + + + maven-surefire-plugin + + ${unit-tests.skip} + + **/*LiveTest.java + + + + + + maven-failsafe-plugin + + + integration-test + + integration-test + + + ${live-tests.skip} + + **/*LiveTest.class + + + + + + + + + live + + false + false + + + + UTF-8 1.8 2.4.0 + false + true diff --git a/spring-security-custom-permission/src/main/resources/application.properties b/spring-security-custom-permission/src/main/resources/application.properties index 0b40f62fa9..4433a53ac7 100644 --- a/spring-security-custom-permission/src/main/resources/application.properties +++ b/spring-security-custom-permission/src/main/resources/application.properties @@ -1,6 +1,6 @@ server.port=8081 spring.datasource.driver-class-name=org.h2.Driver -spring.datasource.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1 +spring.datasource.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE spring.datasource.username=sa spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop diff --git a/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java b/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java index 80b1390083..7e92765dcd 100644 --- a/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java +++ b/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java @@ -3,35 +3,45 @@ package org.baeldung.web; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import org.baeldung.Application; import org.baeldung.persistence.model.Foo; import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.IntegrationTest; +import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; import com.jayway.restassured.RestAssured; import com.jayway.restassured.authentication.FormAuthConfig; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.RequestSpecification; +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = Application.class) +@WebAppConfiguration +@IntegrationTest("server.port:8082") public class LiveTest { - private final FormAuthConfig formAuthConfig = new FormAuthConfig("http://localhost:8081/login", "username", "password"); + private final FormAuthConfig formAuthConfig = new FormAuthConfig("http://localhost:8082/login", "username", "password"); @Test public void givenUserWithReadPrivilegeAndHasPermission_whenGetFooById_thenOK() { - final Response response = givenAuth("john", "123").get("http://localhost:8081/foos/1"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/foos/1"); assertEquals(200, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @Test public void givenUserWithNoWritePrivilegeAndHasPermission_whenPostFoo_thenForbidden() { - final Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8081/foos"); + final Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8082/foos"); assertEquals(403, response.getStatusCode()); } @Test public void givenUserWithWritePrivilegeAndHasPermission_whenPostFoo_thenOk() { - final Response response = givenAuth("tom", "111").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8081/foos"); + final Response response = givenAuth("tom", "111").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8082/foos"); assertEquals(201, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @@ -40,14 +50,14 @@ public class LiveTest { @Test public void givenUserMemberInOrganization_whenGetOrganization_thenOK() { - final Response response = givenAuth("john", "123").get("http://localhost:8081/organizations/1"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/organizations/1"); assertEquals(200, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @Test public void givenUserMemberNotInOrganization_whenGetOrganization_thenForbidden() { - final Response response = givenAuth("john", "123").get("http://localhost:8081/organizations/2"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/organizations/2"); assertEquals(403, response.getStatusCode()); } @@ -55,7 +65,7 @@ public class LiveTest { @Test public void givenDisabledSecurityExpression_whenGetFooByName_thenError() { - final Response response = givenAuth("john", "123").get("http://localhost:8081/foos?name=sample"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/foos?name=sample"); assertEquals(500, response.getStatusCode()); assertTrue(response.asString().contains("method hasAuthority() not allowed")); } From 65cd2dfb064dcae0c98112d4b37c470e59385e38 Mon Sep 17 00:00:00 2001 From: Kiran Date: Wed, 12 Oct 2016 12:08:13 -0400 Subject: [PATCH 062/193] Code refactored and updated (#746) * Updated indentation and refactored code * Updated indentation and refactored code * Updated indentation and refactored code * Updated indentation and refactored code * Updated indentation * Updated indentation and refactored code * Updated indentation and refactored code --- spring-jms/pom.xml | 27 +++++----- .../spring/jms/SampleJmsMessageSender.java | 6 +-- .../baeldung/spring/jms/SampleListener.java | 17 +++--- .../src/main/resources/EmbeddedActiveMQ.xml | 27 +++++----- .../src/main/resources/applicationContext.xml | 53 +++++++++++-------- .../jms/MapMessageConvertAndSendTest.java | 6 +-- 6 files changed, 76 insertions(+), 60 deletions(-) diff --git a/spring-jms/pom.xml b/spring-jms/pom.xml index b15c18f991..8e83f82f38 100644 --- a/spring-jms/pom.xml +++ b/spring-jms/pom.xml @@ -11,6 +11,7 @@ 4.3.2.RELEASE 5.12.0 + 4.12 @@ -29,7 +30,7 @@ junit junit - 4.12 + ${junit.version} test @@ -58,16 +59,16 @@ - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - spring-jms + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + spring-jms - \ No newline at end of file + diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java index 1ef3902a31..927762f05b 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java @@ -24,10 +24,6 @@ public class SampleJmsMessageSender { } public void sendMessage(final Employee employee) { - System.out.println("Jms Message Sender : " + employee); - Map map = new HashMap<>(); - map.put("name", employee.getName()); - map.put("age", employee.getAge()); - this.jmsTemplate.convertAndSend(map); + this.jmsTemplate.convertAndSend(employee); } } diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java index eb9d51160d..6d4bef5402 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java @@ -5,13 +5,21 @@ import org.springframework.jms.core.JmsTemplate; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; +import javax.jms.Queue; import javax.jms.TextMessage; import java.util.Map; public class SampleListener implements MessageListener { - public JmsTemplate getJmsTemplate() { - return getJmsTemplate(); + private JmsTemplate jmsTemplate; + private Queue queue; + + public void setJmsTemplate(JmsTemplate jmsTemplate) { + this.jmsTemplate = jmsTemplate; + } + + public void setQueue(Queue queue) { + this.queue = queue; } public void onMessage(Message message) { @@ -19,17 +27,14 @@ public class SampleListener implements MessageListener { try { String msg = ((TextMessage) message).getText(); - System.out.println("Message has been consumed : " + msg); } catch (JMSException ex) { throw new RuntimeException(ex); } - } else { - throw new IllegalArgumentException("Message Error"); } } public Employee receiveMessage() throws JMSException { - Map map = (Map) getJmsTemplate().receiveAndConvert(); + Map map = (Map) this.jmsTemplate.receiveAndConvert(); return new Employee((String) map.get("name"), (Integer) map.get("age")); } } diff --git a/spring-jms/src/main/resources/EmbeddedActiveMQ.xml b/spring-jms/src/main/resources/EmbeddedActiveMQ.xml index 6b419c3270..016b07e831 100644 --- a/spring-jms/src/main/resources/EmbeddedActiveMQ.xml +++ b/spring-jms/src/main/resources/EmbeddedActiveMQ.xml @@ -1,15 +1,18 @@ - - - - - - - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" + xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" + xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" + xmlns:amq="http://activemq.apache.org/schema/core" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://activemq.apache.org/schema/core + http://activemq.apache.org/schema/core/activemq-core-5.2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> + + + + + + + diff --git a/spring-jms/src/main/resources/applicationContext.xml b/spring-jms/src/main/resources/applicationContext.xml index d94eb4c371..28bf848e59 100644 --- a/spring-jms/src/main/resources/applicationContext.xml +++ b/spring-jms/src/main/resources/applicationContext.xml @@ -1,34 +1,45 @@ + xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd + http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd"> + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - + + + + + + - + + + + + Date: Wed, 12 Oct 2016 19:58:56 +0200 Subject: [PATCH 063/193] modify live test configuration --- spring-security-custom-permission/pom.xml | 129 ++++++++++++------ .../main/java/org/baeldung/Application.java | 3 +- .../src/main/resources/application.properties | 3 +- .../test/java/org/baeldung/web/LiveTest.java | 24 +--- 4 files changed, 102 insertions(+), 57 deletions(-) diff --git a/spring-security-custom-permission/pom.xml b/spring-security-custom-permission/pom.xml index b2854fe7c5..74134ba260 100644 --- a/spring-security-custom-permission/pom.xml +++ b/spring-security-custom-permission/pom.xml @@ -101,53 +101,106 @@ spring-boot-maven-plugin + - maven-surefire-plugin - - ${unit-tests.skip} - - **/*LiveTest.java - - - - - - maven-failsafe-plugin - - - integration-test - - integration-test - - - ${live-tests.skip} - - **/*LiveTest.class - - - - - - + org.apache.maven.plugins + maven-surefire-plugin + + + **/*LiveTest.java + + + + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + tomcat8x + embedded + + + + + + + 8082 + + + + + + - - - live - - false - false - - - + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + UTF-8 1.8 2.4.0 - false - true + 1.6.0 diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/Application.java b/spring-security-custom-permission/src/main/java/org/baeldung/Application.java index a9d6f3b8b1..b4e8d04b49 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/Application.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/Application.java @@ -2,9 +2,10 @@ package org.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.web.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-security-custom-permission/src/main/resources/application.properties b/spring-security-custom-permission/src/main/resources/application.properties index 4433a53ac7..9b140b3c69 100644 --- a/spring-security-custom-permission/src/main/resources/application.properties +++ b/spring-security-custom-permission/src/main/resources/application.properties @@ -1,4 +1,5 @@ -server.port=8081 +server.port=8082 +server.context-path=/spring-security-custom-permission spring.datasource.driver-class-name=org.h2.Driver spring.datasource.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE spring.datasource.username=sa diff --git a/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java b/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java index 7e92765dcd..47626b814a 100644 --- a/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java +++ b/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java @@ -3,45 +3,35 @@ package org.baeldung.web; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import org.baeldung.Application; import org.baeldung.persistence.model.Foo; import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.IntegrationTest; -import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; import com.jayway.restassured.RestAssured; import com.jayway.restassured.authentication.FormAuthConfig; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.RequestSpecification; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = Application.class) -@WebAppConfiguration -@IntegrationTest("server.port:8082") public class LiveTest { - private final FormAuthConfig formAuthConfig = new FormAuthConfig("http://localhost:8082/login", "username", "password"); + private final FormAuthConfig formAuthConfig = new FormAuthConfig("http://localhost:8082/spring-security-custom-permission/login", "username", "password"); @Test public void givenUserWithReadPrivilegeAndHasPermission_whenGetFooById_thenOK() { - final Response response = givenAuth("john", "123").get("http://localhost:8082/foos/1"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/spring-security-custom-permission/foos/1"); assertEquals(200, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @Test public void givenUserWithNoWritePrivilegeAndHasPermission_whenPostFoo_thenForbidden() { - final Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8082/foos"); + final Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8082/spring-security-custom-permission/foos"); assertEquals(403, response.getStatusCode()); } @Test public void givenUserWithWritePrivilegeAndHasPermission_whenPostFoo_thenOk() { - final Response response = givenAuth("tom", "111").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8082/foos"); + final Response response = givenAuth("tom", "111").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8082/spring-security-custom-permission/foos"); assertEquals(201, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @@ -50,14 +40,14 @@ public class LiveTest { @Test public void givenUserMemberInOrganization_whenGetOrganization_thenOK() { - final Response response = givenAuth("john", "123").get("http://localhost:8082/organizations/1"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/spring-security-custom-permission/organizations/1"); assertEquals(200, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @Test public void givenUserMemberNotInOrganization_whenGetOrganization_thenForbidden() { - final Response response = givenAuth("john", "123").get("http://localhost:8082/organizations/2"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/spring-security-custom-permission/organizations/2"); assertEquals(403, response.getStatusCode()); } @@ -65,7 +55,7 @@ public class LiveTest { @Test public void givenDisabledSecurityExpression_whenGetFooByName_thenError() { - final Response response = givenAuth("john", "123").get("http://localhost:8082/foos?name=sample"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/spring-security-custom-permission/foos?name=sample"); assertEquals(500, response.getStatusCode()); assertTrue(response.asString().contains("method hasAuthority() not allowed")); } From d2ede5b6ceb459635f3d698b30f8d94182f9fa59 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 13 Oct 2016 00:14:52 +0200 Subject: [PATCH 064/193] minor fix --- .../baeldung/persistence/query/JPACriteriaQueryTest.java | 2 +- .../baeldung/persistence/query/JPASpecificationTest.java | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java index f9f9435d75..e9c8659347 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java @@ -98,7 +98,7 @@ public class JPACriteriaQueryTest { @Test public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() { final List params = new ArrayList(); - params.add(new SearchCriteria("firstName", ":", "jo")); + params.add(new SearchCriteria("firstName", ":", "Jo")); final List results = userApi.searchUser(params); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java index 97b2274cf9..52bd43cc8c 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java @@ -54,8 +54,8 @@ public class JPASpecificationTest { @Test public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { - final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.EQUALITY, "john")); - final UserSpecification spec1 = new UserSpecification(new SpecSearchCriteria("lastName", SearchOperation.EQUALITY, "doe")); + final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.EQUALITY, "John")); + final UserSpecification spec1 = new UserSpecification(new SpecSearchCriteria("lastName", SearchOperation.EQUALITY, "Doe")); final List results = repository.findAll(Specifications.where(spec).and(spec1)); assertThat(userJohn, isIn(results)); @@ -64,7 +64,7 @@ public class JPASpecificationTest { @Test public void givenFirstNameInverse_whenGettingListOfUsers_thenCorrect() { - final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.NEGATION, "john")); + final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.NEGATION, "John")); final List results = repository.findAll(Specifications.where(spec)); assertThat(userTom, isIn(results)); @@ -82,7 +82,7 @@ public class JPASpecificationTest { @Test public void givenFirstNamePrefix_whenGettingListOfUsers_thenCorrect() { - final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.STARTS_WITH, "jo")); + final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.STARTS_WITH, "Jo")); final List results = repository.findAll(spec); assertThat(userJohn, isIn(results)); From 15f5a9eca1a2a984b70bd375a417a99c24e907a1 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 13 Oct 2016 00:15:09 +0200 Subject: [PATCH 065/193] config test db --- spring-security-rest-full/pom.xml | 5 +++++ .../resources/persistence-mysql.properties | 22 ++++++++++++++----- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index dff9f7ed4f..b354e61b35 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -173,6 +173,11 @@ runtime + + com.h2database + h2 + + diff --git a/spring-security-rest-full/src/test/resources/persistence-mysql.properties b/spring-security-rest-full/src/test/resources/persistence-mysql.properties index 8263b0d9ac..839a466533 100644 --- a/spring-security-rest-full/src/test/resources/persistence-mysql.properties +++ b/spring-security-rest-full/src/test/resources/persistence-mysql.properties @@ -1,10 +1,22 @@ +## jdbc.X +#jdbc.driverClassName=com.mysql.jdbc.Driver +#jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_01?createDatabaseIfNotExist=true +#jdbc.user=tutorialuser +#jdbc.pass=tutorialmy5ql +# +## hibernate.X +#hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +#hibernate.show_sql=false +#hibernate.hbm2ddl.auto=create-drop + + # jdbc.X -jdbc.driverClassName=com.mysql.jdbc.Driver -jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_01?createDatabaseIfNotExist=true -jdbc.user=tutorialuser -jdbc.pass=tutorialmy5ql +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +jdbc.user=sa +jdbc.pass= # hibernate.X -hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop From 131b695268342726e8e7e78d77ca8b983912164b Mon Sep 17 00:00:00 2001 From: Thai Nguyen Date: Thu, 13 Oct 2016 11:17:46 +0700 Subject: [PATCH 066/193] Refactors Apache CXF JAXRS implementation --- .../java/com/baeldung/cxf/jaxrs/implementation/Course.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java index 9ab74bea58..802a19e961 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java @@ -61,13 +61,11 @@ public class Course { @Path("{studentOrder}") public Response deleteStudent(@PathParam("studentOrder") int studentOrder) { Student student = students.get(studentOrder); - Response response; if (student != null) { students.remove(studentOrder); - response = Response.ok().build(); + return Response.ok().build(); } else { - response = Response.notModified().build(); + return Response.notModified().build(); } - return response; } } \ No newline at end of file From 08c9791cb4559e27857bfdc5c911072c4ffd3ba8 Mon Sep 17 00:00:00 2001 From: maibin Date: Thu, 13 Oct 2016 07:08:59 +0200 Subject: [PATCH 067/193] Thymeleaf decorator (#747) * Expression-Based Access Control PermitAll, hasRole, hasAnyRole etc. I modified classes regards to Security * Added test cases for Spring Security Expressions * Handler Interceptor - logging example * Test for logger interceptor * Removed conflicted part * UserInterceptor (adding user information to model) * Spring Handler Interceptor - session timers * Spring Security CSRF attack protection with Thymeleaf * Fix and(); * Logger update * Changed config for Thymeleaf * Thymeleaf Natural Processing and Inlining * Expression Utility Objects, Thymeleaf * listOfStudents edited * Thymeleaf layout decorators --- spring-thymeleaf/pom.xml | 356 +++++++++--------- .../thymeleaf/config/WebMVCConfig.java | 4 + .../controller/LayoutDialectController.java | 16 + .../main/webapp/WEB-INF/views/content.html | 16 + .../webapp/WEB-INF/views/listStudents.html | 2 +- .../main/webapp/WEB-INF/views/template.html | 20 + .../LayoutDialectControllerTest.java | 58 +++ 7 files changed, 296 insertions(+), 176 deletions(-) create mode 100644 spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/LayoutDialectController.java create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/views/content.html create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/views/template.html create mode 100644 spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerTest.java diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index a13f1de4c7..960b358fe2 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -5,186 +5,192 @@ spring-thymeleaf 0.1-SNAPSHOT war - - 1.8 - - 4.3.3.RELEASE - 3.0.1 - - 1.7.12 - 1.1.3 - - 3.0.1.RELEASE - - 1.1.0.Final - 5.1.2.Final + + 1.8 + + 4.3.3.RELEASE + 3.0.1 + + 1.7.12 + 1.1.3 + + 3.0.1.RELEASE + + 1.1.0.Final + 5.1.2.Final - - 3.5.1 - 2.6 - 2.19.1 - 1.4.18 - + + 3.5.1 + 2.6 + 2.19.1 + 1.4.18 + - - - - org.springframework - spring-context - ${org.springframework-version} - - - - commons-logging - commons-logging - - - - - org.springframework - spring-webmvc - ${org.springframework-version} - - - - org.springframework.security - spring-security-web - 4.1.3.RELEASE - - - org.springframework.security - spring-security-config - 4.1.3.RELEASE - - - - org.thymeleaf - thymeleaf - ${org.thymeleaf-version} - - - org.thymeleaf - thymeleaf-spring4 - ${org.thymeleaf-version} - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - - javax.servlet - javax.servlet-api - ${javax.servlet-version} - provided - - - - javax.validation - validation-api - ${javax.validation-version} - - - org.hibernate - hibernate-validator - ${org.hibernate-version} - - + + + + org.springframework + spring-context + ${org.springframework-version} + + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + ${org.springframework-version} + + + + org.springframework.security + spring-security-web + 4.1.3.RELEASE + + + org.springframework.security + spring-security-config + 4.1.3.RELEASE + + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring4 + ${org.thymeleaf-version} + + + + nz.net.ultraq.thymeleaf + thymeleaf-layout-dialect + 2.0.4 + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + javax.servlet + javax.servlet-api + ${javax.servlet-version} + provided + + + + javax.validation + validation-api + ${javax.validation-version} + + + org.hibernate + hibernate-validator + ${org.hibernate-version} + + - - org.springframework - spring-test - 4.1.3.RELEASE - test - + + org.springframework + spring-test + 4.1.3.RELEASE + test + - - - org.springframework.security - spring-security-test - 4.1.3.RELEASE - test - + + + org.springframework.security + spring-security-test + 4.1.3.RELEASE + test + - - - junit - junit - 4.12 - test - + + + junit + junit + 4.12 + test + - + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java-version} + ${java-version} + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + 8082 + + + + + + - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java-version} - ${java-version} - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - - - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - 8082 - - - - - - - diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java index 444b780673..ab048bdd87 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java @@ -22,6 +22,9 @@ import org.thymeleaf.templateresolver.ITemplateResolver; import com.baeldung.thymeleaf.formatter.NameFormatter; import com.baeldung.thymeleaf.utils.ArrayUtil; +import nz.net.ultraq.thymeleaf.LayoutDialect; +import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy; + @Configuration @EnableWebMvc @@ -70,6 +73,7 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application private TemplateEngine templateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine engine = new SpringTemplateEngine(); + engine.addDialect(new LayoutDialect(new GroupingStrategy())); engine.setTemplateResolver(templateResolver); return engine; } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/LayoutDialectController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/LayoutDialectController.java new file mode 100644 index 0000000000..28a38ce30b --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/LayoutDialectController.java @@ -0,0 +1,16 @@ +package com.baeldung.thymeleaf.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class LayoutDialectController { + + @RequestMapping(value = "/layout", method = RequestMethod.GET) + public String getNewPage(Model model) { + return "content.html"; + } + +} diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/content.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/content.html new file mode 100644 index 0000000000..1184e28e13 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/content.html @@ -0,0 +1,16 @@ + + + +Layout Dialect Example + + +
+

This is a custom content that you can provide

+
+
+

This is some footer content + that you can change

+
+ + \ No newline at end of file diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html index a894e41e88..c7d17a4f66 100644 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html @@ -6,7 +6,7 @@ - + + +
+

New dialect example

+
+
+

Your page content goes here

+
+
+

My custom footer

+

Your custom footer here

+
+ + \ No newline at end of file diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerTest.java new file mode 100644 index 0000000000..33731f130d --- /dev/null +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerTest.java @@ -0,0 +1,58 @@ +package com.baeldung.thymeleaf.controller; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import javax.servlet.Filter; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.ContextConfiguration; +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.request.RequestPostProcessor; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.thymeleaf.config.InitSecurity; +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import com.baeldung.thymeleaf.config.WebMVCSecurity; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) +public class LayoutDialectControllerTest { + + @Autowired + WebApplicationContext wac; + @Autowired + MockHttpSession session; + + private MockMvc mockMvc; + + @Autowired + private Filter springSecurityFilterChain; + + protected RequestPostProcessor testUser() { + return user("user1").password("user1Pass").roles("USER"); + } + + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); + } + + @Test + public void testGetDates() throws Exception{ + mockMvc.perform(get("/layout").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("content.html")); + } + +} From e92dbccb7834c6769634be174b00293606331fd3 Mon Sep 17 00:00:00 2001 From: nguyennamthai Date: Thu, 13 Oct 2016 12:16:33 +0700 Subject: [PATCH 068/193] Refactors Apache CXF JAXRS implementation (#748) --- .../java/com/baeldung/cxf/jaxrs/implementation/Course.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java index 9ab74bea58..802a19e961 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java @@ -61,13 +61,11 @@ public class Course { @Path("{studentOrder}") public Response deleteStudent(@PathParam("studentOrder") int studentOrder) { Student student = students.get(studentOrder); - Response response; if (student != null) { students.remove(studentOrder); - response = Response.ok().build(); + return Response.ok().build(); } else { - response = Response.notModified().build(); + return Response.notModified().build(); } - return response; } } \ No newline at end of file From 6a7e380efd723779d337ae241281fe34282cbba0 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Thu, 13 Oct 2016 07:22:11 +0200 Subject: [PATCH 069/193] Refactor REST with CXF example --- .../cxf/jaxrs/implementation/Baeldung.java | 18 ++++------- .../cxf/jaxrs/implementation/Course.java | 14 +++------ .../cxf/jaxrs/implementation/ServiceTest.java | 30 ++++++++----------- 3 files changed, 23 insertions(+), 39 deletions(-) diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java index 5617f482f8..592df4b7c3 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java @@ -1,17 +1,12 @@ package com.baeldung.cxf.jaxrs.implementation; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Response; - @Path("baeldung") @Produces("text/xml") public class Baeldung { @@ -51,14 +46,13 @@ public class Baeldung { @Path("courses/{courseOrder}") public Response putCourse(@PathParam("courseOrder") int courseOrder, Course course) { Course existingCourse = courses.get(courseOrder); - Response response; + if (existingCourse == null || existingCourse.getId() != course.getId() || !(existingCourse.getName().equals(course.getName()))) { courses.put(courseOrder, course); - response = Response.ok().build(); - } else { - response = Response.notModified().build(); + return Response.ok().build(); } - return response; + + return Response.notModified().build(); } @Path("courses/{courseOrder}/students") diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java index 802a19e961..32689a332f 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java @@ -1,17 +1,11 @@ package com.baeldung.cxf.jaxrs.implementation; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Response; - -import javax.xml.bind.annotation.XmlRootElement; - @XmlRootElement(name = "Course") public class Course { private int id; @@ -51,7 +45,7 @@ public class Course { @POST public Response postStudent(Student student) { if (students == null) { - students = new ArrayList(); + students = new ArrayList<>(); } students.add(student); return Response.ok(student).build(); diff --git a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java index 48749a568e..8c606436c8 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java @@ -1,18 +1,5 @@ package com.baeldung.cxf.jaxrs.implementation; -import static org.junit.Assert.assertEquals; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; - -import javax.xml.bind.JAXB; - import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpPost; @@ -20,6 +7,17 @@ import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.InputStreamEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import javax.xml.bind.JAXB; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; + +import static org.junit.Assert.assertEquals; public class ServiceTest { private static final String BASE_URL = "http://localhost:8080/baeldung/courses/"; @@ -80,14 +78,12 @@ public class ServiceTest { private Course getCourse(int courseOrder) throws IOException { URL url = new URL(BASE_URL + courseOrder); InputStream input = url.openStream(); - Course course = JAXB.unmarshal(new InputStreamReader(input), Course.class); - return course; + return JAXB.unmarshal(new InputStreamReader(input), Course.class); } private Student getStudent(int courseOrder, int studentOrder) throws IOException { URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder); InputStream input = url.openStream(); - Student student = JAXB.unmarshal(new InputStreamReader(input), Student.class); - return student; + return JAXB.unmarshal(new InputStreamReader(input), Student.class); } } \ No newline at end of file From c8e034a07b114dd2329ec6c5cc12aca34c8c67fe Mon Sep 17 00:00:00 2001 From: "lcrusoveanu@optaros.com" Date: Thu, 13 Oct 2016 09:53:11 +0300 Subject: [PATCH 070/193] fix imports --- .../test/java/org/baeldung/web/CustomUserDetailsServiceTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java index 0c82a4e98b..fbc0c20144 100644 --- a/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java +++ b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java @@ -9,6 +9,7 @@ import org.baeldung.persistence.dao.UserRepository; import org.baeldung.persistence.model.User; import org.junit.Test; import org.junit.runner.RunWith; +import org.junit.After; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.security.authentication.AuthenticationProvider; From 70eb0501c651b13cc74f9fff1164e7d3aac9bd5b Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Thu, 13 Oct 2016 10:02:09 +0200 Subject: [PATCH 071/193] Delete okhttp project --- okhttp/pom.xml | 76 ------------ .../okhttp/DefaultContentTypeInterceptor.java | 26 ----- .../okhttp/ProgressRequestWrapper.java | 74 ------------ .../okhttp/OkHttpFileUploadingTest.java | 81 ------------- .../org/baeldung/okhttp/OkHttpGetTest.java | 78 ------------- .../org/baeldung/okhttp/OkHttpHeaderTest.java | 48 -------- .../org/baeldung/okhttp/OkHttpMiscTest.java | 107 ----------------- .../baeldung/okhttp/OkHttpPostingTest.java | 109 ------------------ .../baeldung/okhttp/OkHttpRedirectTest.java | 33 ------ okhttp/src/test/resources/test.txt | 1 - 10 files changed, 633 deletions(-) delete mode 100644 okhttp/pom.xml delete mode 100644 okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java delete mode 100644 okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java delete mode 100644 okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java delete mode 100644 okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java delete mode 100644 okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java delete mode 100644 okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java delete mode 100644 okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java delete mode 100644 okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java delete mode 100644 okhttp/src/test/resources/test.txt diff --git a/okhttp/pom.xml b/okhttp/pom.xml deleted file mode 100644 index 4d371f40b0..0000000000 --- a/okhttp/pom.xml +++ /dev/null @@ -1,76 +0,0 @@ - - 4.0.0 - org.baeldung.okhttp - okhttp - 0.0.1-SNAPSHOT - - - - - - - com.squareup.okhttp3 - okhttp - ${com.squareup.okhttp3.version} - - - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - - - junit - junit - ${junit.version} - test - - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - - - - - - 3.4.1 - - - 1.7.13 - 1.1.3 - - - 1.3 - 4.12 - - - - diff --git a/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java b/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java deleted file mode 100644 index 2a33a1febd..0000000000 --- a/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.baeldung.okhttp; - -import java.io.IOException; - -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -public class DefaultContentTypeInterceptor implements Interceptor { - - private final String contentType; - - public DefaultContentTypeInterceptor(String contentType) { - this.contentType = contentType; - } - - public Response intercept(Interceptor.Chain chain) throws IOException { - - Request originalRequest = chain.request(); - Request requestWithUserAgent = originalRequest.newBuilder() - .header("Content-Type", contentType) - .build(); - - return chain.proceed(requestWithUserAgent); - } -} diff --git a/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java b/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java deleted file mode 100644 index 255d10b98a..0000000000 --- a/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.baeldung.okhttp; - -import okhttp3.RequestBody; -import okhttp3.MediaType; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSink; -import okio.ForwardingSink; -import okio.Okio; -import okio.Sink; - -public class ProgressRequestWrapper extends RequestBody { - - protected RequestBody delegate; - protected ProgressListener listener; - - protected CountingSink countingSink; - - public ProgressRequestWrapper(RequestBody delegate, ProgressListener listener) { - this.delegate = delegate; - this.listener = listener; - } - - @Override - public MediaType contentType() { - return delegate.contentType(); - } - - @Override - public long contentLength() throws IOException { - return delegate.contentLength(); - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - - BufferedSink bufferedSink; - - countingSink = new CountingSink(sink); - bufferedSink = Okio.buffer(countingSink); - - delegate.writeTo(bufferedSink); - - bufferedSink.flush(); - } - - protected final class CountingSink extends ForwardingSink { - - private long bytesWritten = 0; - - public CountingSink(Sink delegate) { - super(delegate); - } - - @Override - public void write(Buffer source, long byteCount) throws IOException { - - super.write(source, byteCount); - - bytesWritten += byteCount; - listener.onRequestProgress(bytesWritten, contentLength()); - } - - } - - public interface ProgressListener { - - void onRequestProgress(long bytesWritten, long contentLength); - - } -} - diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java deleted file mode 100644 index 77219b8e22..0000000000 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.baeldung.okhttp; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - -import java.io.File; -import java.io.IOException; - -import org.baeldung.okhttp.ProgressRequestWrapper; -import org.junit.Test; - -import okhttp3.Call; -import okhttp3.MediaType; -import okhttp3.MultipartBody; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; - -public class OkHttpFileUploadingTest { - - private static final String BASE_URL = "http://localhost:8080/spring-rest"; - - @Test - public void whenUploadFile_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - RequestBody requestBody = new MultipartBody.Builder() - .setType(MultipartBody.FORM) - .addFormDataPart("file", "file.txt", - RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) - .build(); - - Request request = new Request.Builder() - .url(BASE_URL + "/users/upload") - .post(requestBody) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } - - @Test - public void whenGetUploadFileProgress_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - RequestBody requestBody = new MultipartBody.Builder() - .setType(MultipartBody.FORM) - .addFormDataPart("file", "file.txt", - RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) - .build(); - - - ProgressRequestWrapper.ProgressListener listener = new ProgressRequestWrapper.ProgressListener() { - - public void onRequestProgress(long bytesWritten, long contentLength) { - - float percentage = 100f * bytesWritten / contentLength; - assertFalse(Float.compare(percentage, 100) > 0); - } - }; - - ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, listener); - - Request request = new Request.Builder() - .url(BASE_URL + "/users/upload") - .post(countingBody) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - - } -} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java deleted file mode 100644 index de954e3dd7..0000000000 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.baeldung.okhttp; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; - -import org.junit.Test; - -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - -public class OkHttpGetTest { - - private static final String BASE_URL = "http://localhost:8080/spring-rest"; - - @Test - public void whenGetRequest_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - Request request = new Request.Builder() - .url(BASE_URL + "/date") - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } - - @Test - public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); - urlBuilder.addQueryParameter("id", "1"); - - String url = urlBuilder.build().toString(); - - Request request = new Request.Builder() - .url(url) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } - - @Test - public void whenAsynchronousGetRequest_thenCorrect() { - - OkHttpClient client = new OkHttpClient(); - - Request request = new Request.Builder() - .url(BASE_URL + "/date") - .build(); - - Call call = client.newCall(request); - - call.enqueue(new Callback() { - - public void onResponse(Call call, Response response) throws IOException { - assertThat(response.code(), equalTo(200)); - } - - public void onFailure(Call call, IOException e) { - - } - }); - } -} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java deleted file mode 100644 index 958eeb51ce..0000000000 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.baeldung.okhttp; - -import java.io.IOException; - -import org.junit.Test; - -import okhttp3.Call; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - -public class OkHttpHeaderTest { - - private static final String SAMPLE_URL = "http://www.github.com"; - - @Test - public void whenSetHeader_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - Request request = new Request.Builder() - .url(SAMPLE_URL) - .addHeader("Content-Type", "application/json") - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - response.close(); - } - - @Test - public void whenSetDefaultHeader_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient.Builder() - .addInterceptor(new DefaultContentTypeInterceptor("application/json")) - .build(); - - Request request = new Request.Builder() - .url(SAMPLE_URL) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - response.close(); - } - - -} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java deleted file mode 100644 index fe15a76200..0000000000 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.baeldung.okhttp; - -import java.io.File; -import java.io.IOException; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import okhttp3.Cache; -import okhttp3.Call; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - -public class OkHttpMiscTest { - - private static final String BASE_URL = "http://localhost:8080/spring-rest"; - private static Logger logger = LoggerFactory.getLogger(OkHttpMiscTest.class); - - @Test - public void whenSetRequestTimeout_thenFail() throws IOException { - - OkHttpClient client = new OkHttpClient.Builder() - .readTimeout(1, TimeUnit.SECONDS) - .build(); - - Request request = new Request.Builder() - .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - response.close(); - } - - @Test - public void whenCancelRequest_thenCorrect() throws IOException { - - ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); - - OkHttpClient client = new OkHttpClient(); - - Request request = new Request.Builder() - .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. - .build(); - - final int seconds = 1; - - final long startNanos = System.nanoTime(); - final Call call = client.newCall(request); - - // Schedule a job to cancel the call in 1 second. - executor.schedule(new Runnable() { - public void run() { - - logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f); - call.cancel(); - logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f); - } - }, seconds, TimeUnit.SECONDS); - - try { - - logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f); - Response response = call.execute(); - logger.debug("Call was expected to fail, but completed: " + (System.nanoTime() - startNanos) / 1e9f, response); - - } catch (IOException e) { - - logger.debug("Call failed as expected: " + (System.nanoTime() - startNanos) / 1e9f, e); - } - } - - @Test - public void whenSetResponseCache_thenCorrect() throws IOException { - - int cacheSize = 10 * 1024 * 1024; // 10 MiB - File cacheDirectory = new File("src/test/resources/cache"); - Cache cache = new Cache(cacheDirectory, cacheSize); - - OkHttpClient client = new OkHttpClient.Builder() - .cache(cache) - .build(); - - Request request = new Request.Builder() - .url("http://publicobject.com/helloworld.txt") - .build(); - - Response response1 = client.newCall(request).execute(); - logResponse(response1); - - Response response2 = client.newCall(request).execute(); - logResponse(response2); - } - - private void logResponse(Response response) throws IOException { - - logger.debug("Response response: " + response); - logger.debug("Response cache response: " + response.cacheResponse()); - logger.debug("Response network response: " + response.networkResponse()); - logger.debug("Response responseBody: " + response.body().string()); - } -} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java deleted file mode 100644 index 41a024d2ee..0000000000 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.baeldung.okhttp; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.File; -import java.io.IOException; - -import org.junit.Test; - -import okhttp3.Call; -import okhttp3.Credentials; -import okhttp3.FormBody; -import okhttp3.MediaType; -import okhttp3.MultipartBody; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; - -public class OkHttpPostingTest { - - private static final String BASE_URL = "http://localhost:8080/spring-rest"; - private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; - - @Test - public void whenSendPostRequest_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - RequestBody formBody = new FormBody.Builder() - .add("username", "test") - .add("password", "test") - .build(); - - Request request = new Request.Builder() - .url(BASE_URL + "/users") - .post(formBody) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } - - @Test - public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException { - - String postBody = "test post"; - - OkHttpClient client = new OkHttpClient(); - - Request request = new Request.Builder() - .url(URL_SECURED_BY_BASIC_AUTHENTICATION) - .addHeader("Authorization", Credentials.basic("test", "test")) - .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody)) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } - - @Test - public void whenPostJson_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - String json = "{\"id\":1,\"name\":\"John\"}"; - - RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); - - Request request = new Request.Builder() - .url(BASE_URL + "/users/detail") - .post(body) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } - - @Test - public void whenSendMultipartRequest_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - - RequestBody requestBody = new MultipartBody.Builder() - .setType(MultipartBody.FORM) - .addFormDataPart("username", "test") - .addFormDataPart("password", "test") - .addFormDataPart("file", "file.txt", - RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) - .build(); - - Request request = new Request.Builder() - .url(BASE_URL + "/users/multipart") - .post(requestBody) - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(200)); - } -} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java deleted file mode 100644 index c709253478..0000000000 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.baeldung.okhttp; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; - -import org.junit.Test; - -import okhttp3.Call; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - -public class OkHttpRedirectTest { - - @Test - public void whenSetFollowRedirects_thenNotRedirected() throws IOException { - - OkHttpClient client = new OkHttpClient().newBuilder() - .followRedirects(false) - .build(); - - Request request = new Request.Builder() - .url("http://t.co/I5YYd9tddw") - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - - assertThat(response.code(), equalTo(301)); - } -} diff --git a/okhttp/src/test/resources/test.txt b/okhttp/src/test/resources/test.txt deleted file mode 100644 index 95d09f2b10..0000000000 --- a/okhttp/src/test/resources/test.txt +++ /dev/null @@ -1 +0,0 @@ -hello world \ No newline at end of file From 5329c54f28fc2c6b853454547b62b256f03c2ffc Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Thu, 13 Oct 2016 10:20:18 +0200 Subject: [PATCH 072/193] Code improvement --- pom.xml | 3 +-- spring-rest/README.md | 3 ++- ...ileUploadingTest.java => OkHttpFileUploadingLiveTest.java} | 2 +- .../okhttp/{OkHttpGetTest.java => OkHttpGetLiveTest.java} | 2 +- .../{OkHttpHeaderTest.java => OkHttpHeaderLiveTest.java} | 2 +- .../okhttp/{OkHttpMiscTest.java => OkHttpMiscLiveTest.java} | 4 ++-- .../{OkHttpPostingTest.java => OkHttpPostingLiveTest.java} | 2 +- .../{OkHttpRedirectTest.java => OkHttpRedirectLiveTest.java} | 2 +- 8 files changed, 10 insertions(+), 10 deletions(-) rename spring-rest/src/test/java/org/baeldung/okhttp/{OkHttpFileUploadingTest.java => OkHttpFileUploadingLiveTest.java} (95%) rename spring-rest/src/test/java/org/baeldung/okhttp/{OkHttpGetTest.java => OkHttpGetLiveTest.java} (94%) rename spring-rest/src/test/java/org/baeldung/okhttp/{OkHttpHeaderTest.java => OkHttpHeaderLiveTest.java} (93%) rename spring-rest/src/test/java/org/baeldung/okhttp/{OkHttpMiscTest.java => OkHttpMiscLiveTest.java} (95%) rename spring-rest/src/test/java/org/baeldung/okhttp/{OkHttpPostingTest.java => OkHttpPostingLiveTest.java} (95%) rename spring-rest/src/test/java/org/baeldung/okhttp/{OkHttpRedirectTest.java => OkHttpRedirectLiveTest.java} (91%) diff --git a/pom.xml b/pom.xml index 5526c1e2a3..0808397464 100644 --- a/pom.xml +++ b/pom.xml @@ -18,7 +18,7 @@ apache-cxf autovalue-tutorial - + cdi core-java core-java-8 @@ -69,7 +69,6 @@ rest-assured rest-testing resteasy - okhttp spring-all spring-akka diff --git a/spring-rest/README.md b/spring-rest/README.md index 7d993b38b8..77d12063ed 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -5,8 +5,9 @@ ###The Course The "REST With Spring" Classes: http://bit.ly/restwithspring -### Relevant Articles: +### Relevant Articles: - [Spring @RequestMapping](http://www.baeldung.com/spring-requestmapping) - [Http Message Converters with the Spring Framework](http://www.baeldung.com/spring-httpmessageconverter-rest) - [Redirect in Spring](http://www.baeldung.com/spring-redirect-and-forward) - [Returning Custom Status Codes from Spring Controllers](http://www.baeldung.com/spring-mvc-controller-custom-http-status-code) +- [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp) diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java similarity index 95% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java index 77219b8e22..d1cc67b99a 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java @@ -18,7 +18,7 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; -public class OkHttpFileUploadingTest { +public class OkHttpFileUploadingLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java similarity index 94% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index de954e3dd7..9a49c8d9a2 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -14,7 +14,7 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; -public class OkHttpGetTest { +public class OkHttpGetLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java similarity index 93% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java index 958eeb51ce..8eddfcb135 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java @@ -9,7 +9,7 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; -public class OkHttpHeaderTest { +public class OkHttpHeaderLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java similarity index 95% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java index fe15a76200..c44500f4be 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -16,10 +16,10 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; -public class OkHttpMiscTest { +public class OkHttpMiscLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; - private static Logger logger = LoggerFactory.getLogger(OkHttpMiscTest.class); + private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class); @Test public void whenSetRequestTimeout_thenFail() throws IOException { diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java similarity index 95% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java index 41a024d2ee..18bd4cdcb3 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java @@ -18,7 +18,7 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; -public class OkHttpPostingTest { +public class OkHttpPostingLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectLiveTest.java similarity index 91% rename from spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectLiveTest.java index c709253478..d568a4fdf7 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectLiveTest.java @@ -12,7 +12,7 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; -public class OkHttpRedirectTest { +public class OkHttpRedirectLiveTest { @Test public void whenSetFollowRedirects_thenNotRedirected() throws IOException { From c4638f1b4aa0efccdd4ce03fbcdff43170be7306 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Thu, 13 Oct 2016 18:35:13 +0300 Subject: [PATCH 073/193] Fix SpringJMS examples --- .../baeldung/spring/jms/SampleListener.java | 2 +- .../jms/MapMessageConvertAndSendTest.java | 24 ------------------- 2 files changed, 1 insertion(+), 25 deletions(-) delete mode 100644 spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java index 6d4bef5402..f35c22e144 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java @@ -25,8 +25,8 @@ public class SampleListener implements MessageListener { public void onMessage(Message message) { if (message instanceof TextMessage) { try { - String msg = ((TextMessage) message).getText(); + System.out.println("Received message: " + msg); } catch (JMSException ex) { throw new RuntimeException(ex); } diff --git a/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java b/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java deleted file mode 100644 index c0761939ad..0000000000 --- a/spring-jms/src/test/java/com/baeldung/spring/jms/MapMessageConvertAndSendTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.spring.jms; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class DefaultTextMessageSenderTest { - - private static SampleJmsMessageSender messageProducer; - - @SuppressWarnings("resource") - @BeforeClass - public static void setUp() { - ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); - messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); - } - - @Test - public void testSimpleSend() { - messageProducer.simpleSend(); - } - -} From cef8adfdaebc62faa9fa2baeaa190fd0de94d296 Mon Sep 17 00:00:00 2001 From: Sandeep Kumar Date: Fri, 14 Oct 2016 15:36:00 +0530 Subject: [PATCH 074/193] Changes as per Live Test guidelines --- selenium-junit-testng/pom.xml | 28 ++++++++++++++++--- ...it.java => SeleniumWithJUnitLiveTest.java} | 2 +- ...G.java => SeleniumWithTestNGLiveTest.java} | 2 +- 3 files changed, 26 insertions(+), 6 deletions(-) rename selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/{TestSeleniumWithJUnit.java => SeleniumWithJUnitLiveTest.java} (96%) rename selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/{TestSeleniumWithTestNG.java => SeleniumWithTestNGLiveTest.java} (96%) diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml index c6461816af..f964f94ed4 100644 --- a/selenium-junit-testng/pom.xml +++ b/selenium-junit-testng/pom.xml @@ -20,14 +20,34 @@ maven-surefire-plugin 2.19.1 - - - Test*.java - + true + + **/*LiveTest.java + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*LiveTest.java + + + + + + + + org.seleniumhq.selenium diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java similarity index 96% rename from selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java rename to selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java index 85c20f62a5..f8d9a5dada 100644 --- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java @@ -9,7 +9,7 @@ import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -public class TestSeleniumWithJUnit { +public class SeleniumWithJUnitLiveTest { private static SeleniumExample seleniumExample; private String expecteTilteAboutBaeldungPage = "About Baeldung | Baeldung"; diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java similarity index 96% rename from selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java rename to selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java index 40b0424820..5ec9ade39f 100644 --- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java @@ -9,7 +9,7 @@ import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; -public class TestSeleniumWithTestNG { +public class SeleniumWithTestNGLiveTest { private SeleniumExample seleniumExample; private String expecteTilteAboutBaeldungPage = "About Baeldung | Baeldung"; From f37718124ae2dc6ab9c7c12c68e4cb17e802cf1e Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 14 Oct 2016 12:37:05 +0200 Subject: [PATCH 075/193] skip live test --- spring-zuul/spring-zuul-ui/pom.xml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/spring-zuul/spring-zuul-ui/pom.xml b/spring-zuul/spring-zuul-ui/pom.xml index 9eaf4b7c45..99df27f2f9 100644 --- a/spring-zuul/spring-zuul-ui/pom.xml +++ b/spring-zuul/spring-zuul-ui/pom.xml @@ -87,5 +87,18 @@ true + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*LiveTest.java + + + + + + \ No newline at end of file From 97d0c7144961367887dfb7cb1bc54e062002d851 Mon Sep 17 00:00:00 2001 From: Prashant Khanal Date: Tue, 11 Oct 2016 16:06:10 -0700 Subject: [PATCH 076/193] Code cleanup Signed-off-by: nguyenminhtuanfit@gmail.com --- .../hazelcast/cluster/NativeClient.java | 12 +++--- .../hazelcast/cluster/ServerNode.java | 9 +--- .../listener/CountryEntryListener.java | 41 ------------------- 3 files changed, 7 insertions(+), 55 deletions(-) delete mode 100644 hazelcast/src/main/java/com/baeldung/hazelcast/listener/CountryEntryListener.java diff --git a/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/NativeClient.java b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/NativeClient.java index bda4b94733..697e362289 100644 --- a/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/NativeClient.java +++ b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/NativeClient.java @@ -1,9 +1,7 @@ package com.baeldung.hazelcast.cluster; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.Map.Entry; -import com.baeldung.hazelcast.listener.CountryEntryListener; import com.hazelcast.client.HazelcastClient; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.config.GroupConfig; @@ -11,7 +9,6 @@ import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; public class NativeClient { - private static final Logger logger = LoggerFactory.getLogger(NativeClient.class); public static void main(String[] args) throws InterruptedException { ClientConfig config = new ClientConfig(); @@ -19,8 +16,9 @@ public class NativeClient { groupConfig.setName("dev"); groupConfig.setPassword("dev-pass"); HazelcastInstance hazelcastInstanceClient = HazelcastClient.newHazelcastClient(config); - IMap countryMap = hazelcastInstanceClient.getMap("country"); - countryMap.addEntryListener(new CountryEntryListener(), true); - logger.info("Country map size: " + countryMap.size()); + IMap map = hazelcastInstanceClient.getMap("data"); + for (Entry entry : map.entrySet()) { + System.out.println(String.format("Key: %d, Value: %s", entry.getKey(), entry.getValue())); + } } } diff --git a/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java index 01043cf712..36028834a4 100644 --- a/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java +++ b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java @@ -2,23 +2,18 @@ package com.baeldung.hazelcast.cluster; import java.util.Map; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IdGenerator; public class ServerNode { - private static final Logger logger = LoggerFactory.getLogger(ServerNode.class); public static void main(String[] args) { HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(); - Map countryMap = hazelcastInstance.getMap("country"); + Map map = hazelcastInstance.getMap("data"); IdGenerator idGenerator = hazelcastInstance.getIdGenerator("newid"); for (int i = 0; i < 10; i++) { - countryMap.put(idGenerator.newId(), "message" + 1); + map.put(idGenerator.newId(), "message" + 1); } - logger.info("Country map size: " + countryMap.size()); } } diff --git a/hazelcast/src/main/java/com/baeldung/hazelcast/listener/CountryEntryListener.java b/hazelcast/src/main/java/com/baeldung/hazelcast/listener/CountryEntryListener.java deleted file mode 100644 index 1f95dcd9f3..0000000000 --- a/hazelcast/src/main/java/com/baeldung/hazelcast/listener/CountryEntryListener.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.hazelcast.listener; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.hazelcast.core.EntryEvent; -import com.hazelcast.core.MapEvent; -import com.hazelcast.map.listener.EntryAddedListener; -import com.hazelcast.map.listener.EntryEvictedListener; -import com.hazelcast.map.listener.EntryRemovedListener; -import com.hazelcast.map.listener.EntryUpdatedListener; -import com.hazelcast.map.listener.MapClearedListener; -import com.hazelcast.map.listener.MapEvictedListener; - -public class CountryEntryListener implements EntryAddedListener, EntryRemovedListener, EntryUpdatedListener, EntryEvictedListener, MapEvictedListener, MapClearedListener { - private static final Logger logger = LoggerFactory.getLogger(CountryEntryListener.class); - - public void entryAdded(EntryEvent event) { - logger.info("entryAdded:" + event); - } - - public void entryUpdated(EntryEvent event) { - logger.info("entryUpdated:" + event); - } - - public void entryRemoved(EntryEvent event) { - logger.info("entryRemoved:" + event); - } - - public void entryEvicted(EntryEvent event) { - logger.info("entryEvicted:" + event); - } - - public void mapCleared(MapEvent event) { - logger.info("mapCleared:" + event); - } - - public void mapEvicted(MapEvent event) { - logger.info("mapEvicted:" + event); - } -} From eb2fc383161f3f77a2df45997b7eea24cc3a70c1 Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 14 Oct 2016 16:40:06 +0200 Subject: [PATCH 077/193] configure live test --- spring-katharsis/pom.xml | 97 ++++++++++++++++++- .../main/java/org/baeldung/Application.java | 3 +- .../src/main/resources/application.properties | 5 +- .../org/baeldung/test/JsonApiLiveTest.java | 10 +- 4 files changed, 103 insertions(+), 12 deletions(-) diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 892aaf24f1..e2e3ea6f97 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -3,11 +3,12 @@ org.springframework.samples spring-katharsis 0.0.1-SNAPSHOT + war org.springframework.boot spring-boot-starter-parent - 1.2.6.RELEASE + 1.3.3.RELEASE @@ -62,6 +63,7 @@ 1.8 1.0.0 2.4.0 + 1.6.0
@@ -71,7 +73,100 @@ org.springframework.boot spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*LiveTest.java + + + + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + tomcat8x + embedded + + + + + + + 8082 + + + + + + + + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + diff --git a/spring-katharsis/src/main/java/org/baeldung/Application.java b/spring-katharsis/src/main/java/org/baeldung/Application.java index 1b409f8b91..e7beb16e04 100644 --- a/spring-katharsis/src/main/java/org/baeldung/Application.java +++ b/spring-katharsis/src/main/java/org/baeldung/Application.java @@ -2,9 +2,10 @@ package org.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.web.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-katharsis/src/main/resources/application.properties b/spring-katharsis/src/main/resources/application.properties index 25d4559e3d..b55fdbba03 100644 --- a/spring-katharsis/src/main/resources/application.properties +++ b/spring-katharsis/src/main/resources/application.properties @@ -3,4 +3,7 @@ spring.datasource.username = sa spring.datasource.password = spring.jpa.show-sql = false spring.jpa.hibernate.ddl-auto = create-drop -spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect \ No newline at end of file +spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect + +server.port=8082 +server.context-path=/spring-katharsis \ No newline at end of file diff --git a/spring-katharsis/src/test/java/org/baeldung/test/JsonApiLiveTest.java b/spring-katharsis/src/test/java/org/baeldung/test/JsonApiLiveTest.java index bbddba3490..26a8c42a25 100644 --- a/spring-katharsis/src/test/java/org/baeldung/test/JsonApiLiveTest.java +++ b/spring-katharsis/src/test/java/org/baeldung/test/JsonApiLiveTest.java @@ -2,22 +2,14 @@ package org.baeldung.test; import static org.junit.Assert.assertEquals; -import org.baeldung.Application; import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = Application.class) -@WebAppConfiguration public class JsonApiLiveTest { - private final static String URL_PREFIX = "http://localhost:8080/users"; + private final static String URL_PREFIX = "http://localhost:8082/spring-katharsis/users"; @Test public void whenGettingAllUsers_thenCorrect() { From 63024cc8e92e8d93fdbcc0eeb3f6e787b5e48cd2 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 15 Oct 2016 13:48:40 +0200 Subject: [PATCH 078/193] cleanup test --- .../baeldung/spring/PersistenceConfig.java | 2 +- .../src/main/resources/data.sql | 5 ++ .../resources/persistence-h2.properties} | 0 .../baeldung/client/RestTemplateLiveTest.java | 2 +- .../baeldung/common/web/AbstractLiveTest.java | 2 +- .../query/JPACriteriaQueryTest.java | 22 ++++---- .../persistence/query/JPAQuerydslTest.java | 16 +++--- .../query/JPASpecificationLiveTest.java | 30 ++++------- .../query/JPASpecificationTest.java | 16 +++--- .../csrf/CsrfAbstractIntegrationTest.java | 4 +- .../csrf/CsrfEnabledIntegrationTest.java | 4 +- .../security/csrf/SecurityWithCsrfConfig.java | 2 +- .../java/org/baeldung/web/MyUserLiveTest.java | 50 +++++++------------ 13 files changed, 70 insertions(+), 85 deletions(-) create mode 100644 spring-security-rest-full/src/main/resources/data.sql rename spring-security-rest-full/src/{test/resources/persistence-mysql.properties => main/resources/persistence-h2.properties} (100%) diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java index dad4808a56..f3a87b189e 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java @@ -23,7 +23,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement -@PropertySource({ "classpath:persistence-${envTarget:mysql}.properties" }) +@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" }) @ComponentScan({ "org.baeldung.persistence" }) // @ImportResource("classpath*:springDataPersistenceConfig.xml") @EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") diff --git a/spring-security-rest-full/src/main/resources/data.sql b/spring-security-rest-full/src/main/resources/data.sql new file mode 100644 index 0000000000..5fba12dd85 --- /dev/null +++ b/spring-security-rest-full/src/main/resources/data.sql @@ -0,0 +1,5 @@ +insert into User (id, firstName, lastName, email, age) values (1, 'john', 'doe', 'john@doe.com', 22); +insert into User (id, firstName, lastName, email, age) values (2, 'tom', 'doe', 'tom@doe.com', 26); + +insert into MyUser (id, firstName, lastName, email, age) values (1, 'john', 'doe', 'john@doe.com', 22); +insert into MyUser (id, firstName, lastName, email, age) values (2, 'tom', 'doe', 'tom@doe.com', 26); diff --git a/spring-security-rest-full/src/test/resources/persistence-mysql.properties b/spring-security-rest-full/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-security-rest-full/src/test/resources/persistence-mysql.properties rename to spring-security-rest-full/src/main/resources/persistence-h2.properties diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java index fb40bd9d62..0f0a73b536 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java @@ -51,7 +51,7 @@ import com.google.common.base.Charsets; public class RestTemplateLiveTest { private RestTemplate restTemplate; - private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/foos"; + private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/auth/foos"; @Before public void beforeTest() { diff --git a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java index 95fce10e45..a3e6c8858d 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java @@ -57,7 +57,7 @@ public abstract class AbstractLiveTest { // protected String getURL() { - return "http://localhost:" + APPLICATION_PORT + "/foos"; + return "http://localhost:" + APPLICATION_PORT + "/auth/foos"; } protected final RequestSpecification givenAuth() { diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java index e9c8659347..1d0826e6ba 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java @@ -36,15 +36,15 @@ public class JPACriteriaQueryTest { @Before public void init() { userJohn = new User(); - userJohn.setFirstName("John"); - userJohn.setLastName("Doe"); + userJohn.setFirstName("john"); + userJohn.setLastName("doe"); userJohn.setEmail("john@doe.com"); userJohn.setAge(22); userApi.save(userJohn); userTom = new User(); - userTom.setFirstName("Tom"); - userTom.setLastName("Doe"); + userTom.setFirstName("tom"); + userTom.setLastName("doe"); userTom.setEmail("tom@doe.com"); userTom.setAge(26); userApi.save(userTom); @@ -53,8 +53,8 @@ public class JPACriteriaQueryTest { @Test public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { final List params = new ArrayList(); - params.add(new SearchCriteria("firstName", ":", "John")); - params.add(new SearchCriteria("lastName", ":", "Doe")); + params.add(new SearchCriteria("firstName", ":", "john")); + params.add(new SearchCriteria("lastName", ":", "doe")); final List results = userApi.searchUser(params); @@ -65,7 +65,7 @@ public class JPACriteriaQueryTest { @Test public void givenLast_whenGettingListOfUsers_thenCorrect() { final List params = new ArrayList(); - params.add(new SearchCriteria("lastName", ":", "Doe")); + params.add(new SearchCriteria("lastName", ":", "doe")); final List results = userApi.searchUser(params); assertThat(userJohn, isIn(results)); @@ -75,7 +75,7 @@ public class JPACriteriaQueryTest { @Test public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() { final List params = new ArrayList(); - params.add(new SearchCriteria("lastName", ":", "Doe")); + params.add(new SearchCriteria("lastName", ":", "doe")); params.add(new SearchCriteria("age", ">", "25")); final List results = userApi.searchUser(params); @@ -87,8 +87,8 @@ public class JPACriteriaQueryTest { @Test public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() { final List params = new ArrayList(); - params.add(new SearchCriteria("firstName", ":", "Adam")); - params.add(new SearchCriteria("lastName", ":", "Fox")); + params.add(new SearchCriteria("firstName", ":", "adam")); + params.add(new SearchCriteria("lastName", ":", "fox")); final List results = userApi.searchUser(params); assertThat(userJohn, not(isIn(results))); @@ -98,7 +98,7 @@ public class JPACriteriaQueryTest { @Test public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() { final List params = new ArrayList(); - params.add(new SearchCriteria("firstName", ":", "Jo")); + params.add(new SearchCriteria("firstName", ":", "jo")); final List results = userApi.searchUser(params); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java index b7b38a4fcb..d5fbc819fd 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java @@ -35,15 +35,15 @@ public class JPAQuerydslTest { @Before public void init() { userJohn = new MyUser(); - userJohn.setFirstName("John"); - userJohn.setLastName("Doe"); + userJohn.setFirstName("john"); + userJohn.setLastName("doe"); userJohn.setEmail("john@doe.com"); userJohn.setAge(22); repo.save(userJohn); userTom = new MyUser(); - userTom.setFirstName("Tom"); - userTom.setLastName("Doe"); + userTom.setFirstName("tom"); + userTom.setLastName("doe"); userTom.setEmail("tom@doe.com"); userTom.setAge(26); repo.save(userTom); @@ -51,7 +51,7 @@ public class JPAQuerydslTest { @Test public void givenLast_whenGettingListOfUsers_thenCorrect() { - final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("lastName", ":", "Doe"); + final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("lastName", ":", "doe"); final Iterable results = repo.findAll(builder.build()); assertThat(results, containsInAnyOrder(userJohn, userTom)); @@ -59,7 +59,7 @@ public class JPAQuerydslTest { @Test public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { - final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("firstName", ":", "John").with("lastName", ":", "Doe"); + final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("firstName", ":", "john").with("lastName", ":", "doe"); final Iterable results = repo.findAll(builder.build()); @@ -69,7 +69,7 @@ public class JPAQuerydslTest { @Test public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() { - final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("lastName", ":", "Doe").with("age", ">", "25"); + final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("lastName", ":", "doe").with("age", ">", "25"); final Iterable results = repo.findAll(builder.build()); @@ -79,7 +79,7 @@ public class JPAQuerydslTest { @Test public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() { - final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("firstName", ":", "Adam").with("lastName", ":", "Fox"); + final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("firstName", ":", "adam").with("lastName", ":", "fox"); final Iterable results = repo.findAll(builder.build()); assertThat(results, emptyIterable()); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java index 544161dfd5..4fa15d536a 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java @@ -3,52 +3,44 @@ package org.baeldung.persistence.query; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.baeldung.persistence.dao.UserRepository; import org.baeldung.persistence.model.User; -import org.baeldung.spring.ConfigTest; -import org.baeldung.spring.PersistenceConfig; 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.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.RequestSpecification; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ConfigTest.class, PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +//@RunWith(SpringJUnit4ClassRunner.class) +//@ContextConfiguration(classes = { ConfigTest.class, PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class JPASpecificationLiveTest { - @Autowired - private UserRepository repository; + // @Autowired + // private UserRepository repository; private User userJohn; private User userTom; - private final String URL_PREFIX = "http://localhost:8080/users/spec?search="; + private final String URL_PREFIX = "http://localhost:8080/auth/users/spec?search="; @Before public void init() { userJohn = new User(); - userJohn.setFirstName("John"); - userJohn.setLastName("Doe"); + userJohn.setFirstName("john"); + userJohn.setLastName("doe"); userJohn.setEmail("john@doe.com"); userJohn.setAge(22); - repository.save(userJohn); + // repository.save(userJohn); userTom = new User(); - userTom.setFirstName("Tom"); - userTom.setLastName("Doe"); + userTom.setFirstName("tom"); + userTom.setLastName("doe"); userTom.setEmail("tom@doe.com"); userTom.setAge(26); - repository.save(userTom); + // repository.save(userTom); } @Test diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java index 52bd43cc8c..0d8773dd61 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java @@ -38,15 +38,15 @@ public class JPASpecificationTest { @Before public void init() { userJohn = new User(); - userJohn.setFirstName("John"); - userJohn.setLastName("Doe"); + userJohn.setFirstName("john"); + userJohn.setLastName("doe"); userJohn.setEmail("john@doe.com"); userJohn.setAge(22); repository.save(userJohn); userTom = new User(); - userTom.setFirstName("Tom"); - userTom.setLastName("Doe"); + userTom.setFirstName("tom"); + userTom.setLastName("doe"); userTom.setEmail("tom@doe.com"); userTom.setAge(26); repository.save(userTom); @@ -54,8 +54,8 @@ public class JPASpecificationTest { @Test public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { - final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.EQUALITY, "John")); - final UserSpecification spec1 = new UserSpecification(new SpecSearchCriteria("lastName", SearchOperation.EQUALITY, "Doe")); + final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.EQUALITY, "john")); + final UserSpecification spec1 = new UserSpecification(new SpecSearchCriteria("lastName", SearchOperation.EQUALITY, "doe")); final List results = repository.findAll(Specifications.where(spec).and(spec1)); assertThat(userJohn, isIn(results)); @@ -64,7 +64,7 @@ public class JPASpecificationTest { @Test public void givenFirstNameInverse_whenGettingListOfUsers_thenCorrect() { - final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.NEGATION, "John")); + final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.NEGATION, "john")); final List results = repository.findAll(Specifications.where(spec)); assertThat(userTom, isIn(results)); @@ -82,7 +82,7 @@ public class JPASpecificationTest { @Test public void givenFirstNamePrefix_whenGettingListOfUsers_thenCorrect() { - final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.STARTS_WITH, "Jo")); + final UserSpecification spec = new UserSpecification(new SpecSearchCriteria("firstName", SearchOperation.STARTS_WITH, "jo")); final List results = repository.findAll(spec); assertThat(userJohn, isIn(results)); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java index 13cb92a745..be9b7cf27e 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java @@ -23,7 +23,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @Transactional -public class CsrfAbstractIntegrationTest { +public abstract class CsrfAbstractIntegrationTest { @Autowired private WebApplicationContext context; @@ -41,7 +41,7 @@ public class CsrfAbstractIntegrationTest { } protected RequestPostProcessor testUser() { - return user("user").password("userPass").roles("USER"); + return user("user1").password("user1Pass").roles("USER"); } protected RequestPostProcessor testAdmin() { diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java index c7caf61525..b04644f847 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -15,12 +15,12 @@ public class CsrfEnabledIntegrationTest extends CsrfAbstractIntegrationTest { @Test public void givenNoCsrf_whenAddFoo_thenForbidden() throws Exception { - mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isForbidden()); + mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isForbidden()); } @Test public void givenCsrf_whenAddFoo_thenCreated() throws Exception { - mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser()).with(csrf())).andExpect(status().isCreated()); + mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser()).with(csrf())).andExpect(status().isCreated()); } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java index 99b94cd7b5..ae4a655265 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java @@ -41,7 +41,7 @@ public class SecurityWithCsrfConfig extends WebSecurityConfigurerAdapter { // @formatter:off http .authorizeRequests() - .antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN") + .antMatchers("/auth/admin/*").hasAnyRole("ROLE_ADMIN") .anyRequest().authenticated() .and() .httpBasic() diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java index 835b32c95c..c7fb26d70b 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java @@ -3,52 +3,44 @@ package org.baeldung.web; import static org.junit.Assert.assertEquals; import org.baeldung.persistence.model.MyUser; -import org.baeldung.spring.ConfigTest; -import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.RequestSpecification; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) +//@RunWith(SpringJUnit4ClassRunner.class) +//@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class MyUserLiveTest { - private ObjectMapper mapper = new ObjectMapper(); - private MyUser userJohn = new MyUser("john", "doe", "john@test.com", 11); - private MyUser userTom = new MyUser("tom", "doe", "tom@test.com", 20); + private final ObjectMapper mapper = new ObjectMapper(); + private final MyUser userJohn = new MyUser("john", "doe", "john@doe.com", 11); + private final MyUser userTom = new MyUser("tom", "doe", "tom@doe.com", 20); - private static boolean setupDataCreated = false; - - @Before - public void setupData() throws JsonProcessingException { - if (!setupDataCreated) { - withRequestBody(givenAuth(), userJohn).post("http://localhost:8080/myusers"); - withRequestBody(givenAuth(), userTom).post("http://localhost:8080/myusers"); - setupDataCreated = true; - } - } + // private static boolean setupDataCreated = false; + // + // @Before + // public void setupData() throws JsonProcessingException { + // if (!setupDataCreated) { + // withRequestBody(givenAuth(), userJohn).post("http://localhost:8080/auth/myusers"); + // withRequestBody(givenAuth(), userTom).post("http://localhost:8080/auth/myusers"); + // setupDataCreated = true; + // } + // } @Test public void whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get("http://localhost:8080/api/myusers"); + final Response response = givenAuth().get("http://localhost:8080/auth/api/myusers"); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 2); } @Test public void givenFirstName_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get("http://localhost:8080/api/myusers?firstName=john"); + final Response response = givenAuth().get("http://localhost:8080/auth/api/myusers?firstName=john"); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 1); assertEquals(result[0].getEmail(), userJohn.getEmail()); @@ -56,14 +48,14 @@ public class MyUserLiveTest { @Test public void givenPartialLastName_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get("http://localhost:8080/api/myusers?lastName=do"); + final Response response = givenAuth().get("http://localhost:8080/auth/api/myusers?lastName=do"); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 2); } @Test public void givenEmail_whenGettingListOfUsers_thenIgnored() { - final Response response = givenAuth().get("http://localhost:8080/api/myusers?email=john"); + final Response response = givenAuth().get("http://localhost:8080/auth/api/myusers?email=john"); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 2); } @@ -71,8 +63,4 @@ public class MyUserLiveTest { private RequestSpecification givenAuth() { return RestAssured.given().auth().preemptive().basic("user1", "user1Pass"); } - - private RequestSpecification withRequestBody(final RequestSpecification req, final Object obj) throws JsonProcessingException { - return req.contentType(MediaType.APPLICATION_JSON_VALUE).body(mapper.writeValueAsString(obj)); - } } From bf887e71d9949c815e6e521d85d4c17c60d03560 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 15 Oct 2016 16:44:51 +0200 Subject: [PATCH 079/193] minor cleanup --- ...dResultsRetrievedDiscoverabilityListener.java | 6 +++--- .../java/org/baeldung/web/MyUserLiveTest.java | 16 ---------------- 2 files changed, 3 insertions(+), 19 deletions(-) diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java b/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java index 312ead0ab0..603c91007d 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java @@ -77,7 +77,7 @@ class PaginatedResultsRetrievedDiscoverabilityListener implements ApplicationLis } final boolean hasNextPage(final int page, final int totalPages) { - return page < totalPages - 1; + return page < (totalPages - 1); } final boolean hasPreviousPage(final int page) { @@ -89,7 +89,7 @@ class PaginatedResultsRetrievedDiscoverabilityListener implements ApplicationLis } final boolean hasLastPage(final int page, final int totalPages) { - return totalPages > 1 && hasNextPage(page, totalPages); + return (totalPages > 1) && hasNextPage(page, totalPages); } final void appendCommaIfNecessary(final StringBuilder linkHeader) { @@ -102,7 +102,7 @@ class PaginatedResultsRetrievedDiscoverabilityListener implements ApplicationLis protected void plural(final UriComponentsBuilder uriBuilder, final Class clazz) { final String resourceName = clazz.getSimpleName().toLowerCase() + "s"; - uriBuilder.path("/" + resourceName); + uriBuilder.path("/auth/" + resourceName); } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java index c7fb26d70b..4a3bd50f90 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java @@ -6,30 +6,14 @@ import org.baeldung.persistence.model.MyUser; import org.junit.Test; import org.springframework.test.context.ActiveProfiles; -import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.RequestSpecification; -//@RunWith(SpringJUnit4ClassRunner.class) -//@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class MyUserLiveTest { - private final ObjectMapper mapper = new ObjectMapper(); private final MyUser userJohn = new MyUser("john", "doe", "john@doe.com", 11); - private final MyUser userTom = new MyUser("tom", "doe", "tom@doe.com", 20); - - // private static boolean setupDataCreated = false; - // - // @Before - // public void setupData() throws JsonProcessingException { - // if (!setupDataCreated) { - // withRequestBody(givenAuth(), userJohn).post("http://localhost:8080/auth/myusers"); - // withRequestBody(givenAuth(), userTom).post("http://localhost:8080/auth/myusers"); - // setupDataCreated = true; - // } - // } @Test public void whenGettingListOfUsers_thenCorrect() { From 66c5db02a3602c3d9c571f8d12938398e061e6eb Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 15 Oct 2016 17:34:11 +0200 Subject: [PATCH 080/193] configure test profiles --- spring-security-rest-full/pom.xml | 39 ++++++++++++++++++- .../java/org/baeldung/spring/Application.java | 2 +- .../src/main/resources/application.properties | 2 + .../src/test/java/org/baeldung/Consts.java | 2 +- .../baeldung/client/RestTemplateLiveTest.java | 2 +- .../baeldung/common/web/AbstractLiveTest.java | 2 +- .../query/JPASpecificationLiveTest.java | 2 +- .../java/org/baeldung/web/MyUserLiveTest.java | 10 ++--- 8 files changed, 49 insertions(+), 12 deletions(-) create mode 100644 spring-security-rest-full/src/main/resources/application.properties diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index b354e61b35..5cd0ed51f3 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -339,7 +339,7 @@ - 8080 + 8082 @@ -386,10 +386,45 @@ - none + **/*LiveTest.java **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + live + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + **/*LiveTest.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/Application.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/Application.java index c44e37fee8..f8bc6c0160 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/Application.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/Application.java @@ -10,7 +10,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter /** * Main Application Class - uses Spring Boot. Just run this as a normal Java - * class to run up a Jetty Server (on http://localhost:8080) + * class to run up a Jetty Server (on http://localhost:8082/spring-security-rest-full) * */ @EnableScheduling diff --git a/spring-security-rest-full/src/main/resources/application.properties b/spring-security-rest-full/src/main/resources/application.properties new file mode 100644 index 0000000000..58c6f8eec7 --- /dev/null +++ b/spring-security-rest-full/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port=8082 +server.context-path=/spring-security-rest-full \ No newline at end of file diff --git a/spring-security-rest-full/src/test/java/org/baeldung/Consts.java b/spring-security-rest-full/src/test/java/org/baeldung/Consts.java index 9c44d63c4d..e5f0be160f 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/Consts.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/Consts.java @@ -1,5 +1,5 @@ package org.baeldung; public interface Consts { - int APPLICATION_PORT = 8080; + int APPLICATION_PORT = 8082; } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java index 0f0a73b536..a1cd9fcfe1 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java @@ -51,7 +51,7 @@ import com.google.common.base.Charsets; public class RestTemplateLiveTest { private RestTemplate restTemplate; - private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/auth/foos"; + private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-security-rest-full/auth/foos"; @Before public void beforeTest() { diff --git a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java index a3e6c8858d..a2890d8643 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java @@ -57,7 +57,7 @@ public abstract class AbstractLiveTest { // protected String getURL() { - return "http://localhost:" + APPLICATION_PORT + "/auth/foos"; + return "http://localhost:" + APPLICATION_PORT + "/spring-security-rest-full/auth/foos"; } protected final RequestSpecification givenAuth() { diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java index 4fa15d536a..3b85cfb487 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java @@ -24,7 +24,7 @@ public class JPASpecificationLiveTest { private User userTom; - private final String URL_PREFIX = "http://localhost:8080/auth/users/spec?search="; + private final String URL_PREFIX = "http://localhost:8082/spring-security-rest-full/auth/users/spec?search="; @Before public void init() { diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java index 4a3bd50f90..16ed9db253 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java @@ -14,17 +14,17 @@ import com.jayway.restassured.specification.RequestSpecification; public class MyUserLiveTest { private final MyUser userJohn = new MyUser("john", "doe", "john@doe.com", 11); - + private String URL_PREFIX = "http://localhost:8082/spring-security-rest-full/auth/api/myusers"; @Test public void whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get("http://localhost:8080/auth/api/myusers"); + final Response response = givenAuth().get(URL_PREFIX); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 2); } @Test public void givenFirstName_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get("http://localhost:8080/auth/api/myusers?firstName=john"); + final Response response = givenAuth().get(URL_PREFIX + "?firstName=john"); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 1); assertEquals(result[0].getEmail(), userJohn.getEmail()); @@ -32,14 +32,14 @@ public class MyUserLiveTest { @Test public void givenPartialLastName_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get("http://localhost:8080/auth/api/myusers?lastName=do"); + final Response response = givenAuth().get(URL_PREFIX + "?lastName=do"); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 2); } @Test public void givenEmail_whenGettingListOfUsers_thenIgnored() { - final Response response = givenAuth().get("http://localhost:8080/auth/api/myusers?email=john"); + final Response response = givenAuth().get(URL_PREFIX + "?email=john"); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 2); } From db2b93a1b65a217c6de07642f17d73950ec143ae Mon Sep 17 00:00:00 2001 From: Ante Pocedulic Date: Sun, 16 Oct 2016 11:12:51 +0200 Subject: [PATCH 081/193] Ehcache article source code (#751) * - created packages for each logical part of application - created validator for WebsiteUser rest API - created ValidatorEventRegister class which fixes known bug for not detecting generated events - created custom Exception Handler which creates better response messages * Code formatting * formated pom.xml replaced for loops with streams fixed bug while getting all beans * removed unnecessary code changed repository type * - added test for Spring Data REST APIs - changed bad request return code - formated code * - added source code for ehcache article - added ehcache dependency to pom.xml * - added test for ehcache article - removed main method which was only for testing purposes --- .../ehcache/SquareCalculatorTest.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java diff --git a/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java b/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java new file mode 100644 index 0000000000..875fd2a25e --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java @@ -0,0 +1,43 @@ +package org.baeldung.ehcache; + +import static org.junit.Assert.*; + +import org.baeldung.ehcache.calculator.SquaredCalculator; +import org.baeldung.ehcache.config.CacheHelper; +import org.junit.Before; +import org.junit.Test; + +public class SquareCalculatorTest { + SquaredCalculator squaredCalculator = new SquaredCalculator(); + CacheHelper cacheHelper = new CacheHelper(); + + @Before + public void setup() { + squaredCalculator.setCache(cacheHelper); + + } + + @Test + public void whenCalculatingSquareValueOnce_thenCacheDontHaveValues() { + for (int i = 10; i < 15; i++) { + assertFalse(cacheHelper.getSquareNumberCache().containsKey(i)); + System.out.println("Square value of " + i + " is: " + + squaredCalculator.getSquareValueOfNumber(i) + "\n"); + } + } + + @Test + public void whenCalculatingSquareValueAgain_thenCacheHasAllValues() { + for (int i = 10; i < 15; i++) { + assertFalse(cacheHelper.getSquareNumberCache().containsKey(i)); + System.out.println("Square value of " + i + " is: " + + squaredCalculator.getSquareValueOfNumber(i) + "\n"); + } + + for (int i = 10; i < 15; i++) { + assertTrue(cacheHelper.getSquareNumberCache().containsKey(i)); + System.out.println("Square value of " + i + " is: " + + squaredCalculator.getSquareValueOfNumber(i) + "\n"); + } + } +} From 6c509ba738c326a31e03b867cfb4e8c1729926b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20van=20de=20Giessen?= Date: Sun, 16 Oct 2016 12:00:10 +0200 Subject: [PATCH 082/193] some minor cleanup (#649) * minor cleanup pom maven.compiler java versions as properties only specifing spring-data-elasticsearch as dependency formatting net.java.dev.jna dependency grouping main/test and logging dependencies removed unused org.springframework.data.version property * updated logback conf to this example * builder patttern code on multiple lines for readablilty * autowire via constructor into final variable as of spring-4.3 the @Autowired can be omitted \o/ jaj * @ContextConfiguration with less config --- spring-data-elasticsearch/pom.xml | 33 ++++++++----------- .../spring/data/es/config/Config.java | 14 +++++--- .../data/es/service/ArticleServiceImpl.java | 6 ++-- .../src/main/resources/logback.xml | 6 ++-- .../data/es/ElasticSearchQueryTest.java | 3 +- .../spring/data/es/ElasticSearchTest.java | 3 +- 6 files changed, 30 insertions(+), 35 deletions(-) diff --git a/spring-data-elasticsearch/pom.xml b/spring-data-elasticsearch/pom.xml index 084695c2f3..42cf8fc740 100644 --- a/spring-data-elasticsearch/pom.xml +++ b/spring-data-elasticsearch/pom.xml @@ -11,8 +11,9 @@ UTF-8 + 1.8 + 1.8 - 1.3.2.RELEASE 4.2.5.RELEASE 4.11 @@ -27,6 +28,12 @@ spring-core ${org.springframework.version}
+ + org.springframework.data + spring-data-elasticsearch + ${elasticsearch.version} + + junit junit-dep @@ -39,16 +46,13 @@ ${org.springframework.version} test - - org.springframework.data - spring-data-elasticsearch - ${elasticsearch.version} - - net.java.dev.jna + + net.java.dev.jna jna 4.1.0 test + org.slf4j slf4j-api @@ -81,16 +85,5 @@ 1.2.13 - - - - maven-compiler-plugin - 2.3.2 - - 1.8 - 1.8 - - - - - + + \ No newline at end of file diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java index f93999a1cc..37e9fd46eb 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java @@ -32,18 +32,22 @@ public class Config { public Client client() { try { final Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data"); - + logger.debug(tmpDir.toAbsolutePath().toString()); + // @formatter:off final Settings.Builder elasticsearchSettings = Settings.settingsBuilder().put("http.enabled", "false") .put("path.data", tmpDir.toAbsolutePath().toString()) .put("path.home", elasticsearchHome); + + return new NodeBuilder() + .local(true) + .settings(elasticsearchSettings) + .node() + .client(); + // @formatter:on - - logger.debug(tmpDir.toAbsolutePath().toString()); - - return new NodeBuilder().local(true).settings(elasticsearchSettings.build()).node().client(); } catch (final IOException ioex) { logger.error("Cannot create temp dir", ioex); throw new RuntimeException(); diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java index 0ea922bdd3..2a31b52602 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java @@ -10,10 +10,10 @@ import org.springframework.stereotype.Service; @Service public class ArticleServiceImpl implements ArticleService { - private ArticleRepository articleRepository; - + private final ArticleRepository articleRepository; + @Autowired - public void setArticleRepository(ArticleRepository articleRepository) { + public ArticleServiceImpl(ArticleRepository articleRepository) { this.articleRepository = articleRepository; } diff --git a/spring-data-elasticsearch/src/main/resources/logback.xml b/spring-data-elasticsearch/src/main/resources/logback.xml index 37a9e2edbf..db75fcbe40 100644 --- a/spring-data-elasticsearch/src/main/resources/logback.xml +++ b/spring-data-elasticsearch/src/main/resources/logback.xml @@ -8,10 +8,10 @@ - - - + + + diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java index 1551d6442e..ddf0ef4dac 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java @@ -34,7 +34,6 @@ import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilde import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.baeldung.spring.data.es.config.Config; import com.baeldung.spring.data.es.model.Article; @@ -42,7 +41,7 @@ import com.baeldung.spring.data.es.model.Author; import com.baeldung.spring.data.es.service.ArticleService; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { Config.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = Config.class) public class ElasticSearchQueryTest { @Autowired diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java index e10b5f48d7..863e1e4620 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java @@ -21,7 +21,6 @@ import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilde import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.baeldung.spring.data.es.config.Config; import com.baeldung.spring.data.es.model.Article; @@ -29,7 +28,7 @@ import com.baeldung.spring.data.es.model.Author; import com.baeldung.spring.data.es.service.ArticleService; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { Config.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = Config.class) public class ElasticSearchTest { @Autowired From 722f932795adabee6c9f36810f74caa21c1d6289 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 14:55:31 +0600 Subject: [PATCH 083/193] Updated README.md --- spring-security-rest-full/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index 1cbe1191a8..f79df797c2 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -25,6 +25,9 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [REST Query Language with RSQL](http://www.baeldung.com/rest-api-search-language-rsql-fiql) - [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template) - [A Guide to CSRF Protection in Spring Security](http://www.baeldung.com/spring-security-csrf) +- [Intro to Spring Security Expressions](http://www.baeldung.com/spring-security-expressions) +- [Changing Spring Model Parameters with Handler Interceptor](http://www.baeldung.com/spring-model-parameters-with-handler-interceptor) +- [Introduction to Spring MVC HandlerInterceptor](http://www.baeldung.com/spring-mvc-handlerinterceptor) ### Build the Project ``` From f22c3060497d4a987b87d660fedee3585455cb78 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 14:56:26 +0600 Subject: [PATCH 084/193] Updated 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 23fe12465f..a93a5dad47 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -13,3 +13,5 @@ - [Java – Write to File](http://www.baeldung.com/java-write-to-file) - [Java Scanner](http://www.baeldung.com/java-scanner) - [Java Timer](http://www.baeldung.com/java-timer-and-timertask) +- [Java – Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer) +- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java) From 46604ddf6dfc6b146564d4d1fca5ff6912d6935c Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 14:57:16 +0600 Subject: [PATCH 085/193] Updated README.md --- spring-hibernate4/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spring-hibernate4/README.md b/spring-hibernate4/README.md index 1f18e1d0e8..7888e8b4ee 100644 --- a/spring-hibernate4/README.md +++ b/spring-hibernate4/README.md @@ -10,6 +10,8 @@ - [Auditing with JPA, Hibernate, and Spring Data JPA](http://www.baeldung.com/database-auditing-jpa) - [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial) - [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate/) +- [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading) +- [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) ### Quick Start From d148076180138cf557a2b2f7e4d842ec002d678f Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 14:58:16 +0600 Subject: [PATCH 086/193] Updated README.md --- spring-all/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spring-all/README.md b/spring-all/README.md index 0bbb600860..aae98440f3 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -12,3 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Profiles](http://www.baeldung.com/spring-profiles) - [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor) - [What's New in Spring 4.3?](http://www.baeldung.com/whats-new-in-spring-4-3/) +- [Guide To Running Logic on Startup in Spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring) +- [Quick Guide to Spring Controllers](http://www.baeldung.com/spring-controllers) +- [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes) From e2e9ac294dc91caaeb1c23e465aadc91272e5e6d Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 14:59:03 +0600 Subject: [PATCH 087/193] Updated README.md --- spring-mvc-java/README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 951d80033e..996a7d96b1 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -10,3 +10,9 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to Pointcut Expressions in Spring](http://www.baeldung.com/spring-aop-pointcut-tutorial) - [Introduction to Advice Types in Spring](http://www.baeldung.com/spring-aop-advice-tutorial) - [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) +- [Integration Testing in Spring](http://www.baeldung.com/integration-testing-in-spring) +- [Spring JSON-P with Jackson](http://www.baeldung.com/spring-jackson-jsonp) +- [A Quick Guide to Spring MVC Matrix Variables](http://www.baeldung.com/spring-mvc-matrix-variables) +- [Intro to WebSockets with Spring](http://www.baeldung.com/websockets-spring) +- [File Upload with Spring MVC](http://www.baeldung.com/spring-file-upload) +- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) From 5d9131771cff5aaf9b485843cd14725c87373dd7 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 14:59:44 +0600 Subject: [PATCH 088/193] Updated README.md --- spring-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-jpa/README.md b/spring-jpa/README.md index f974c6e22c..066e009c72 100644 --- a/spring-jpa/README.md +++ b/spring-jpa/README.md @@ -10,3 +10,4 @@ - [JPA Pagination](http://www.baeldung.com/jpa-pagination) - [Sorting with JPA](http://www.baeldung.com/jpa-sort) - [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases) +- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) From 918257839f1266b12b268c6650ab952f7c984465 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:00:35 +0600 Subject: [PATCH 089/193] Updated README.md --- gson/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/gson/README.md b/gson/README.md index 67651b732e..60c80477b1 100644 --- a/gson/README.md +++ b/gson/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide) +- [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson) From 45dc8efe1c36a2ef86b26cac6ab0c57f4d1b6b29 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:01:26 +0600 Subject: [PATCH 090/193] Updated README.md --- jackson/README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/jackson/README.md b/jackson/README.md index 68765de686..f48a7dc8ab 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -19,3 +19,8 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Jackson – Decide What Fields Get Serialized/Deserializaed](http://www.baeldung.com/jackson-field-serializable-deserializable-or-not) - [A Guide to Jackson Annotations](http://www.baeldung.com/jackson-annotations) - [Working with Tree Model Nodes in Jackson](http://www.baeldung.com/jackson-json-node-tree-model) +- [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson) +- [Intro to the Jackson ObjectMapper](http://www.baeldung.com/jackson-object-mapper-tutorial) +- [XML Serialization and Deserialization with Jackson](http://www.baeldung.com/jackson-xml-serialization-and-deserialization) +- [More Jackson Annotations](http://www.baeldung.com/jackson-advanced-annotations) +- [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance) From 779c6dd52cc279170daaf5550abce54cad0b6a40 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:02:05 +0600 Subject: [PATCH 091/193] Update README.md --- spring-exceptions/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-exceptions/README.md b/spring-exceptions/README.md index ab6a9643e9..fd9250c6da 100644 --- a/spring-exceptions/README.md +++ b/spring-exceptions/README.md @@ -10,3 +10,4 @@ This project is used to replicate Spring Exceptions only. - [Spring DataIntegrityViolationException](http://www.baeldung.com/spring-dataIntegrityviolationexception) - [Spring BeanDefinitionStoreException](http://www.baeldung.com/spring-beandefinitionstoreexception) - [Spring NoSuchBeanDefinitionException](http://www.baeldung.com/spring-nosuchbeandefinitionexception) +- [Guide to Spring NonTransientDataAccessException](http://www.baeldung.com/nontransientdataaccessexception) From c8716019a05d53d81e9b95743ae86d289be7cb4c Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:04:39 +0600 Subject: [PATCH 092/193] Updated README.md --- json/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/json/README.md b/json/README.md index c47eca3e84..e217da170f 100644 --- a/json/README.md +++ b/json/README.md @@ -5,3 +5,5 @@ ### Relevant Articles: - [Introduction to JSON Schema in Java](http://www.baeldung.com/introduction-to-json-schema-in-java) - [A Guide to FastJson](http://www.baeldung.com/????????) +- [Introduction to JSONForms](http://www.baeldung.com/introduction-to-jsonforms) +- [Introduction to JsonPath](http://www.baeldung.com/guide-to-jayway-jsonpath) From c1dcfd5d92d3c7f3174bc0a38eca3e4df52fb43f Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:05:14 +0600 Subject: [PATCH 093/193] Updated README.md --- mutation-testing/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mutation-testing/README.md b/mutation-testing/README.md index 5dd60620ba..f49aeeb881 100644 --- a/mutation-testing/README.md +++ b/mutation-testing/README.md @@ -4,3 +4,5 @@ ### Relevant Articles: - [Introduction to Mutation Testing Using the PITest Library](http://www.baeldung.com/java-mutation-testing-with-pitest) +- [Intro to JaCoCo](http://www.baeldung.com/jacoco) +- [Mutation Testing with PITest](http://www.baeldung.com/java-mutation-testing-with-pitest) From 41f26d8acf0555f5b6f2f98d849e6239c4f492e3 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:06:11 +0600 Subject: [PATCH 094/193] Updated README.md --- mocks/jmockit/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/mocks/jmockit/README.md b/mocks/jmockit/README.md index db78b2a3ac..3063fdc31d 100644 --- a/mocks/jmockit/README.md +++ b/mocks/jmockit/README.md @@ -7,3 +7,4 @@ - [JMockit 101](http://www.baeldung.com/jmockit-101) - [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations) - [JMockit Advanced Topics](http://www.baeldung.com/jmockit-advanced-topics) +- [JMockit Advanced Usage](http://www.baeldung.com/jmockit-advanced-usage) From 201d3b255196bdd84d59b85a21ae8d09d438d2c8 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:07:13 +0600 Subject: [PATCH 095/193] Updated README.md --- spring-security-custom-permission/README.MD | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spring-security-custom-permission/README.MD b/spring-security-custom-permission/README.MD index 5ac974203b..760cf41c63 100644 --- a/spring-security-custom-permission/README.MD +++ b/spring-security-custom-permission/README.MD @@ -1,2 +1,5 @@ ###The Course The "REST With Spring" Classes: http://github.learnspringsecurity.com + +###Relevant Articles: +- [A Custom Security Expression with Spring Security](http://www.baeldung.com/spring-security-create-new-custom-security-expression) From 2bff26194979e00620e49e307227c3982441cb07 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:08:02 +0600 Subject: [PATCH 096/193] Updated README.md --- xmlunit2-tutorial/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/xmlunit2-tutorial/README.md b/xmlunit2-tutorial/README.md index e69de29bb2..72b683796e 100644 --- a/xmlunit2-tutorial/README.md +++ b/xmlunit2-tutorial/README.md @@ -0,0 +1,2 @@ +###Relevant Articles: +- [Introduction To XMLUnit 2.x](http://www.baeldung.com/xmlunit2) From 38dc8ad0a5ae5fdacefe8c7ba917f0dedfda9fa0 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:08:58 +0600 Subject: [PATCH 097/193] Updated README.md --- rest-assured/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rest-assured/README.md b/rest-assured/README.md index e69de29bb2..50f36f61eb 100644 --- a/rest-assured/README.md +++ b/rest-assured/README.md @@ -0,0 +1,2 @@ +###Relevant Articles: +- [A Guide to REST-assured](http://www.baeldung.com/rest-assured-tutorial) From d106b886358d7c759e5cc05255e4923d517ed787 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:09:51 +0600 Subject: [PATCH 098/193] Updated README.md --- spring-boot/README.MD | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 2a87b46021..1610d77e81 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -1,2 +1,7 @@ ###The Course The "REST With Spring" Classes: http://bit.ly/restwithspring + +###Relevant Articles: +- [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot) +- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) +- [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring) From 7433424dba3d4ccc4c7e70a02045c42c2ae4780a Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:10:41 +0600 Subject: [PATCH 099/193] Updated README.md --- spring-rest/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/spring-rest/README.md b/spring-rest/README.md index 77d12063ed..671fa4996b 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -1,5 +1,3 @@ -========= - ## Spring REST Example Project ###The Course @@ -11,3 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Redirect in Spring](http://www.baeldung.com/spring-redirect-and-forward) - [Returning Custom Status Codes from Spring Controllers](http://www.baeldung.com/spring-mvc-controller-custom-http-status-code) - [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp) +- [Binary Data Formats in a Spring REST API](http://www.baeldung.com/spring-rest-api-with-binary-data-formats) From cd853fafbc686af65ff43e15a4eaf909e50acd41 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:11:13 +0600 Subject: [PATCH 100/193] Updated README.md --- guava/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/guava/README.md b/guava/README.md index 28bcfeb912..40e7f19f41 100644 --- a/guava/README.md +++ b/guava/README.md @@ -15,3 +15,4 @@ - [Guava – Lists](http://www.baeldung.com/guava-lists) - [Guava – Sets](http://www.baeldung.com/guava-sets) - [Guava – Maps](http://www.baeldung.com/guava-maps) +- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial) From 4ebd8b7f7b4c869134b66065feffa9611456902c Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:11:52 +0600 Subject: [PATCH 101/193] Updated README.md --- rest-testing/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rest-testing/README.md b/rest-testing/README.md index 54a2e98dda..5dd4e49162 100644 --- a/rest-testing/README.md +++ b/rest-testing/README.md @@ -7,3 +7,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Test a REST API with Java](http://www.baeldung.com/2011/10/13/integration-testing-a-rest-api/) +- [Introduction to WireMock](http://www.baeldung.com/introduction-to-wiremock) +- [REST API Testing with Cucumber](http://www.baeldung.com/cucumber-rest-api-testing) From ce7621c66e75efa73962029ebbaeecb69d491dae Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:16:59 +0600 Subject: [PATCH 102/193] Updated README.md --- spring-rest-docs/README.MD | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spring-rest-docs/README.MD b/spring-rest-docs/README.MD index 2a87b46021..f5d001d126 100644 --- a/spring-rest-docs/README.MD +++ b/spring-rest-docs/README.MD @@ -1,2 +1,5 @@ ###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) From 38ad5840f6c612c5ce56c8eb07863341f9845965 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:17:41 +0600 Subject: [PATCH 103/193] Updated README.md --- spring-mvc-xml/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index ce823a9682..783bbb2ef4 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -11,3 +11,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC Tutorial](http://www.baeldung.com/spring-mvc-tutorial) - [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout) - [Basic Forms with Spring MVC](http://www.baeldung.com/spring-mvc-form-tutorial) +- [Returning Image/Media Data with Spring MVC](http://www.baeldung.com/spring-mvc-image-media-data) From caa9bc658510961e8e2d5ee4b183cc66d575a70d Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:18:43 +0600 Subject: [PATCH 104/193] Updated README.md --- spring-security-mvc-login/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-mvc-login/README.md b/spring-security-mvc-login/README.md index 7cddc42e1d..d1f6b884b1 100644 --- a/spring-security-mvc-login/README.md +++ b/spring-security-mvc-login/README.md @@ -9,7 +9,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Spring Security Form Login](http://www.baeldung.com/spring-security-login) - [Spring Security Logout](http://www.baeldung.com/spring-security-logout) - [Spring Security Expressions – hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) - +- [Spring HTTP/HTTPS Channel Security](http://www.baeldung.com/spring-channel-security-https) ### Build the Project ``` From c0a6cb227d1a147d41ea6a4bfa72d95a9cace45b Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:19:28 +0600 Subject: [PATCH 105/193] Updated README.md --- mockito/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mockito/README.md b/mockito/README.md index 5e7cd19f78..6de2fb0c7a 100644 --- a/mockito/README.md +++ b/mockito/README.md @@ -8,3 +8,5 @@ - [Mockito When/Then Cookbook](http://www.baeldung.com/mockito-behavior) - [Mockito – Using Spies](http://www.baeldung.com/mockito-spy) - [Mockito – @Mock, @Spy, @Captor and @InjectMocks](http://www.baeldung.com/mockito-annotations) +- [Mockito’s Mock Methods](http://www.baeldung.com/mockito-mock-methods) +- [Introduction to PowerMock](http://www.baeldung.com/intro-to-powermock) From f4ada6eaa1ce58e18afaaf0509aac0d042c5ac7e Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:21:09 +0600 Subject: [PATCH 106/193] Updated README.md --- spring-data-elasticsearch/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spring-data-elasticsearch/README.md b/spring-data-elasticsearch/README.md index 74d9e4f642..589343710b 100644 --- a/spring-data-elasticsearch/README.md +++ b/spring-data-elasticsearch/README.md @@ -1,6 +1,9 @@ ## Spring Data Elasticsearch - [Introduction to Spring Data Elasticsearch](http://www.baeldung.com/spring-data-elasticsearch-tutorial) +###Relevant Articles: +- [Elasticsearch Queries with Spring Data](http://www.baeldung.com/spring-data-elasticsearch-queries) + ### Build the Project with Tests Running ``` mvn clean install From 488850ce9ab2f18e4be724f4d2379a7948534609 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:22:02 +0600 Subject: [PATCH 107/193] Updated README.md --- spring-data-redis/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-data-redis/README.md b/spring-data-redis/README.md index 89eae99f05..da44920e16 100644 --- a/spring-data-redis/README.md +++ b/spring-data-redis/README.md @@ -2,6 +2,7 @@ ### Relevant Articles: - [Introduction to Spring Data Redis](http://www.baeldung.com/spring-data-redis-tutorial) +- [PubSub Messaging with Spring Data Redis](http://www.baeldung.com/spring-data-redis-pub-sub) ### Build the Project with Tests Running ``` From 94ad1f631f8a7c85a9c5476dbf95abfa8a80c172 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:24:08 +0600 Subject: [PATCH 108/193] Updated README.md --- gson-jackson-performance/README.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 gson-jackson-performance/README.md diff --git a/gson-jackson-performance/README.md b/gson-jackson-performance/README.md new file mode 100644 index 0000000000..e662219718 --- /dev/null +++ b/gson-jackson-performance/README.md @@ -0,0 +1,6 @@ +## Performance of Gson and Jackson + +Standalone java programs to measure the performance of both JSON APIs based on file size and object graph complexity. + +###Relevant Articles: +- [Jackson vs Gson: A Quick Look At Performance](http://www.baeldung.com/jackson-gson-performance) From fe805ea2022dd12963bd48f8c00984b6f0fa1a73 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:26:33 +0600 Subject: [PATCH 109/193] Updated README.md --- spring-thymeleaf/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index 8cb1c2e982..52c8dda13e 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -4,7 +4,7 @@ ### Relevant Articles: - +- [Introduction to Using Thymeleaf in Spring](http://www.baeldung.com/thymeleaf-in-spring-mvc) ### Build the Project From 87fd44bc38b78c03f0e51b02e5cd58cc487ad911 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:28:03 +0600 Subject: [PATCH 110/193] Updated README.md --- core-java/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core-java/README.md b/core-java/README.md index a93a5dad47..440af67252 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -15,3 +15,6 @@ - [Java Timer](http://www.baeldung.com/java-timer-and-timertask) - [Java – Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer) - [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java) +- [MD5 Hashing in Java](http://www.baeldung.com/java-md5) +- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist) +- [Guide to Java Reflection](http://www.baeldung.com/java-reflection) From 8748eb504151daf1a7d3ac0a684d9d83d4e1bf0a Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:28:55 +0600 Subject: [PATCH 111/193] Updated README.md --- spring-data-elasticsearch/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-data-elasticsearch/README.md b/spring-data-elasticsearch/README.md index 589343710b..a7b090818e 100644 --- a/spring-data-elasticsearch/README.md +++ b/spring-data-elasticsearch/README.md @@ -3,6 +3,7 @@ ###Relevant Articles: - [Elasticsearch Queries with Spring Data](http://www.baeldung.com/spring-data-elasticsearch-queries) +- [Guide to Elasticsearch in Java](http://www.baeldung.com/elasticsearch-java) ### Build the Project with Tests Running ``` From 8a7c5968212abb40d76e7ef0c1d70a626ee8acd1 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:30:35 +0600 Subject: [PATCH 112/193] Updated README.md --- spring-data-rest/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spring-data-rest/README.md b/spring-data-rest/README.md index 7dc439206b..4e8828a688 100644 --- a/spring-data-rest/README.md +++ b/spring-data-rest/README.md @@ -12,3 +12,6 @@ The application uses [Spring Boot](http://projects.spring.io/spring-boot/), so i # Viewing the running application To view the running application, visit [http://localhost:8080](http://localhost:8080) in your browser + +###Relevant Articles: +- [Guide to Spring Data REST Validators](http://www.baeldung.com/spring-data-rest-validators) From ef363e2684897ff81874ab8d569a92cc8ca4cd7a Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:32:01 +0600 Subject: [PATCH 113/193] Updated README.md --- spring-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-jpa/README.md b/spring-jpa/README.md index 066e009c72..4568c0bc7f 100644 --- a/spring-jpa/README.md +++ b/spring-jpa/README.md @@ -11,3 +11,4 @@ - [Sorting with JPA](http://www.baeldung.com/jpa-sort) - [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases) - [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) +- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) From fc68da25dfd0b5968582e476f6e37c4788241b59 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:33:02 +0600 Subject: [PATCH 114/193] Updated README.md --- spring-thymeleaf/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index 52c8dda13e..a8ca755044 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -5,6 +5,7 @@ ### Relevant Articles: - [Introduction to Using Thymeleaf in Spring](http://www.baeldung.com/thymeleaf-in-spring-mvc) +- [CSRF Protection with Spring MVC and Thymeleaf](http://www.baeldung.com/csrf-thymeleaf-with-spring-security) ### Build the Project From e5c171f8971f2194de775163f737b655085cde03 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:34:40 +0600 Subject: [PATCH 115/193] Updated README.md --- spring-security-rest-full/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index f79df797c2..faeeac1ec2 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -28,6 +28,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Intro to Spring Security Expressions](http://www.baeldung.com/spring-security-expressions) - [Changing Spring Model Parameters with Handler Interceptor](http://www.baeldung.com/spring-model-parameters-with-handler-interceptor) - [Introduction to Spring MVC HandlerInterceptor](http://www.baeldung.com/spring-mvc-handlerinterceptor) +- [Using a Custom Spring MVC’s Handler Interceptor to Manage Sessions](http://www.baeldung.com/spring-mvc-custom-handler-interceptor) ### Build the Project ``` From 14ca00a93c3497d0fbc61a0ca07e685a3ba3022e Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Tue, 4 Oct 2016 15:35:25 +0600 Subject: [PATCH 116/193] Updated README.md --- feign-client/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/feign-client/README.md b/feign-client/README.md index e6ade4d161..149f7320d9 100644 --- a/feign-client/README.md +++ b/feign-client/README.md @@ -3,3 +3,6 @@ This is the implementation of a [spring-hypermedia-api][1] client using Feign. [1]: https://github.com/eugenp/spring-hypermedia-api + +###Relevant Articles: +- [Intro to Feign](http://www.baeldung.com/intro-to-feign) From 298c5e309100d2104096d74f0299596bc5d90718 Mon Sep 17 00:00:00 2001 From: Naoshadul Islam Date: Sun, 16 Oct 2016 16:25:05 +0600 Subject: [PATCH 117/193] Created README.md and added relevant articles (#742) * Updated readme.md * Updated readme.md * Updated readme.md * Updated readme.md * Updated readme.md * Updated readme.md * Updated readme.md * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Updated readme.md * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Updated readme.md * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Updated readme.md * Created README.md and added relevant articles * Created README.md and added relevant articles * Created README.md and added relevant articles * Updated readme.md * Updated readme.md * Created README.md and added relevant articles * Created README.md and added relevant articles --- annotations/readme.md | 3 ++- apache-cxf/cxf-introduction/README.md | 2 ++ assertj/README.md | 3 +++ autovalue-tutorial/README.md | 2 ++ cdi/README.md | 2 ++ core-java-8/src/main/java/com/baeldung/datetime/README.md | 2 ++ core-java-8/src/main/java/com/baeldung/enums/README.md | 2 ++ core-java-9/src/test/java/com/baeldung/java9/README.MD | 3 ++- core-java/src/test/java/org/baeldung/java/lists/README.md | 2 ++ dependency-injection/README.md | 2 ++ dozer/README.md | 2 ++ flyway-migration/README.MD | 3 ++- gatling/README.md | 2 ++ guava/src/test/java/org/baeldung/hamcrest/README.md | 2 ++ handling-spring-static-resources/README.md | 3 +++ hystrix/README.md | 3 +++ immutables/README.md | 2 ++ jee7schedule/README.md | 2 ++ jooq-spring/README.md | 3 +++ jpa-storedprocedure/README.md | 2 ++ jsf/README.md | 4 ++++ junit5/REDAME.md | 2 ++ log4j/README.md | 2 ++ lombok/README.md | 2 ++ orika/README.md | 2 ++ querydsl/README.md | 2 ++ raml/resource-types-and-traits/README.md | 2 ++ sockets/README.md | 2 ++ spring-akka/README.md | 2 ++ spring-autowire/README.md | 2 ++ spring-boot/src/main/java/com/baeldung/git/README.md | 2 ++ spring-cloud-data-flow/README.MD | 4 +++- spring-cloud/spring-cloud-bootstrap/README.MD | 3 ++- spring-cloud/spring-cloud-config/README.md | 2 ++ spring-cloud/spring-cloud-eureka/README.md | 2 ++ spring-cloud/spring-cloud-hystrix/README.MD | 3 ++- spring-cucumber/README.md | 2 ++ spring-mvc-java/src/main/README.md | 2 ++ spring-mvc-java/src/test/README.md | 2 ++ .../src/test/java/com/baeldung/web/controller/README.md | 2 ++ spring-mvc-velocity/README.md | 2 ++ spring-mvc-web-vs-initializer/README.MD | 3 ++- spring-protobuf/README.md | 2 ++ spring-security-x509/README.md | 2 ++ spring-spel/README.md | 2 ++ xml/README.md | 2 ++ xstream/README.md | 4 ++++ 47 files changed, 103 insertions(+), 7 deletions(-) create mode 100644 apache-cxf/cxf-introduction/README.md create mode 100644 assertj/README.md create mode 100644 autovalue-tutorial/README.md create mode 100644 cdi/README.md create mode 100644 core-java-8/src/main/java/com/baeldung/datetime/README.md create mode 100644 core-java-8/src/main/java/com/baeldung/enums/README.md create mode 100644 core-java/src/test/java/org/baeldung/java/lists/README.md create mode 100644 dependency-injection/README.md create mode 100644 dozer/README.md create mode 100644 gatling/README.md create mode 100644 guava/src/test/java/org/baeldung/hamcrest/README.md create mode 100644 handling-spring-static-resources/README.md create mode 100644 hystrix/README.md create mode 100644 immutables/README.md create mode 100644 jee7schedule/README.md create mode 100644 jooq-spring/README.md create mode 100644 jpa-storedprocedure/README.md create mode 100644 jsf/README.md create mode 100644 junit5/REDAME.md create mode 100644 log4j/README.md create mode 100644 lombok/README.md create mode 100644 orika/README.md create mode 100644 querydsl/README.md create mode 100644 raml/resource-types-and-traits/README.md create mode 100644 sockets/README.md create mode 100644 spring-akka/README.md create mode 100644 spring-autowire/README.md create mode 100644 spring-boot/src/main/java/com/baeldung/git/README.md create mode 100644 spring-cloud/spring-cloud-config/README.md create mode 100644 spring-cloud/spring-cloud-eureka/README.md create mode 100644 spring-cucumber/README.md create mode 100644 spring-mvc-java/src/main/README.md create mode 100644 spring-mvc-java/src/test/README.md create mode 100644 spring-mvc-java/src/test/java/com/baeldung/web/controller/README.md create mode 100644 spring-mvc-velocity/README.md create mode 100644 spring-protobuf/README.md create mode 100644 spring-security-x509/README.md create mode 100644 spring-spel/README.md create mode 100644 xml/README.md create mode 100644 xstream/README.md diff --git a/annotations/readme.md b/annotations/readme.md index 8b13789179..2b052803e6 100644 --- a/annotations/readme.md +++ b/annotations/readme.md @@ -1 +1,2 @@ - +### Relevant Articles: +- [Java Annotation Processing and Creating a Builder](http://www.baeldung.com/java-annotation-processing-builder) diff --git a/apache-cxf/cxf-introduction/README.md b/apache-cxf/cxf-introduction/README.md new file mode 100644 index 0000000000..9a076524b7 --- /dev/null +++ b/apache-cxf/cxf-introduction/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf) diff --git a/assertj/README.md b/assertj/README.md new file mode 100644 index 0000000000..86eff05057 --- /dev/null +++ b/assertj/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [AssertJ’s Java 8 Features](http://www.baeldung.com/assertJ-java-8-features) +- [AssertJ for Guava](http://www.baeldung.com/assertJ-for-guava) diff --git a/autovalue-tutorial/README.md b/autovalue-tutorial/README.md new file mode 100644 index 0000000000..2385e82847 --- /dev/null +++ b/autovalue-tutorial/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to AutoValue](http://www.baeldung.com/introduction-to-autovalue) diff --git a/cdi/README.md b/cdi/README.md new file mode 100644 index 0000000000..a27c35772a --- /dev/null +++ b/cdi/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [CDI Interceptor vs Spring AspectJ](http://www.baeldung.com/cdi-interceptor-vs-spring-aspectj) diff --git a/core-java-8/src/main/java/com/baeldung/datetime/README.md b/core-java-8/src/main/java/com/baeldung/datetime/README.md new file mode 100644 index 0000000000..1e4adbb612 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/datetime/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) diff --git a/core-java-8/src/main/java/com/baeldung/enums/README.md b/core-java-8/src/main/java/com/baeldung/enums/README.md new file mode 100644 index 0000000000..6ccfa725f5 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/enums/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums) diff --git a/core-java-9/src/test/java/com/baeldung/java9/README.MD b/core-java-9/src/test/java/com/baeldung/java9/README.MD index 8b13789179..2f44a2336b 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/README.MD +++ b/core-java-9/src/test/java/com/baeldung/java9/README.MD @@ -1 +1,2 @@ - +### Relevant Artiles: +- [Filtering a Stream of Optionals in Java](http://www.baeldung.com/java-filter-stream-of-optional) diff --git a/core-java/src/test/java/org/baeldung/java/lists/README.md b/core-java/src/test/java/org/baeldung/java/lists/README.md new file mode 100644 index 0000000000..2a1e8aeeaa --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/lists/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality) diff --git a/dependency-injection/README.md b/dependency-injection/README.md new file mode 100644 index 0000000000..5554412c31 --- /dev/null +++ b/dependency-injection/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Wiring in Spring: @Autowired, @Resource and @Inject](http://www.baeldung.com/spring-annotations-resource-inject-autowire) diff --git a/dozer/README.md b/dozer/README.md new file mode 100644 index 0000000000..5e104d914c --- /dev/null +++ b/dozer/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Guide to Mapping With Dozer](http://www.baeldung.com/dozer) diff --git a/flyway-migration/README.MD b/flyway-migration/README.MD index 8b13789179..1b3f3c05ee 100644 --- a/flyway-migration/README.MD +++ b/flyway-migration/README.MD @@ -1 +1,2 @@ - +### Relevant Articles: +- [Database Migrations with Flyway](http://www.baeldung.com/database-migrations-with-flyway) diff --git a/gatling/README.md b/gatling/README.md new file mode 100644 index 0000000000..5c81c4bd6a --- /dev/null +++ b/gatling/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Intro to Gatling](http://www.baeldung.com/introduction-to-gatling) diff --git a/guava/src/test/java/org/baeldung/hamcrest/README.md b/guava/src/test/java/org/baeldung/hamcrest/README.md new file mode 100644 index 0000000000..7266ecda3a --- /dev/null +++ b/guava/src/test/java/org/baeldung/hamcrest/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Testing with Hamcrest](http://www.baeldung.com/java-junit-hamcrest-guide) diff --git a/handling-spring-static-resources/README.md b/handling-spring-static-resources/README.md new file mode 100644 index 0000000000..d8f64bc427 --- /dev/null +++ b/handling-spring-static-resources/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Cachable Static Assets with Spring MVC](http://www.baeldung.com/cachable-static-assets-with-spring-mvc) +- [Minification of JS and CSS Assets with Maven](http://www.baeldung.com/maven-minification-of-js-and-css-assets) diff --git a/hystrix/README.md b/hystrix/README.md new file mode 100644 index 0000000000..cc5c8a197f --- /dev/null +++ b/hystrix/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Hystrix Integration with Existing Spring Application](http://www.baeldung.com/hystrix-integration-with-spring-aop) +- [Introduction to Hystrix](http://www.baeldung.com/introduction-to-hystrix) diff --git a/immutables/README.md b/immutables/README.md new file mode 100644 index 0000000000..b69a14f035 --- /dev/null +++ b/immutables/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Immutables](http://www.baeldung.com/immutables) diff --git a/jee7schedule/README.md b/jee7schedule/README.md new file mode 100644 index 0000000000..44ca9c2f6e --- /dev/null +++ b/jee7schedule/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Scheduling in Java EE](http://www.baeldung.com/scheduling-in-java-enterprise-edition) diff --git a/jooq-spring/README.md b/jooq-spring/README.md new file mode 100644 index 0000000000..79718e74c6 --- /dev/null +++ b/jooq-spring/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Spring Boot Support for jOOQ](http://www.baeldung.com/spring-boot-support-for-jooq) +- [Introduction to jOOQ with Spring](http://www.baeldung.com/jooq-with-spring) diff --git a/jpa-storedprocedure/README.md b/jpa-storedprocedure/README.md new file mode 100644 index 0000000000..39d6784d8b --- /dev/null +++ b/jpa-storedprocedure/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) diff --git a/jsf/README.md b/jsf/README.md new file mode 100644 index 0000000000..ae92ffc42f --- /dev/null +++ b/jsf/README.md @@ -0,0 +1,4 @@ +### Relevant Articles: +- [Introduction to JSF Expression Language 3.0](http://www.baeldung.com/jsf-expression-language-el-3) +- [Introduction to JSF EL 2](http://www.baeldung.com/intro-to-jsf-expression-language) +- [JavaServer Faces (JSF) with Spring](http://www.baeldung.com/spring-jsf) diff --git a/junit5/REDAME.md b/junit5/REDAME.md new file mode 100644 index 0000000000..d4e30cd257 --- /dev/null +++ b/junit5/REDAME.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [The Basics of JUnit 5 – A Preview](http://www.baeldung.com/junit-5-preview) diff --git a/log4j/README.md b/log4j/README.md new file mode 100644 index 0000000000..7355372f23 --- /dev/null +++ b/log4j/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Java Logging](http://www.baeldung.com/java-logging-intro) diff --git a/lombok/README.md b/lombok/README.md new file mode 100644 index 0000000000..4dc1c2d09d --- /dev/null +++ b/lombok/README.md @@ -0,0 +1,2 @@ +## Relevant Articles: +- [Introduction to Project Lombok](http://www.baeldung.com/intro-to-project-lombok) diff --git a/orika/README.md b/orika/README.md new file mode 100644 index 0000000000..4ed033c170 --- /dev/null +++ b/orika/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Mapping with Orika](http://www.baeldung.com/orika-mapping) diff --git a/querydsl/README.md b/querydsl/README.md new file mode 100644 index 0000000000..ef9f8f894c --- /dev/null +++ b/querydsl/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Intro to Querydsl](http://www.baeldung.com/intro-to-querydsl) diff --git a/raml/resource-types-and-traits/README.md b/raml/resource-types-and-traits/README.md new file mode 100644 index 0000000000..72e7b454d6 --- /dev/null +++ b/raml/resource-types-and-traits/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Eliminate Redundancies in RAML with Resource Types and Traits](http://www.baeldung.com/simple-raml-with-resource-types-and-traits) diff --git a/sockets/README.md b/sockets/README.md new file mode 100644 index 0000000000..ad8811ee80 --- /dev/null +++ b/sockets/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) diff --git a/spring-akka/README.md b/spring-akka/README.md new file mode 100644 index 0000000000..0f1c013214 --- /dev/null +++ b/spring-akka/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Spring with Akka](http://www.baeldung.com/akka-with-spring) diff --git a/spring-autowire/README.md b/spring-autowire/README.md new file mode 100644 index 0000000000..d5b8221b25 --- /dev/null +++ b/spring-autowire/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Guide to Spring @Autowired](http://www.baeldung.com/spring-autowire) diff --git a/spring-boot/src/main/java/com/baeldung/git/README.md b/spring-boot/src/main/java/com/baeldung/git/README.md new file mode 100644 index 0000000000..7e6a597c28 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/git/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information) diff --git a/spring-cloud-data-flow/README.MD b/spring-cloud-data-flow/README.MD index 8b13789179..17d0ec6286 100644 --- a/spring-cloud-data-flow/README.MD +++ b/spring-cloud-data-flow/README.MD @@ -1 +1,3 @@ - +### Relevant Articles: +- [Batch Processing with Spring Cloud Data Flow](http://www.baeldung.com/spring-cloud-data-flow-batch-processing) +- [Getting Started with Stream Processing with Spring Cloud Data Flow](http://www.baeldung.com/spring-cloud-data-flow-stream-processing) diff --git a/spring-cloud/spring-cloud-bootstrap/README.MD b/spring-cloud/spring-cloud-bootstrap/README.MD index 8b13789179..c16ba3e247 100644 --- a/spring-cloud/spring-cloud-bootstrap/README.MD +++ b/spring-cloud/spring-cloud-bootstrap/README.MD @@ -1 +1,2 @@ - +### Relevant Articles: +- [Spring Cloud – Bootstrapping](http://www.baeldung.com/spring-cloud-bootstrapping) diff --git a/spring-cloud/spring-cloud-config/README.md b/spring-cloud/spring-cloud-config/README.md new file mode 100644 index 0000000000..b28c750ee6 --- /dev/null +++ b/spring-cloud/spring-cloud-config/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) diff --git a/spring-cloud/spring-cloud-eureka/README.md b/spring-cloud/spring-cloud-eureka/README.md new file mode 100644 index 0000000000..badf4c8d50 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Spring Cloud Netflix – Eureka](http://www.baeldung.com/spring-cloud-netflix-eureka) diff --git a/spring-cloud/spring-cloud-hystrix/README.MD b/spring-cloud/spring-cloud-hystrix/README.MD index 8b13789179..a235f6311f 100644 --- a/spring-cloud/spring-cloud-hystrix/README.MD +++ b/spring-cloud/spring-cloud-hystrix/README.MD @@ -1 +1,2 @@ - +### Relevant Articles: +- [A Guide to Spring Cloud Netflix – Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix) diff --git a/spring-cucumber/README.md b/spring-cucumber/README.md new file mode 100644 index 0000000000..1e506f3a09 --- /dev/null +++ b/spring-cucumber/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Cucumber Spring Integration](http://www.baeldung.com/cucumber-spring-integration) diff --git a/spring-mvc-java/src/main/README.md b/spring-mvc-java/src/main/README.md new file mode 100644 index 0000000000..20ee1918af --- /dev/null +++ b/spring-mvc-java/src/main/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) diff --git a/spring-mvc-java/src/test/README.md b/spring-mvc-java/src/test/README.md new file mode 100644 index 0000000000..20ee1918af --- /dev/null +++ b/spring-mvc-java/src/test/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/README.md b/spring-mvc-java/src/test/java/com/baeldung/web/controller/README.md new file mode 100644 index 0000000000..9923962dde --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [WebAppConfiguration in Spring Tests](http://www.baeldung.com/spring-webappconfiguration) diff --git a/spring-mvc-velocity/README.md b/spring-mvc-velocity/README.md new file mode 100644 index 0000000000..401e135f75 --- /dev/null +++ b/spring-mvc-velocity/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Quick Guide to Spring MVC with Velocity](http://www.baeldung.com/spring-mvc-with-velocity) diff --git a/spring-mvc-web-vs-initializer/README.MD b/spring-mvc-web-vs-initializer/README.MD index 8b13789179..4759cf6137 100644 --- a/spring-mvc-web-vs-initializer/README.MD +++ b/spring-mvc-web-vs-initializer/README.MD @@ -1 +1,2 @@ - +### Relevant Articles: +- [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) diff --git a/spring-protobuf/README.md b/spring-protobuf/README.md new file mode 100644 index 0000000000..dad0e3f54a --- /dev/null +++ b/spring-protobuf/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Spring REST API with Protocol Buffers](http://www.baeldung.com/spring-rest-api-with-protocol-buffers) diff --git a/spring-security-x509/README.md b/spring-security-x509/README.md new file mode 100644 index 0000000000..2a4b84eae6 --- /dev/null +++ b/spring-security-x509/README.md @@ -0,0 +1,2 @@ +Relevant Articles: +- [X.509 Authentication in Spring Security](http://www.baeldung.com/x-509-authentication-in-spring-security) diff --git a/spring-spel/README.md b/spring-spel/README.md new file mode 100644 index 0000000000..d7e69e114c --- /dev/null +++ b/spring-spel/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Spring Expression Language Guide](http://www.baeldung.com/spring-expression-language) diff --git a/xml/README.md b/xml/README.md new file mode 100644 index 0000000000..8531f8b063 --- /dev/null +++ b/xml/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Intro to XPath with Java](http://www.baeldung.com/java-xpath) diff --git a/xstream/README.md b/xstream/README.md new file mode 100644 index 0000000000..e8302c14ef --- /dev/null +++ b/xstream/README.md @@ -0,0 +1,4 @@ +### Relevant Articles: +- [XStream User Guide: JSON](http://www.baeldung.com/xstream-json-processing) +- [XStream User Guide: Converting XML to Objects](http://www.baeldung.com/xstream-deserialize-xml-to-object) +- [XStream User Guide: Converting Objects to XML](http://www.baeldung.com/xstream-serialize-object-to-xml) From 4db81e96b21bec4a0b1f0e3283605033efe8e720 Mon Sep 17 00:00:00 2001 From: Sameera Date: Mon, 17 Oct 2016 00:24:25 +0530 Subject: [PATCH 118/193] Adding Print Screen in Java --- printscreen/pom.xml | 31 ++++++++++++++ .../org/baeldung/corejava/Screenshot.java | 42 +++++++++++++++++++ .../org/baeldung/corejava/ScreenshotTest.java | 39 +++++++++++++++++ 3 files changed, 112 insertions(+) create mode 100644 printscreen/pom.xml create mode 100644 printscreen/src/main/java/org/baeldung/corejava/Screenshot.java create mode 100644 printscreen/src/test/java/org/baeldung/corejava/ScreenshotTest.java diff --git a/printscreen/pom.xml b/printscreen/pom.xml new file mode 100644 index 0000000000..25316a3b48 --- /dev/null +++ b/printscreen/pom.xml @@ -0,0 +1,31 @@ + + 4.0.0 + + com.baeldung + corejava-printscreen + 1.0-SNAPSHOT + jar + + How to Print Screen in Java + https://github.com/eugenp/tutorials + + + UTF-8 + + + + + junit + junit + 3.8.1 + test + + + junit + junit + 4.12 + test + + + diff --git a/printscreen/src/main/java/org/baeldung/corejava/Screenshot.java b/printscreen/src/main/java/org/baeldung/corejava/Screenshot.java new file mode 100644 index 0000000000..57a754bb83 --- /dev/null +++ b/printscreen/src/main/java/org/baeldung/corejava/Screenshot.java @@ -0,0 +1,42 @@ +package org.baeldung.corejava;; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.File; + +public class Screenshot { + + private String filePath; + private String filenamePrefix; + private String fileType; + private int timeToWait; + + public Screenshot(String filePath, String filenamePrefix, + String fileType, int timeToWait) { + this.filePath = filePath; + this.filenamePrefix = filenamePrefix; + this.fileType = fileType; + this.timeToWait = timeToWait; + } + + public void getScreenshot() { + try { + Thread.sleep(timeToWait); + Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); + Robot robot = new Robot(); + BufferedImage img = robot.createScreenCapture(rectangle); + ImageIO.write(img, fileType, setupFileNamePath()); + } catch (Exception ex) { + System.out.println("Error occurred while getting the Print Screen."); + } + } + + private File setupFileNamePath() { + return new File(filePath + filenamePrefix + "." + fileType); + } + + private Rectangle getScreenSizedRectangle(final Dimension d) { + return new Rectangle(0, 0, d.width, d.height); + } +} diff --git a/printscreen/src/test/java/org/baeldung/corejava/ScreenshotTest.java b/printscreen/src/test/java/org/baeldung/corejava/ScreenshotTest.java new file mode 100644 index 0000000000..588c2eea78 --- /dev/null +++ b/printscreen/src/test/java/org/baeldung/corejava/ScreenshotTest.java @@ -0,0 +1,39 @@ +package org.baeldung.corejava; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; + +import static org.junit.Assert.*; + + +public class ScreenshotTest { + + private Screenshot screenshot; + private String filePath; + private String fileName; + private String fileType; + private File file; + + @Before + public void setUp() throws Exception { + filePath = ""; + fileName = "Screenshot"; + fileType = "jpg"; + file = new File(filePath + fileName + "." + fileType); + screenshot = new Screenshot(filePath, fileName, fileType, 2000); + } + + @Test + public void testGetScreenshot() throws Exception { + screenshot.getScreenshot(); + assertTrue(file.exists()); + } + + @After + public void tearDown() throws Exception { + file.delete(); + } +} \ No newline at end of file From f9ec757a44087f793bf90d9344d0426a500cb69f Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 17 Oct 2016 07:49:55 +0300 Subject: [PATCH 119/193] minor httpclient cleanup --- .../{HttpAsyncClientTest.java => HttpAsyncClientLiveTest.java} | 2 +- .../httpclient/{SandboxTest.java => SandboxLiveTest.java} | 2 +- ...entTest.java => HttpClientConnectionManagementLiveTest.java} | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename httpclient/src/test/java/org/baeldung/httpclient/{HttpAsyncClientTest.java => HttpAsyncClientLiveTest.java} (99%) rename httpclient/src/test/java/org/baeldung/httpclient/{SandboxTest.java => SandboxLiveTest.java} (99%) rename httpclient/src/test/java/org/baeldung/httpclient/conn/{HttpClientConnectionManagementTest.java => HttpClientConnectionManagementLiveTest.java} (99%) diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java similarity index 99% rename from httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientTest.java rename to httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java index 151ed10f37..bfe1e68ebe 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java @@ -33,7 +33,7 @@ import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.junit.Test; -public class HttpAsyncClientTest { +public class HttpAsyncClientLiveTest { private static final String HOST = "http://www.google.com"; private static final String HOST_WITH_SSL = "https://mms.nw.ru/"; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/SandboxTest.java b/httpclient/src/test/java/org/baeldung/httpclient/SandboxLiveTest.java similarity index 99% rename from httpclient/src/test/java/org/baeldung/httpclient/SandboxTest.java rename to httpclient/src/test/java/org/baeldung/httpclient/SandboxLiveTest.java index dc1a206f0d..61269c33a1 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/SandboxTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/SandboxLiveTest.java @@ -29,7 +29,7 @@ import org.apache.http.util.EntityUtils; import org.junit.Ignore; import org.junit.Test; -public class SandboxTest { +public class SandboxLiveTest { // original example @Ignore diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java similarity index 99% rename from httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java rename to httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java index c5c960f527..e9db8c1e16 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java @@ -36,7 +36,7 @@ import org.junit.Before; import org.junit.Ignore; import org.junit.Test; -public class HttpClientConnectionManagementTest { +public class HttpClientConnectionManagementLiveTest { private static final String SERVER1 = "http://www.petrikainulainen.net/"; private static final String SERVER7 = "http://www.baeldung.com/"; From 299504659b29d5d36316329448e745c9c1c2677d Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 17 Oct 2016 07:52:17 +0300 Subject: [PATCH 120/193] adding a sandbox test --- .../baeldung/httpclient/SandboxLiveTest.java | 188 ------------------ .../base/HttpClientSandboxLiveTest.java | 12 ++ 2 files changed, 12 insertions(+), 188 deletions(-) delete mode 100644 httpclient/src/test/java/org/baeldung/httpclient/SandboxLiveTest.java diff --git a/httpclient/src/test/java/org/baeldung/httpclient/SandboxLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/SandboxLiveTest.java deleted file mode 100644 index 61269c33a1..0000000000 --- a/httpclient/src/test/java/org/baeldung/httpclient/SandboxLiveTest.java +++ /dev/null @@ -1,188 +0,0 @@ -package org.baeldung.httpclient; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.http.Header; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.AuthCache; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.CookieStore; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.impl.auth.DigestScheme; -import org.apache.http.impl.client.BasicAuthCache; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.cookie.BasicClientCookie; -import org.apache.http.util.EntityUtils; -import org.junit.Ignore; -import org.junit.Test; - -public class SandboxLiveTest { - - // original example - @Ignore - @Test - public final void whenInterestingDigestAuthScenario_then401UnAuthorized() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException { - final HttpHost targetHost = new HttpHost("httpbin.org", 80, "http"); - - // set up the credentials to run agains the server - final CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user", "passwd")); - - // We need a first run to get a 401 to seed the digest auth - - // Make a client using those creds - final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); - - // And make a call to the URL we are after - final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd"); - - // Create a context to use - final HttpClientContext context = HttpClientContext.create(); - - // Get a response from the sever (expect a 401!) - final HttpResponse authResponse = client.execute(targetHost, httpget, context); - - // Pull out the auth header that came back from the server - final Header challenge = authResponse.getHeaders("WWW-Authenticate")[0]; - - // Lets use a digest scheme to solve it - final DigestScheme digest = new DigestScheme(); - digest.processChallenge(challenge); - - // Make a header with the solution based upon user/password and what the digest got out of the initial 401 reponse - final Header solution = digest.authenticate(new UsernamePasswordCredentials("user", "passwd"), httpget, context); - - // Need an auth cache to use the new digest we made - final AuthCache authCache = new BasicAuthCache(); - authCache.put(targetHost, digest); - - // Add the authCache and thus solved digest to the context - context.setAuthCache(authCache); - - // Pimp up our http get with the solved header made by the digest - httpget.addHeader(solution); - - // use it! - System.out.println("Executing request " + httpget.getRequestLine() + " to target " + targetHost); - - for (int i = 0; i < 3; i++) { - final CloseableHttpResponse responseGood = client.execute(targetHost, httpget, context); - - try { - System.out.println("----------------------------------------"); - System.out.println(responseGood.getStatusLine()); - System.out.println(EntityUtils.toString(responseGood.getEntity())); - } finally { - responseGood.close(); - } - } - } - - @Test - public final void whenInterestingDigestAuthScenario_then200OK() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException { - final HttpHost targetHost = new HttpHost("httpbin.org", 80, "http"); - - // set up the credentials to run agains the server - final CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user", "passwd")); - - // This endpoint need fake cookie to work properly - final CookieStore cookieStore = new BasicCookieStore(); - final BasicClientCookie cookie = new BasicClientCookie("fake", "fake_value"); - cookie.setDomain("httpbin.org"); - cookie.setPath("/"); - cookieStore.addCookie(cookie); - - // Make a client using those creds - final CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credsProvider).build(); - - // And make a call to the URL we are after - final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd"); - - // Create a context to use - final HttpClientContext context = HttpClientContext.create(); - - // Get a response from the sever (401 implicitly) - final HttpResponse authResponse = client.execute(targetHost, httpget, context); - assertEquals(200, authResponse.getStatusLine().getStatusCode()); - - // HttpClient will use cached digest parameters for future requests - System.out.println("Executing request " + httpget.getRequestLine() + " to target " + targetHost); - - for (int i = 0; i < 3; i++) { - final CloseableHttpResponse responseGood = client.execute(targetHost, httpget, context); - - try { - System.out.println("----------------------------------------"); - System.out.println(responseGood.getStatusLine()); - assertEquals(200, responseGood.getStatusLine().getStatusCode()); - } finally { - responseGood.close(); - } - } - client.close(); - } - - // This test needs module spring-security-rest-digest-auth to be running - @Test - public final void whenWeKnowDigestParameters_thenNo401Status() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException { - final HttpHost targetHost = new HttpHost("localhost", 8080, "http"); - - final CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1Pass")); - - final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); - - final HttpGet httpget = new HttpGet("http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"); - - final HttpClientContext context = HttpClientContext.create(); - // == make it preemptive - final AuthCache authCache = new BasicAuthCache(); - final DigestScheme digestAuth = new DigestScheme(); - digestAuth.overrideParamter("realm", "Custom Realm Name"); - digestAuth.overrideParamter("nonce", "nonce value goes here"); - authCache.put(targetHost, digestAuth); - context.setAuthCache(authCache); - // == end - System.out.println("Executing The Request knowing the digest parameters ==== "); - final HttpResponse authResponse = client.execute(targetHost, httpget, context); - assertEquals(200, authResponse.getStatusLine().getStatusCode()); - client.close(); - } - - // This test needs module spring-security-rest-digest-auth to be running - @Test - public final void whenDoNotKnowParameters_thenOnlyOne401() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException { - final HttpClientContext context = HttpClientContext.create(); - final HttpHost targetHost = new HttpHost("localhost", 8080, "http"); - final CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1Pass")); - final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); - - final HttpGet httpget = new HttpGet("http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"); - System.out.println("Executing The Request NOT knowing the digest parameters ==== "); - final HttpResponse tempResponse = client.execute(targetHost, httpget, context); - assertEquals(200, tempResponse.getStatusLine().getStatusCode()); - - for (int i = 0; i < 3; i++) { - System.out.println("No more Challenges or 401"); - final CloseableHttpResponse authResponse = client.execute(targetHost, httpget, context); - assertEquals(200, authResponse.getStatusLine().getStatusCode()); - authResponse.close(); - } - client.close(); - } -} diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java index ff2f1cd194..2333e2f8c9 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java @@ -10,9 +10,11 @@ import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; +import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; import org.junit.After; import org.junit.Test; @@ -58,4 +60,14 @@ public class HttpClientSandboxLiveTest { System.out.println(response.getStatusLine()); } + @Test + public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, IOException { + final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + + final HttpGet httpGet = new HttpGet("https://sesar3.geoinfogeochem.org/sample/igsn/ODP000002"); + httpGet.setHeader("Accept", "application/xml"); + + response = httpClient.execute(httpGet); + } + } From 04482ef902b9a2cc3c1cff5407719d2d8f6030d1 Mon Sep 17 00:00:00 2001 From: maibin Date: Mon, 17 Oct 2016 10:10:12 +0200 Subject: [PATCH 121/193] Executable Jar Maven (#752) * Expression-Based Access Control PermitAll, hasRole, hasAnyRole etc. I modified classes regards to Security * Added test cases for Spring Security Expressions * Handler Interceptor - logging example * Test for logger interceptor * Removed conflicted part * UserInterceptor (adding user information to model) * Spring Handler Interceptor - session timers * Spring Security CSRF attack protection with Thymeleaf * Fix and(); * Logger update * Changed config for Thymeleaf * Thymeleaf Natural Processing and Inlining * Expression Utility Objects, Thymeleaf * listOfStudents edited * Thymeleaf layout decorators * Executable Jar with Maven --- core-java/pom.xml | 454 +++++++++++------- .../executable/ExecutableMavenJar.java | 11 + 2 files changed, 293 insertions(+), 172 deletions(-) create mode 100644 core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java diff --git a/core-java/pom.xml b/core-java/pom.xml index a5e89d2a76..75608b59ba 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -1,211 +1,321 @@ - - 4.0.0 - com.baeldung - core-java - 0.1.0-SNAPSHOT + + 4.0.0 + com.baeldung + core-java + 0.1.0-SNAPSHOT + jar - core-java + core-java - + - - - net.sourceforge.collections - collections-generic - 4.01 - - - com.google.guava - guava - ${guava.version} - + + + net.sourceforge.collections + collections-generic + 4.01 + + + com.google.guava + guava + ${guava.version} + - - org.apache.commons - commons-collections4 - 4.0 - + + org.apache.commons + commons-collections4 + 4.0 + - - commons-io - commons-io - 2.4 - + + commons-io + commons-io + 2.4 + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - - org.apache.commons - commons-math3 - 3.3 - + + org.apache.commons + commons-math3 + 3.3 + - + - + - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + - + - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + - + - - junit - junit - ${junit.version} - test - + + junit + junit + ${junit.version} + test + - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + - - org.assertj - assertj-core - ${assertj.version} - test - + + org.assertj + assertj-core + ${assertj.version} + test + - - org.testng - testng - ${testng.version} - test - + + org.testng + testng + ${testng.version} + test + - - org.mockito - mockito-core - ${mockito.version} - test - - - - commons-codec - commons-codec - 1.10 - + + org.mockito + mockito-core + ${mockito.version} + test + - + + commons-codec + commons-codec + 1.10 + - - core-java - - - src/main/resources - true - - + - + + core-java + + + src/main/resources + true + + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*IntegrationTest.java - - - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + - + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + ${project.build.directory}/libs + + + + - - - 4.3.11.Final - 5.1.38 + + org.apache.maven.plugins + maven-jar-plugin + + + + true + libs/ + org.baeldung.executable.ExecutableMavenJar + + + + - - 2.7.8 + + org.apache.maven.plugins + maven-assembly-plugin + + + package + + single + + + + + org.baeldung.executable.ExecutableMavenJar + + + + jar-with-dependencies + + + + + - - 1.7.13 - 1.1.3 + + org.apache.maven.plugins + maven-shade-plugin + + + + shade + + + true + + + org.baeldung.executable.ExecutableMavenJar + + + + + + - - 5.1.3.Final + + com.jolira + onejar-maven-plugin + + + + org.baeldung.executable.ExecutableMavenJar + true + ${project.build.finalName}-onejar.${project.packaging} + + + one-jar + + + + - - 19.0 - 3.4 + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + spring-boot + org.baeldung.executable.ExecutableMavenJar + + + + + + - - 1.3 - 4.12 - 1.10.19 - 6.8 - 3.5.1 + - 4.4.1 - 4.5 + + + 4.3.11.Final + 5.1.38 - 2.9.0 + + 2.7.8 - - 3.5.1 - 2.6 - 2.19.1 - 2.7 - 1.4.18 + + 1.7.13 + 1.1.3 - + + 5.1.3.Final + + + 19.0 + 3.4 + + + 1.3 + 4.12 + 1.10.19 + 6.8 + 3.5.1 + + 4.4.1 + 4.5 + + 2.9.0 + + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 + + \ No newline at end of file diff --git a/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java new file mode 100644 index 0000000000..2c52a17904 --- /dev/null +++ b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java @@ -0,0 +1,11 @@ +package org.baeldung.executable; + +import javax.swing.JOptionPane; + +public class ExecutableMavenJar { + + public static void main(String[] args) { + JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1); + } + +} From 091d02afbbf534434317dd7c423ca6470cf18c94 Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 17 Oct 2016 12:39:30 +0200 Subject: [PATCH 122/193] add integration test profile --- spring-userservice/pom.xml | 59 +++++++++++-------- ...tomUserDetailsServiceIntegrationTest.java} | 2 +- 2 files changed, 37 insertions(+), 24 deletions(-) rename spring-userservice/src/test/java/org/baeldung/userservice/{CustomUserDetailsServiceTest.java => CustomUserDetailsServiceIntegrationTest.java} (98%) diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml index 93b01ee49c..dc0d4d295c 100644 --- a/spring-userservice/pom.xml +++ b/spring-userservice/pom.xml @@ -240,39 +240,52 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 4.1.3.RELEASE diff --git a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java similarity index 98% rename from spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java rename to spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java index 6e1cd67e06..79d60aa540 100644 --- a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java +++ b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java @@ -25,7 +25,7 @@ import java.util.logging.Logger; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) @WebAppConfiguration -public class CustomUserDetailsServiceTest { +public class CustomUserDetailsServiceIntegrationTest { private static final Logger LOG = Logger.getLogger("CustomUserDetailsServiceTest"); From 7667d25bb7fd4ca0da58f0452d828af5f6d96f65 Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 17 Oct 2016 12:57:13 +0200 Subject: [PATCH 123/193] add integration test profile --- spring-thymeleaf/pom.xml | 58 ++++++++++++------- ...lityObjectsControllerIntegrationTest.java} | 2 +- ...youtDialectControllerIntegrationTest.java} | 2 +- 3 files changed, 39 insertions(+), 23 deletions(-) rename spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/{ExpressionUtilityObjectsControllerTest.java => ExpressionUtilityObjectsControllerIntegrationTest.java} (97%) rename spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/{LayoutDialectControllerTest.java => LayoutDialectControllerIntegrationTest.java} (97%) diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index 960b358fe2..d2b3be1651 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -166,31 +166,47 @@ ${maven-surefire-plugin.version} + **/*IntegrationTest.java + **/*LiveTest.java - - - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - 8082 - - + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java similarity index 97% rename from spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerTest.java rename to spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java index f6a79b7570..0638dbbc11 100644 --- a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java @@ -29,7 +29,7 @@ import com.baeldung.thymeleaf.config.WebMVCSecurity; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) -public class ExpressionUtilityObjectsControllerTest { +public class ExpressionUtilityObjectsControllerIntegrationTest { @Autowired WebApplicationContext wac; diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java similarity index 97% rename from spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerTest.java rename to spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java index 33731f130d..23113dc229 100644 --- a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java @@ -29,7 +29,7 @@ import com.baeldung.thymeleaf.config.WebMVCSecurity; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) -public class LayoutDialectControllerTest { +public class LayoutDialectControllerIntegrationTest { @Autowired WebApplicationContext wac; From 167d2de4acd9723813028c49efb5d5c18e28dbbd Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 17 Oct 2016 13:19:52 +0200 Subject: [PATCH 124/193] add integration test profile --- spring-spel/pom.xml | 46 +++++++++++++++++++ ...SpelTest.java => SpelIntegrationTest.java} | 2 +- 2 files changed, 47 insertions(+), 1 deletion(-) rename spring-spel/src/test/java/com/baeldung/spel/{SpelTest.java => SpelIntegrationTest.java} (99%) diff --git a/spring-spel/pom.xml b/spring-spel/pom.xml index 12b7164e27..add5e53348 100644 --- a/spring-spel/pom.xml +++ b/spring-spel/pom.xml @@ -46,7 +46,53 @@ true + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + \ No newline at end of file diff --git a/spring-spel/src/test/java/com/baeldung/spel/SpelTest.java b/spring-spel/src/test/java/com/baeldung/spel/SpelIntegrationTest.java similarity index 99% rename from spring-spel/src/test/java/com/baeldung/spel/SpelTest.java rename to spring-spel/src/test/java/com/baeldung/spel/SpelIntegrationTest.java index 5cf18bc1d2..bff42caead 100644 --- a/spring-spel/src/test/java/com/baeldung/spel/SpelTest.java +++ b/spring-spel/src/test/java/com/baeldung/spel/SpelIntegrationTest.java @@ -13,7 +13,7 @@ import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) -public class SpelTest { +public class SpelIntegrationTest { @Autowired private SpelArithmetic spelArithmetic = new SpelArithmetic(); From 1e9d1a75663a4c02bbdab5aeebd85345bb6d1ef6 Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 17 Oct 2016 13:30:13 +0200 Subject: [PATCH 125/193] add integration test profile --- .../spring-security-x509-basic-auth/pom.xml | 63 ++++++++++++++++--- ...9AuthenticationServerIntegrationTest.java} | 2 +- .../spring-security-x509-client-auth/pom.xml | 62 +++++++++++++++--- ...9AuthenticationServerIntegrationTest.java} | 2 +- 4 files changed, 111 insertions(+), 18 deletions(-) rename spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/{X509AuthenticationServerTests.java => X509AuthenticationServerIntegrationTest.java} (85%) rename spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/{X509AuthenticationServerTests.java => X509AuthenticationServerIntegrationTest.java} (85%) diff --git a/spring-security-x509/spring-security-x509-basic-auth/pom.xml b/spring-security-x509/spring-security-x509-basic-auth/pom.xml index 87fdd64727..8f460c83ec 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-basic-auth/pom.xml @@ -16,12 +16,59 @@ 0.0.1-SNAPSHOT - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerIntegrationTest.java similarity index 85% rename from spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java rename to spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerIntegrationTest.java index 0b9a11552a..5eb1c25ed6 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java +++ b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class X509AuthenticationServerTests { +public class X509AuthenticationServerIntegrationTest { @Test public void contextLoads() { } diff --git a/spring-security-x509/spring-security-x509-client-auth/pom.xml b/spring-security-x509/spring-security-x509-client-auth/pom.xml index 56cef8ea07..ffddabef40 100644 --- a/spring-security-x509/spring-security-x509-client-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-client-auth/pom.xml @@ -16,12 +16,58 @@ 0.0.1-SNAPSHOT - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java b/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerIntegrationTest.java similarity index 85% rename from spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java rename to spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerIntegrationTest.java index 0b9a11552a..5eb1c25ed6 100644 --- a/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java +++ b/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class X509AuthenticationServerTests { +public class X509AuthenticationServerIntegrationTest { @Test public void contextLoads() { } From 903c9c52999f1421f2f3d8c18a78865e29b73c36 Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 17 Oct 2016 19:35:24 +0200 Subject: [PATCH 126/193] add integration test profile --- spring-protobuf/pom.xml | 48 ++++++++++- ...t.java => ApplicationIntegrationTest.java} | 2 +- spring-rest-angular/pom.xml | 85 ++++++++++++++----- ...ava => StudentServiceIntegrationTest.java} | 2 +- 4 files changed, 113 insertions(+), 24 deletions(-) rename spring-protobuf/src/test/java/com/baeldung/protobuf/{ApplicationTest.java => ApplicationIntegrationTest.java} (98%) rename spring-rest-angular/src/test/java/org/baeldung/web/service/{StudentServiceTest.java => StudentServiceIntegrationTest.java} (98%) diff --git a/spring-protobuf/pom.xml b/spring-protobuf/pom.xml index 1275d72edf..a080d51221 100644 --- a/spring-protobuf/pom.xml +++ b/spring-protobuf/pom.xml @@ -37,7 +37,6 @@ org.apache.httpcomponents httpclient - 4.5.2 @@ -47,12 +46,57 @@ org.apache.maven.plugins maven-compiler-plugin - 3.3 1.8 1.8 + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationTest.java b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java similarity index 98% rename from spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationTest.java rename to spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java index a17082cea7..914cf18627 100644 --- a/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationTest.java +++ b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java @@ -24,7 +24,7 @@ import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebIntegrationTest -public class ApplicationTest { +public class ApplicationIntegrationTest { private static final String COURSE1_URL = "http://localhost:8080/courses/1"; diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 981ee9dabc..ce496df742 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -71,30 +71,75 @@ - - angular-spring-rest-sample - + + angular-spring-rest-sample + - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + - - org.apache.maven.plugins - maven-war-plugin - - false - - + + org.apache.maven.plugins + maven-war-plugin + + false + + - - + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 19.0 diff --git a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java similarity index 98% rename from spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java rename to spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java index 1199f15ab3..6ad80e5caf 100644 --- a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java +++ b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java @@ -18,7 +18,7 @@ import static org.hamcrest.core.IsEqual.*; @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration @IntegrationTest("server.port:8888") -public class StudentServiceTest { +public class StudentServiceIntegrationTest { private static final String ENDPOINT = "http://localhost:8888/student/get"; From e9f3cfd7c6e872d86b84132c98b760da2b33eca0 Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 17 Oct 2016 19:43:48 +0200 Subject: [PATCH 127/193] add integration test profile --- spring-mvc-web-vs-initializer/pom.xml | 67 ++++++++++++++++--- ...t.java => JavaServletIntegrationTest.java} | 2 +- ...st.java => XmlServletIntegrationTest.java} | 2 +- 3 files changed, 59 insertions(+), 12 deletions(-) rename spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/{JavaServletTest.java => JavaServletIntegrationTest.java} (97%) rename spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/{XmlServletTest.java => XmlServletIntegrationTest.java} (97%) diff --git a/spring-mvc-web-vs-initializer/pom.xml b/spring-mvc-web-vs-initializer/pom.xml index 0d735e7188..b448673ef8 100644 --- a/spring-mvc-web-vs-initializer/pom.xml +++ b/spring-mvc-web-vs-initializer/pom.xml @@ -146,17 +146,64 @@ - - spring-mvc-web-vs-initializer - - - src/main/resources - true - - - - + + spring-mvc-web-vs-initializer + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 4.3.1.RELEASE diff --git a/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletTest.java b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletIntegrationTest.java similarity index 97% rename from spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletTest.java rename to spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletIntegrationTest.java index 99b5ef8c2f..0461cc8fcc 100644 --- a/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletTest.java +++ b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletIntegrationTest.java @@ -20,7 +20,7 @@ import org.springframework.web.servlet.ModelAndView; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(loader=AnnotationConfigWebContextLoader.class, classes = MvcConfig.class) -public class JavaServletTest { +public class JavaServletIntegrationTest { private MockMvc mockMvc; diff --git a/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletTest.java b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletIntegrationTest.java similarity index 97% rename from spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletTest.java rename to spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletIntegrationTest.java index e7695e36c0..e1273f8f88 100644 --- a/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletTest.java +++ b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletIntegrationTest.java @@ -19,7 +19,7 @@ import org.springframework.web.servlet.ModelAndView; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(loader=GenericXmlWebContextLoader.class, locations = "classpath*:mvc-configuration.xml") -public class XmlServletTest { +public class XmlServletIntegrationTest { private MockMvc mockMvc; From b4f778a0e74642cf8dfc17e23c368b103b8af5b0 Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 18 Oct 2016 12:55:02 +0200 Subject: [PATCH 128/193] add integration test profile --- spring-mvc-velocity/pom.xml | 37 ++++++++++++++++++- ...DataContentControllerIntegrationTest.java} | 2 +- 2 files changed, 37 insertions(+), 2 deletions(-) rename spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/{DataContentControllerTest.java => DataContentControllerIntegrationTest.java} (98%) diff --git a/spring-mvc-velocity/pom.xml b/spring-mvc-velocity/pom.xml index 6c63e0be18..83f3150df9 100644 --- a/spring-mvc-velocity/pom.xml +++ b/spring-mvc-velocity/pom.xml @@ -139,7 +139,7 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java @@ -151,6 +151,41 @@ + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 4.1.4.RELEASE diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerIntegrationTest.java similarity index 98% rename from spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java rename to spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerIntegrationTest.java index 1f90b0fc67..7f92e1ee45 100644 --- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java +++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerIntegrationTest.java @@ -29,7 +29,7 @@ import com.baeldung.mvc.velocity.test.config.TestConfig; // @ContextConfiguration(locations = {"classpath:mvc-servlet.xml"}) @ContextConfiguration(classes = { TestConfig.class, WebConfig.class }) @WebAppConfiguration -public class DataContentControllerTest { +public class DataContentControllerIntegrationTest { private MockMvc mockMvc; From 668605c4e30bd1d992f39e2dec774aa5f36c70ce Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 18 Oct 2016 13:29:59 +0200 Subject: [PATCH 129/193] add integration test profile --- spring-mockito/pom.xml | 61 ++++++++++++++++--- ...t.java => UserServiceIntegrationTest.java} | 2 +- 2 files changed, 54 insertions(+), 9 deletions(-) rename spring-mockito/src/test/java/com/baeldung/{UserServiceTest.java => UserServiceIntegrationTest.java} (95%) diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index 3dcca7aab7..c8e0d3b7f5 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -34,15 +34,60 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + UTF-8 1.8 diff --git a/spring-mockito/src/test/java/com/baeldung/UserServiceTest.java b/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java similarity index 95% rename from spring-mockito/src/test/java/com/baeldung/UserServiceTest.java rename to spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java index 631a8634be..70861a96e1 100644 --- a/spring-mockito/src/test/java/com/baeldung/UserServiceTest.java +++ b/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ActiveProfiles("test") @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MocksApplication.class) -public class UserServiceTest { +public class UserServiceIntegrationTest { @Autowired private UserService userService; From de1b5e0a174f363846bf70863362bfc6a1056cc0 Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 18 Oct 2016 15:52:19 +0200 Subject: [PATCH 130/193] minor cleanup --- spring-jpa/pom.xml | 25 ++----------------------- 1 file changed, 2 insertions(+), 23 deletions(-) diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index ebb9c5bc83..cf0c2246af 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -182,7 +182,7 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java @@ -190,31 +190,10 @@ - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - - + 4.3.2.RELEASE From 35009ad3c469e1dd4a5c8c95d8ca73206c7add4a Mon Sep 17 00:00:00 2001 From: Ante Pocedulic Date: Tue, 18 Oct 2016 16:54:54 +0200 Subject: [PATCH 131/193] - refactored CacheHelper class (#756) --- .../java/org/baeldung/ehcache/app/App.java | 24 ------------------- .../baeldung/ehcache/config/CacheHelper.java | 8 +++++-- 2 files changed, 6 insertions(+), 26 deletions(-) delete mode 100755 spring-all/src/main/java/org/baeldung/ehcache/app/App.java diff --git a/spring-all/src/main/java/org/baeldung/ehcache/app/App.java b/spring-all/src/main/java/org/baeldung/ehcache/app/App.java deleted file mode 100755 index 99370186a3..0000000000 --- a/spring-all/src/main/java/org/baeldung/ehcache/app/App.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung.ehcache.app; - -import org.baeldung.ehcache.calculator.SquaredCalculator; -import org.baeldung.ehcache.config.CacheHelper; - -public class App { - - public static void main(String[] args) { - - SquaredCalculator squaredCalculator = new SquaredCalculator(); - CacheHelper cacheHelper = new CacheHelper(); - - squaredCalculator.setCache(cacheHelper); - - calculate(squaredCalculator); - calculate(squaredCalculator); - } - - private static void calculate(SquaredCalculator squaredCalculator) { - for (int i = 10; i < 15; i++) { - System.out.println("Square value of " + i + " is: " + squaredCalculator.getSquareValueOfNumber(i) + "\n"); - } - } -} diff --git a/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java b/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java index 387a57880b..7f59ad8cfb 100755 --- a/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java +++ b/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java @@ -12,14 +12,18 @@ public class CacheHelper { private Cache squareNumberCache; public CacheHelper() { - cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("squaredNumber", CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Integer.class, ResourcePoolsBuilder.heap(10))).build(); + cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(); cacheManager.init(); - squareNumberCache = cacheManager.getCache("squaredNumber", Integer.class, Integer.class); + squareNumberCache = cacheManager.createCache("squaredNumber", CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Integer.class, ResourcePoolsBuilder.heap(10))); } public Cache getSquareNumberCache() { return squareNumberCache; } + public Cache getSquareNumberCacheFromCacheManager() { + return cacheManager.getCache("squaredNumber", Integer.class, Integer.class); + } + } From 4a2546b8fc4a1abfcf6fff91b8a46b4fae41d69f Mon Sep 17 00:00:00 2001 From: Sandeep Kumar Date: Tue, 18 Oct 2016 21:58:50 +0530 Subject: [PATCH 132/193] Changes for integration test --- selenium-junit-testng/pom.xml | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml index f964f94ed4..9ad601fdcd 100644 --- a/selenium-junit-testng/pom.xml +++ b/selenium-junit-testng/pom.xml @@ -15,18 +15,6 @@ 1.8 - - org.apache.maven.plugins - maven-surefire-plugin - 2.19.1 - - true - - **/*LiveTest.java - - - - @@ -37,6 +25,7 @@ org.apache.maven.plugins maven-surefire-plugin + 2.19.1 **/*LiveTest.java From 8fb51bdfd6f4e915e0e542ab795d5adab1eeef2b Mon Sep 17 00:00:00 2001 From: Sameera Date: Tue, 18 Oct 2016 22:35:50 +0530 Subject: [PATCH 133/193] Removed unwanted Junit deps and updating the Junit version as a property --- printscreen/pom.xml | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/printscreen/pom.xml b/printscreen/pom.xml index 25316a3b48..ddb813a7a2 100644 --- a/printscreen/pom.xml +++ b/printscreen/pom.xml @@ -12,19 +12,14 @@ UTF-8 + 4.12 junit junit - 3.8.1 - test - - - junit - junit - 4.12 + ${junit.version} test From 199fdf2198c843011052e9f2ab3dc337acdd8d73 Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 18 Oct 2016 19:16:53 +0200 Subject: [PATCH 134/193] configure integration test --- spring-hibernate4/pom.xml | 23 +------------------ ... => HibernateCriteriaIntegrationTest.java} | 2 +- .../criteria/HibernateCriteriaTestSuite.java | 2 +- ... => HibernateFetchingIntegrationTest.java} | 2 +- .../persistence/audit/AuditTestSuite.java | 6 ++--- ... => EnversFooBarAuditIntegrationTest.java} | 4 ++-- ...t.java => JPABarAuditIntegrationTest.java} | 4 ++-- ...SpringDataJPABarAuditIntegrationTest.java} | 4 ++-- 8 files changed, 13 insertions(+), 34 deletions(-) rename spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/{HibernateCriteriaTest.java => HibernateCriteriaIntegrationTest.java} (99%) rename spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/{HibernateFetchingTest.java => HibernateFetchingIntegrationTest.java} (96%) rename spring-hibernate4/src/test/java/com/baeldung/persistence/audit/{EnversFooBarAuditTest.java => EnversFooBarAuditIntegrationTest.java} (98%) rename spring-hibernate4/src/test/java/com/baeldung/persistence/audit/{JPABarAuditTest.java => JPABarAuditIntegrationTest.java} (97%) rename spring-hibernate4/src/test/java/com/baeldung/persistence/audit/{SpringDataJPABarAuditTest.java => SpringDataJPABarAuditIntegrationTest.java} (96%) diff --git a/spring-hibernate4/pom.xml b/spring-hibernate4/pom.xml index 4f5cd0c290..d4dabcc274 100644 --- a/spring-hibernate4/pom.xml +++ b/spring-hibernate4/pom.xml @@ -185,7 +185,7 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java @@ -193,27 +193,6 @@ - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java similarity index 99% rename from spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java rename to spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java index 88186098cc..2275bf14f2 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -12,7 +12,7 @@ import com.baeldung.hibernate.criteria.model.Item; import com.baeldung.hibernate.criteria.util.HibernateUtil; import com.baeldung.hibernate.criteria.view.ApplicationView; -public class HibernateCriteriaTest { +public class HibernateCriteriaIntegrationTest { final private ApplicationView av = new ApplicationView(); diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java index 2911fb4725..dc1040734f 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java @@ -4,7 +4,7 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) -@Suite.SuiteClasses({ HibernateCriteriaTest.class }) +@Suite.SuiteClasses({ HibernateCriteriaIntegrationTest.class }) public class HibernateCriteriaTestSuite { diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java similarity index 96% rename from spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java rename to spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java index 42245ca89e..65bf36f8bf 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java @@ -11,7 +11,7 @@ import java.util.Set; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -public class HibernateFetchingTest { +public class HibernateFetchingIntegrationTest { // this loads sample data in the database @Before diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java index 8a8a3445f6..34c725d62b 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java @@ -5,9 +5,9 @@ import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ // @formatter:off - EnversFooBarAuditTest.class, - JPABarAuditTest.class, - SpringDataJPABarAuditTest.class + EnversFooBarAuditIntegrationTest.class, + JPABarAuditIntegrationTest.class, + SpringDataJPABarAuditIntegrationTest.class }) // @formatter:on public class AuditTestSuite { // diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java similarity index 98% rename from spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditTest.java rename to spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java index 6c13816b63..ed2e111c8f 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java @@ -28,9 +28,9 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class EnversFooBarAuditTest { +public class EnversFooBarAuditIntegrationTest { - private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditTest.class); + private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class); @BeforeClass public static void setUpBeforeClass() throws Exception { diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java similarity index 97% rename from spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditTest.java rename to spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java index 1e4a10f61c..b63a4b989b 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java @@ -27,9 +27,9 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class JPABarAuditTest { +public class JPABarAuditIntegrationTest { - private static Logger logger = LoggerFactory.getLogger(JPABarAuditTest.class); + private static Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class); @BeforeClass public static void setUpBeforeClass() throws Exception { diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java similarity index 96% rename from spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditTest.java rename to spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java index 05c0e9fa83..e794b282f6 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java @@ -26,9 +26,9 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class SpringDataJPABarAuditTest { +public class SpringDataJPABarAuditIntegrationTest { - private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditTest.class); + private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); @BeforeClass public static void setUpBeforeClass() throws Exception { From 3e31921e49e3d06ea55c51a497b157ad0f42ff8b Mon Sep 17 00:00:00 2001 From: Sameera Date: Tue, 18 Oct 2016 22:49:09 +0530 Subject: [PATCH 135/193] Removed try catch and set to throw the exception --- .../java/org/baeldung/corejava/Screenshot.java | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/printscreen/src/main/java/org/baeldung/corejava/Screenshot.java b/printscreen/src/main/java/org/baeldung/corejava/Screenshot.java index 57a754bb83..d33761932f 100644 --- a/printscreen/src/main/java/org/baeldung/corejava/Screenshot.java +++ b/printscreen/src/main/java/org/baeldung/corejava/Screenshot.java @@ -20,16 +20,12 @@ public class Screenshot { this.timeToWait = timeToWait; } - public void getScreenshot() { - try { - Thread.sleep(timeToWait); - Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); - Robot robot = new Robot(); - BufferedImage img = robot.createScreenCapture(rectangle); - ImageIO.write(img, fileType, setupFileNamePath()); - } catch (Exception ex) { - System.out.println("Error occurred while getting the Print Screen."); - } + public void getScreenshot() throws Exception { + Thread.sleep(timeToWait); + Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); + Robot robot = new Robot(); + BufferedImage img = robot.createScreenCapture(rectangle); + ImageIO.write(img, fileType, setupFileNamePath()); } private File setupFileNamePath() { From 1c775ef0efb1c6240e4b6c089536ea40b2177901 Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 18 Oct 2016 19:30:36 +0200 Subject: [PATCH 136/193] add integration test profile --- spring-hibernate3/pom.xml | 68 ++++++++++++------- .../baeldung/spring/PersistenceConfig.java | 2 +- .../main/resources/persistence-h2.properties | 10 +++ 3 files changed, 55 insertions(+), 25 deletions(-) create mode 100644 spring-hibernate3/src/main/resources/persistence-h2.properties diff --git a/spring-hibernate3/pom.xml b/spring-hibernate3/pom.xml index 59053be596..9f99d83a42 100644 --- a/spring-hibernate3/pom.xml +++ b/spring-hibernate3/pom.xml @@ -46,7 +46,13 @@ tomcat-dbcp ${tomcat-dbcp.version} - + + + com.h2database + h2 + ${h2.version} + + @@ -127,39 +133,52 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 4.2.5.RELEASE @@ -170,6 +189,7 @@ 3.6.10.Final 5.1.38 7.0.47 + 1.4.191 1.7.13 diff --git a/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfig.java b/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfig.java index 15752165cc..fea76dfc70 100644 --- a/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfig.java +++ b/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfig.java @@ -21,7 +21,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement -@PropertySource({ "classpath:persistence-mysql.properties" }) +@PropertySource({ "classpath:persistence-h2.properties" }) @ComponentScan({ "org.baeldung.persistence.dao", "org.baeldung.persistence.service" }) public class PersistenceConfig { diff --git a/spring-hibernate3/src/main/resources/persistence-h2.properties b/spring-hibernate3/src/main/resources/persistence-h2.properties new file mode 100644 index 0000000000..d2fcd9545b --- /dev/null +++ b/spring-hibernate3/src/main/resources/persistence-h2.properties @@ -0,0 +1,10 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:spring_hibernate3_01;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +jdbc.user=sa +jdbc.pass= + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file From 1dac21c3a60fdcb447a8ac89ce6fde9647b020e5 Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 18 Oct 2016 19:52:38 +0200 Subject: [PATCH 137/193] configure integration test --- spring-exceptions/pom.xml | 23 +------------------ ...bcConnectionExceptionIntegrationTest.java} | 2 +- ...ataIntegrityExceptionIntegrationTest.java} | 2 +- ...ataRetrievalExceptionIntegrationTest.java} | 2 +- ...SourceLookupExceptionIntegrationTest.java} | 2 +- ...esourceUsageExceptionIntegrationTest.java} | 2 +- 6 files changed, 6 insertions(+), 27 deletions(-) rename spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/{CannotGetJdbcConnectionExceptionTest.java => CannotGetJdbcConnectionExceptionIntegrationTest.java} (95%) rename spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/{DataIntegrityExceptionTest.java => DataIntegrityExceptionIntegrationTest.java} (96%) rename spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/{DataRetrievalExceptionTest.java => DataRetrievalExceptionIntegrationTest.java} (97%) rename spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/{DataSourceLookupExceptionTest.java => DataSourceLookupExceptionIntegrationTest.java} (95%) rename spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/{InvalidResourceUsageExceptionTest.java => InvalidResourceUsageExceptionIntegrationTest.java} (96%) diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index 733a721c58..12b7e5de79 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -194,7 +194,7 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java @@ -202,27 +202,6 @@ - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionIntegrationTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionIntegrationTest.java index 7a1804ec49..84038e4dcf 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionIntegrationTest.java @@ -18,7 +18,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause5NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class CannotGetJdbcConnectionExceptionTest { +public class CannotGetJdbcConnectionExceptionIntegrationTest { @Autowired private DataSource restDataSource; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionIntegrationTest.java similarity index 96% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionIntegrationTest.java index 357eb168cd..e62a455dd4 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionIntegrationTest.java @@ -17,7 +17,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DataIntegrityExceptionTest { +public class DataIntegrityExceptionIntegrationTest { @Autowired private IFooService fooService; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionIntegrationTest.java similarity index 97% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionIntegrationTest.java index 69b98b0539..8a7c237708 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionIntegrationTest.java @@ -17,7 +17,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DataRetrievalExceptionTest { +public class DataRetrievalExceptionIntegrationTest { @Autowired private DataSource restDataSource; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionIntegrationTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionIntegrationTest.java index 036f99ac8f..161bf3252b 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause4NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DataSourceLookupExceptionTest { +public class DataSourceLookupExceptionIntegrationTest { @Test(expected = DataSourceLookupFailureException.class) public void whenLookupNonExistentDataSource_thenDataSourceLookupFailureException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionIntegrationTest.java similarity index 96% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionIntegrationTest.java index 64f12e82e9..316efba0b9 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionIntegrationTest.java @@ -16,7 +16,7 @@ import javax.sql.DataSource; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class InvalidResourceUsageExceptionTest { +public class InvalidResourceUsageExceptionIntegrationTest { @Autowired private IFooService fooService; From 66dfb6fd3781685943e7118464925b1bd87bd606 Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 18 Oct 2016 20:20:13 +0200 Subject: [PATCH 138/193] configure integration test --- spring-data-redis/pom.xml | 21 ++++++++++++++++++- ... RedisMessageListenerIntegrationTest.java} | 2 +- ... => StudentRepositoryIntegrationTest.java} | 2 +- 3 files changed, 22 insertions(+), 3 deletions(-) rename spring-data-redis/src/test/java/com/baeldung/spring/data/redis/{RedisMessageListenerTest.java => RedisMessageListenerIntegrationTest.java} (95%) rename spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/{StudentRepositoryTest.java => StudentRepositoryIntegrationTest.java} (98%) diff --git a/spring-data-redis/pom.xml b/spring-data-redis/pom.xml index 25686fca16..6f1fc9294d 100644 --- a/spring-data-redis/pom.xml +++ b/spring-data-redis/pom.xml @@ -12,6 +12,7 @@ 4.2.5.RELEASE 1.6.2.RELEASE 0.8.0 + 2.19.1 @@ -72,5 +73,23 @@ ${nosqlunit.version} - + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + + + + + + + diff --git a/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerTest.java b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java similarity index 95% rename from spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerTest.java rename to spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java index 403cf990e0..01dbfcff4d 100644 --- a/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerTest.java +++ b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java @@ -15,7 +15,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = RedisConfig.class) -public class RedisMessageListenerTest { +public class RedisMessageListenerIntegrationTest { @Autowired private RedisMessagePublisher redisMessagePublisher; diff --git a/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryTest.java b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java similarity index 98% rename from spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryTest.java rename to spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java index c32dfc7670..1028c0bc24 100644 --- a/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryTest.java +++ b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java @@ -15,7 +15,7 @@ import static org.junit.Assert.assertNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = RedisConfig.class) -public class StudentRepositoryTest { +public class StudentRepositoryIntegrationTest { @Autowired private StudentRepository studentRepository; From 278ada7e7f605bd5729ed78c27e611aba8136839 Mon Sep 17 00:00:00 2001 From: Sandeep Kumar Date: Wed, 19 Oct 2016 12:38:32 +0530 Subject: [PATCH 139/193] Default Unit Test changes --- selenium-junit-testng/pom.xml | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml index 9ad601fdcd..861c0b1986 100644 --- a/selenium-junit-testng/pom.xml +++ b/selenium-junit-testng/pom.xml @@ -15,6 +15,18 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + true + + **/*UnitTest.java + + + + @@ -27,9 +39,9 @@ maven-surefire-plugin 2.19.1 - - **/*LiveTest.java - + + **/*LiveTest.java + From 1e4cd5a47c7ad4b5687327786f543861c0a14bed Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 19 Oct 2016 12:56:46 +0200 Subject: [PATCH 140/193] add integration test profile --- spring-data-neo4j/pom.xml | 60 ++++++++++++++++--- ...va => MovieRepositoryIntegrationTest.java} | 4 +- 2 files changed, 55 insertions(+), 9 deletions(-) rename spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/{MovieRepositoryTest.java => MovieRepositoryIntegrationTest.java} (97%) diff --git a/spring-data-neo4j/pom.xml b/spring-data-neo4j/pom.xml index b0cf62ef2e..653dd6b2f6 100644 --- a/spring-data-neo4j/pom.xml +++ b/spring-data-neo4j/pom.xml @@ -13,6 +13,7 @@ UTF-8 3.0.1 4.1.1.RELEASE + 2.19.1 @@ -83,12 +84,57 @@ - - - - maven-compiler-plugin - - - + + + + maven-compiler-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java b/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java similarity index 97% rename from spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java rename to spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java index 0e54208c31..95bc38aafc 100644 --- a/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java +++ b/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java @@ -24,7 +24,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MovieDatabaseNeo4jTestConfiguration.class) @ActiveProfiles(profiles = "test") -public class MovieRepositoryTest { +public class MovieRepositoryIntegrationTest { @Autowired private MovieRepository movieRepository; @@ -32,7 +32,7 @@ public class MovieRepositoryTest { @Autowired private PersonRepository personRepository; - public MovieRepositoryTest() { + public MovieRepositoryIntegrationTest() { } @Before From 890128654bc8f24c3affb9ee5c4b8cbee1acda2e Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 19 Oct 2016 13:15:28 +0200 Subject: [PATCH 141/193] add integration test profile --- spring-data-mongodb/pom.xml | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 102344a3fa..fd212548d0 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -112,9 +112,55 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + UTF-8 @@ -130,6 +176,7 @@ 1.7.12 1.1.3 + 2.19.1 From 496553caaf737ce986b5694fba52326dd478b6a0 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 19 Oct 2016 13:40:56 +0200 Subject: [PATCH 142/193] add integration test profile --- spring-data-elasticsearch/pom.xml | 51 +++++++++++++++++++ ...java => ElasticSearchIntegrationTest.java} | 2 +- ...=> ElasticSearchQueryIntegrationTest.java} | 2 +- 3 files changed, 53 insertions(+), 2 deletions(-) rename spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/{ElasticSearchTest.java => ElasticSearchIntegrationTest.java} (99%) rename spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/{ElasticSearchQueryTest.java => ElasticSearchQueryIntegrationTest.java} (99%) diff --git a/spring-data-elasticsearch/pom.xml b/spring-data-elasticsearch/pom.xml index 42cf8fc740..dcb702ab16 100644 --- a/spring-data-elasticsearch/pom.xml +++ b/spring-data-elasticsearch/pom.xml @@ -20,6 +20,7 @@ 1.7.12 1.1.3 2.0.1.RELEASE + 2.19.1 @@ -86,4 +87,54 @@ + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + \ No newline at end of file diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java similarity index 99% rename from spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java rename to spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java index 863e1e4620..1280c8e1de 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java @@ -29,7 +29,7 @@ import com.baeldung.spring.data.es.service.ArticleService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Config.class) -public class ElasticSearchTest { +public class ElasticSearchIntegrationTest { @Autowired private ElasticsearchTemplate elasticsearchTemplate; diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java similarity index 99% rename from spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java rename to spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java index ddf0ef4dac..cc4bce0c75 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java @@ -42,7 +42,7 @@ import com.baeldung.spring.data.es.service.ArticleService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Config.class) -public class ElasticSearchQueryTest { +public class ElasticSearchQueryIntegrationTest { @Autowired private ElasticsearchTemplate elasticsearchTemplate; From 29ae3bc0102500ca55f3431f6cf3f30b6e553519 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 19 Oct 2016 14:02:32 +0200 Subject: [PATCH 143/193] configure integration test --- spring-data-couchbase-2/pom.xml | 13 ++++++++++++- ... => PersonRepositoryServiceIntegrationTest.java} | 2 +- ...eTest.java => PersonServiceIntegrationTest.java} | 2 +- ...va => PersonTemplateServiceIntegrationTest.java} | 2 +- ...=> StudentRepositoryServiceIntegrationTest.java} | 2 +- ...Test.java => StudentServiceIntegrationTest.java} | 2 +- ...a => StudentTemplateServiceIntegrationTest.java} | 2 +- ...t.java => CampusServiceImplIntegrationTest.java} | 2 +- ...t.java => PersonServiceImplIntegrationTest.java} | 2 +- ....java => StudentServiceImplIntegrationTest.java} | 2 +- 10 files changed, 21 insertions(+), 10 deletions(-) rename spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/{PersonRepositoryServiceTest.java => PersonRepositoryServiceIntegrationTest.java} (78%) rename spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/{PersonServiceTest.java => PersonServiceIntegrationTest.java} (98%) rename spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/{PersonTemplateServiceTest.java => PersonTemplateServiceIntegrationTest.java} (79%) rename spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/{StudentRepositoryServiceTest.java => StudentRepositoryServiceIntegrationTest.java} (78%) rename spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/{StudentServiceTest.java => StudentServiceIntegrationTest.java} (98%) rename spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/{StudentTemplateServiceTest.java => StudentTemplateServiceIntegrationTest.java} (79%) rename spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/{CampusServiceImplTest.java => CampusServiceImplIntegrationTest.java} (98%) rename spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/{PersonServiceImplTest.java => PersonServiceImplIntegrationTest.java} (98%) rename spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/{StudentServiceImplTest.java => StudentServiceImplIntegrationTest.java} (98%) diff --git a/spring-data-couchbase-2/pom.xml b/spring-data-couchbase-2/pom.xml index d24ef4aeaa..6716f82246 100644 --- a/spring-data-couchbase-2/pom.xml +++ b/spring-data-couchbase-2/pom.xml @@ -86,6 +86,17 @@ 1.7 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + @@ -99,7 +110,7 @@ 1.1.3 1.7.12 4.11 - + 2.19.1 diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceIntegrationTest.java similarity index 78% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceIntegrationTest.java index ce5cf7667d..d710e57def 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceIntegrationTest.java @@ -3,7 +3,7 @@ package org.baeldung.spring.data.couchbase.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -public class PersonRepositoryServiceTest extends PersonServiceTest { +public class PersonRepositoryServiceIntegrationTest extends PersonServiceIntegrationTest { @Autowired @Qualifier("PersonRepositoryService") diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceIntegrationTest.java similarity index 98% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceIntegrationTest.java index c3bf9f2138..4044183849 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceIntegrationTest.java @@ -20,7 +20,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public abstract class PersonServiceTest extends IntegrationTest { +public abstract class PersonServiceIntegrationTest extends IntegrationTest { static final String typeField = "_class"; static final String john = "John"; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceIntegrationTest.java similarity index 79% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceIntegrationTest.java index 0238fa21fb..e19df8fc84 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceIntegrationTest.java @@ -3,7 +3,7 @@ package org.baeldung.spring.data.couchbase.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -public class PersonTemplateServiceTest extends PersonServiceTest { +public class PersonTemplateServiceIntegrationTest extends PersonServiceIntegrationTest { @Autowired @Qualifier("PersonTemplateService") diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceIntegrationTest.java similarity index 78% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceIntegrationTest.java index 040453fd73..3b3f2a531a 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceIntegrationTest.java @@ -3,7 +3,7 @@ package org.baeldung.spring.data.couchbase.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -public class StudentRepositoryServiceTest extends StudentServiceTest { +public class StudentRepositoryServiceIntegrationTest extends StudentServiceIntegrationTest { @Autowired @Qualifier("StudentRepositoryService") diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceIntegrationTest.java similarity index 98% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceIntegrationTest.java index 0bf2c5d673..fba549a9e5 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceIntegrationTest.java @@ -22,7 +22,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public abstract class StudentServiceTest extends IntegrationTest { +public abstract class StudentServiceIntegrationTest extends IntegrationTest { static final String typeField = "_class"; static final String joe = "Joe"; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceIntegrationTest.java similarity index 79% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceIntegrationTest.java index dd5be8e059..29fd605bc6 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceIntegrationTest.java @@ -3,7 +3,7 @@ package org.baeldung.spring.data.couchbase.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -public class StudentTemplateServiceTest extends StudentServiceTest { +public class StudentTemplateServiceIntegrationTest extends StudentServiceIntegrationTest { @Autowired @Qualifier("StudentTemplateService") diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java similarity index 98% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java index d3982e1ecc..71648cf59b 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java @@ -18,7 +18,7 @@ import org.springframework.data.geo.Distance; import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Point; -public class CampusServiceImplTest extends MultiBucketIntegationTest { +public class CampusServiceImplIntegrationTest extends MultiBucketIntegationTest { @Autowired private CampusServiceImpl campusService; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java similarity index 98% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java index e1a880d9da..819798d536 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java @@ -21,7 +21,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class PersonServiceImplTest extends MultiBucketIntegationTest { +public class PersonServiceImplIntegrationTest extends MultiBucketIntegationTest { static final String typeField = "_class"; static final String john = "John"; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java similarity index 98% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java index c503726377..f37f11744d 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java @@ -23,7 +23,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class StudentServiceImplTest extends MultiBucketIntegationTest { +public class StudentServiceImplIntegrationTest extends MultiBucketIntegationTest { static final String typeField = "_class"; static final String joe = "Joe"; From 7d59175bb6969b3e43e373de06a315d8e0f4f95d Mon Sep 17 00:00:00 2001 From: maibin Date: Wed, 19 Oct 2016 16:19:08 +0200 Subject: [PATCH 144/193] Executable WAR (#757) * Expression-Based Access Control PermitAll, hasRole, hasAnyRole etc. I modified classes regards to Security * Added test cases for Spring Security Expressions * Handler Interceptor - logging example * Test for logger interceptor * Removed conflicted part * UserInterceptor (adding user information to model) * Spring Handler Interceptor - session timers * Spring Security CSRF attack protection with Thymeleaf * Fix and(); * Logger update * Changed config for Thymeleaf * Thymeleaf Natural Processing and Inlining * Expression Utility Objects, Thymeleaf * listOfStudents edited * Thymeleaf layout decorators * Executable Jar with Maven * Maven War executable --- spring-thymeleaf/pom.xml | 113 ++++++++++++++++++++++++++------------- 1 file changed, 76 insertions(+), 37 deletions(-) diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index d2b3be1651..e59ce77e57 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -166,47 +166,86 @@ ${maven-surefire-plugin.version} - **/*IntegrationTest.java - **/*LiveTest.java + **/*IntegrationTest.java + **/*LiveTest.java - + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + 8082 + + + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.0 + + + tomcat-run + + exec-war-only + + package + + / + false + webapp.jar + utf-8 + + + + - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + From 09825ca25ad14739a27213e341a9f8b9fa59ae95 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 19 Oct 2016 16:25:35 +0200 Subject: [PATCH 145/193] add integration test profile --- spring-data-cassandra/pom.xml | 51 +++++++++++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/spring-data-cassandra/pom.xml b/spring-data-cassandra/pom.xml index e5f8779942..5c1a42b8bd 100644 --- a/spring-data-cassandra/pom.xml +++ b/spring-data-cassandra/pom.xml @@ -23,6 +23,7 @@ 2.1.9.2 2.1.9.2 2.0-0 + 2.19.1 @@ -108,6 +109,52 @@ 1.7 - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + From e4f1be2daa87bdbd1c212d7de905c87ac3004667 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 19 Oct 2016 16:45:26 +0200 Subject: [PATCH 146/193] add integration test profile --- spring-cucumber/pom.xml | 52 +++++++++++++++++-- ...Test.java => CucumberIntegrationTest.java} | 2 +- ...efs.java => OtherDefsIntegrationTest.java} | 2 +- ...Defs.java => StepDefsIntegrationTest.java} | 2 +- 4 files changed, 52 insertions(+), 6 deletions(-) rename spring-cucumber/src/test/java/com/baeldung/{CucumberTest.java => CucumberIntegrationTest.java} (83%) rename spring-cucumber/src/test/java/com/baeldung/{OtherDefs.java => OtherDefsIntegrationTest.java} (85%) rename spring-cucumber/src/test/java/com/baeldung/{StepDefs.java => StepDefsIntegrationTest.java} (93%) diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index f3b9c983f0..b493962a75 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -73,17 +73,63 @@ - - - + + + org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-cucumber/src/test/java/com/baeldung/CucumberTest.java b/spring-cucumber/src/test/java/com/baeldung/CucumberIntegrationTest.java similarity index 83% rename from spring-cucumber/src/test/java/com/baeldung/CucumberTest.java rename to spring-cucumber/src/test/java/com/baeldung/CucumberIntegrationTest.java index c31a35b271..56eb810c09 100644 --- a/spring-cucumber/src/test/java/com/baeldung/CucumberTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/CucumberIntegrationTest.java @@ -6,5 +6,5 @@ import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions(features = "src/test/resources") -public class CucumberTest { +public class CucumberIntegrationTest { } \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/OtherDefs.java b/spring-cucumber/src/test/java/com/baeldung/OtherDefsIntegrationTest.java similarity index 85% rename from spring-cucumber/src/test/java/com/baeldung/OtherDefs.java rename to spring-cucumber/src/test/java/com/baeldung/OtherDefsIntegrationTest.java index edbc14f319..17f298c3fb 100644 --- a/spring-cucumber/src/test/java/com/baeldung/OtherDefs.java +++ b/spring-cucumber/src/test/java/com/baeldung/OtherDefsIntegrationTest.java @@ -3,7 +3,7 @@ package com.baeldung; import cucumber.api.java.en.Given; import cucumber.api.java.en.When; -public class OtherDefs extends SpringIntegrationTest { +public class OtherDefsIntegrationTest extends SpringIntegrationTest { @When("^the client calls /baeldung$") public void the_client_issues_POST_hello() throws Throwable { executePost("http://localhost:8080/baeldung"); diff --git a/spring-cucumber/src/test/java/com/baeldung/StepDefs.java b/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java similarity index 93% rename from spring-cucumber/src/test/java/com/baeldung/StepDefs.java rename to spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java index 865a1e13fa..8220d5e861 100644 --- a/spring-cucumber/src/test/java/com/baeldung/StepDefs.java +++ b/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java @@ -9,7 +9,7 @@ import cucumber.api.java.en.And; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; -public class StepDefs extends SpringIntegrationTest { +public class StepDefsIntegrationTest extends SpringIntegrationTest { @When("^the client calls /version$") public void the_client_issues_GET_version() throws Throwable { From 72bdf6c2be5671079e7959683a051523177c554e Mon Sep 17 00:00:00 2001 From: Thai Nguyen Date: Wed, 19 Oct 2016 22:27:02 +0700 Subject: [PATCH 147/193] Changes HTTP request handling methods, adds negative test cases --- .../cxf/jaxrs/implementation/Baeldung.java | 17 +++--- .../cxf/jaxrs/implementation/Course.java | 34 ++++++++---- .../cxf/jaxrs/implementation/Student.java | 10 ++++ .../src/main/resources/changed_course.xml | 4 ++ .../src/main/resources/conflict_student.xml | 4 ++ .../{student.xml => created_student.xml} | 1 - .../{course.xml => non_existent_course.xml} | 0 .../src/main/resources/unchanged_course.xml | 4 ++ .../cxf/jaxrs/implementation/ServiceTest.java | 54 ++++++++++++++++--- 9 files changed, 101 insertions(+), 27 deletions(-) create mode 100644 apache-cxf/cxf-jaxrs-implementation/src/main/resources/changed_course.xml create mode 100644 apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml rename apache-cxf/cxf-jaxrs-implementation/src/main/resources/{student.xml => created_student.xml} (82%) rename apache-cxf/cxf-jaxrs-implementation/src/main/resources/{course.xml => non_existent_course.xml} (100%) create mode 100644 apache-cxf/cxf-jaxrs-implementation/src/main/resources/unchanged_course.xml diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java index 592df4b7c3..39872f4e32 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java @@ -44,15 +44,16 @@ public class Baeldung { @PUT @Path("courses/{courseOrder}") - public Response putCourse(@PathParam("courseOrder") int courseOrder, Course course) { - Course existingCourse = courses.get(courseOrder); - - if (existingCourse == null || existingCourse.getId() != course.getId() || !(existingCourse.getName().equals(course.getName()))) { - courses.put(courseOrder, course); - return Response.ok().build(); + public Response updateCourse(@PathParam("courseOrder") int courseOrder, Course course) { + Course existingCourse = courses.get(courseOrder); + if (existingCourse == null) { + return Response.status(Response.Status.NOT_FOUND).build(); } - - return Response.notModified().build(); + if (existingCourse.equals(course)) { + return Response.notModified().build(); + } + courses.put(courseOrder, course); + return Response.ok().build(); } @Path("courses/{courseOrder}/students") diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java index 32689a332f..efb7191290 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java @@ -3,6 +3,7 @@ package com.baeldung.cxf.jaxrs.implementation; import javax.ws.rs.*; import javax.ws.rs.core.Response; import javax.xml.bind.annotation.XmlRootElement; + import java.util.ArrayList; import java.util.List; @@ -35,31 +36,42 @@ public class Course { public void setStudents(List students) { this.students = students; } - + @GET @Path("{studentOrder}") - public Student getStudent(@PathParam("studentOrder")int studentOrder) { + public Student getStudent(@PathParam("studentOrder") int studentOrder) { return students.get(studentOrder); } - + @POST - public Response postStudent(Student student) { + public Response createStudent(Student student) { if (students == null) { students = new ArrayList<>(); } + if (students.contains(student)) { + return Response.status(Response.Status.CONFLICT).build(); + } students.add(student); return Response.ok(student).build(); } - + @DELETE @Path("{studentOrder}") public Response deleteStudent(@PathParam("studentOrder") int studentOrder) { - Student student = students.get(studentOrder); - if (student != null) { - students.remove(studentOrder); - return Response.ok().build(); - } else { - return Response.notModified().build(); + if (students == null || studentOrder >= students.size()) { + return Response.status(Response.Status.NOT_FOUND).build(); } + students.remove(studentOrder); + return Response.ok().build(); + } + + @Override + public int hashCode() { + return id + name.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return (obj instanceof Course) && (id == ((Course) obj).getId()) && (name.equals(((Course) obj).getName())); } } \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java index de782e4edb..bd3dad0f5e 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java @@ -22,4 +22,14 @@ public class Student { public void setName(String name) { this.name = name; } + + @Override + public int hashCode() { + return id + name.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return (obj instanceof Student) && (id == ((Student) obj).getId()) && (name.equals(((Student) obj).getName())); + } } \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/changed_course.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/changed_course.xml new file mode 100644 index 0000000000..097cf2ce58 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/changed_course.xml @@ -0,0 +1,4 @@ + + 2 + Apache CXF Support for RESTful + \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml new file mode 100644 index 0000000000..ccf97edb2e --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml @@ -0,0 +1,4 @@ + + 1 + Student A + \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/student.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/created_student.xml similarity index 82% rename from apache-cxf/cxf-jaxrs-implementation/src/main/resources/student.xml rename to apache-cxf/cxf-jaxrs-implementation/src/main/resources/created_student.xml index 7fb6189815..068c9dae4b 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/student.xml +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/created_student.xml @@ -1,4 +1,3 @@ - 3 Student C diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/course.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/non_existent_course.xml similarity index 100% rename from apache-cxf/cxf-jaxrs-implementation/src/main/resources/course.xml rename to apache-cxf/cxf-jaxrs-implementation/src/main/resources/non_existent_course.xml diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/unchanged_course.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/unchanged_course.xml new file mode 100644 index 0000000000..5936fdc094 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/unchanged_course.xml @@ -0,0 +1,4 @@ + + 1 + REST with Spring + \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java index 8c606436c8..8d06518df2 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java @@ -34,24 +34,57 @@ public class ServiceTest { } @Test - public void whenPutCourse_thenCorrect() throws IOException { + public void whenUpdateNonExistentCourse_thenReceiveNotFoundResponse() throws IOException { HttpPut httpPut = new HttpPut(BASE_URL + "3"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("course.xml"); + InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("non_existent_course.xml"); + httpPut.setEntity(new InputStreamEntity(resourceStream)); + httpPut.setHeader("Content-Type", "text/xml"); + + HttpResponse response = client.execute(httpPut); + assertEquals(404, response.getStatusLine().getStatusCode()); + } + + @Test + public void whenUpdateUnchangedCourse_thenReceiveNotModifiedResponse() throws IOException { + HttpPut httpPut = new HttpPut(BASE_URL + "1"); + InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("unchanged_course.xml"); + httpPut.setEntity(new InputStreamEntity(resourceStream)); + httpPut.setHeader("Content-Type", "text/xml"); + + HttpResponse response = client.execute(httpPut); + assertEquals(304, response.getStatusLine().getStatusCode()); + } + + @Test + public void whenUpdateValidCourse_thenReceiveOKResponse() throws IOException { + HttpPut httpPut = new HttpPut(BASE_URL + "2"); + InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("changed_course.xml"); httpPut.setEntity(new InputStreamEntity(resourceStream)); httpPut.setHeader("Content-Type", "text/xml"); HttpResponse response = client.execute(httpPut); assertEquals(200, response.getStatusLine().getStatusCode()); - Course course = getCourse(3); - assertEquals(3, course.getId()); + Course course = getCourse(2); + assertEquals(2, course.getId()); assertEquals("Apache CXF Support for RESTful", course.getName()); } + + @Test + public void whenCreateConflictStudent_thenReceiveConflictResponse() throws IOException { + HttpPost httpPost = new HttpPost(BASE_URL + "1/students"); + InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("conflict_student.xml"); + httpPost.setEntity(new InputStreamEntity(resourceStream)); + httpPost.setHeader("Content-Type", "text/xml"); + + HttpResponse response = client.execute(httpPost); + assertEquals(409, response.getStatusLine().getStatusCode()); + } @Test - public void whenPostStudent_thenCorrect() throws IOException { + public void whenCreateValidStudent_thenReceiveOKResponse() throws IOException { HttpPost httpPost = new HttpPost(BASE_URL + "2/students"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("student.xml"); + InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("created_student.xml"); httpPost.setEntity(new InputStreamEntity(resourceStream)); httpPost.setHeader("Content-Type", "text/xml"); @@ -64,7 +97,14 @@ public class ServiceTest { } @Test - public void whenDeleteStudent_thenCorrect() throws IOException { + public void whenDeleteInvalidStudent_thenReceiveNotFoundResponse() throws IOException { + HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/2"); + HttpResponse response = client.execute(httpDelete); + assertEquals(404, response.getStatusLine().getStatusCode()); + } + + @Test + public void whenDeleteValidStudent_thenReceiveOKResponse() throws IOException { HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/0"); HttpResponse response = client.execute(httpDelete); assertEquals(200, response.getStatusLine().getStatusCode()); From 15ab6c6326927cdb3fc0d3f81cf90335aa4f9f28 Mon Sep 17 00:00:00 2001 From: Thai Nguyen Date: Thu, 20 Oct 2016 16:41:38 +0700 Subject: [PATCH 148/193] Changes order parameter to id --- .../cxf/jaxrs/implementation/Baeldung.java | 31 ++++++++++++------- .../cxf/jaxrs/implementation/Course.java | 29 ++++++++++------- .../src/main/resources/conflict_student.xml | 4 +-- .../cxf/jaxrs/implementation/ServiceTest.java | 6 ++-- 4 files changed, 43 insertions(+), 27 deletions(-) diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java index 39872f4e32..9dd63cf3ac 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java @@ -37,27 +37,36 @@ public class Baeldung { } @GET - @Path("courses/{courseOrder}") - public Course getCourse(@PathParam("courseOrder") int courseOrder) { - return courses.get(courseOrder); + @Path("courses/{courseId}") + public Course getCourse(@PathParam("courseId") int courseId) { + return findById(courseId); } @PUT - @Path("courses/{courseOrder}") - public Response updateCourse(@PathParam("courseOrder") int courseOrder, Course course) { - Course existingCourse = courses.get(courseOrder); + @Path("courses/{courseId}") + public Response updateCourse(@PathParam("courseId") int courseId, Course course) { + Course existingCourse = findById(courseId); if (existingCourse == null) { return Response.status(Response.Status.NOT_FOUND).build(); } if (existingCourse.equals(course)) { - return Response.notModified().build(); + return Response.notModified().build(); } - courses.put(courseOrder, course); + courses.put(courseId, course); return Response.ok().build(); } - @Path("courses/{courseOrder}/students") - public Course pathToStudent(@PathParam("courseOrder") int courseOrder) { - return courses.get(courseOrder); + @Path("courses/{courseId}/students") + public Course pathToStudent(@PathParam("courseId") int courseId) { + return findById(courseId); + } + + private Course findById(int id) { + for (Map.Entry course : courses.entrySet()) { + if (course.getKey() == id) { + return course.getValue(); + } + } + return null; } } \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java index efb7191290..dfbe8eef1d 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java @@ -11,7 +11,7 @@ import java.util.List; public class Course { private int id; private String name; - private List students; + private List students = new ArrayList<>(); public int getId() { return id; @@ -38,16 +38,13 @@ public class Course { } @GET - @Path("{studentOrder}") - public Student getStudent(@PathParam("studentOrder") int studentOrder) { - return students.get(studentOrder); + @Path("{studentId}") + public Student getStudent(@PathParam("studentId") int studentId) { + return findById(studentId); } @POST public Response createStudent(Student student) { - if (students == null) { - students = new ArrayList<>(); - } if (students.contains(student)) { return Response.status(Response.Status.CONFLICT).build(); } @@ -56,14 +53,24 @@ public class Course { } @DELETE - @Path("{studentOrder}") - public Response deleteStudent(@PathParam("studentOrder") int studentOrder) { - if (students == null || studentOrder >= students.size()) { + @Path("{studentId}") + public Response deleteStudent(@PathParam("studentId") int studentId) { + Student student = findById(studentId); + if (student == null) { return Response.status(Response.Status.NOT_FOUND).build(); } - students.remove(studentOrder); + students.remove(student); return Response.ok().build(); } + + private Student findById(int id) { + for (Student student : students) { + if (student.getId() == id) { + return student; + } + } + return null; + } @Override public int hashCode() { diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml index ccf97edb2e..7d083dbdc9 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml @@ -1,4 +1,4 @@ - 1 - Student A + 2 + Student B \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java index 8d06518df2..b8fc833194 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java @@ -91,21 +91,21 @@ public class ServiceTest { HttpResponse response = client.execute(httpPost); assertEquals(200, response.getStatusLine().getStatusCode()); - Student student = getStudent(2, 0); + Student student = getStudent(2, 3); assertEquals(3, student.getId()); assertEquals("Student C", student.getName()); } @Test public void whenDeleteInvalidStudent_thenReceiveNotFoundResponse() throws IOException { - HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/2"); + HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/3"); HttpResponse response = client.execute(httpDelete); assertEquals(404, response.getStatusLine().getStatusCode()); } @Test public void whenDeleteValidStudent_thenReceiveOKResponse() throws IOException { - HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/0"); + HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/1"); HttpResponse response = client.execute(httpDelete); assertEquals(200, response.getStatusLine().getStatusCode()); From 4d54080b3ec57559b0c1d842fcb885a23340f3c5 Mon Sep 17 00:00:00 2001 From: Nikhil Khatwani Date: Thu, 20 Oct 2016 16:00:31 +0530 Subject: [PATCH 149/193] Fixed Failing EchoTest --- .../java/nio/selector/EchoServer.java | 26 ++++++++++++++----- .../baeldung/java/nio/selector/EchoTest.java | 7 +++-- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java index aedcbb319b..285d4e51fc 100644 --- a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java @@ -1,14 +1,15 @@ package com.baeldung.java.nio.selector; +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; -import java.nio.channels.Selector; -import java.nio.channels.SelectionKey; -import java.nio.ByteBuffer; -import java.io.IOException; -import java.util.Set; import java.util.Iterator; -import java.net.InetSocketAddress; +import java.util.Set; public class EchoServer { @@ -47,4 +48,15 @@ public class EchoServer { } } } -} + + public static Process start() throws IOException, InterruptedException { + String javaHome = System.getProperty("java.home"); + String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; + String classpath = System.getProperty("java.class.path"); + String className = EchoServer.class.getCanonicalName(); + + ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className); + + return builder.start(); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java b/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java index 63da2fe2bf..d1ac6df5e4 100644 --- a/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java @@ -2,17 +2,20 @@ package com.baeldung.java.nio.selector; import static org.junit.Assert.assertEquals; +import java.io.IOException; + import org.junit.Test; public class EchoTest { @Test - public void givenClient_whenServerEchosMessage_thenCorrect() { + public void givenClient_whenServerEchosMessage_thenCorrect() throws IOException, InterruptedException { + Process process = EchoServer.start(); EchoClient client = EchoClient.start(); String resp1 = client.sendMessage("hello"); String resp2 = client.sendMessage("world"); assertEquals("hello", resp1); assertEquals("world", resp2); + process.destroy(); } - } From b6e9223fed08d43d78241020b39f8b01d9507aa9 Mon Sep 17 00:00:00 2001 From: Thai Nguyen Date: Thu, 20 Oct 2016 17:47:34 +0700 Subject: [PATCH 150/193] Refactors Apache CXF support for REST --- .../com/baeldung/cxf/jaxrs/implementation/Course.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java index dfbe8eef1d..dba9b9c661 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java @@ -45,8 +45,10 @@ public class Course { @POST public Response createStudent(Student student) { - if (students.contains(student)) { - return Response.status(Response.Status.CONFLICT).build(); + for (Student element : students) { + if (element.getId() == student.getId()) { + return Response.status(Response.Status.CONFLICT).build(); + } } students.add(student); return Response.ok(student).build(); @@ -62,7 +64,7 @@ public class Course { students.remove(student); return Response.ok().build(); } - + private Student findById(int id) { for (Student student : students) { if (student.getId() == id) { From 017dc13db1ebf30907a7cb05b42b619a765803fd Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 20 Oct 2016 13:44:16 +0200 Subject: [PATCH 151/193] add integration test profile --- spring-boot/pom.xml | 46 +++++++++++++++++++ ...ebjarsdemoApplicationIntegrationTest.java} | 2 +- ...Test.java => CommitIdIntegrationTest.java} | 4 +- ...SpringBootApplicationIntegrationTest.java} | 2 +- ...java => SpringBootJPAIntegrationTest.java} | 2 +- ...ava => SpringBootMailIntegrationTest.java} | 2 +- ...s.java => ApplicationIntegrationTest.java} | 2 +- ...va => DemoApplicationIntegrationTest.java} | 2 +- ...java => FooRepositoryIntegrationTest.java} | 4 +- ...a => HibernateSessionIntegrationTest.java} | 4 +- ...=> NoHibernateSessionIntegrationTest.java} | 4 +- ... DetailsServiceClientIntegrationTest.java} | 2 +- .../data-flow-shell/spring-shell.log | 1 + 13 files changed, 62 insertions(+), 15 deletions(-) rename spring-boot/src/test/java/com/baeldung/{WebjarsdemoApplicationTests.java => WebjarsdemoApplicationIntegrationTest.java} (89%) rename spring-boot/src/test/java/com/baeldung/git/{CommitIdTest.java => CommitIdIntegrationTest.java} (93%) rename spring-boot/src/test/java/org/baeldung/{SpringBootApplicationTest.java => SpringBootApplicationIntegrationTest.java} (97%) rename spring-boot/src/test/java/org/baeldung/{SpringBootJPATest.java => SpringBootJPAIntegrationTest.java} (95%) rename spring-boot/src/test/java/org/baeldung/{SpringBootMailTest.java => SpringBootMailIntegrationTest.java} (98%) rename spring-boot/src/test/java/org/baeldung/boot/{ApplicationTests.java => ApplicationIntegrationTest.java} (92%) rename spring-boot/src/test/java/org/baeldung/boot/{DemoApplicationTests.java => DemoApplicationIntegrationTest.java} (90%) rename spring-boot/src/test/java/org/baeldung/boot/repository/{FooRepositoryTest.java => FooRepositoryIntegrationTest.java} (84%) rename spring-boot/src/test/java/org/baeldung/boot/repository/{HibernateSessionTest.java => HibernateSessionIntegrationTest.java} (88%) rename spring-boot/src/test/java/org/baeldung/boot/repository/{NoHibernateSessionTest.java => NoHibernateSessionIntegrationTest.java} (81%) rename spring-boot/src/test/java/org/baeldung/client/{DetailsServiceClientTest.java => DetailsServiceClientIntegrationTest.java} (96%) create mode 100644 spring-cloud-data-flow/data-flow-shell/spring-shell.log diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 5281b9b2c0..a2555259b0 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -133,10 +133,56 @@ 2.2.1 + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + spring-snapshots diff --git a/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java b/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationIntegrationTest.java similarity index 89% rename from spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java rename to spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationIntegrationTest.java index c43b13ea0b..3558682b97 100644 --- a/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java +++ b/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = WebjarsdemoApplication.class) @WebAppConfiguration -public class WebjarsdemoApplicationTests { +public class WebjarsdemoApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java b/spring-boot/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java similarity index 93% rename from spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java rename to spring-boot/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java index c0fc1befd3..348d594c05 100644 --- a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java +++ b/spring-boot/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java @@ -12,9 +12,9 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @ContextConfiguration(classes = CommitIdApplication.class) -public class CommitIdTest { +public class CommitIdIntegrationTest { - private static final Logger LOG = LoggerFactory.getLogger(CommitIdTest.class); + private static final Logger LOG = LoggerFactory.getLogger(CommitIdIntegrationTest.class); @Value("${git.commit.message.short:UNKNOWN}") private String commitMessage; diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java similarity index 97% rename from spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java rename to spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java index 1255180e44..3c5444942c 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java @@ -26,7 +26,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration -public class SpringBootApplicationTest { +public class SpringBootApplicationIntegrationTest { @Autowired private WebApplicationContext webApplicationContext; private MockMvc mockMvc; diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootJPATest.java b/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java similarity index 95% rename from spring-boot/src/test/java/org/baeldung/SpringBootJPATest.java rename to spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java index 8a6b5139fe..233684bc24 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootJPATest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java @@ -13,7 +13,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) -public class SpringBootJPATest { +public class SpringBootJPAIntegrationTest { @Autowired private GenericEntityRepository genericEntityRepository; diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java similarity index 98% rename from spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java rename to spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java index f4ce158661..cec25f20f9 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java @@ -24,7 +24,7 @@ import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) -public class SpringBootMailTest { +public class SpringBootMailIntegrationTest { @Autowired private JavaMailSender javaMailSender; diff --git a/spring-boot/src/test/java/org/baeldung/boot/ApplicationTests.java b/spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java similarity index 92% rename from spring-boot/src/test/java/org/baeldung/boot/ApplicationTests.java rename to spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java index 7911465048..57a8abc1ee 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/ApplicationTests.java +++ b/spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java @@ -10,7 +10,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) @TestPropertySource("classpath:exception.properties") -public class ApplicationTests { +public class ApplicationIntegrationTest { @Test public void contextLoads() { } diff --git a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationTests.java b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java similarity index 90% rename from spring-boot/src/test/java/org/baeldung/boot/DemoApplicationTests.java rename to spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java index 7f9b2ba912..4fcea35b4a 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationTests.java +++ b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = DemoApplication.class) @WebAppConfiguration -public class DemoApplicationTests { +public class DemoApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java similarity index 84% rename from spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryTest.java rename to spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java index 9de7790a75..a844b26b2d 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java @@ -2,7 +2,7 @@ package org.baeldung.boot.repository; import static org.junit.Assert.assertThat; -import org.baeldung.boot.DemoApplicationTests; +import org.baeldung.boot.DemoApplicationIntegrationTest; import org.baeldung.boot.model.Foo; import static org.hamcrest.Matchers.notNullValue; @@ -14,7 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @Transactional -public class FooRepositoryTest extends DemoApplicationTests { +public class FooRepositoryIntegrationTest extends DemoApplicationIntegrationTest { @Autowired private FooRepository fooRepository; diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java similarity index 88% rename from spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionTest.java rename to spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java index 4cb1b60cde..be992bcc36 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java @@ -4,7 +4,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; -import org.baeldung.boot.ApplicationTests; +import org.baeldung.boot.ApplicationIntegrationTest; import org.baeldung.boot.model.Foo; import org.baeldung.session.exception.repository.FooRepository; import org.junit.Test; @@ -14,7 +14,7 @@ import org.springframework.transaction.annotation.Transactional; @Transactional @TestPropertySource("classpath:exception-hibernate.properties") -public class HibernateSessionTest extends ApplicationTests { +public class HibernateSessionIntegrationTest extends ApplicationIntegrationTest { @Autowired private FooRepository fooRepository; diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java similarity index 81% rename from spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionTest.java rename to spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java index 5f5a49841a..55b7fa7216 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java @@ -1,6 +1,6 @@ package org.baeldung.boot.repository; -import org.baeldung.boot.ApplicationTests; +import org.baeldung.boot.ApplicationIntegrationTest; import org.baeldung.boot.model.Foo; import org.baeldung.session.exception.repository.FooRepository; import org.hibernate.HibernateException; @@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @Transactional -public class NoHibernateSessionTest extends ApplicationTests { +public class NoHibernateSessionIntegrationTest extends ApplicationIntegrationTest { @Autowired private FooRepository fooRepository; diff --git a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java similarity index 96% rename from spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java rename to spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java index ba0da968ad..5627855aa3 100644 --- a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java +++ b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java @@ -16,7 +16,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat @RunWith(SpringRunner.class) @RestClientTest(DetailsServiceClient.class) -public class DetailsServiceClientTest { +public class DetailsServiceClientIntegrationTest { @Autowired private DetailsServiceClient client; diff --git a/spring-cloud-data-flow/data-flow-shell/spring-shell.log b/spring-cloud-data-flow/data-flow-shell/spring-shell.log new file mode 100644 index 0000000000..d497215e2a --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/spring-shell.log @@ -0,0 +1 @@ +// dataflow 1.2.0.RELEASE log opened at 2016-10-20 13:13:20 From a4f8b50c4f6a1e95a88e991459fa3f07419f28a8 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 20 Oct 2016 13:49:04 +0200 Subject: [PATCH 152/193] add integration test profile --- spring-autowire/pom.xml | 41 +++++++++++++++++++ ...st.java => FooServiceIntegrationTest.java} | 2 +- 2 files changed, 42 insertions(+), 1 deletion(-) rename spring-autowire/src/test/java/com/baeldung/autowire/sample/{FooServiceTest.java => FooServiceIntegrationTest.java} (94%) diff --git a/spring-autowire/pom.xml b/spring-autowire/pom.xml index e28efdae61..fd03c77605 100644 --- a/spring-autowire/pom.xml +++ b/spring-autowire/pom.xml @@ -57,7 +57,48 @@ org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java b/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceIntegrationTest.java similarity index 94% rename from spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java rename to spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceIntegrationTest.java index 50e89fcc55..34ba7902ca 100644 --- a/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java +++ b/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceIntegrationTest.java @@ -10,7 +10,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class) -public class FooServiceTest { +public class FooServiceIntegrationTest { @Autowired FooService fooService; From 5a0c407987dfd93eb6672170c7665b3f850bb005 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 20 Oct 2016 14:14:55 +0200 Subject: [PATCH 153/193] add integration test profile --- spring-all/pom.xml | 58 ++++++++++++------- ...syncAnnotationExampleIntegrationTest.java} | 2 +- ....java => AsyncWithXMLIntegrationTest.java} | 2 +- ... ControllerAnnotationIntegrationTest.java} | 2 +- ...st.java => ControllerIntegrationTest.java} | 2 +- ... DataAccessAnnotationIntegrationTest.java} | 2 +- ...taAccessFieldCallbackIntegrationTest.java} | 2 +- ...t.java => EmployeeDAOIntegrationTest.java} | 2 +- ...ProfileWithAnnotationIntegrationTest.java} | 2 +- ...ProfileWithAnnotationIntegrationTest.java} | 2 +- ...PlaceHolderPropertiesIntegrationTest.java} | 2 +- ...pertySourcePropertiesIntegrationTest.java} | 2 +- ...uledAnnotationExampleIntegrationTest.java} | 2 +- ...hedulingWithXmlConfigIntegrationTest.java} | 2 +- ...> AttributeAnnotationIntegrationTest.java} | 2 +- ...a => CacheRefinementsIntegrationTest.java} | 2 +- ...va => ComposedMappingIntegrationTest.java} | 2 +- ...nConstructorInjectionIntegrationTest.java} | 2 +- ...> ImplicitConstructorIntegrationTest.java} | 2 +- ...faultMethodsInjectionIntegrationTest.java} | 2 +- ...java => TransactionalIntegrationTest.java} | 2 +- ...ava => ObjectProviderIntegrationTest.java} | 2 +- ...a => ScopeAnnotationsIntegrationTest.java} | 2 +- ...ousCustomSpringEventsIntegrationTest.java} | 2 +- ...textRefreshedListenerIntegrationTest.java} | 2 +- ...ousCustomSpringEventsIntegrationTest.java} | 2 +- ...java => SpringStartupIntegrationTest.java} | 2 +- ...pringStartupXMLConfigIntegrationTest.java} | 2 +- 28 files changed, 63 insertions(+), 49 deletions(-) rename spring-all/src/test/java/org/baeldung/async/{AsyncAnnotationExampleTest.java => AsyncAnnotationExampleIntegrationTest.java} (97%) rename spring-all/src/test/java/org/baeldung/async/{AsyncWithXMLTest.java => AsyncWithXMLIntegrationTest.java} (95%) rename spring-all/src/test/java/org/baeldung/controller/{ControllerAnnotationTest.java => ControllerAnnotationIntegrationTest.java} (95%) rename spring-all/src/test/java/org/baeldung/controller/{ControllerTest.java => ControllerIntegrationTest.java} (98%) rename spring-all/src/test/java/org/baeldung/customannotation/{DataAccessAnnotationTest.java => DataAccessAnnotationIntegrationTest.java} (97%) rename spring-all/src/test/java/org/baeldung/customannotation/{DataAccessFieldCallbackTest.java => DataAccessFieldCallbackIntegrationTest.java} (97%) rename spring-all/src/test/java/org/baeldung/jdbc/{EmployeeDAOTest.java => EmployeeDAOIntegrationTest.java} (99%) rename spring-all/src/test/java/org/baeldung/profiles/{DevProfileWithAnnotationTest.java => DevProfileWithAnnotationIntegrationTest.java} (93%) rename spring-all/src/test/java/org/baeldung/profiles/{ProductionProfileWithAnnotationTest.java => ProductionProfileWithAnnotationIntegrationTest.java} (94%) rename spring-all/src/test/java/org/baeldung/properties/parentchild/{ParentChildPropertyPlaceHolderPropertiesTest.java => ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java} (96%) rename spring-all/src/test/java/org/baeldung/properties/parentchild/{ParentChildPropertySourcePropertiesTest.java => ParentChildPropertySourcePropertiesIntegrationTest.java} (96%) rename spring-all/src/test/java/org/baeldung/scheduling/{ScheduledAnnotationExampleTest.java => ScheduledAnnotationExampleIntegrationTest.java} (90%) rename spring-all/src/test/java/org/baeldung/scheduling/{SchedulingWithXmlConfigTest.java => SchedulingWithXmlConfigIntegrationTest.java} (89%) rename spring-all/src/test/java/org/baeldung/spring43/attributeannotations/{AttributeAnnotationTest.java => AttributeAnnotationIntegrationTest.java} (94%) rename spring-all/src/test/java/org/baeldung/spring43/cache/{CacheRefinementsTest.java => CacheRefinementsIntegrationTest.java} (92%) rename spring-all/src/test/java/org/baeldung/spring43/composedmapping/{ComposedMappingTest.java => ComposedMappingIntegrationTest.java} (94%) rename spring-all/src/test/java/org/baeldung/spring43/ctor/{ConfigurationConstructorInjectionTest.java => ConfigurationConstructorInjectionIntegrationTest.java} (85%) rename spring-all/src/test/java/org/baeldung/spring43/ctor/{ImplicitConstructorTest.java => ImplicitConstructorIntegrationTest.java} (86%) rename spring-all/src/test/java/org/baeldung/spring43/defaultmethods/{DefaultMethodsInjectionTest.java => DefaultMethodsInjectionIntegrationTest.java} (87%) rename spring-all/src/test/java/org/baeldung/spring43/defaultmethods/{TransactionalTest.java => TransactionalIntegrationTest.java} (76%) rename spring-all/src/test/java/org/baeldung/spring43/depresolution/{ObjectProviderTest.java => ObjectProviderIntegrationTest.java} (87%) rename spring-all/src/test/java/org/baeldung/spring43/scopeannotations/{ScopeAnnotationsTest.java => ScopeAnnotationsIntegrationTest.java} (97%) rename spring-all/src/test/java/org/baeldung/springevents/asynchronous/{AsynchronousCustomSpringEventsTest.java => AsynchronousCustomSpringEventsIntegrationTest.java} (93%) rename spring-all/src/test/java/org/baeldung/springevents/synchronous/{ContextRefreshedListenerTest.java => ContextRefreshedListenerIntegrationTest.java} (92%) rename spring-all/src/test/java/org/baeldung/springevents/synchronous/{SynchronousCustomSpringEventsTest.java => SynchronousCustomSpringEventsIntegrationTest.java} (93%) rename spring-all/src/test/java/org/baeldung/startup/{SpringStartupTest.java => SpringStartupIntegrationTest.java} (97%) rename spring-all/src/test/java/org/baeldung/startup/{SpringStartupXMLConfigTest.java => SpringStartupXMLConfigIntegrationTest.java} (93%) diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 003cdacc2c..23f2531b51 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -224,7 +224,7 @@ maven-surefire-plugin - + **/*IntegrationTest.java @@ -232,31 +232,45 @@ - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 4.3.1.RELEASE diff --git a/spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleTest.java b/spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleTest.java rename to spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleIntegrationTest.java index 2f41766cb6..0c010cf732 100644 --- a/spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleTest.java +++ b/spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SpringAsyncConfig.class }, loader = AnnotationConfigContextLoader.class) -public class AsyncAnnotationExampleTest { +public class AsyncAnnotationExampleIntegrationTest { @Autowired private AsyncComponent asyncAnnotationExample; diff --git a/spring-all/src/test/java/org/baeldung/async/AsyncWithXMLTest.java b/spring-all/src/test/java/org/baeldung/async/AsyncWithXMLIntegrationTest.java similarity index 95% rename from spring-all/src/test/java/org/baeldung/async/AsyncWithXMLTest.java rename to spring-all/src/test/java/org/baeldung/async/AsyncWithXMLIntegrationTest.java index b91666261c..ffaa653a9a 100644 --- a/spring-all/src/test/java/org/baeldung/async/AsyncWithXMLTest.java +++ b/spring-all/src/test/java/org/baeldung/async/AsyncWithXMLIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:springAsync-config.xml") -public class AsyncWithXMLTest { +public class AsyncWithXMLIntegrationTest { @Autowired private AsyncComponent asyncAnnotationExample; diff --git a/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java b/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationIntegrationTest.java similarity index 95% rename from spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java rename to spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationIntegrationTest.java index 84bc3a8033..82c8704360 100644 --- a/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java +++ b/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationIntegrationTest.java @@ -21,7 +21,7 @@ import org.springframework.web.servlet.ModelAndView; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class) -public class ControllerAnnotationTest { +public class ControllerAnnotationIntegrationTest { private MockMvc mockMvc; diff --git a/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java b/spring-all/src/test/java/org/baeldung/controller/ControllerIntegrationTest.java similarity index 98% rename from spring-all/src/test/java/org/baeldung/controller/ControllerTest.java rename to spring-all/src/test/java/org/baeldung/controller/ControllerIntegrationTest.java index 47915b8ce9..8e8a021530 100644 --- a/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java +++ b/spring-all/src/test/java/org/baeldung/controller/ControllerIntegrationTest.java @@ -20,7 +20,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration({ "classpath:test-mvc.xml" }) -public class ControllerTest { +public class ControllerIntegrationTest { private MockMvc mockMvc; diff --git a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationTest.java b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationTest.java rename to spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java index ec0d46876e..ae3d53fb9b 100644 --- a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationTest.java +++ b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java @@ -14,7 +14,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { CustomAnnotationConfiguration.class }) -public class DataAccessAnnotationTest { +public class DataAccessAnnotationIntegrationTest { @DataAccess(entity = Person.class) private GenericDAO personGenericDAO; diff --git a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java rename to spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java index e47d03c961..bab2574cd2 100644 --- a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java +++ b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java @@ -17,7 +17,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { CustomAnnotationConfiguration.class }) -public class DataAccessFieldCallbackTest { +public class DataAccessFieldCallbackIntegrationTest { @Autowired private ConfigurableListableBeanFactory configurableListableBeanFactory; diff --git a/spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOTest.java b/spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOIntegrationTest.java similarity index 99% rename from spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOTest.java rename to spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOIntegrationTest.java index d544409254..4a92aa838f 100644 --- a/spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOTest.java +++ b/spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOIntegrationTest.java @@ -15,7 +15,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SpringJdbcConfig.class }, loader = AnnotationConfigContextLoader.class) -public class EmployeeDAOTest { +public class EmployeeDAOIntegrationTest { @Autowired private EmployeeDAO employeeDao; diff --git a/spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationTest.java b/spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java similarity index 93% rename from spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationTest.java rename to spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java index 2b65928da8..cf5ca132e6 100644 --- a/spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationTest.java +++ b/spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("dev") @ContextConfiguration(classes = { SpringProfilesConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DevProfileWithAnnotationTest { +public class DevProfileWithAnnotationIntegrationTest { @Autowired DatasourceConfig datasourceConfig; diff --git a/spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationTest.java b/spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java similarity index 94% rename from spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationTest.java rename to spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java index 551636bd31..5bacaef07b 100644 --- a/spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationTest.java +++ b/spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("production") @ContextConfiguration(classes = { SpringProfilesConfig.class }, loader = AnnotationConfigContextLoader.class) -public class ProductionProfileWithAnnotationTest { +public class ProductionProfileWithAnnotationIntegrationTest { @Autowired DatasourceConfig datasourceConfig; diff --git a/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesTest.java b/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java similarity index 96% rename from spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesTest.java rename to spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java index 92af3f52f0..e0eccc978a 100644 --- a/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java @@ -18,7 +18,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextHierarchy({ @ContextConfiguration(classes = ParentConfig2.class), @ContextConfiguration(classes = ChildConfig2.class) }) -public class ParentChildPropertyPlaceHolderPropertiesTest { +public class ParentChildPropertyPlaceHolderPropertiesIntegrationTest { @Autowired private WebApplicationContext wac; diff --git a/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesTest.java b/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesIntegrationTest.java similarity index 96% rename from spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesTest.java rename to spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesIntegrationTest.java index 3ffd490c87..e9990523a7 100644 --- a/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesIntegrationTest.java @@ -18,7 +18,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextHierarchy({ @ContextConfiguration(classes = ParentConfig.class), @ContextConfiguration(classes = ChildConfig.class) }) -public class ParentChildPropertySourcePropertiesTest { +public class ParentChildPropertySourcePropertiesIntegrationTest { @Autowired private WebApplicationContext wac; diff --git a/spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleTest.java b/spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleIntegrationTest.java similarity index 90% rename from spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleTest.java rename to spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleIntegrationTest.java index 9317c7bb7f..c5ca78aaa1 100644 --- a/spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleTest.java +++ b/spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SpringSchedulingConfig.class }, loader = AnnotationConfigContextLoader.class) -public class ScheduledAnnotationExampleTest { +public class ScheduledAnnotationExampleIntegrationTest { @Test public void testScheduledAnnotation() throws InterruptedException { diff --git a/spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigTest.java b/spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigIntegrationTest.java similarity index 89% rename from spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigTest.java rename to spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigIntegrationTest.java index 0fca4d21c8..08df73f8fd 100644 --- a/spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigTest.java +++ b/spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:springScheduled-config.xml") -public class SchedulingWithXmlConfigTest { +public class SchedulingWithXmlConfigIntegrationTest { @Test public void testXmlBasedScheduling() throws InterruptedException { diff --git a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java similarity index 94% rename from spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java rename to spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java index 5162a067d7..fff2716a64 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java @@ -17,7 +17,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @ContextConfiguration(classes = AttributeAnnotationConfiguration.class) @WebAppConfiguration -public class AttributeAnnotationTest extends AbstractJUnit4SpringContextTests { +public class AttributeAnnotationIntegrationTest extends AbstractJUnit4SpringContextTests { private MockMvc mockMvc; diff --git a/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsTest.java b/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java similarity index 92% rename from spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsTest.java rename to spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java index bfd6e5047c..986932dafe 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.junit.Assert.assertEquals; @ContextConfiguration(classes = CacheRefinementsConfiguration.class) -public class CacheRefinementsTest extends AbstractJUnit4SpringContextTests { +public class CacheRefinementsIntegrationTest extends AbstractJUnit4SpringContextTests { private ExecutorService executorService = Executors.newFixedThreadPool(10); diff --git a/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java b/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java similarity index 94% rename from spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java rename to spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java index 75d828c3d3..d0af48cd0e 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java @@ -17,7 +17,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @ContextConfiguration(classes = ComposedMappingConfiguration.class) @WebAppConfiguration -public class ComposedMappingTest extends AbstractJUnit4SpringContextTests { +public class ComposedMappingIntegrationTest extends AbstractJUnit4SpringContextTests { @Autowired private AppointmentService appointmentService; diff --git a/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java b/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java similarity index 85% rename from spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java rename to spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java index 3edf693a13..871a985479 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.junit.Assert.assertNotNull; @ContextConfiguration(classes = { FooRepositoryConfiguration.class, FooServiceConfiguration.class }) -public class ConfigurationConstructorInjectionTest extends AbstractJUnit4SpringContextTests { +public class ConfigurationConstructorInjectionIntegrationTest extends AbstractJUnit4SpringContextTests { @Autowired public FooService fooService; diff --git a/spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorTest.java b/spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java similarity index 86% rename from spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorTest.java rename to spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java index be0cf77a62..83fa11294e 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.junit.Assert.assertNotNull; @ContextConfiguration("classpath:implicit-ctor-context.xml") -public class ImplicitConstructorTest extends AbstractJUnit4SpringContextTests { +public class ImplicitConstructorIntegrationTest extends AbstractJUnit4SpringContextTests { @Autowired private FooService fooService; diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionTest.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java similarity index 87% rename from spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionTest.java rename to spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java index e29d89a679..956df44821 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java @@ -10,7 +10,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.junit.Assert.assertEquals; @ContextConfiguration("classpath:defaultmethods-context.xml") -public class DefaultMethodsInjectionTest extends AbstractJUnit4SpringContextTests { +public class DefaultMethodsInjectionIntegrationTest extends AbstractJUnit4SpringContextTests { @Autowired private IDateHolder dateHolder; diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTest.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java similarity index 76% rename from spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTest.java rename to spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java index 89c96ba1d4..b4ac7e8ccf 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java @@ -5,7 +5,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; @ContextConfiguration(classes = TransactionalTestConfiguration.class) -public class TransactionalTest extends AbstractTransactionalJUnit4SpringContextTests implements ITransactionalTest { +public class TransactionalIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests implements ITransactionalTest { @Test public void whenDefaultMethodAnnotatedWithBeforeTransaction_thenDefaultMethodIsExecuted() { diff --git a/spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderTest.java b/spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java similarity index 87% rename from spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderTest.java rename to spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java index eeeb005f81..6d06bfdc2a 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.junit.Assert.assertNotNull; @ContextConfiguration(classes = ObjectProviderConfiguration.class) -public class ObjectProviderTest extends AbstractJUnit4SpringContextTests { +public class ObjectProviderIntegrationTest extends AbstractJUnit4SpringContextTests { @Autowired private FooService fooService; diff --git a/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java b/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java rename to spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java index ecf14f0d6c..69cce15029 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java @@ -19,7 +19,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @ContextConfiguration(classes = ScopeAnnotationsConfiguration.class) @WebAppConfiguration -public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests { +public class ScopeAnnotationsIntegrationTest extends AbstractJUnit4SpringContextTests { private MockMvc mockMvc; diff --git a/spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsTest.java b/spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java similarity index 93% rename from spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsTest.java rename to spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java index 2b45ae4e68..e12baed7e0 100644 --- a/spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsTest.java +++ b/spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java @@ -10,7 +10,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { AsynchronousSpringEventsConfig.class }, loader = AnnotationConfigContextLoader.class) -public class AsynchronousCustomSpringEventsTest { +public class AsynchronousCustomSpringEventsIntegrationTest { @Autowired private CustomSpringEventPublisher publisher; diff --git a/spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerTest.java b/spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java similarity index 92% rename from spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerTest.java rename to spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java index d971698e3f..ac8758bbf6 100644 --- a/spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerTest.java +++ b/spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SynchronousSpringEventsConfig.class }, loader = AnnotationConfigContextLoader.class) -public class ContextRefreshedListenerTest { +public class ContextRefreshedListenerIntegrationTest { @Test public void testContextRefreshedListener() throws InterruptedException { diff --git a/spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsTest.java b/spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java similarity index 93% rename from spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsTest.java rename to spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java index b559ca9fc9..f9783f57dc 100644 --- a/spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsTest.java +++ b/spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SynchronousSpringEventsConfig.class }, loader = AnnotationConfigContextLoader.class) -public class SynchronousCustomSpringEventsTest { +public class SynchronousCustomSpringEventsIntegrationTest { @Autowired private CustomSpringEventPublisher publisher; diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java rename to spring-all/src/test/java/org/baeldung/startup/SpringStartupIntegrationTest.java index 523a27c2c4..6263482948 100644 --- a/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java +++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SpringStartupConfig.class }, loader = AnnotationConfigContextLoader.class) -public class SpringStartupTest { +public class SpringStartupIntegrationTest { @Autowired private ApplicationContext ctx; diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java similarity index 93% rename from spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java rename to spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java index 19a35bb92b..a46d24fa3b 100644 --- a/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java +++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:startupConfig.xml") -public class SpringStartupXMLConfigTest { +public class SpringStartupXMLConfigIntegrationTest { @Autowired private ApplicationContext ctx; From c1017af8a09d9b10a5821c237a01d263b785084e Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 20 Oct 2016 14:21:12 +0200 Subject: [PATCH 154/193] add integration test profile --- spring-akka/pom.xml | 51 ++++++++++++++++++- ...st.java => SpringAkkaIntegrationTest.java} | 2 +- 2 files changed, 50 insertions(+), 3 deletions(-) rename spring-akka/src/test/java/org/baeldung/akka/{SpringAkkaTest.java => SpringAkkaIntegrationTest.java} (94%) diff --git a/spring-akka/pom.xml b/spring-akka/pom.xml index 6299448ec8..eb33ca4848 100644 --- a/spring-akka/pom.xml +++ b/spring-akka/pom.xml @@ -65,9 +65,54 @@ + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + - - + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + 4.3.2.RELEASE @@ -75,6 +120,8 @@ 4.12 3.5.1 + 2.19.1 + \ No newline at end of file diff --git a/spring-akka/src/test/java/org/baeldung/akka/SpringAkkaTest.java b/spring-akka/src/test/java/org/baeldung/akka/SpringAkkaIntegrationTest.java similarity index 94% rename from spring-akka/src/test/java/org/baeldung/akka/SpringAkkaTest.java rename to spring-akka/src/test/java/org/baeldung/akka/SpringAkkaIntegrationTest.java index e5351e9d0f..c5da0f747e 100644 --- a/spring-akka/src/test/java/org/baeldung/akka/SpringAkkaTest.java +++ b/spring-akka/src/test/java/org/baeldung/akka/SpringAkkaIntegrationTest.java @@ -20,7 +20,7 @@ import static akka.pattern.Patterns.ask; import static org.baeldung.akka.SpringExtension.SPRING_EXTENSION_PROVIDER; @ContextConfiguration(classes = AppConfiguration.class) -public class SpringAkkaTest extends AbstractJUnit4SpringContextTests { +public class SpringAkkaIntegrationTest extends AbstractJUnit4SpringContextTests { @Autowired private ActorSystem system; From 511d96614d086daf4216e880b8de09b4aff3dd53 Mon Sep 17 00:00:00 2001 From: Sameera Date: Thu, 20 Oct 2016 23:10:17 +0530 Subject: [PATCH 155/193] PrintScreen code samples moved to core-java module --- .../com/baeldung/printscreen}/Screenshot.java | 2 +- .../baeldung/printscreen}/ScreenshotTest.java | 2 +- printscreen/pom.xml | 26 ------------------- 3 files changed, 2 insertions(+), 28 deletions(-) rename {printscreen/src/main/java/org/baeldung/corejava => core-java/src/main/java/com/baeldung/printscreen}/Screenshot.java (97%) rename {printscreen/src/test/java/org/baeldung/corejava => core-java/src/test/java/com/baeldung/printscreen}/ScreenshotTest.java (95%) delete mode 100644 printscreen/pom.xml diff --git a/printscreen/src/main/java/org/baeldung/corejava/Screenshot.java b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java similarity index 97% rename from printscreen/src/main/java/org/baeldung/corejava/Screenshot.java rename to core-java/src/main/java/com/baeldung/printscreen/Screenshot.java index d33761932f..500860640a 100644 --- a/printscreen/src/main/java/org/baeldung/corejava/Screenshot.java +++ b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java @@ -1,4 +1,4 @@ -package org.baeldung.corejava;; +package com.baeldung.printscreen; import javax.imageio.ImageIO; import java.awt.*; diff --git a/printscreen/src/test/java/org/baeldung/corejava/ScreenshotTest.java b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java similarity index 95% rename from printscreen/src/test/java/org/baeldung/corejava/ScreenshotTest.java rename to core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java index 588c2eea78..5c0341cb36 100644 --- a/printscreen/src/test/java/org/baeldung/corejava/ScreenshotTest.java +++ b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java @@ -1,4 +1,4 @@ -package org.baeldung.corejava; +package com.baeldung.printscreen; import org.junit.After; import org.junit.Before; diff --git a/printscreen/pom.xml b/printscreen/pom.xml deleted file mode 100644 index ddb813a7a2..0000000000 --- a/printscreen/pom.xml +++ /dev/null @@ -1,26 +0,0 @@ - - 4.0.0 - - com.baeldung - corejava-printscreen - 1.0-SNAPSHOT - jar - - How to Print Screen in Java - https://github.com/eugenp/tutorials - - - UTF-8 - 4.12 - - - - - junit - junit - ${junit.version} - test - - - From cdbd83e8518b2cf0dcf66ce8d64b105fde479015 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 20 Oct 2016 21:53:32 +0200 Subject: [PATCH 156/193] add integration test profile --- spring-mvc-java/pom.xml | 54 ++++++++++++------- ...arDependencyA => CircularDependencyA.java} | 0 ...arDependencyB => CircularDependencyB.java} | 0 .../CircularDependencyIntegrationTest.java | 35 ++++++++++++ .../circulardependency/CircularDependencyTest | 35 ------------ .../{TestConfig => TestConfig.java} | 0 .../HtmlUnitAndSpringIntegrationTest.java | 4 +- 7 files changed, 73 insertions(+), 55 deletions(-) rename spring-mvc-java/src/main/java/com/baeldung/circulardependency/{CircularDependencyA => CircularDependencyA.java} (100%) rename spring-mvc-java/src/main/java/com/baeldung/circulardependency/{CircularDependencyB => CircularDependencyB.java} (100%) create mode 100644 spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java delete mode 100644 spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyTest rename spring-mvc-java/src/test/java/com/baeldung/circulardependency/{TestConfig => TestConfig.java} (100%) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 8248343105..011de70ad2 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -208,28 +208,44 @@ - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - - jetty8x - embedded - - - - - - - 8082 - - - - + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 4.2.5.RELEASE diff --git a/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA b/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA rename to spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB b/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB rename to spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java new file mode 100644 index 0000000000..42847f4dd1 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.circulardependency; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { TestConfig.class }) +public class CircularDependencyIntegrationTest { + + @Autowired + ApplicationContext context; + + @Bean + public CircularDependencyA getCircularDependencyA() { + return new CircularDependencyA(); + } + + @Bean + public CircularDependencyB getCircularDependencyB() { + return new CircularDependencyB(); + } + + @Test + public void givenCircularDependency_whenSetterInjection_thenItWorks() { + final CircularDependencyA circA = context.getBean(CircularDependencyA.class); + + Assert.assertEquals("Hi!", circA.getCircB().getMessage()); + } +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyTest b/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyTest deleted file mode 100644 index 4229f21f10..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyTest +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.circulardependency; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { TestConfig.class }) -public class CircularDependencyTest { - - @Autowired - ApplicationContext context; - - @Bean - public CircularDependencyA getCircularDependencyA() { - return new CircularDependencyA(); - } - - @Bean - public CircularDependencyB getCircularDependencyB() { - return new CircularDependencyB(); - } - - @Test - public void givenCircularDependency_whenSetterInjection_thenItWorks() { - final CircularDependencyA circA = context.getBean(CircularDependencyA.class); - - Assert.assertEquals("Hi!", circA.getCircB().getMessage()); - } -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig b/spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig rename to spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java index 7a23908fe5..406975b6cc 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java @@ -5,6 +5,7 @@ import java.net.MalformedURLException; import org.junit.Assert; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -39,9 +40,10 @@ public class HtmlUnitAndSpringIntegrationTest { // @Test + @Ignore("Related view message.html does not exist check MessageController") public void givenAMessage_whenSent_thenItShows() throws FailingHttpStatusCodeException, MalformedURLException, IOException { final String text = "Hello world!"; - HtmlPage page = webClient.getPage("http://localhost/message/showForm"); + final HtmlPage page = webClient.getPage("http://localhost/message/showForm"); System.out.println(page.asXml()); final HtmlTextInput messageText = page.getHtmlElementById("message"); From fd1a5796a91be4db4d30c2166c98e4a94a39046d Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Thu, 20 Oct 2016 23:10:14 +0200 Subject: [PATCH 157/193] Refactor Screenshot examples --- .../com/baeldung/printscreen/Screenshot.java | 13 +++++------- .../baeldung/printscreen/ScreenshotTest.java | 21 ++++--------------- .../ehcache/SquareCalculatorTest.java | 18 ++++++++-------- 3 files changed, 18 insertions(+), 34 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java index 500860640a..7c29a61842 100644 --- a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java +++ b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java @@ -7,20 +7,17 @@ import java.io.File; public class Screenshot { - private String filePath; - private String filenamePrefix; - private String fileType; - private int timeToWait; + private final String filePath; + private final String filenamePrefix; + private final String fileType; - public Screenshot(String filePath, String filenamePrefix, - String fileType, int timeToWait) { + public Screenshot(String filePath, String filenamePrefix, String fileType) { this.filePath = filePath; this.filenamePrefix = filenamePrefix; this.fileType = fileType; - this.timeToWait = timeToWait; } - public void getScreenshot() throws Exception { + public void getScreenshot(int timeToWait) throws Exception { Thread.sleep(timeToWait); Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); Robot robot = new Robot(); diff --git a/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java index 5c0341cb36..895f514f4a 100644 --- a/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java +++ b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java @@ -1,34 +1,21 @@ package com.baeldung.printscreen; import org.junit.After; -import org.junit.Before; import org.junit.Test; import java.io.File; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; public class ScreenshotTest { - private Screenshot screenshot; - private String filePath; - private String fileName; - private String fileType; - private File file; - - @Before - public void setUp() throws Exception { - filePath = ""; - fileName = "Screenshot"; - fileType = "jpg"; - file = new File(filePath + fileName + "." + fileType); - screenshot = new Screenshot(filePath, fileName, fileType, 2000); - } + private Screenshot screenshot = new Screenshot("", "Screenshot", "jpg"); + private File file = new File("Screenshot.jpg"); @Test public void testGetScreenshot() throws Exception { - screenshot.getScreenshot(); + screenshot.getScreenshot(2000); assertTrue(file.exists()); } diff --git a/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java b/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java index 875fd2a25e..ab7aebf7a1 100644 --- a/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java +++ b/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java @@ -1,20 +1,20 @@ package org.baeldung.ehcache; -import static org.junit.Assert.*; - import org.baeldung.ehcache.calculator.SquaredCalculator; import org.baeldung.ehcache.config.CacheHelper; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + public class SquareCalculatorTest { - SquaredCalculator squaredCalculator = new SquaredCalculator(); - CacheHelper cacheHelper = new CacheHelper(); + private SquaredCalculator squaredCalculator = new SquaredCalculator(); + private CacheHelper cacheHelper = new CacheHelper(); @Before public void setup() { squaredCalculator.setCache(cacheHelper); - } @Test @@ -22,7 +22,7 @@ public class SquareCalculatorTest { for (int i = 10; i < 15; i++) { assertFalse(cacheHelper.getSquareNumberCache().containsKey(i)); System.out.println("Square value of " + i + " is: " - + squaredCalculator.getSquareValueOfNumber(i) + "\n"); + + squaredCalculator.getSquareValueOfNumber(i) + "\n"); } } @@ -31,13 +31,13 @@ public class SquareCalculatorTest { for (int i = 10; i < 15; i++) { assertFalse(cacheHelper.getSquareNumberCache().containsKey(i)); System.out.println("Square value of " + i + " is: " - + squaredCalculator.getSquareValueOfNumber(i) + "\n"); + + squaredCalculator.getSquareValueOfNumber(i) + "\n"); } - + for (int i = 10; i < 15; i++) { assertTrue(cacheHelper.getSquareNumberCache().containsKey(i)); System.out.println("Square value of " + i + " is: " - + squaredCalculator.getSquareValueOfNumber(i) + "\n"); + + squaredCalculator.getSquareValueOfNumber(i) + "\n"); } } } From 89754421a293f8882b6b7cb4f632d5a027c67db6 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Thu, 20 Oct 2016 23:14:05 +0200 Subject: [PATCH 158/193] Refactor Screenshot examples 2 --- .../com/baeldung/printscreen/Screenshot.java | 20 ++++--------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java index 7c29a61842..27fd84e374 100644 --- a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java +++ b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java @@ -7,14 +7,10 @@ import java.io.File; public class Screenshot { - private final String filePath; - private final String filenamePrefix; - private final String fileType; + private final String path; - public Screenshot(String filePath, String filenamePrefix, String fileType) { - this.filePath = filePath; - this.filenamePrefix = filenamePrefix; - this.fileType = fileType; + public Screenshot(String path) { + this.path = path; } public void getScreenshot(int timeToWait) throws Exception { @@ -22,14 +18,6 @@ public class Screenshot { Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); Robot robot = new Robot(); BufferedImage img = robot.createScreenCapture(rectangle); - ImageIO.write(img, fileType, setupFileNamePath()); - } - - private File setupFileNamePath() { - return new File(filePath + filenamePrefix + "." + fileType); - } - - private Rectangle getScreenSizedRectangle(final Dimension d) { - return new Rectangle(0, 0, d.width, d.height); + ImageIO.write(img, "jpg", new File(path)); } } From 1018c4b3fb3acedac854011e69cac0c925560284 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Thu, 20 Oct 2016 23:18:50 +0200 Subject: [PATCH 159/193] Refactor JedisTest --- .../src/test/java/com/baeldung/JedisTest.java | 25 +++++-------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/redis/src/test/java/com/baeldung/JedisTest.java b/redis/src/test/java/com/baeldung/JedisTest.java index 766fd7b5e9..582bb266aa 100644 --- a/redis/src/test/java/com/baeldung/JedisTest.java +++ b/redis/src/test/java/com/baeldung/JedisTest.java @@ -1,28 +1,15 @@ package com.baeldung; +import org.junit.*; +import redis.clients.jedis.*; +import redis.embedded.RedisServer; + import java.io.IOException; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.Set; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; -import redis.clients.jedis.Pipeline; -import redis.clients.jedis.Response; -import redis.clients.jedis.Transaction; -import redis.embedded.RedisServer; - -/** - * Unit test for Redis Java library - Jedis. - */ public class JedisTest { private Jedis jedis; @@ -140,9 +127,9 @@ public class JedisTest { scores.put("PlayerTwo", 1500.0); scores.put("PlayerThree", 8200.0); - for (String player : scores.keySet()) { + scores.keySet().forEach(player -> { jedis.zadd(key, scores.get(player), player); - } + }); Set players = jedis.zrevrange(key, 0, 1); Assert.assertEquals("PlayerThree", players.iterator().next()); From 395a6731d9a1bfac956c820ca8e86f0b3f0026ea Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 21 Oct 2016 00:11:19 +0200 Subject: [PATCH 160/193] add integration test profile --- rest-testing/pom.xml | 42 +++++++++++++++++++ ...Test.java => CucumberIntegrationTest.java} | 2 +- 2 files changed, 43 insertions(+), 1 deletion(-) rename rest-testing/src/test/java/com/baeldung/rest/cucumber/{CucumberTest.java => CucumberIntegrationTest.java} (84%) diff --git a/rest-testing/pom.xml b/rest-testing/pom.xml index 819e8de8a5..90c160af15 100644 --- a/rest-testing/pom.xml +++ b/rest-testing/pom.xml @@ -148,12 +148,54 @@ org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*UnitTest.java + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + json + + + + + + + + 2.7.8 diff --git a/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberTest.java b/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java similarity index 84% rename from rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberTest.java rename to rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java index 041de592e9..f80178a43d 100644 --- a/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberTest.java +++ b/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java @@ -6,5 +6,5 @@ import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features = "classpath:Feature") -public class CucumberTest { +public class CucumberIntegrationTest { } \ No newline at end of file From 13cf6590ba0e0e5738a6cf8c7d51b35503a4010a Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 21 Oct 2016 00:24:15 +0200 Subject: [PATCH 161/193] add integration test profile --- querydsl/pom.xml | 49 +++++++++++++++++++ ...est.java => PersonDaoIntegrationTest.java} | 2 +- 2 files changed, 50 insertions(+), 1 deletion(-) rename querydsl/src/test/java/org/baeldung/dao/{PersonDaoTest.java => PersonDaoIntegrationTest.java} (98%) diff --git a/querydsl/pom.xml b/querydsl/pom.xml index bed0cf90e5..13528526ea 100644 --- a/querydsl/pom.xml +++ b/querydsl/pom.xml @@ -20,6 +20,7 @@ 5.2.1.Final 4.1.3 1.7.21 + 2.19.1 @@ -166,7 +167,55 @@ + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + \ No newline at end of file diff --git a/querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java b/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java similarity index 98% rename from querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java rename to querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java index 0e5996a8c8..a666aea8da 100644 --- a/querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java +++ b/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java @@ -17,7 +17,7 @@ import junit.framework.Assert; @RunWith(SpringJUnit4ClassRunner.class) @Transactional @TransactionConfiguration(defaultRollback = true) -public class PersonDaoTest { +public class PersonDaoIntegrationTest { @Autowired private PersonDao personDao; From 60d60508c38580ddcb2763794b895d152be4b784 Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 21 Oct 2016 13:08:10 +0200 Subject: [PATCH 162/193] add integration test profile --- mapstruct/pom.xml | 52 ++++++++++++++++++- ...urceDestinationMapperIntegrationTest.java} | 2 +- 2 files changed, 51 insertions(+), 3 deletions(-) rename mapstruct/src/test/java/com/baeldung/mapper/{SimpleSourceDestinationMapperTest.java => SimpleSourceDestinationMapperIntegrationTest.java} (96%) diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml index 4159ef35c9..aaa3e95f8c 100644 --- a/mapstruct/pom.xml +++ b/mapstruct/pom.xml @@ -55,6 +55,54 @@ - - + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + diff --git a/mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperTest.java b/mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperIntegrationTest.java similarity index 96% rename from mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperTest.java rename to mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperIntegrationTest.java index a7addf33a7..31d60c0d7d 100644 --- a/mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperTest.java +++ b/mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") -public class SimpleSourceDestinationMapperTest { +public class SimpleSourceDestinationMapperIntegrationTest { @Autowired SimpleSourceDestinationMapper simpleSourceDestinationMapper; From 60a1c5f481e2db0911cbaf7b4106bd95b63c5d71 Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 21 Oct 2016 14:02:01 +0200 Subject: [PATCH 163/193] add integration test profile --- jooq-spring/pom.xml | 47 +++++++++++++++++++ ...=> PersistenceContextIntegrationTest.java} | 2 +- ...eryTest.java => QueryIntegrationTest.java} | 4 +- ...st.java => SpringBootIntegrationTest.java} | 2 +- 4 files changed, 51 insertions(+), 4 deletions(-) rename jooq-spring/src/test/java/com/baeldung/jooq/introduction/{PersistenceContext.java => PersistenceContextIntegrationTest.java} (98%) rename jooq-spring/src/test/java/com/baeldung/jooq/introduction/{QueryTest.java => QueryIntegrationTest.java} (97%) rename jooq-spring/src/test/java/com/baeldung/jooq/springboot/{SpringBootTest.java => SpringBootIntegrationTest.java} (99%) diff --git a/jooq-spring/pom.xml b/jooq-spring/pom.xml index e77ff0cbfd..96a3de11db 100644 --- a/jooq-spring/pom.xml +++ b/jooq-spring/pom.xml @@ -161,9 +161,55 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 3.7.3 1.4.191 @@ -173,6 +219,7 @@ 4.12 3.5.1 + 2.19.1 \ No newline at end of file diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java similarity index 98% rename from jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java rename to jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java index df628f9f78..06290ae8db 100644 --- a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java +++ b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java @@ -22,7 +22,7 @@ import javax.sql.DataSource; @ComponentScan({ "com.baeldung.jooq.introduction.db.public_.tables" }) @EnableTransactionManagement @PropertySource("classpath:intro_config.properties") -public class PersistenceContext { +public class PersistenceContextIntegrationTest { @Autowired private Environment environment; diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java similarity index 97% rename from jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java rename to jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java index 68f975dd6d..28bc4c63c7 100644 --- a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java +++ b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java @@ -17,10 +17,10 @@ import static com.baeldung.jooq.introduction.db.public_.tables.AuthorBook.AUTHOR import static com.baeldung.jooq.introduction.db.public_.tables.Book.BOOK; import static org.junit.Assert.assertEquals; -@ContextConfiguration(classes = PersistenceContext.class) +@ContextConfiguration(classes = PersistenceContextIntegrationTest.class) @Transactional(transactionManager = "transactionManager") @RunWith(SpringJUnit4ClassRunner.class) -public class QueryTest { +public class QueryIntegrationTest { @Autowired private DSLContext dsl; diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootTest.java b/jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java similarity index 99% rename from jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootTest.java rename to jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java index f9427f30fb..fa3f342ecd 100644 --- a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootTest.java +++ b/jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java @@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals; @SpringApplicationConfiguration(Application.class) @Transactional("transactionManager") @RunWith(SpringJUnit4ClassRunner.class) -public class SpringBootTest { +public class SpringBootIntegrationTest { @Autowired private DSLContext dsl; From 1d3ac0836f12ccb5a59fb619b2bcfd339e89fbaa Mon Sep 17 00:00:00 2001 From: Eugen Date: Fri, 21 Oct 2016 20:50:38 +0300 Subject: [PATCH 164/193] Update README.md --- spring-all/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-all/README.md b/spring-all/README.md index aae98440f3..90ae69300a 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -15,3 +15,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Guide To Running Logic on Startup in Spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring) - [Quick Guide to Spring Controllers](http://www.baeldung.com/spring-controllers) - [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes) +- [Introduction To Ehcache](http://www.baeldung.com/ehcache) From d55903a667e6d494c4dbdc9d68108bcd6dc9c695 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sat, 22 Oct 2016 07:16:14 +0200 Subject: [PATCH 165/193] BAEL-276 - URL encoding --- .../encoderdecoder/EncoderDecoder.java | 72 +++++++++++++++---- 1 file changed, 59 insertions(+), 13 deletions(-) diff --git a/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java b/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java index 62d2663994..208a23eb91 100644 --- a/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java +++ b/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java @@ -3,36 +3,82 @@ package com.baeldung.encoderdecoder; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; public class EncoderDecoder { - @Test - public void givenPlainURL_whenUsingUTF8EncodingScheme_thenEncodeURL() throws UnsupportedEncodingException { - String plainURL = "http://www.baeldung.com" ; - String encodedURL = URLEncoder.encode(plainURL, StandardCharsets.UTF_8.toString()); + private static final String URL = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253"; + private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoder.class); - Assert.assertThat("http%3A%2F%2Fwww.baeldung.com", CoreMatchers.is(encodedURL)); + private String encodeValue(String value) { + String encoded = null; + try { + encoded = URLEncoder.encode(value, StandardCharsets.UTF_8.toString()); + } catch (UnsupportedEncodingException e) { + LOGGER.error("Error encoding parameter {}", e.getMessage(), e); + } + return encoded; + } + + + private String decode(String value) { + String decoded = null; + try { + decoded = URLDecoder.decode(value, StandardCharsets.UTF_8.toString()); + } catch (UnsupportedEncodingException e) { + LOGGER.error("Error encoding parameter {}", e.getMessage(), e); + } + return decoded; } @Test - public void givenEncodedURL_whenUsingUTF8EncodingScheme_thenDecodeURL() throws UnsupportedEncodingException { - String encodedURL = "http%3A%2F%2Fwww.baeldung.com" ; - String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_8.toString()); + public void givenURL_whenAnalyze_thenCorrect() throws Exception { + URL url = new URL(URL); - Assert.assertThat("http://www.baeldung.com", CoreMatchers.is(decodedURL)); + Assert.assertThat(url.getProtocol(), CoreMatchers.is("http")); + Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com")); + Assert.assertThat(url.getQuery(), CoreMatchers.is("key1=value+1&key2=value%40%21%242&key3=value%253")); } @Test - public void givenEncodedURL_whenUsingWrongEncodingScheme_thenDecodeInvalidURL() throws UnsupportedEncodingException { - String encodedURL = "http%3A%2F%2Fwww.baeldung.com"; + public void givenRequestParam_whenUTF8Scheme_thenEncode() throws Exception { + Map requestParams = new HashMap<>(); + requestParams.put("key1", "value 1"); + requestParams.put("key2", "value@!$2"); + requestParams.put("key3", "value%3"); - String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_16.toString()); + String encodedQuery = requestParams.keySet().stream() + .map(key -> key + "=" + encodeValue(requestParams.get(key))) + .collect(Collectors.joining("&")); + String encodedURL = "http://www.baeldung.com?" + encodedQuery; - Assert.assertFalse("http://www.baeldung.com".equals(decodedURL)); + Assert.assertThat(URL, CoreMatchers.is(encodedURL)); } + + @Test + public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception { + URL url = new URL(URL); + String query = url.getQuery(); + + String decodedQuery = Arrays.stream(query.split("&")) + .map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])) + .collect(Collectors.joining("&")); + + Assert.assertEquals( + "http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery); + } + } From 37ccb60f1d312e3de9049569e2d8c15c886fa3f7 Mon Sep 17 00:00:00 2001 From: ambrusadrianz Date: Sat, 22 Oct 2016 15:50:19 +0300 Subject: [PATCH 166/193] [BAEL-123] Created an example about custom AccessDecisionVoters in Spring Security. (#728) * Created an example about custom AccessDecisionVoters in Spring Security. * Added module in root pom file. * Added test cases --- pom.xml | 1 + spring-security-custom-voter/pom.xml | 96 +++++++++++++++++++ .../main/java/org/baeldung/Application.java | 12 +++ .../baeldung/security/MinuteBasedVoter.java | 38 ++++++++ .../baeldung/security/WebSecurityConfig.java | 69 +++++++++++++ .../baeldung/security/XmlSecurityConfig.java | 15 +++ .../main/java/org/baeldung/web/MvcConfig.java | 18 ++++ .../src/main/resources/spring-security.xml | 40 ++++++++ .../src/main/resources/templates/private.html | 10 ++ .../src/main/webapp/WEB-INF/web.xml | 47 +++++++++ .../test/java/org/baeldung/web/LiveTest.java | 42 ++++++++ 11 files changed, 388 insertions(+) create mode 100644 spring-security-custom-voter/pom.xml create mode 100644 spring-security-custom-voter/src/main/java/org/baeldung/Application.java create mode 100644 spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java create mode 100644 spring-security-custom-voter/src/main/java/org/baeldung/security/WebSecurityConfig.java create mode 100644 spring-security-custom-voter/src/main/java/org/baeldung/security/XmlSecurityConfig.java create mode 100644 spring-security-custom-voter/src/main/java/org/baeldung/web/MvcConfig.java create mode 100644 spring-security-custom-voter/src/main/resources/spring-security.xml create mode 100644 spring-security-custom-voter/src/main/resources/templates/private.html create mode 100644 spring-security-custom-voter/src/main/webapp/WEB-INF/web.xml create mode 100644 spring-security-custom-voter/src/test/java/org/baeldung/web/LiveTest.java diff --git a/pom.xml b/pom.xml index eee9f07ab9..9979ff95a5 100644 --- a/pom.xml +++ b/pom.xml @@ -107,6 +107,7 @@ spring-security-basic-auth spring-security-custom-permission + spring-security-custom-voter spring-security-mvc-custom spring-security-mvc-digest-auth spring-security-mvc-ldap diff --git a/spring-security-custom-voter/pom.xml b/spring-security-custom-voter/pom.xml new file mode 100644 index 0000000000..727efa48ab --- /dev/null +++ b/spring-security-custom-voter/pom.xml @@ -0,0 +1,96 @@ + + + 4.0.0 + + org.baeldung + spring-security-custom-voter + 0.0.1-SNAPSHOT + war + + spring-security-custom-voter + Custom AccessDecisionVoter with Spring Security + + + org.springframework.boot + spring-boot-starter-parent + 1.4.1.RELEASE + + + + + UTF-8 + UTF-8 + 3.0.1 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + junit + junit + test + + + + org.hamcrest + hamcrest-core + test + + + + org.hamcrest + hamcrest-library + test + + + + org.springframework + spring-test + 4.3.3.RELEASE + + + + org.springframework.security + spring-security-test + 4.1.3.RELEASE + test + + + + org.springframework.security + spring-security-web + 4.1.3.RELEASE + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-security-custom-voter/src/main/java/org/baeldung/Application.java b/spring-security-custom-voter/src/main/java/org/baeldung/Application.java new file mode 100644 index 0000000000..a9d6f3b8b1 --- /dev/null +++ b/spring-security-custom-voter/src/main/java/org/baeldung/Application.java @@ -0,0 +1,12 @@ +package org.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java b/spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java new file mode 100644 index 0000000000..8d22c52b0d --- /dev/null +++ b/spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java @@ -0,0 +1,38 @@ +package org.baeldung.security; + +import org.springframework.security.access.AccessDecisionVoter; +import org.springframework.security.access.ConfigAttribute; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; + +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +public class MinuteBasedVoter implements AccessDecisionVoter { + @Override + public boolean supports(ConfigAttribute attribute) { + return true; + } + + @Override + public boolean supports(Class clazz) { + return true; + } + + @Override + public int vote(Authentication authentication, Object object, Collection collection) { + List roles = authentication + .getAuthorities() + .stream().map(GrantedAuthority::getAuthority) + .collect(Collectors.toList()); + + for (String role: roles) { + if ("ROLE_USER".equals(role) && LocalDateTime.now().getMinute() % 2 != 0) { + return ACCESS_DENIED; + } + } + return ACCESS_ABSTAIN; + } +} diff --git a/spring-security-custom-voter/src/main/java/org/baeldung/security/WebSecurityConfig.java b/spring-security-custom-voter/src/main/java/org/baeldung/security/WebSecurityConfig.java new file mode 100644 index 0000000000..b3fb196424 --- /dev/null +++ b/spring-security-custom-voter/src/main/java/org/baeldung/security/WebSecurityConfig.java @@ -0,0 +1,69 @@ +package org.baeldung.security; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.AccessDecisionManager; +import org.springframework.security.access.AccessDecisionVoter; +import org.springframework.security.access.vote.AuthenticatedVoter; +import org.springframework.security.access.vote.RoleVoter; +import org.springframework.security.access.vote.UnanimousBased; +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; +import org.springframework.security.web.access.expression.WebExpressionVoter; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; + +import java.util.Arrays; +import java.util.List; + +@Configuration +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + // @formatter: off + auth.inMemoryAuthentication() + .withUser("user").password("pass").roles("USER") + .and() + .withUser("admin").password("pass").roles("ADMIN"); + // @formatter: on + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter: off + http + // needed so our login could work + .csrf() + .disable() + .authorizeRequests() + .anyRequest() + .authenticated() + .accessDecisionManager(accessDecisionManager()) + .antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER") + .and() + .formLogin() + .permitAll() + .and() + .logout() + .permitAll() + .deleteCookies("JSESSIONID") + .logoutSuccessUrl("/login"); + // @formatter: on + } + + @Bean + public AccessDecisionManager accessDecisionManager() { + // @formatter: off + List> decisionVoters = + Arrays.asList( + new WebExpressionVoter(), + new RoleVoter(), + new AuthenticatedVoter(), + new MinuteBasedVoter()); + // @formatter: on + return new UnanimousBased(decisionVoters); + } +} diff --git a/spring-security-custom-voter/src/main/java/org/baeldung/security/XmlSecurityConfig.java b/spring-security-custom-voter/src/main/java/org/baeldung/security/XmlSecurityConfig.java new file mode 100644 index 0000000000..45e095c66e --- /dev/null +++ b/spring-security-custom-voter/src/main/java/org/baeldung/security/XmlSecurityConfig.java @@ -0,0 +1,15 @@ +package org.baeldung.security; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; + +/** + * Created by ambrusadrianz on 09/10/2016. + */ +@Configuration +//@ImportResource({"classpath:spring-security.xml"}) +public class XmlSecurityConfig { + public XmlSecurityConfig() { + super(); + } +} diff --git a/spring-security-custom-voter/src/main/java/org/baeldung/web/MvcConfig.java b/spring-security-custom-voter/src/main/java/org/baeldung/web/MvcConfig.java new file mode 100644 index 0000000000..5d38dca1ff --- /dev/null +++ b/spring-security-custom-voter/src/main/java/org/baeldung/web/MvcConfig.java @@ -0,0 +1,18 @@ +package org.baeldung.web; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +/** + * Created by ambrusadrianz on 30/09/2016. + */ + +@Configuration +public class MvcConfig extends WebMvcConfigurerAdapter { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("private"); + } +} diff --git a/spring-security-custom-voter/src/main/resources/spring-security.xml b/spring-security-custom-voter/src/main/resources/spring-security.xml new file mode 100644 index 0000000000..117638289e --- /dev/null +++ b/spring-security-custom-voter/src/main/resources/spring-security.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-security-custom-voter/src/main/resources/templates/private.html b/spring-security-custom-voter/src/main/resources/templates/private.html new file mode 100644 index 0000000000..5af8c7a13e --- /dev/null +++ b/spring-security-custom-voter/src/main/resources/templates/private.html @@ -0,0 +1,10 @@ + + + + Private + + +

Congrats!

+ + \ No newline at end of file diff --git a/spring-security-custom-voter/src/main/webapp/WEB-INF/web.xml b/spring-security-custom-voter/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..d69bce35ae --- /dev/null +++ b/spring-security-custom-voter/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,47 @@ + + + + Spring Secured Application + + + + mvc + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc + / + + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + org.baeldung.spring.web.config + + + + org.springframework.web.context.ContextLoaderListener + + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + \ No newline at end of file diff --git a/spring-security-custom-voter/src/test/java/org/baeldung/web/LiveTest.java b/spring-security-custom-voter/src/test/java/org/baeldung/web/LiveTest.java new file mode 100644 index 0000000000..3ddeab5920 --- /dev/null +++ b/spring-security-custom-voter/src/test/java/org/baeldung/web/LiveTest.java @@ -0,0 +1,42 @@ +package org.baeldung.web; + +import org.junit.Before; +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.ContextConfiguration; +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.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @WebAppConfiguration @SpringBootTest public class LiveTest { + @Autowired private WebApplicationContext context; + + private MockMvc mvc; + + @Before public void setup() { + mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); + } + + @Test public void givenUnauthenticatedUser_whenAccessingMainPage_thenRedirect() throws Exception { + mvc.perform(get("/")).andExpect(status().is3xxRedirection()); + } + + @Test public void givenValidUsernameAndPassword_whenLogin_thenOK() throws Exception { + mvc.perform(formLogin("/login").user("user").password("pass")).andExpect(authenticated()); + } + + @Test public void givenAuthenticatedAdmin_whenAccessingMainPage_thenOK() throws Exception { + mvc.perform(get("/").with(user("admin").password("pass").roles("ADMIN"))).andExpect(status().isOk()); + } +} From 18dfed06d0c68fe46eeffc0d7730a64d49d76f75 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 22 Oct 2016 15:08:10 +0200 Subject: [PATCH 167/193] add integration test profile --- jjwt/pom.xml | 49 +++++++++++++++++-- ...va => DemoApplicationIntegrationTest.java} | 2 +- 2 files changed, 47 insertions(+), 4 deletions(-) rename jjwt/src/test/java/io/jsonwebtoken/jjwtfun/{DemoApplicationTests.java => DemoApplicationIntegrationTest.java} (91%) diff --git a/jjwt/pom.xml b/jjwt/pom.xml index 24f1c5c5ab..d2a3f1cdd8 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -58,8 +58,51 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + - - - + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationTests.java b/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java similarity index 91% rename from jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationTests.java rename to jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java index 82138ea23e..df147232d9 100644 --- a/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationTests.java +++ b/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = JJWTFunApplication.class) @WebAppConfiguration -public class DemoApplicationTests { +public class DemoApplicationIntegrationTest { @Test public void contextLoads() { From d60874a90d873b334f46c7d08190fb3d941c0387 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 22 Oct 2016 17:01:45 +0200 Subject: [PATCH 168/193] add integration test profile --- java-cassandra/pom.xml | 49 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/java-cassandra/pom.xml b/java-cassandra/pom.xml index a91c3b9b62..92d3a8ede6 100644 --- a/java-cassandra/pom.xml +++ b/java-cassandra/pom.xml @@ -76,8 +76,54 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + - + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + UTF-8 @@ -97,6 +143,7 @@ 3.5.1 + 2.19.1 3.1.0 From 5c7d521402e858d532255ce506b628f447705c13 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 22 Oct 2016 17:07:54 +0200 Subject: [PATCH 169/193] add integration test profile --- hystrix/pom.xml | 49 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 42828e1c97..54c17f1487 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -112,9 +112,54 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + - - + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + From c9b956e9b949561ee557b7a8b886b3411568f4da Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 22 Oct 2016 17:21:26 +0200 Subject: [PATCH 170/193] add integration test profile --- dependency-injection/pom.xml | 42 +++++++++++++++++-- ...ava => FieldAutowiredIntegrationTest.java} | 2 +- ...=> FieldAutowiredNameIntegrationTest.java} | 2 +- ...eldQualifierAutowiredIntegrationTest.java} | 2 +- ... => FieldByNameInjectIntegrationTest.java} | 2 +- ...t.java => FieldInjectIntegrationTest.java} | 2 +- ... FieldQualifierInjectIntegrationTest.java} | 2 +- ...ieldResourceInjectionIntegrationTest.java} | 2 +- ...odByQualifierResourceIntegrationTest.java} | 2 +- ... MethodByTypeResourceIntegrationTest.java} | 2 +- ...thodResourceInjectionIntegrationTest.java} | 2 +- ...java => NamedResourceIntegrationTest.java} | 2 +- ...fierResourceInjectionIntegrationTest.java} | 2 +- ...tterResourceInjectionIntegrationTest.java} | 2 +- 14 files changed, 52 insertions(+), 16 deletions(-) rename dependency-injection/src/test/java/com/baeldung/autowired/{FieldAutowiredTest.java => FieldAutowiredIntegrationTest.java} (95%) rename dependency-injection/src/test/java/com/baeldung/autowired/{FieldAutowiredNameTest.java => FieldAutowiredNameIntegrationTest.java} (95%) rename dependency-injection/src/test/java/com/baeldung/autowired/{FieldQualifierAutowiredTest.java => FieldQualifierAutowiredIntegrationTest.java} (96%) rename dependency-injection/src/test/java/com/baeldung/inject/{FieldByNameInjectTest.java => FieldByNameInjectIntegrationTest.java} (95%) rename dependency-injection/src/test/java/com/baeldung/inject/{FieldInjectTest.java => FieldInjectIntegrationTest.java} (95%) rename dependency-injection/src/test/java/com/baeldung/inject/{FieldQualifierInjectTest.java => FieldQualifierInjectIntegrationTest.java} (96%) rename dependency-injection/src/test/java/com/baeldung/resource/{FieldResourceInjectionTest.java => FieldResourceInjectionIntegrationTest.java} (94%) rename dependency-injection/src/test/java/com/baeldung/resource/{MethodByQualifierResourceTest.java => MethodByQualifierResourceIntegrationTest.java} (96%) rename dependency-injection/src/test/java/com/baeldung/resource/{MethodByTypeResourceTest.java => MethodByTypeResourceIntegrationTest.java} (95%) rename dependency-injection/src/test/java/com/baeldung/resource/{MethodResourceInjectionTest.java => MethodResourceInjectionIntegrationTest.java} (95%) rename dependency-injection/src/test/java/com/baeldung/resource/{NamedResourceTest.java => NamedResourceIntegrationTest.java} (95%) rename dependency-injection/src/test/java/com/baeldung/resource/{QualifierResourceInjectionTest.java => QualifierResourceInjectionIntegrationTest.java} (95%) rename dependency-injection/src/test/java/com/baeldung/resource/{SetterResourceInjectionTest.java => SetterResourceInjectionIntegrationTest.java} (95%) diff --git a/dependency-injection/pom.xml b/dependency-injection/pom.xml index 9e78a66ad6..9b94ba7b35 100644 --- a/dependency-injection/pom.xml +++ b/dependency-injection/pom.xml @@ -66,9 +66,10 @@ org.apache.maven.plugins maven-surefire-plugin - - **/*Test.java - + + **/*IntegrationTest.java + **/*LiveTest.java + @@ -85,6 +86,41 @@ + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 2.6 diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java rename to dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java index b736871f85..a78799f1d9 100644 --- a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java +++ b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestAutowiredType.class) -public class FieldAutowiredTest { +public class FieldAutowiredIntegrationTest { @Autowired private ArbitraryDependency fieldDependency; diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java rename to dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java index cbdac68543..8f09e73c33 100644 --- a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java +++ b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestAutowiredName.class) -public class FieldAutowiredNameTest { +public class FieldAutowiredNameIntegrationTest { @Autowired private ArbitraryDependency autowiredFieldDependency; diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java b/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java similarity index 96% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java rename to dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java index cbc3d56f67..01317aef6f 100644 --- a/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java +++ b/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestAutowiredQualifier.class) -public class FieldQualifierAutowiredTest { +public class FieldQualifierAutowiredIntegrationTest { @Autowired @Qualifier("autowiredFieldDependency") diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java b/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java rename to dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java index 665c9f1ddc..f5897febab 100644 --- a/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java +++ b/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java @@ -18,7 +18,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestInjectName.class) -public class FieldByNameInjectTest { +public class FieldByNameInjectIntegrationTest { @Inject @Named("yetAnotherFieldInjectDependency") diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectTest.java b/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldInjectTest.java rename to dependency-injection/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java index 7561c39e76..45b7c8015c 100644 --- a/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectTest.java +++ b/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestInjectType.class) -public class FieldInjectTest { +public class FieldInjectIntegrationTest { @Inject private ArbitraryDependency fieldInjectDependency; diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java b/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java similarity index 96% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java rename to dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java index 7e5f7e7453..0fd6a0e4c1 100644 --- a/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java +++ b/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestInjectQualifier.class) -public class FieldQualifierInjectTest { +public class FieldQualifierInjectIntegrationTest { @Inject @Qualifier("defaultFile") diff --git a/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionTest.java b/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java similarity index 94% rename from dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionTest.java rename to dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java index ef7e7b0aeb..63a25cb499 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionTest.java +++ b/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class FieldResourceInjectionTest { +public class FieldResourceInjectionIntegrationTest { @Resource(name = "namedFile") private File defaultFile; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceTest.java b/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java similarity index 96% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceTest.java rename to dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java index 95e9fc0bd5..f5bb9f10cf 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceTest.java +++ b/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java @@ -18,7 +18,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceQualifier.class) -public class MethodByQualifierResourceTest { +public class MethodByQualifierResourceIntegrationTest { private File arbDependency; private File anotherArbDependency; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java b/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java rename to dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java index ad9a9a4fb6..171cbfea47 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java +++ b/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class MethodByTypeResourceTest { +public class MethodByTypeResourceIntegrationTest { private File defaultFile; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java b/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java rename to dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java index 1622d8896c..2e1c3c39a9 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java +++ b/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class MethodResourceInjectionTest { +public class MethodResourceInjectionIntegrationTest { private File defaultFile; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java b/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java rename to dependency-injection/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java index da104ecaae..d52660e9b8 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java +++ b/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class NamedResourceTest { +public class NamedResourceIntegrationTest { @Resource(name = "namedFile") private File testFile; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionTest.java b/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionTest.java rename to dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java index 024c8e2bbe..3f812350c9 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionTest.java +++ b/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java @@ -18,7 +18,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceQualifier.class) -public class QualifierResourceInjectionTest { +public class QualifierResourceInjectionIntegrationTest { @Resource @Qualifier("defaultFile") diff --git a/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java b/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java rename to dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java index aa7cfda975..ae13b2336a 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java +++ b/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class SetterResourceInjectionTest { +public class SetterResourceInjectionIntegrationTest { private File defaultFile; From d8c4b20e71201d04e03f3dd6600342f391d2ec7f Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 22 Oct 2016 19:27:31 +0200 Subject: [PATCH 171/193] add integration test profile --- cdi/pom.xml | 52 +++++++++++++++++++ ... => SpringInterceptorIntegrationTest.java} | 2 +- 2 files changed, 53 insertions(+), 1 deletion(-) rename cdi/src/test/java/com/baeldung/test/{TestSpringInterceptor.java => SpringInterceptorIntegrationTest.java} (95%) diff --git a/cdi/pom.xml b/cdi/pom.xml index b771857938..30dd167fa8 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -45,8 +45,60 @@
+ + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + 4.3.1.RELEASE + 2.19.1 \ No newline at end of file diff --git a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java b/cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java similarity index 95% rename from cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java rename to cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java index 1f3a8d83e3..cffa2256ca 100644 --- a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java +++ b/cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java @@ -16,7 +16,7 @@ import com.baeldung.spring.service.SpringSuperService; @RunWith(SpringRunner.class) @ContextConfiguration(classes = { AppConfig.class }) -public class TestSpringInterceptor { +public class SpringInterceptorIntegrationTest { @Autowired SpringSuperService springSuperService; From 366914a25ead8352c66290acd6047e6a6524b2d4 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 22 Oct 2016 20:22:23 +0200 Subject: [PATCH 172/193] Fix Screenshot Test --- .../src/test/java/com/baeldung/printscreen/ScreenshotTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java index 895f514f4a..7e35fc3e30 100644 --- a/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java +++ b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java @@ -10,7 +10,7 @@ import static org.junit.Assert.assertTrue; public class ScreenshotTest { - private Screenshot screenshot = new Screenshot("", "Screenshot", "jpg"); + private Screenshot screenshot = new Screenshot("Screenshot.jpg"); private File file = new File("Screenshot.jpg"); @Test From b018c6ca3b38994c7b01a4f362d0d634536ea620 Mon Sep 17 00:00:00 2001 From: Nancy Bosecker Date: Sat, 22 Oct 2016 22:47:44 -0700 Subject: [PATCH 173/193] Fixed http ssl apache 4.4 test, moved from Sandbox to Live class (#764) * Moved project to core-java from eclipse folder * Fixed http ssl test, moved from Sandbox to Live. --- .../httpclient/HttpsClientSslLiveTest.java | 31 ++++++++++++++++++- .../base/HttpClientSandboxLiveTest.java | 11 ------- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java index 952ce3af25..34f99b9fb6 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java @@ -1,10 +1,12 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import java.io.IOException; import java.security.GeneralSecurityException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; @@ -16,6 +18,7 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.SSLContexts; @@ -108,4 +111,30 @@ public class HttpsClientSslLiveTest { assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } + @Test + public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, IOException { + + TrustStrategy acceptingTrustStrategy = new TrustStrategy() { + @Override + public boolean isTrusted(X509Certificate[] certificate, String authType) { + return true; + } + }; + + SSLContext sslContext = null; + try { + sslContext = new SSLContextBuilder().loadTrustMaterial(null, acceptingTrustStrategy).build(); + + } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { + e.printStackTrace(); + } + + CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + final HttpGet httpGet = new HttpGet("https://sesar3.geoinfogeochem.org/sample/igsn/ODP000002"); + httpGet.setHeader("Accept", "application/xml"); + + final HttpResponse response = client.execute(httpGet); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + } + } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java index 2333e2f8c9..ce4057aa6d 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java @@ -59,15 +59,4 @@ public class HttpClientSandboxLiveTest { System.out.println(response.getStatusLine()); } - - @Test - public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, IOException { - final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); - - final HttpGet httpGet = new HttpGet("https://sesar3.geoinfogeochem.org/sample/igsn/ODP000002"); - httpGet.setHeader("Accept", "application/xml"); - - response = httpClient.execute(httpGet); - } - } From d0a376e6226b9658003d59ac0eb0872f7fdd457b Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 07:54:09 +0200 Subject: [PATCH 174/193] Refactor HttpClient test --- .../httpclient/HttpsClientSslLiveTest.java | 57 ++++++------------- .../httpclient/base/HttpClientLiveTest.java | 25 ++++---- .../base/HttpClientSandboxLiveTest.java | 11 ++-- 3 files changed, 33 insertions(+), 60 deletions(-) diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java index 34f99b9fb6..66b4f5cff4 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java @@ -1,30 +1,11 @@ package org.baeldung.httpclient; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLException; - import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.NoopHostnameVerifier; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLContextBuilder; -import org.apache.http.conn.ssl.SSLContexts; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.conn.ssl.TrustStrategy; +import org.apache.http.conn.ssl.*; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClientBuilder; @@ -32,6 +13,17 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.junit.Test; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + /** * This test requires a localhost server over HTTPS
* It should only be manually run, not part of the automated build @@ -45,7 +37,7 @@ public class HttpsClientSslLiveTest { // tests @Test(expected = SSLException.class) - public final void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException { + public final void whenHttpsUrlIsConsumed_thenException() throws IOException { final CloseableHttpClient httpClient = HttpClientBuilder.create().build(); final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); @@ -56,12 +48,7 @@ public class HttpsClientSslLiveTest { @SuppressWarnings("deprecation") @Test public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { - final TrustStrategy acceptingTrustStrategy = new TrustStrategy() { - @Override - public final boolean isTrusted(final X509Certificate[] certificate, final String authType) { - return true; - } - }; + final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", 443, sf)); @@ -78,12 +65,7 @@ public class HttpsClientSslLiveTest { @Test public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { - final TrustStrategy acceptingTrustStrategy = new TrustStrategy() { - @Override - public final boolean isTrusted(final X509Certificate[] certificate, final String authType) { - return true; - } - }; + final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); @@ -112,14 +94,9 @@ public class HttpsClientSslLiveTest { } @Test - public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, IOException { + public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException { - TrustStrategy acceptingTrustStrategy = new TrustStrategy() { - @Override - public boolean isTrusted(X509Certificate[] certificate, String authType) { - return true; - } - }; + TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; SSLContext sslContext = null; try { diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java index 23c1fdf430..878d220f67 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java @@ -1,16 +1,8 @@ package org.baeldung.httpclient.base; -import static org.hamcrest.Matchers.emptyArray; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -23,6 +15,13 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; +import java.io.InputStream; + +import static org.hamcrest.Matchers.emptyArray; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; + public class HttpClientLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; @@ -56,7 +55,7 @@ public class HttpClientLiveTest { // tests @Test(expected = ConnectTimeoutException.class) - public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws ClientProtocolException, IOException { + public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException { final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(20).build(); final HttpGet request = new HttpGet(SAMPLE_URL); request.setConfig(requestConfig); @@ -66,20 +65,20 @@ public class HttpClientLiveTest { // tests - configs @Test - public final void givenHttpClientIsConfiguredWithCustomConnectionManager_whenExecutingRequest_thenNoExceptions() throws ClientProtocolException, IOException { + public final void givenHttpClientIsConfiguredWithCustomConnectionManager_whenExecutingRequest_thenNoExceptions() throws IOException { instance = HttpClientBuilder.create().setConnectionManager(new BasicHttpClientConnectionManager()).build(); response = instance.execute(new HttpGet(SAMPLE_URL)); } @Test - public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws ClientProtocolException, IOException { + public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); request.addHeader(HttpHeaders.ACCEPT, "application/xml"); response = instance.execute(request); } @Test - public final void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws ClientProtocolException, IOException { + public final void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws IOException { response = instance.execute(new HttpGet(SAMPLE_URL)); final Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE); @@ -89,7 +88,7 @@ public class HttpClientLiveTest { // tests - cancel request @Test - public final void whenRequestIsCanceled_thenCorrect() throws ClientProtocolException, IOException { + public final void whenRequestIsCanceled_thenCorrect() throws IOException { instance = HttpClients.custom().build(); final HttpGet request = new HttpGet(SAMPLE_URL); response = instance.execute(request); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java index ce4057aa6d..c82022eb3f 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java @@ -1,23 +1,20 @@ package org.baeldung.httpclient.base; -import java.io.IOException; -import java.io.InputStream; - import org.apache.http.HttpEntity; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; import org.junit.After; import org.junit.Test; +import java.io.IOException; +import java.io.InputStream; + public class HttpClientSandboxLiveTest { private CloseableHttpClient client; @@ -47,7 +44,7 @@ public class HttpClientSandboxLiveTest { // simple request - response @Test - public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws ClientProtocolException, IOException { + public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); final AuthScope authscp = new AuthScope("localhost", 8080); credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass")); From bfddf3344d5f65342c2cbbc8871c925f678ca6f4 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 07:55:07 +0200 Subject: [PATCH 175/193] Refactor LiveTest --- .../base/HttpClientSandboxLiveTest.java | 36 ++++++------------- 1 file changed, 10 insertions(+), 26 deletions(-) diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java index c82022eb3f..22b32e7ef5 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java @@ -9,7 +9,6 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.junit.After; import org.junit.Test; import java.io.IOException; @@ -17,15 +16,18 @@ import java.io.InputStream; public class HttpClientSandboxLiveTest { - private CloseableHttpClient client; + @Test + public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { + final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + final AuthScope authscp = new AuthScope("localhost", 8080); + credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass")); - private CloseableHttpResponse response; + CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build(); - @After - public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } + final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1"); + CloseableHttpResponse response = client.execute(httpGet); + + System.out.println(response.getStatusLine()); try { final HttpEntity entity = response.getEntity(); @@ -38,22 +40,4 @@ public class HttpClientSandboxLiveTest { response.close(); } } - - // tests - - // simple request - response - - @Test - public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { - final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - final AuthScope authscp = new AuthScope("localhost", 8080); - credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass")); - - client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build(); - - final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1"); - response = client.execute(httpGet); - - System.out.println(response.getStatusLine()); - } } From 1e53355b1315be5b34bb3f807b82c97248013b52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ambrus=20Adri=C3=A1n-Zolt=C3=A1n?= Date: Sun, 23 Oct 2016 10:52:59 +0300 Subject: [PATCH 176/193] Changed collect, forEach call to filter, findAny, orElseGet --- .../java/org/baeldung/security/MinuteBasedVoter.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java b/spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java index 8d22c52b0d..ae698789e1 100644 --- a/spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java +++ b/spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java @@ -23,16 +23,17 @@ public class MinuteBasedVoter implements AccessDecisionVoter { @Override public int vote(Authentication authentication, Object object, Collection collection) { - List roles = authentication + String role = authentication .getAuthorities() .stream().map(GrantedAuthority::getAuthority) - .collect(Collectors.toList()); + .filter("ROLE_USER"::equals) + .findAny() + .orElseGet(() -> "ROLE_ADMIN"); - for (String role: roles) { - if ("ROLE_USER".equals(role) && LocalDateTime.now().getMinute() % 2 != 0) { + if ("ROLE_USER".equals(role) && LocalDateTime.now().getMinute() % 2 != 0) { return ACCESS_DENIED; - } } + return ACCESS_ABSTAIN; } } From 4670b8dbdabaf3dd0294c69f93d6399322e55509 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 11:25:09 +0200 Subject: [PATCH 177/193] Sockets moved to core-java --- core-java/README.md | 1 + .../java/com/baeldung/socket/EchoClient.java | 0 .../com/baeldung/socket/EchoMultiServer.java | 2 +- .../java/com/baeldung/socket/EchoServer.java | 2 +- .../java/com/baeldung/socket/GreetClient.java | 0 .../java/com/baeldung/socket/GreetServer.java | 0 .../com/baeldung/socket/EchoMultiTest.java | 6 ++-- .../java/com/baeldung/socket/EchoTest.java | 2 +- .../com/baeldung/socket/GreetServerTest.java | 0 sockets/README.md | 2 -- sockets/pom.xml | 30 ------------------- 11 files changed, 7 insertions(+), 38 deletions(-) rename {sockets => core-java}/src/main/java/com/baeldung/socket/EchoClient.java (100%) rename {sockets => core-java}/src/main/java/com/baeldung/socket/EchoMultiServer.java (97%) rename {sockets => core-java}/src/main/java/com/baeldung/socket/EchoServer.java (96%) rename {sockets => core-java}/src/main/java/com/baeldung/socket/GreetClient.java (100%) rename {sockets => core-java}/src/main/java/com/baeldung/socket/GreetServer.java (100%) rename {sockets => core-java}/src/test/java/com/baeldung/socket/EchoMultiTest.java (91%) rename {sockets => core-java}/src/test/java/com/baeldung/socket/EchoTest.java (95%) rename {sockets => core-java}/src/test/java/com/baeldung/socket/GreetServerTest.java (100%) delete mode 100644 sockets/README.md delete mode 100644 sockets/pom.xml diff --git a/core-java/README.md b/core-java/README.md index 440af67252..fbbfa65589 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -18,3 +18,4 @@ - [MD5 Hashing in Java](http://www.baeldung.com/java-md5) - [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist) - [Guide to Java Reflection](http://www.baeldung.com/java-reflection) +- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) diff --git a/sockets/src/main/java/com/baeldung/socket/EchoClient.java b/core-java/src/main/java/com/baeldung/socket/EchoClient.java similarity index 100% rename from sockets/src/main/java/com/baeldung/socket/EchoClient.java rename to core-java/src/main/java/com/baeldung/socket/EchoClient.java diff --git a/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java similarity index 97% rename from sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java rename to core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java index 2ece1ceebe..1177b82c87 100644 --- a/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java @@ -46,7 +46,7 @@ public class EchoMultiServer { clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { - if (".".equals(inputLine)) { + if ("".equals(inputLine)) { out.println("bye"); break; } diff --git a/sockets/src/main/java/com/baeldung/socket/EchoServer.java b/core-java/src/main/java/com/baeldung/socket/EchoServer.java similarity index 96% rename from sockets/src/main/java/com/baeldung/socket/EchoServer.java rename to core-java/src/main/java/com/baeldung/socket/EchoServer.java index 3607afa7f5..395624933c 100644 --- a/sockets/src/main/java/com/baeldung/socket/EchoServer.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoServer.java @@ -18,7 +18,7 @@ public class EchoServer { clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { - if (".".equals(inputLine)) { + if ("".equals(inputLine)) { out.println("good bye"); break; } diff --git a/sockets/src/main/java/com/baeldung/socket/GreetClient.java b/core-java/src/main/java/com/baeldung/socket/GreetClient.java similarity index 100% rename from sockets/src/main/java/com/baeldung/socket/GreetClient.java rename to core-java/src/main/java/com/baeldung/socket/GreetClient.java diff --git a/sockets/src/main/java/com/baeldung/socket/GreetServer.java b/core-java/src/main/java/com/baeldung/socket/GreetServer.java similarity index 100% rename from sockets/src/main/java/com/baeldung/socket/GreetServer.java rename to core-java/src/main/java/com/baeldung/socket/GreetServer.java diff --git a/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java b/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java similarity index 91% rename from sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java rename to core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java index 19a59c211c..ef08385551 100644 --- a/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java @@ -21,7 +21,7 @@ public class EchoMultiTest { client.startConnection("127.0.0.1", 5555); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage("."); + String terminate = client.sendMessage(""); assertEquals(msg1, "hello"); assertEquals(msg2, "world"); assertEquals(terminate, "bye"); @@ -34,7 +34,7 @@ public class EchoMultiTest { client.startConnection("127.0.0.1", 5555); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage("."); + String terminate = client.sendMessage(""); assertEquals(msg1, "hello"); assertEquals(msg2, "world"); assertEquals(terminate, "bye"); @@ -47,7 +47,7 @@ public class EchoMultiTest { client.startConnection("127.0.0.1", 5555); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage("."); + String terminate = client.sendMessage(""); assertEquals(msg1, "hello"); assertEquals(msg2, "world"); assertEquals(terminate, "bye"); diff --git a/sockets/src/test/java/com/baeldung/socket/EchoTest.java b/core-java/src/test/java/com/baeldung/socket/EchoTest.java similarity index 95% rename from sockets/src/test/java/com/baeldung/socket/EchoTest.java rename to core-java/src/test/java/com/baeldung/socket/EchoTest.java index 0f0c02e4d8..c12bd28a29 100644 --- a/sockets/src/test/java/com/baeldung/socket/EchoTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoTest.java @@ -26,7 +26,7 @@ public class EchoTest { String resp1 = client.sendMessage("hello"); String resp2 = client.sendMessage("world"); String resp3 = client.sendMessage("!"); - String resp4 = client.sendMessage("."); + String resp4 = client.sendMessage(""); assertEquals("hello", resp1); assertEquals("world", resp2); assertEquals("!", resp3); diff --git a/sockets/src/test/java/com/baeldung/socket/GreetServerTest.java b/core-java/src/test/java/com/baeldung/socket/GreetServerTest.java similarity index 100% rename from sockets/src/test/java/com/baeldung/socket/GreetServerTest.java rename to core-java/src/test/java/com/baeldung/socket/GreetServerTest.java diff --git a/sockets/README.md b/sockets/README.md deleted file mode 100644 index ad8811ee80..0000000000 --- a/sockets/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) diff --git a/sockets/pom.xml b/sockets/pom.xml deleted file mode 100644 index 24e8e436f3..0000000000 --- a/sockets/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - 4.0.0 - com.baeldung - sockets - 1.0 - sockets - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 8 - 8 - - - - - - - junit - junit - 4.3 - test - - - - From 803145826525fd88d3138d12fc9513f5cb16b8a5 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 11:53:43 +0200 Subject: [PATCH 178/193] Refactor Socket tests --- .../com/baeldung/socket/EchoMultiTest.java | 20 ++++++++++--------- .../java/com/baeldung/socket/EchoTest.java | 16 +++++++++------ .../com/baeldung/socket/GreetServerTest.java | 13 ++++++++---- 3 files changed, 30 insertions(+), 19 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java b/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java index ef08385551..ccb5f48ddb 100644 --- a/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java @@ -1,7 +1,6 @@ package com.baeldung.socket; -import org.junit.After; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import java.util.concurrent.Executors; @@ -10,18 +9,22 @@ import static org.junit.Assert.assertEquals; public class EchoMultiTest { - { - Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(5555)); - } + private static final Integer PORT = 5555; + @BeforeClass + public static void start() throws InterruptedException { + Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(PORT)); + Thread.sleep(500); + } @Test public void givenClient1_whenServerResponds_thenCorrect() { EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", 5555); + client.startConnection("127.0.0.1", PORT); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); String terminate = client.sendMessage(""); + assertEquals(msg1, "hello"); assertEquals(msg2, "world"); assertEquals(terminate, "bye"); @@ -31,7 +34,7 @@ public class EchoMultiTest { @Test public void givenClient2_whenServerResponds_thenCorrect() { EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", 5555); + client.startConnection("127.0.0.1", PORT); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); String terminate = client.sendMessage(""); @@ -44,7 +47,7 @@ public class EchoMultiTest { @Test public void givenClient3_whenServerResponds_thenCorrect() { EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", 5555); + client.startConnection("127.0.0.1", PORT); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); String terminate = client.sendMessage(""); @@ -53,5 +56,4 @@ public class EchoMultiTest { assertEquals(terminate, "bye"); client.stopConnection(); } - } diff --git a/core-java/src/test/java/com/baeldung/socket/EchoTest.java b/core-java/src/test/java/com/baeldung/socket/EchoTest.java index c12bd28a29..76391f0f20 100644 --- a/core-java/src/test/java/com/baeldung/socket/EchoTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoTest.java @@ -2,6 +2,7 @@ package com.baeldung.socket; import org.junit.After; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import java.util.concurrent.Executors; @@ -9,15 +10,19 @@ import java.util.concurrent.Executors; import static org.junit.Assert.assertEquals; public class EchoTest { - { - Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(4444)); - } + private static final Integer PORT = 4444; - EchoClient client = new EchoClient(); + @BeforeClass + public static void start() throws InterruptedException { + Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(PORT)); + Thread.sleep(500); + } + + private EchoClient client = new EchoClient(); @Before public void init() { - client.startConnection("127.0.0.1", 4444); + client.startConnection("127.0.0.1", PORT); } @Test @@ -37,5 +42,4 @@ public class EchoTest { public void tearDown() { client.stopConnection(); } - } diff --git a/core-java/src/test/java/com/baeldung/socket/GreetServerTest.java b/core-java/src/test/java/com/baeldung/socket/GreetServerTest.java index fedc32fb39..caf56a8c76 100644 --- a/core-java/src/test/java/com/baeldung/socket/GreetServerTest.java +++ b/core-java/src/test/java/com/baeldung/socket/GreetServerTest.java @@ -2,6 +2,7 @@ package com.baeldung.socket; import org.junit.After; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import java.util.concurrent.Executors; @@ -10,16 +11,20 @@ import static org.junit.Assert.assertEquals; public class GreetServerTest { - GreetClient client; + private GreetClient client; - { - Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(6666)); + private static final Integer PORT = 6666; + + @BeforeClass + public static void start() throws InterruptedException { + Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(PORT)); + Thread.sleep(500); } @Before public void init() { client = new GreetClient(); - client.startConnection("127.0.0.1", 6666); + client.startConnection("127.0.0.1", PORT); } From 65daa3aee2de7c813e852b1627be5fd288eac0eb Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 11:57:11 +0200 Subject: [PATCH 179/193] Refactor examples --- core-java/src/main/java/com/baeldung/socket/EchoClient.java | 3 +-- .../src/main/java/com/baeldung/socket/EchoMultiServer.java | 2 +- core-java/src/main/java/com/baeldung/socket/EchoServer.java | 2 +- .../src/main/java/com/baeldung/socket/GreetClient.java | 3 +-- .../src/test/java/com/baeldung/socket/EchoMultiTest.java | 6 +++--- core-java/src/test/java/com/baeldung/socket/EchoTest.java | 2 +- 6 files changed, 8 insertions(+), 10 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/socket/EchoClient.java b/core-java/src/main/java/com/baeldung/socket/EchoClient.java index e8ec97c80a..1ddf752a03 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoClient.java @@ -23,8 +23,7 @@ public class EchoClient { public String sendMessage(String msg) { try { out.println(msg); - String resp = in.readLine(); - return resp; + return in.readLine(); } catch (Exception e) { return null; } 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 1177b82c87..2ece1ceebe 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java @@ -46,7 +46,7 @@ public class EchoMultiServer { clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { - if ("".equals(inputLine)) { + if (".".equals(inputLine)) { out.println("bye"); break; } diff --git a/core-java/src/main/java/com/baeldung/socket/EchoServer.java b/core-java/src/main/java/com/baeldung/socket/EchoServer.java index 395624933c..3607afa7f5 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoServer.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoServer.java @@ -18,7 +18,7 @@ public class EchoServer { clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { - if ("".equals(inputLine)) { + if (".".equals(inputLine)) { out.println("good bye"); break; } diff --git a/core-java/src/main/java/com/baeldung/socket/GreetClient.java b/core-java/src/main/java/com/baeldung/socket/GreetClient.java index 7252827c87..21959c7469 100644 --- a/core-java/src/main/java/com/baeldung/socket/GreetClient.java +++ b/core-java/src/main/java/com/baeldung/socket/GreetClient.java @@ -26,8 +26,7 @@ public class GreetClient { public String sendMessage(String msg) { try { out.println(msg); - String resp = in.readLine(); - return resp; + return in.readLine(); } catch (Exception e) { return null; } diff --git a/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java b/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java index ccb5f48ddb..fcf353281d 100644 --- a/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java @@ -23,7 +23,7 @@ public class EchoMultiTest { client.startConnection("127.0.0.1", PORT); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage(""); + String terminate = client.sendMessage("."); assertEquals(msg1, "hello"); assertEquals(msg2, "world"); @@ -37,7 +37,7 @@ public class EchoMultiTest { client.startConnection("127.0.0.1", PORT); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage(""); + String terminate = client.sendMessage("."); assertEquals(msg1, "hello"); assertEquals(msg2, "world"); assertEquals(terminate, "bye"); @@ -50,7 +50,7 @@ public class EchoMultiTest { client.startConnection("127.0.0.1", PORT); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage(""); + String terminate = client.sendMessage("."); assertEquals(msg1, "hello"); assertEquals(msg2, "world"); assertEquals(terminate, "bye"); diff --git a/core-java/src/test/java/com/baeldung/socket/EchoTest.java b/core-java/src/test/java/com/baeldung/socket/EchoTest.java index 76391f0f20..cb09d42f79 100644 --- a/core-java/src/test/java/com/baeldung/socket/EchoTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoTest.java @@ -31,7 +31,7 @@ public class EchoTest { String resp1 = client.sendMessage("hello"); String resp2 = client.sendMessage("world"); String resp3 = client.sendMessage("!"); - String resp4 = client.sendMessage(""); + String resp4 = client.sendMessage("."); assertEquals("hello", resp1); assertEquals("world", resp2); assertEquals("!", resp3); From 8cdc680e6f76174625e5eba32f18d3f521301e3a Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 12:11:23 +0200 Subject: [PATCH 180/193] Remove gson-jackson-performance --- gson-jackson-performance/README.md | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 gson-jackson-performance/README.md diff --git a/gson-jackson-performance/README.md b/gson-jackson-performance/README.md deleted file mode 100644 index e662219718..0000000000 --- a/gson-jackson-performance/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Performance of Gson and Jackson - -Standalone java programs to measure the performance of both JSON APIs based on file size and object graph complexity. - -###Relevant Articles: -- [Jackson vs Gson: A Quick Look At Performance](http://www.baeldung.com/jackson-gson-performance) From bc9b170e89c1fa927eabc83fe268f35ddc88021e Mon Sep 17 00:00:00 2001 From: DOHA Date: Sun, 23 Oct 2016 12:19:55 +0200 Subject: [PATCH 181/193] configure test profiles --- apache-cxf/cxf-introduction/pom.xml | 65 ++++++++++- ...{StudentTest.java => StudentLiveTest.java} | 30 +++-- apache-cxf/cxf-jaxrs-implementation/pom.xml | 65 ++++++++++- ...{ServiceTest.java => ServiceLiveTest.java} | 107 +++++++++--------- apache-cxf/cxf-spring/pom.xml | 4 +- ...{StudentTest.java => StudentLiveTest.java} | 2 +- 6 files changed, 198 insertions(+), 75 deletions(-) rename apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/{StudentTest.java => StudentLiveTest.java} (65%) rename apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/{ServiceTest.java => ServiceLiveTest.java} (63%) rename apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/{StudentTest.java => StudentLiveTest.java} (97%) diff --git a/apache-cxf/cxf-introduction/pom.xml b/apache-cxf/cxf-introduction/pom.xml index 232a4f0089..9629dfda1b 100644 --- a/apache-cxf/cxf-introduction/pom.xml +++ b/apache-cxf/cxf-introduction/pom.xml @@ -11,6 +11,7 @@ 3.1.6 + 2.19.1 @@ -26,7 +27,7 @@ 2.19.1 - **/StudentTest.java + **/*LiveTest.java @@ -44,4 +45,66 @@ ${cxf.version} + + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + 1.4.19 + + + tomcat8x + embedded + + + + localhost + 8082 + + + + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + maven-surefire-plugin + ${surefire.version} + + + integration-test + + test + + + + none + + + + + + + + + + diff --git a/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentTest.java b/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java similarity index 65% rename from apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentTest.java rename to apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java index e1e5b60ec3..1c50fcb9b6 100644 --- a/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentTest.java +++ b/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java @@ -2,20 +2,16 @@ package com.baeldung.cxf.introduction; import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.Test; - import java.util.Map; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.soap.SOAPBinding; -import com.baeldung.cxf.introduction.Baeldung; -import com.baeldung.cxf.introduction.Student; -import com.baeldung.cxf.introduction.StudentImpl; +import org.junit.Before; +import org.junit.Test; -public class StudentTest { +public class StudentLiveTest { private static QName SERVICE_NAME = new QName("http://introduction.cxf.baeldung.com/", "Baeldung"); private static QName PORT_NAME = new QName("http://introduction.cxf.baeldung.com/", "BaeldungPort"); @@ -25,7 +21,7 @@ public class StudentTest { { service = Service.create(SERVICE_NAME); - String endpointAddress = "http://localhost:8080/baeldung"; + final String endpointAddress = "http://localhost:8082/cxf-introduction/baeldung"; service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress); } @@ -37,28 +33,28 @@ public class StudentTest { @Test public void whenUsingHelloMethod_thenCorrect() { - String endpointResponse = baeldungProxy.hello("Baeldung"); - String localResponse = baeldungImpl.hello("Baeldung"); + final String endpointResponse = baeldungProxy.hello("Baeldung"); + final String localResponse = baeldungImpl.hello("Baeldung"); assertEquals(localResponse, endpointResponse); } @Test public void whenUsingHelloStudentMethod_thenCorrect() { - Student student = new StudentImpl("John Doe"); - String endpointResponse = baeldungProxy.helloStudent(student); - String localResponse = baeldungImpl.helloStudent(student); + final Student student = new StudentImpl("John Doe"); + final String endpointResponse = baeldungProxy.helloStudent(student); + final String localResponse = baeldungImpl.helloStudent(student); assertEquals(localResponse, endpointResponse); } @Test public void usingGetStudentsMethod_thenCorrect() { - Student student1 = new StudentImpl("Adam"); + final Student student1 = new StudentImpl("Adam"); baeldungProxy.helloStudent(student1); - Student student2 = new StudentImpl("Eve"); + final Student student2 = new StudentImpl("Eve"); baeldungProxy.helloStudent(student2); - - Map students = baeldungProxy.getStudents(); + + final Map students = baeldungProxy.getStudents(); assertEquals("Adam", students.get(1).getName()); assertEquals("Eve", students.get(2).getName()); } diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml index 1f83ecf934..24dad05a0f 100644 --- a/apache-cxf/cxf-jaxrs-implementation/pom.xml +++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml @@ -13,6 +13,7 @@ UTF-8 3.1.7 4.5.2 + 2.19.1
@@ -28,7 +29,7 @@ 2.19.1 - **/ServiceTest + **/*LiveTest.java @@ -51,4 +52,66 @@ ${httpclient.version} + + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + 1.4.19 + + + tomcat8x + embedded + + + + localhost + 8082 + + + + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + maven-surefire-plugin + ${surefire.version} + + + integration-test + + test + + + + none + + + + + + + + + + diff --git a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java similarity index 63% rename from apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java rename to apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java index b8fc833194..692def81f5 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java @@ -1,5 +1,14 @@ package com.baeldung.cxf.jaxrs.implementation; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; + +import javax.xml.bind.JAXB; + import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpPost; @@ -11,119 +20,111 @@ import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import javax.xml.bind.JAXB; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; - -import static org.junit.Assert.assertEquals; - -public class ServiceTest { - private static final String BASE_URL = "http://localhost:8080/baeldung/courses/"; +public class ServiceLiveTest { + private static final String BASE_URL = "http://localhost:8082/baeldung/courses/"; private static CloseableHttpClient client; - + @BeforeClass public static void createClient() { client = HttpClients.createDefault(); } - + @AfterClass public static void closeClient() throws IOException { client.close(); } - + @Test public void whenUpdateNonExistentCourse_thenReceiveNotFoundResponse() throws IOException { - HttpPut httpPut = new HttpPut(BASE_URL + "3"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("non_existent_course.xml"); + final HttpPut httpPut = new HttpPut(BASE_URL + "3"); + final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("non_existent_course.xml"); httpPut.setEntity(new InputStreamEntity(resourceStream)); httpPut.setHeader("Content-Type", "text/xml"); - - HttpResponse response = client.execute(httpPut); + + final HttpResponse response = client.execute(httpPut); assertEquals(404, response.getStatusLine().getStatusCode()); } - + @Test public void whenUpdateUnchangedCourse_thenReceiveNotModifiedResponse() throws IOException { - HttpPut httpPut = new HttpPut(BASE_URL + "1"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("unchanged_course.xml"); + final HttpPut httpPut = new HttpPut(BASE_URL + "1"); + final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("unchanged_course.xml"); httpPut.setEntity(new InputStreamEntity(resourceStream)); httpPut.setHeader("Content-Type", "text/xml"); - - HttpResponse response = client.execute(httpPut); + + final HttpResponse response = client.execute(httpPut); assertEquals(304, response.getStatusLine().getStatusCode()); } - + @Test public void whenUpdateValidCourse_thenReceiveOKResponse() throws IOException { - HttpPut httpPut = new HttpPut(BASE_URL + "2"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("changed_course.xml"); + final HttpPut httpPut = new HttpPut(BASE_URL + "2"); + final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("changed_course.xml"); httpPut.setEntity(new InputStreamEntity(resourceStream)); httpPut.setHeader("Content-Type", "text/xml"); - - HttpResponse response = client.execute(httpPut); + + final HttpResponse response = client.execute(httpPut); assertEquals(200, response.getStatusLine().getStatusCode()); - - Course course = getCourse(2); + + final Course course = getCourse(2); assertEquals(2, course.getId()); assertEquals("Apache CXF Support for RESTful", course.getName()); } - + @Test public void whenCreateConflictStudent_thenReceiveConflictResponse() throws IOException { - HttpPost httpPost = new HttpPost(BASE_URL + "1/students"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("conflict_student.xml"); + final HttpPost httpPost = new HttpPost(BASE_URL + "1/students"); + final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("conflict_student.xml"); httpPost.setEntity(new InputStreamEntity(resourceStream)); httpPost.setHeader("Content-Type", "text/xml"); - - HttpResponse response = client.execute(httpPost); + + final HttpResponse response = client.execute(httpPost); assertEquals(409, response.getStatusLine().getStatusCode()); } @Test public void whenCreateValidStudent_thenReceiveOKResponse() throws IOException { - HttpPost httpPost = new HttpPost(BASE_URL + "2/students"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("created_student.xml"); + final HttpPost httpPost = new HttpPost(BASE_URL + "2/students"); + final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("created_student.xml"); httpPost.setEntity(new InputStreamEntity(resourceStream)); httpPost.setHeader("Content-Type", "text/xml"); - - HttpResponse response = client.execute(httpPost); + + final HttpResponse response = client.execute(httpPost); assertEquals(200, response.getStatusLine().getStatusCode()); - - Student student = getStudent(2, 3); + + final Student student = getStudent(2, 3); assertEquals(3, student.getId()); assertEquals("Student C", student.getName()); } - + @Test public void whenDeleteInvalidStudent_thenReceiveNotFoundResponse() throws IOException { - HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/3"); - HttpResponse response = client.execute(httpDelete); + final HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/3"); + final HttpResponse response = client.execute(httpDelete); assertEquals(404, response.getStatusLine().getStatusCode()); - } - + } + @Test public void whenDeleteValidStudent_thenReceiveOKResponse() throws IOException { - HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/1"); - HttpResponse response = client.execute(httpDelete); + final HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/1"); + final HttpResponse response = client.execute(httpDelete); assertEquals(200, response.getStatusLine().getStatusCode()); - - Course course = getCourse(1); + + final Course course = getCourse(1); assertEquals(1, course.getStudents().size()); assertEquals(2, course.getStudents().get(0).getId()); assertEquals("Student B", course.getStudents().get(0).getName()); } private Course getCourse(int courseOrder) throws IOException { - URL url = new URL(BASE_URL + courseOrder); - InputStream input = url.openStream(); + final URL url = new URL(BASE_URL + courseOrder); + final InputStream input = url.openStream(); return JAXB.unmarshal(new InputStreamReader(input), Course.class); } private Student getStudent(int courseOrder, int studentOrder) throws IOException { - URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder); - InputStream input = url.openStream(); + final URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder); + final InputStream input = url.openStream(); return JAXB.unmarshal(new InputStreamReader(input), Student.class); } } \ No newline at end of file diff --git a/apache-cxf/cxf-spring/pom.xml b/apache-cxf/cxf-spring/pom.xml index 85e68300f0..8f1dee965a 100644 --- a/apache-cxf/cxf-spring/pom.xml +++ b/apache-cxf/cxf-spring/pom.xml @@ -51,7 +51,7 @@ ${surefire.version} - StudentTest.java + **/*LiveTest.java @@ -60,7 +60,7 @@ - integration + live diff --git a/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java b/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentLiveTest.java similarity index 97% rename from apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java rename to apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentLiveTest.java index 7466944e04..80a8f6c3b8 100644 --- a/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java +++ b/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentLiveTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -public class StudentTest { +public class StudentLiveTest { private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class); private Baeldung baeldungProxy = (Baeldung) context.getBean("client"); From 951552c7428c2aab1f531ffda16f74a070481d92 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 12:27:49 +0200 Subject: [PATCH 182/193] Rename autovalue-tutorial -> autovalue --- {autovalue-tutorial => autovalue}/README.md | 0 {autovalue-tutorial => autovalue}/pom.xml | 0 .../src/main/java/com/baeldung/autovalue/AutoValueMoney.java | 0 .../java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java | 0 .../src/main/java/com/baeldung/autovalue/Foo.java | 0 .../src/main/java/com/baeldung/autovalue/ImmutableMoney.java | 0 .../src/main/java/com/baeldung/autovalue/MutableMoney.java | 0 .../src/test/java/com/baeldung/autovalue/MoneyTest.java | 0 pom.xml | 2 +- 9 files changed, 1 insertion(+), 1 deletion(-) rename {autovalue-tutorial => autovalue}/README.md (100%) rename {autovalue-tutorial => autovalue}/pom.xml (100%) rename {autovalue-tutorial => autovalue}/src/main/java/com/baeldung/autovalue/AutoValueMoney.java (100%) rename {autovalue-tutorial => autovalue}/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java (100%) rename {autovalue-tutorial => autovalue}/src/main/java/com/baeldung/autovalue/Foo.java (100%) rename {autovalue-tutorial => autovalue}/src/main/java/com/baeldung/autovalue/ImmutableMoney.java (100%) rename {autovalue-tutorial => autovalue}/src/main/java/com/baeldung/autovalue/MutableMoney.java (100%) rename {autovalue-tutorial => autovalue}/src/test/java/com/baeldung/autovalue/MoneyTest.java (100%) diff --git a/autovalue-tutorial/README.md b/autovalue/README.md similarity index 100% rename from autovalue-tutorial/README.md rename to autovalue/README.md diff --git a/autovalue-tutorial/pom.xml b/autovalue/pom.xml similarity index 100% rename from autovalue-tutorial/pom.xml rename to autovalue/pom.xml diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoney.java rename to autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java rename to autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/Foo.java b/autovalue/src/main/java/com/baeldung/autovalue/Foo.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/Foo.java rename to autovalue/src/main/java/com/baeldung/autovalue/Foo.java diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/ImmutableMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/ImmutableMoney.java rename to autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/MutableMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/MutableMoney.java rename to autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java diff --git a/autovalue-tutorial/src/test/java/com/baeldung/autovalue/MoneyTest.java b/autovalue/src/test/java/com/baeldung/autovalue/MoneyTest.java similarity index 100% rename from autovalue-tutorial/src/test/java/com/baeldung/autovalue/MoneyTest.java rename to autovalue/src/test/java/com/baeldung/autovalue/MoneyTest.java diff --git a/pom.xml b/pom.xml index 9979ff95a5..0a8b39b14f 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,7 @@ assertj apache-cxf - autovalue-tutorial + autovalue cdi core-java From fc1aaef4717cf0734263e1268070accc68e6c189 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 14:19:10 +0200 Subject: [PATCH 183/193] Rename dependency-injection -> spring-core --- {dependency-injection => spring-core}/.gitignore | 0 {dependency-injection => spring-core}/README.md | 0 {dependency-injection => spring-core}/pom.xml | 0 .../ApplicationContextTestAutowiredName.java | 0 .../ApplicationContextTestAutowiredQualifier.java | 0 .../ApplicationContextTestAutowiredType.java | 0 .../ApplicationContextTestInjectName.java | 0 .../ApplicationContextTestInjectQualifier.java | 0 .../ApplicationContextTestInjectType.java | 0 .../ApplicationContextTestResourceNameType.java | 0 .../ApplicationContextTestResourceQualifier.java | 0 .../dependency/AnotherArbitraryDependency.java | 0 .../com/baeldung/dependency/ArbitraryDependency.java | 0 .../dependency/YetAnotherArbitraryDependency.java | 0 .../autowired/FieldAutowiredIntegrationTest.java | 0 .../autowired/FieldAutowiredNameIntegrationTest.java | 0 .../FieldQualifierAutowiredIntegrationTest.java | 0 .../inject/FieldByNameInjectIntegrationTest.java | 0 .../baeldung/inject/FieldInjectIntegrationTest.java | 0 .../inject/FieldQualifierInjectIntegrationTest.java | 0 .../FieldResourceInjectionIntegrationTest.java | 0 .../MethodByQualifierResourceIntegrationTest.java | 0 .../MethodByTypeResourceIntegrationTest.java | 0 .../MethodResourceInjectionIntegrationTest.java | 0 .../resource/NamedResourceIntegrationTest.java | 0 .../QualifierResourceInjectionIntegrationTest.java | 0 .../SetterResourceInjectionIntegrationTest.java | 0 .../spring/web/config/MainWebAppInitializer.java | 12 +++++------- 28 files changed, 5 insertions(+), 7 deletions(-) rename {dependency-injection => spring-core}/.gitignore (100%) rename {dependency-injection => spring-core}/README.md (100%) rename {dependency-injection => spring-core}/pom.xml (100%) rename {dependency-injection => spring-core}/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java (100%) rename {dependency-injection => spring-core}/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java (100%) rename {dependency-injection => spring-core}/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java (100%) rename {dependency-injection => spring-core}/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java (100%) rename {dependency-injection => spring-core}/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java (100%) rename {dependency-injection => spring-core}/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java (100%) rename {dependency-injection => spring-core}/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java (100%) rename {dependency-injection => spring-core}/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java (100%) rename {dependency-injection => spring-core}/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java (100%) rename {dependency-injection => spring-core}/src/main/java/com/baeldung/dependency/ArbitraryDependency.java (100%) rename {dependency-injection => spring-core}/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java (100%) rename {dependency-injection => spring-core}/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java (100%) rename {dependency-injection => spring-core}/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java (100%) rename {dependency-injection => spring-core}/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java (100%) rename {dependency-injection => spring-core}/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java (100%) rename {dependency-injection => spring-core}/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java (100%) rename {dependency-injection => spring-core}/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java (100%) rename {dependency-injection => spring-core}/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java (100%) rename {dependency-injection => spring-core}/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java (100%) rename {dependency-injection => spring-core}/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java (100%) rename {dependency-injection => spring-core}/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java (100%) rename {dependency-injection => spring-core}/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java (100%) rename {dependency-injection => spring-core}/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java (100%) rename {dependency-injection => spring-core}/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java (100%) diff --git a/dependency-injection/.gitignore b/spring-core/.gitignore similarity index 100% rename from dependency-injection/.gitignore rename to spring-core/.gitignore diff --git a/dependency-injection/README.md b/spring-core/README.md similarity index 100% rename from dependency-injection/README.md rename to spring-core/README.md diff --git a/dependency-injection/pom.xml b/spring-core/pom.xml similarity index 100% rename from dependency-injection/pom.xml rename to spring-core/pom.xml diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java diff --git a/dependency-injection/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java b/spring-core/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java rename to spring-core/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java diff --git a/dependency-injection/src/main/java/com/baeldung/dependency/ArbitraryDependency.java b/spring-core/src/main/java/com/baeldung/dependency/ArbitraryDependency.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/dependency/ArbitraryDependency.java rename to spring-core/src/main/java/com/baeldung/dependency/ArbitraryDependency.java diff --git a/dependency-injection/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java b/spring-core/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java rename to spring-core/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java b/spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java similarity index 100% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java b/spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java similarity index 100% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java b/spring-core/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java similarity index 100% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java b/spring-core/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java similarity index 100% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java b/spring-core/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java similarity index 100% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java b/spring-core/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java similarity index 100% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java diff --git a/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java similarity index 100% rename from dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java similarity index 100% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java similarity index 100% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java similarity index 100% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java diff --git a/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java similarity index 100% rename from dependency-injection/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java diff --git a/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java similarity index 100% rename from dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java diff --git a/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java similarity index 100% rename from dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java index f428fc3223..80ce22edd6 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java @@ -1,17 +1,16 @@ package com.baeldung.spring.web.config; -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; +import java.util.Set; + public class MainWebAppInitializer implements WebApplicationInitializer { private static final String TMP_FOLDER = "/tmp"; @@ -28,7 +27,6 @@ public class MainWebAppInitializer implements WebApplicationInitializer { root.scan("com.baeldung.spring.web.config"); // root.getEnvironment().setDefaultProfiles("embedded"); - // Manages the lifecycle of the root application context sc.addListener(new ContextLoaderListener(root)); // Handles requests into the application From 26fbeb98da706708749575a9497254243c0c247f Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 14:23:56 +0200 Subject: [PATCH 184/193] Rename module --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 0a8b39b14f..b38fe174c9 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,6 @@ dozer - dependency-injection deltaspike patterns @@ -75,6 +74,7 @@ spring-autowire spring-batch spring-boot + spring-core spring-cucumber spring-data-cassandra spring-data-couchbase-2 From b1b4d4ff7fa9c70316352de43cbc44cce6574610 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 18:57:21 +0200 Subject: [PATCH 185/193] Rename jooq-spring -> spring-jooq --- pom.xml | 5 +++-- {jooq-spring => spring-jooq}/.gitignore | 0 {jooq-spring => spring-jooq}/README.md | 0 {jooq-spring => spring-jooq}/pom.xml | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/intro_config.properties | 0 .../src/main/resources/intro_schema.sql | 0 .../com/baeldung/jooq/introduction/ExceptionTranslator.java | 0 .../jooq/introduction/PersistenceContextIntegrationTest.java | 0 .../com/baeldung/jooq/introduction/QueryIntegrationTest.java | 0 .../test/java/com/baeldung/jooq/springboot/Application.java | 0 .../com/baeldung/jooq/springboot/InitialConfiguration.java | 0 .../baeldung/jooq/springboot/SpringBootIntegrationTest.java | 0 13 files changed, 3 insertions(+), 2 deletions(-) rename {jooq-spring => spring-jooq}/.gitignore (100%) rename {jooq-spring => spring-jooq}/README.md (100%) rename {jooq-spring => spring-jooq}/pom.xml (100%) rename {jooq-spring => spring-jooq}/src/main/resources/application.properties (100%) rename {jooq-spring => spring-jooq}/src/main/resources/intro_config.properties (100%) rename {jooq-spring => spring-jooq}/src/main/resources/intro_schema.sql (100%) rename {jooq-spring => spring-jooq}/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java (100%) rename {jooq-spring => spring-jooq}/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java (100%) rename {jooq-spring => spring-jooq}/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java (100%) rename {jooq-spring => spring-jooq}/src/test/java/com/baeldung/jooq/springboot/Application.java (100%) rename {jooq-spring => spring-jooq}/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java (100%) rename {jooq-spring => spring-jooq}/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java (100%) diff --git a/pom.xml b/pom.xml index b38fe174c9..71d12fddcf 100644 --- a/pom.xml +++ b/pom.xml @@ -45,7 +45,7 @@ jackson javaxval jjwt - jooq-spring + jpa-storedprocedure json json-path @@ -87,8 +87,9 @@ spring-freemarker spring-hibernate3 spring-hibernate4 - spring-jpa spring-jms + spring-jooq + spring-jpa spring-katharsis spring-mockito spring-mvc-java diff --git a/jooq-spring/.gitignore b/spring-jooq/.gitignore similarity index 100% rename from jooq-spring/.gitignore rename to spring-jooq/.gitignore diff --git a/jooq-spring/README.md b/spring-jooq/README.md similarity index 100% rename from jooq-spring/README.md rename to spring-jooq/README.md diff --git a/jooq-spring/pom.xml b/spring-jooq/pom.xml similarity index 100% rename from jooq-spring/pom.xml rename to spring-jooq/pom.xml diff --git a/jooq-spring/src/main/resources/application.properties b/spring-jooq/src/main/resources/application.properties similarity index 100% rename from jooq-spring/src/main/resources/application.properties rename to spring-jooq/src/main/resources/application.properties diff --git a/jooq-spring/src/main/resources/intro_config.properties b/spring-jooq/src/main/resources/intro_config.properties similarity index 100% rename from jooq-spring/src/main/resources/intro_config.properties rename to spring-jooq/src/main/resources/intro_config.properties diff --git a/jooq-spring/src/main/resources/intro_schema.sql b/spring-jooq/src/main/resources/intro_schema.sql similarity index 100% rename from jooq-spring/src/main/resources/intro_schema.sql rename to spring-jooq/src/main/resources/intro_schema.sql diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java b/spring-jooq/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java rename to spring-jooq/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java b/spring-jooq/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java rename to spring-jooq/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java b/spring-jooq/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java rename to spring-jooq/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/Application.java b/spring-jooq/src/test/java/com/baeldung/jooq/springboot/Application.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/springboot/Application.java rename to spring-jooq/src/test/java/com/baeldung/jooq/springboot/Application.java diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java b/spring-jooq/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java rename to spring-jooq/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java b/spring-jooq/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java rename to spring-jooq/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java From a757c7e301012dac6c2615bef93dc0d7b2a28cb0 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 19:07:13 +0200 Subject: [PATCH 186/193] Rename flyway-migration -> flyway --- {flyway-migration => flyway}/.gitignore | 6 +- {flyway-migration => flyway}/README.MD | 0 .../V1_0__create_employee_schema.sql | 14 ++-- .../V2_0__create_department_schema.sql | 14 ++-- .../myFlywayConfig.properties | 8 +-- {flyway-migration => flyway}/pom.xml | 66 +++++++++---------- pom.xml | 2 + 7 files changed, 56 insertions(+), 54 deletions(-) rename {flyway-migration => flyway}/.gitignore (75%) rename {flyway-migration => flyway}/README.MD (100%) rename {flyway-migration => flyway}/db/migration/V1_0__create_employee_schema.sql (77%) rename {flyway-migration => flyway}/db/migration/V2_0__create_department_schema.sql (70%) rename {flyway-migration => flyway}/myFlywayConfig.properties (69%) rename {flyway-migration => flyway}/pom.xml (90%) diff --git a/flyway-migration/.gitignore b/flyway/.gitignore similarity index 75% rename from flyway-migration/.gitignore rename to flyway/.gitignore index abffe04ed2..9cdd5b9542 100644 --- a/flyway-migration/.gitignore +++ b/flyway/.gitignore @@ -1,4 +1,4 @@ -.classpath -.project -.settings +.classpath +.project +.settings target/ \ No newline at end of file diff --git a/flyway-migration/README.MD b/flyway/README.MD similarity index 100% rename from flyway-migration/README.MD rename to flyway/README.MD diff --git a/flyway-migration/db/migration/V1_0__create_employee_schema.sql b/flyway/db/migration/V1_0__create_employee_schema.sql similarity index 77% rename from flyway-migration/db/migration/V1_0__create_employee_schema.sql rename to flyway/db/migration/V1_0__create_employee_schema.sql index 09408faecb..b6167bfacc 100644 --- a/flyway-migration/db/migration/V1_0__create_employee_schema.sql +++ b/flyway/db/migration/V1_0__create_employee_schema.sql @@ -1,8 +1,8 @@ -CREATE TABLE IF NOT EXISTS `employee` ( - -`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, -`name` varchar(20), -`email` varchar(50), -`date_of_birth` timestamp - +CREATE TABLE IF NOT EXISTS `employee` ( + +`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, +`name` varchar(20), +`email` varchar(50), +`date_of_birth` timestamp + )ENGINE=InnoDB DEFAULT CHARSET=UTF8; \ No newline at end of file diff --git a/flyway-migration/db/migration/V2_0__create_department_schema.sql b/flyway/db/migration/V2_0__create_department_schema.sql similarity index 70% rename from flyway-migration/db/migration/V2_0__create_department_schema.sql rename to flyway/db/migration/V2_0__create_department_schema.sql index 2b9d3364a5..c85cc81353 100644 --- a/flyway-migration/db/migration/V2_0__create_department_schema.sql +++ b/flyway/db/migration/V2_0__create_department_schema.sql @@ -1,8 +1,8 @@ -CREATE TABLE IF NOT EXISTS `department` ( - -`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, -`name` varchar(20) - -)ENGINE=InnoDB DEFAULT CHARSET=UTF8; - +CREATE TABLE IF NOT EXISTS `department` ( + +`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, +`name` varchar(20) + +)ENGINE=InnoDB DEFAULT CHARSET=UTF8; + ALTER TABLE `employee` ADD `dept_id` int AFTER `email`; \ No newline at end of file diff --git a/flyway-migration/myFlywayConfig.properties b/flyway/myFlywayConfig.properties similarity index 69% rename from flyway-migration/myFlywayConfig.properties rename to flyway/myFlywayConfig.properties index 22f3afefd3..8bb102930a 100644 --- a/flyway-migration/myFlywayConfig.properties +++ b/flyway/myFlywayConfig.properties @@ -1,5 +1,5 @@ -flyway.user=root -flyway.password=mysql -flyway.schemas=app-db -flyway.url=jdbc:mysql://localhost:3306/ +flyway.user=root +flyway.password=mysql +flyway.schemas=app-db +flyway.url=jdbc:mysql://localhost:3306/ flyway.locations=filesystem:db/migration \ No newline at end of file diff --git a/flyway-migration/pom.xml b/flyway/pom.xml similarity index 90% rename from flyway-migration/pom.xml rename to flyway/pom.xml index 6e9d683a0e..d53bc7dc41 100644 --- a/flyway-migration/pom.xml +++ b/flyway/pom.xml @@ -1,34 +1,34 @@ - - 4.0.0 - com.baeldung - flyway-migration - 1.0 - flyway-migration - 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 - - - - + + 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 + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 71d12fddcf..bec40024b7 100644 --- a/pom.xml +++ b/pom.xml @@ -32,6 +32,8 @@ feign-client + flyway + gson guava guava18 From 9055ecbc6fc56e563eead2fc1ae615621e304af3 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 19:10:16 +0200 Subject: [PATCH 187/193] Rename xmlunit2-tutorial -> xmlunit2 --- pom.xml | 1 + {xmlunit2-tutorial => xmlunit2}/README.md | 0 {xmlunit2-tutorial => xmlunit2}/pom.xml | 2 +- .../baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java | 0 .../src/test/java/com/baeldung/xmlunit/XMLUnitTest.java | 0 {xmlunit2-tutorial => xmlunit2}/src/test/resources/control.xml | 0 {xmlunit2-tutorial => xmlunit2}/src/test/resources/students.xml | 0 {xmlunit2-tutorial => xmlunit2}/src/test/resources/students.xsd | 0 .../src/test/resources/students_with_error.xml | 0 {xmlunit2-tutorial => xmlunit2}/src/test/resources/teachers.xml | 0 {xmlunit2-tutorial => xmlunit2}/src/test/resources/test.xml | 0 11 files changed, 2 insertions(+), 1 deletion(-) rename {xmlunit2-tutorial => xmlunit2}/README.md (100%) rename {xmlunit2-tutorial => xmlunit2}/pom.xml (96%) rename {xmlunit2-tutorial => xmlunit2}/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java (100%) rename {xmlunit2-tutorial => xmlunit2}/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java (100%) rename {xmlunit2-tutorial => xmlunit2}/src/test/resources/control.xml (100%) rename {xmlunit2-tutorial => xmlunit2}/src/test/resources/students.xml (100%) rename {xmlunit2-tutorial => xmlunit2}/src/test/resources/students.xsd (100%) rename {xmlunit2-tutorial => xmlunit2}/src/test/resources/students_with_error.xml (100%) rename {xmlunit2-tutorial => xmlunit2}/src/test/resources/teachers.xml (100%) rename {xmlunit2-tutorial => xmlunit2}/src/test/resources/test.xml (100%) diff --git a/pom.xml b/pom.xml index bec40024b7..f1c23bfb55 100644 --- a/pom.xml +++ b/pom.xml @@ -129,6 +129,7 @@ jsf xml + xmlunit2 lombok redis diff --git a/xmlunit2-tutorial/README.md b/xmlunit2/README.md similarity index 100% rename from xmlunit2-tutorial/README.md rename to xmlunit2/README.md diff --git a/xmlunit2-tutorial/pom.xml b/xmlunit2/pom.xml similarity index 96% rename from xmlunit2-tutorial/pom.xml rename to xmlunit2/pom.xml index b4cb684f65..c80e3f37b2 100644 --- a/xmlunit2-tutorial/pom.xml +++ b/xmlunit2/pom.xml @@ -2,7 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung - xmlunit2-tutorial + xmlunit2 1.0 XMLUnit-2 diff --git a/xmlunit2-tutorial/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java b/xmlunit2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java similarity index 100% rename from xmlunit2-tutorial/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java rename to xmlunit2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java diff --git a/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java b/xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java similarity index 100% rename from xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java rename to xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java diff --git a/xmlunit2-tutorial/src/test/resources/control.xml b/xmlunit2/src/test/resources/control.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/control.xml rename to xmlunit2/src/test/resources/control.xml diff --git a/xmlunit2-tutorial/src/test/resources/students.xml b/xmlunit2/src/test/resources/students.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/students.xml rename to xmlunit2/src/test/resources/students.xml diff --git a/xmlunit2-tutorial/src/test/resources/students.xsd b/xmlunit2/src/test/resources/students.xsd similarity index 100% rename from xmlunit2-tutorial/src/test/resources/students.xsd rename to xmlunit2/src/test/resources/students.xsd diff --git a/xmlunit2-tutorial/src/test/resources/students_with_error.xml b/xmlunit2/src/test/resources/students_with_error.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/students_with_error.xml rename to xmlunit2/src/test/resources/students_with_error.xml diff --git a/xmlunit2-tutorial/src/test/resources/teachers.xml b/xmlunit2/src/test/resources/teachers.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/teachers.xml rename to xmlunit2/src/test/resources/teachers.xml diff --git a/xmlunit2-tutorial/src/test/resources/test.xml b/xmlunit2/src/test/resources/test.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/test.xml rename to xmlunit2/src/test/resources/test.xml From 90ca6097627098d2203675524f56e3e51b1ce380 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 19:13:21 +0200 Subject: [PATCH 188/193] Rename jee7schedule -> jee7 --- {jee7schedule => jee7}/README.md | 0 {jee7schedule => jee7}/pom.xml | 0 .../baeldung/timer/AutomaticTimerBean.java | 0 .../baeldung/timer/FixedDelayTimerBean.java | 0 .../ProgrammaticAtFixedRateTimerBean.java | 0 .../baeldung/timer/ProgrammaticTimerBean.java | 0 ...ammaticWithInitialFixedDelayTimerBean.java | 0 .../com/baeldung/timer/ScheduleTimerBean.java | 0 .../java/com/baeldung/timer/TimerEvent.java | 0 .../baeldung/timer/TimerEventListener.java | 0 .../java/com/baeldung/timer/WorkerBean.java | 0 .../src/main/webapp/WEB-INF/beans.xml | 0 .../timer/AutomaticTimerBeanTest.java | 0 .../ProgrammaticAtFixedRateTimerBeanTest.java | 0 .../timer/ProgrammaticTimerBeanTest.java | 0 ...ogrammaticWithFixedDelayTimerBeanTest.java | 0 .../baeldung/timer/ScheduleTimerBeanTest.java | 0 .../baeldung/timer/WithinWindowMatcher.java | 0 pom.xml | 2 +- .../com/baeldung/xmlunit/XMLUnitTest.java | 33 ++++++++----------- 20 files changed, 14 insertions(+), 21 deletions(-) rename {jee7schedule => jee7}/README.md (100%) rename {jee7schedule => jee7}/pom.xml (100%) rename {jee7schedule => jee7}/src/main/java/com/baeldung/timer/AutomaticTimerBean.java (100%) rename {jee7schedule => jee7}/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java (100%) rename {jee7schedule => jee7}/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java (100%) rename {jee7schedule => jee7}/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java (100%) rename {jee7schedule => jee7}/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java (100%) rename {jee7schedule => jee7}/src/main/java/com/baeldung/timer/ScheduleTimerBean.java (100%) rename {jee7schedule => jee7}/src/main/java/com/baeldung/timer/TimerEvent.java (100%) rename {jee7schedule => jee7}/src/main/java/com/baeldung/timer/TimerEventListener.java (100%) rename {jee7schedule => jee7}/src/main/java/com/baeldung/timer/WorkerBean.java (100%) rename {jee7schedule => jee7}/src/main/webapp/WEB-INF/beans.xml (100%) rename {jee7schedule => jee7}/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java (100%) rename {jee7schedule => jee7}/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java (100%) rename {jee7schedule => jee7}/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java (100%) rename {jee7schedule => jee7}/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java (100%) rename {jee7schedule => jee7}/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java (100%) rename {jee7schedule => jee7}/src/test/java/com/baeldung/timer/WithinWindowMatcher.java (100%) diff --git a/jee7schedule/README.md b/jee7/README.md similarity index 100% rename from jee7schedule/README.md rename to jee7/README.md diff --git a/jee7schedule/pom.xml b/jee7/pom.xml similarity index 100% rename from jee7schedule/pom.xml rename to jee7/pom.xml diff --git a/jee7schedule/src/main/java/com/baeldung/timer/AutomaticTimerBean.java b/jee7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/AutomaticTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java b/jee7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java b/jee7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java b/jee7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java b/jee7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ScheduleTimerBean.java b/jee7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/ScheduleTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/TimerEvent.java b/jee7/src/main/java/com/baeldung/timer/TimerEvent.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/TimerEvent.java rename to jee7/src/main/java/com/baeldung/timer/TimerEvent.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/TimerEventListener.java b/jee7/src/main/java/com/baeldung/timer/TimerEventListener.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/TimerEventListener.java rename to jee7/src/main/java/com/baeldung/timer/TimerEventListener.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/WorkerBean.java b/jee7/src/main/java/com/baeldung/timer/WorkerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/WorkerBean.java rename to jee7/src/main/java/com/baeldung/timer/WorkerBean.java diff --git a/jee7schedule/src/main/webapp/WEB-INF/beans.xml b/jee7/src/main/webapp/WEB-INF/beans.xml similarity index 100% rename from jee7schedule/src/main/webapp/WEB-INF/beans.xml rename to jee7/src/main/webapp/WEB-INF/beans.xml diff --git a/jee7schedule/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/WithinWindowMatcher.java b/jee7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/WithinWindowMatcher.java rename to jee7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java diff --git a/pom.xml b/pom.xml index f1c23bfb55..4e8b54446d 100644 --- a/pom.xml +++ b/pom.xml @@ -52,7 +52,7 @@ json json-path junit5 - jee7schedule + jee7 log4j diff --git a/xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java b/xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java index 175250f47b..5af3d48433 100644 --- a/xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java +++ b/xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java @@ -1,37 +1,30 @@ package com.baeldung.xmlunit; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.core.IsNot.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; -import static org.xmlunit.matchers.HasXPathMatcher.hasXPath; - -import java.io.File; -import java.util.Iterator; - import org.junit.Ignore; import org.junit.Test; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xmlunit.builder.DiffBuilder; import org.xmlunit.builder.Input; -import org.xmlunit.diff.ComparisonControllers; -import org.xmlunit.diff.DefaultNodeMatcher; -import org.xmlunit.diff.Diff; -import org.xmlunit.diff.Difference; -import org.xmlunit.diff.ElementSelectors; +import org.xmlunit.diff.*; import org.xmlunit.validation.Languages; import org.xmlunit.validation.ValidationProblem; import org.xmlunit.validation.ValidationResult; import org.xmlunit.validation.Validator; import org.xmlunit.xpath.JAXPXPathEngine; +import java.io.File; +import java.util.Iterator; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.core.IsNot.not; +import static org.junit.Assert.*; +import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo; +import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; +import static org.xmlunit.matchers.HasXPathMatcher.hasXPath; + public class XMLUnitTest { @Test public void givenWrongXml_whenValidateFailsAgainstXsd_thenCorrect() { From 7df435bb6fa0e59aa3835d6fb845a7667b191607 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 19:15:31 +0200 Subject: [PATCH 189/193] Rename feign-client -> feign --- {feign-client => feign}/README.md | 0 {feign-client => feign}/pom.xml | 0 .../com/baeldung/feign/BookControllerFeignClientBuilder.java | 0 .../src/main/java/com/baeldung/feign/clients/BookClient.java | 0 .../src/main/java/com/baeldung/feign/models/Book.java | 0 .../src/main/java/com/baeldung/feign/models/BookResource.java | 0 {feign-client => feign}/src/main/resources/log4j2.xml | 0 .../test/java/com/baeldung/feign/clients/BookClientTest.java | 0 pom.xml | 2 +- 9 files changed, 1 insertion(+), 1 deletion(-) rename {feign-client => feign}/README.md (100%) rename {feign-client => feign}/pom.xml (100%) rename {feign-client => feign}/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java (100%) rename {feign-client => feign}/src/main/java/com/baeldung/feign/clients/BookClient.java (100%) rename {feign-client => feign}/src/main/java/com/baeldung/feign/models/Book.java (100%) rename {feign-client => feign}/src/main/java/com/baeldung/feign/models/BookResource.java (100%) rename {feign-client => feign}/src/main/resources/log4j2.xml (100%) rename {feign-client => feign}/src/test/java/com/baeldung/feign/clients/BookClientTest.java (100%) diff --git a/feign-client/README.md b/feign/README.md similarity index 100% rename from feign-client/README.md rename to feign/README.md diff --git a/feign-client/pom.xml b/feign/pom.xml similarity index 100% rename from feign-client/pom.xml rename to feign/pom.xml diff --git a/feign-client/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java b/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java similarity index 100% rename from feign-client/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java rename to feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java diff --git a/feign-client/src/main/java/com/baeldung/feign/clients/BookClient.java b/feign/src/main/java/com/baeldung/feign/clients/BookClient.java similarity index 100% rename from feign-client/src/main/java/com/baeldung/feign/clients/BookClient.java rename to feign/src/main/java/com/baeldung/feign/clients/BookClient.java diff --git a/feign-client/src/main/java/com/baeldung/feign/models/Book.java b/feign/src/main/java/com/baeldung/feign/models/Book.java similarity index 100% rename from feign-client/src/main/java/com/baeldung/feign/models/Book.java rename to feign/src/main/java/com/baeldung/feign/models/Book.java diff --git a/feign-client/src/main/java/com/baeldung/feign/models/BookResource.java b/feign/src/main/java/com/baeldung/feign/models/BookResource.java similarity index 100% rename from feign-client/src/main/java/com/baeldung/feign/models/BookResource.java rename to feign/src/main/java/com/baeldung/feign/models/BookResource.java diff --git a/feign-client/src/main/resources/log4j2.xml b/feign/src/main/resources/log4j2.xml similarity index 100% rename from feign-client/src/main/resources/log4j2.xml rename to feign/src/main/resources/log4j2.xml diff --git a/feign-client/src/test/java/com/baeldung/feign/clients/BookClientTest.java b/feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java similarity index 100% rename from feign-client/src/test/java/com/baeldung/feign/clients/BookClientTest.java rename to feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java diff --git a/pom.xml b/pom.xml index 4e8b54446d..0de16500d6 100644 --- a/pom.xml +++ b/pom.xml @@ -29,7 +29,7 @@ deltaspike patterns - feign-client + feign flyway From 62c6abfb4aa5c43020e60397d7652f0dbbfb66d0 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 19:49:03 +0200 Subject: [PATCH 190/193] Move Java8 Collectors example --- core-java-8/README.md | 1 - core-java/README.md | 1 + .../test/java/com/baeldung/collectors/Java8CollectorsTest.java | 0 3 files changed, 1 insertion(+), 1 deletion(-) rename {core-java-8 => core-java}/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java (100%) diff --git a/core-java-8/README.md b/core-java-8/README.md index c130e6bd41..300d6ce33b 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -11,7 +11,6 @@ - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) - [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) -- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) - [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) - [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) - [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) diff --git a/core-java/README.md b/core-java/README.md index fbbfa65589..a9310c1c16 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -19,3 +19,4 @@ - [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist) - [Guide to Java Reflection](http://www.baeldung.com/java-reflection) - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) +- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) diff --git a/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java rename to core-java/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java From 93256245ffdff3a698587a0153f54862b80fee2c Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 19:53:01 +0200 Subject: [PATCH 191/193] Move CompletableFuture examples --- core-java-8/README.md | 1 - core-java/README.md | 1 + .../com/baeldung/completablefuture/CompletableFutureTest.java | 0 3 files changed, 1 insertion(+), 1 deletion(-) rename {core-java-8 => core-java}/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java (100%) diff --git a/core-java-8/README.md b/core-java-8/README.md index 300d6ce33b..3d1d89896f 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -14,7 +14,6 @@ - [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) - [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) - [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) -- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) - [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) - [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors) - [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams) diff --git a/core-java/README.md b/core-java/README.md index a9310c1c16..6671d7c2f4 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -20,3 +20,4 @@ - [Guide to Java Reflection](http://www.baeldung.com/java-reflection) - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) - [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) +- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) diff --git a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java rename to core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java From 6dc9bcf33104b02564d74397cf4e49ef0c57c044 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 23 Oct 2016 19:55:41 +0200 Subject: [PATCH 192/193] Move FunctionalInterfaces examples --- core-java-8/README.md | 1 - core-java/README.md | 1 + .../functionalinterface/FunctionalInterfaceTest.java | 6 +++--- .../baeldung/functionalinterface/ShortToByteFunction.java | 0 4 files changed, 4 insertions(+), 4 deletions(-) rename {core-java-8 => core-java}/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java (100%) rename {core-java-8 => core-java}/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java (100%) diff --git a/core-java-8/README.md b/core-java-8/README.md index 3d1d89896f..a835914b4d 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -13,7 +13,6 @@ - [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) - [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) - [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) -- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) - [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) - [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors) - [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams) diff --git a/core-java/README.md b/core-java/README.md index 6671d7c2f4..c18e6670ca 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -21,3 +21,4 @@ - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) - [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) - [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) +- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) diff --git a/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java rename to core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java index ce878026d4..e07bcc9a8d 100644 --- a/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java +++ b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java @@ -1,5 +1,8 @@ package com.baeldung.functionalinterface; +import com.google.common.util.concurrent.Uninterruptibles; +import org.junit.Test; + import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -10,9 +13,6 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; -import com.google.common.util.concurrent.Uninterruptibles; -import org.junit.Test; - import static org.junit.Assert.*; public class FunctionalInterfaceTest { diff --git a/core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java b/core-java/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java rename to core-java/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java From 6c3019540589d574f6dd3d7456ad6fd462e1c8b1 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sun, 23 Oct 2016 20:26:51 +0200 Subject: [PATCH 193/193] minor fix --- apache-cxf/cxf-introduction/pom.xml | 63 +------------------ .../cxf/introduction/StudentLiveTest.java | 2 +- apache-cxf/cxf-jaxrs-implementation/pom.xml | 62 ------------------ .../jaxrs/implementation/ServiceLiveTest.java | 2 +- 4 files changed, 3 insertions(+), 126 deletions(-) diff --git a/apache-cxf/cxf-introduction/pom.xml b/apache-cxf/cxf-introduction/pom.xml index 9629dfda1b..0902bd690e 100644 --- a/apache-cxf/cxf-introduction/pom.xml +++ b/apache-cxf/cxf-introduction/pom.xml @@ -45,66 +45,5 @@ ${cxf.version} - - - - live - - - - org.codehaus.cargo - cargo-maven2-plugin - 1.4.19 - - - tomcat8x - embedded - - - - localhost - 8082 - - - - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - - - - maven-surefire-plugin - ${surefire.version} - - - integration-test - - test - - - - none - - - - - - - - - - + diff --git a/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java b/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java index 1c50fcb9b6..60fc0a10e7 100644 --- a/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java +++ b/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java @@ -21,7 +21,7 @@ public class StudentLiveTest { { service = Service.create(SERVICE_NAME); - final String endpointAddress = "http://localhost:8082/cxf-introduction/baeldung"; + final String endpointAddress = "http://localhost:8080/baeldung"; service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress); } diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml index 24dad05a0f..b3a81aef82 100644 --- a/apache-cxf/cxf-jaxrs-implementation/pom.xml +++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml @@ -52,66 +52,4 @@ ${httpclient.version} - - - - live - - - - org.codehaus.cargo - cargo-maven2-plugin - 1.4.19 - - - tomcat8x - embedded - - - - localhost - 8082 - - - - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - - - - maven-surefire-plugin - ${surefire.version} - - - integration-test - - test - - - - none - - - - - - - - - - diff --git a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java index 692def81f5..29c34ae16b 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java @@ -21,7 +21,7 @@ import org.junit.BeforeClass; import org.junit.Test; public class ServiceLiveTest { - private static final String BASE_URL = "http://localhost:8082/baeldung/courses/"; + private static final String BASE_URL = "http://localhost:8080/baeldung/courses/"; private static CloseableHttpClient client; @BeforeClass