From 22207e646b504c269c0484e1883fa8b9de5a80c8 Mon Sep 17 00:00:00 2001 From: Pritam Banerjee Date: Sat, 15 Oct 2016 14:40:20 -0700 Subject: [PATCH 01/47] BAEL 317: Setting up EJB EJB Client and EJB Remote --- ejb/ejb-client/pom.xml | 28 +++++++ .../com/baeldung/ejb/client/EJBClient.java | 71 ++++++++++++++++ .../resources/jboss-ejb-client.properties | 8 ++ .../baeldung/ejb/setup/test/EJBSetupTest.java | 16 ++++ ejb/ejb-remote/pom.xml | 25 ++++++ .../com/baeldung/ejb/tutorial/HelloWorld.java | 8 ++ .../baeldung/ejb/tutorial/HelloWorldBean.java | 18 ++++ .../src/main/resources/META-INF/ejb-jar.xml | 7 ++ ejb/pom.xml | 83 +++++++++++++++++++ 9 files changed, 264 insertions(+) create mode 100755 ejb/ejb-client/pom.xml create mode 100755 ejb/ejb-client/src/main/java/com/baeldung/ejb/client/EJBClient.java create mode 100755 ejb/ejb-client/src/main/resources/jboss-ejb-client.properties create mode 100755 ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java create mode 100755 ejb/ejb-remote/pom.xml create mode 100755 ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorld.java create mode 100755 ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java create mode 100755 ejb/ejb-remote/src/main/resources/META-INF/ejb-jar.xml create mode 100755 ejb/pom.xml diff --git a/ejb/ejb-client/pom.xml b/ejb/ejb-client/pom.xml new file mode 100755 index 0000000000..d1d245ba6d --- /dev/null +++ b/ejb/ejb-client/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + + com.baeldung.ejb + ejb + 1.0-SNAPSHOT + + ejb-client + EJB3 Client Maven + EJB3 Client Maven + + + + org.wildfly + wildfly-ejb-client-bom + pom + import + + + com.baeldung.ejb + ejb-remote + ejb + + + + \ No newline at end of file diff --git a/ejb/ejb-client/src/main/java/com/baeldung/ejb/client/EJBClient.java b/ejb/ejb-client/src/main/java/com/baeldung/ejb/client/EJBClient.java new file mode 100755 index 0000000000..5426bbdc81 --- /dev/null +++ b/ejb/ejb-client/src/main/java/com/baeldung/ejb/client/EJBClient.java @@ -0,0 +1,71 @@ +package com.baeldung.ejb.client; + +import java.util.Properties; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import com.baeldung.ejb.tutorial.HelloWorld; + +public class EJBClient { + + public EJBClient() { + } + + private Context context = null; + + public String getEJBRemoteMessage() { + EJBClient main = new EJBClient(); + try { + // 1. Obtaining Context + main.createInitialContext(); + // 2. Generate JNDI Lookup name and caste + HelloWorld helloWorld = main.lookup(); + return helloWorld.getHelloWorld(); + } catch (NamingException e) { + e.printStackTrace(); + return ""; + } finally { + try { + main.closeContext(); + } catch (NamingException e) { + e.printStackTrace(); + } + } + } + + public HelloWorld lookup() throws NamingException { + + // The app name is the EAR name of the deployed EJB without .ear suffix. + // Since we haven't deployed the application as a .ear, the app name for + // us will be an empty string + final String appName = ""; + final String moduleName = "remote"; + final String distinctName = ""; + final String beanName = "HelloWorld"; + final String viewClassName = HelloWorld.class.getName(); + final String toLookup = "ejb:" + appName + "/" + moduleName + + "/" + distinctName + "/" + beanName + "!" + viewClassName; + return (HelloWorld) context.lookup(toLookup); + } + + public void createInitialContext() throws NamingException { + Properties prop = new Properties(); + prop.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); + prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"); + prop.put(Context.PROVIDER_URL, "http-remoting://127.0.0.1:8080"); + prop.put(Context.SECURITY_PRINCIPAL, "pritamtest"); + prop.put(Context.SECURITY_CREDENTIALS, "iamtheki9g"); + prop.put("jboss.naming.client.ejb.context", false); + + context = new InitialContext(prop); + } + + public void closeContext() throws NamingException { + if (context != null) { + context.close(); + } + } + +} diff --git a/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties b/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties new file mode 100755 index 0000000000..e17d8ba17e --- /dev/null +++ b/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties @@ -0,0 +1,8 @@ +remote.connections=default +remote.connection.default.host=127.0.0.1 +remote.connection.default.port=8080 +remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false +remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false +remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER} +remote.connection.default.username=pritamtest +remote.connection.default.password=iamtheki9g \ No newline at end of file diff --git a/ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java b/ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java new file mode 100755 index 0000000000..1a8165cee6 --- /dev/null +++ b/ejb/ejb-client/src/test/java/com/baeldung/ejb/setup/test/EJBSetupTest.java @@ -0,0 +1,16 @@ +package com.baeldung.ejb.setup.test; + +import static org.junit.Assert.*; +import org.junit.Test; +import com.baeldung.ejb.client.EJBClient; +import com.baeldung.ejb.tutorial.HelloWorldBean; + +public class EJBSetupTest { + + @Test + public void testEJBClient() { + EJBClient ejbClient = new EJBClient(); + HelloWorldBean bean = new HelloWorldBean(); + assertEquals(bean.getHelloWorld(), ejbClient.getEJBRemoteMessage()); + } +} diff --git a/ejb/ejb-remote/pom.xml b/ejb/ejb-remote/pom.xml new file mode 100755 index 0000000000..14c02edd0e --- /dev/null +++ b/ejb/ejb-remote/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + + com.baeldung.ejb + ejb + 1.0-SNAPSHOT + + ejb-remote + ejb + + ejb-remote + + + org.jboss.spec.javax.ejb + jboss-ejb-api_3.2_spec + provided + + + + + ejb-remote + + \ No newline at end of file diff --git a/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorld.java b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorld.java new file mode 100755 index 0000000000..79684de1a8 --- /dev/null +++ b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorld.java @@ -0,0 +1,8 @@ +package com.baeldung.ejb.tutorial; + +import javax.ejb.Remote; + +@Remote +public interface HelloWorld { + String getHelloWorld(); +} diff --git a/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java new file mode 100755 index 0000000000..6c5ee34afe --- /dev/null +++ b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java @@ -0,0 +1,18 @@ +package com.baeldung.ejb.tutorial; + +import javax.annotation.Resource; +import javax.ejb.SessionContext; +import javax.ejb.Stateless; + +@Stateless(name = "HelloWorld") +public class HelloWorldBean implements HelloWorld { + + @Resource + private SessionContext context; + + @Override + public String getHelloWorld() { + return "Welcome to EJB Tutorial!"; + } + +} diff --git a/ejb/ejb-remote/src/main/resources/META-INF/ejb-jar.xml b/ejb/ejb-remote/src/main/resources/META-INF/ejb-jar.xml new file mode 100755 index 0000000000..d6c2200198 --- /dev/null +++ b/ejb/ejb-remote/src/main/resources/META-INF/ejb-jar.xml @@ -0,0 +1,7 @@ + + + remote + + diff --git a/ejb/pom.xml b/ejb/pom.xml new file mode 100755 index 0000000000..49ddc694e9 --- /dev/null +++ b/ejb/pom.xml @@ -0,0 +1,83 @@ + + + 4.0.0 + com.baeldung.ejb + ejb + 1.0-SNAPSHOT + pom + ejb + EJB Tutorial + + + + jboss-public-repository-group + JBoss Public Maven Repository Group + http://repository.jboss.org/nexus/content/groups/public/ + default + + true + never + + + true + never + + + + + + + + com.baeldung.ejb + ejb-remote + 1.0-SNAPSHOT + ejb + + + + org.jboss.spec + jboss-javaee-7.0 + 1.0.1.Final + pom + import + + + + org.wildfly + wildfly-ejb-client-bom + 10.1.0.Final + pom + import + + + + + + + + + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + + + + + maven-ejb-plugin + 2.4 + + 3.2 + + + + + + + + ejb-remote + ejb-client + + \ No newline at end of file From 66b618d99de96a53c69170aab5b4dc3352c34a13 Mon Sep 17 00:00:00 2001 From: tschiman Date: Mon, 24 Oct 2016 20:13:27 -0600 Subject: [PATCH 02/47] Changing config to user properties to set up security --- .../bootstrap/config/ConfigApplication.java | 6 ++--- .../bootstrap/config/SecurityConfig.java | 22 ++++--------------- .../src/main/resources/application.properties | 5 ++++- 3 files changed, 11 insertions(+), 22 deletions(-) diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java index 847c86f881..c51819dfe5 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java @@ -9,7 +9,7 @@ import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @EnableConfigServer @EnableEurekaClient public class ConfigApplication { - public static void main(String[] args) { - SpringApplication.run(ConfigApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(ConfigApplication.class, args); + } } diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java index 315ab8b543..914efe8160 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java @@ -1,8 +1,6 @@ package com.baeldung.spring.cloud.bootstrap.config; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; -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; @@ -11,20 +9,8 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{ - auth.inMemoryAuthentication().withUser("configUser").password("configPassword").roles("SYSTEM"); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .anyRequest().hasRole("SYSTEM") - .and() - .httpBasic() - .and() - .csrf() - .disable(); - } + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().anyRequest().hasRole("SYSTEM").and().httpBasic().and().csrf().disable(); + } } diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties index 6c47d001f4..5b905929a9 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties @@ -5,4 +5,7 @@ spring.cloud.config.server.git.uri=file:///${user.home}/application-config eureka.client.region = default eureka.client.registryFetchIntervalSeconds = 5 -eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/ \ No newline at end of file +eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/ +security.user.name=configUser +security.user.password=configPassword +security.user.role=SYSTEM \ No newline at end of file From bad9a35061a799fd06a86e33748e7f14f20fc919 Mon Sep 17 00:00:00 2001 From: tschiman Date: Mon, 24 Oct 2016 20:40:06 -0600 Subject: [PATCH 03/47] Modify formatting. --- .../discovery/DiscoveryApplication.java | 6 +- .../bootstrap/discovery/SecurityConfig.java | 68 +++++++------------ .../bootstrap/gateway/GatewayApplication.java | 32 ++++----- .../bootstrap/gateway/SecurityConfig.java | 32 +++------ .../resource/ResourceApplication.java | 42 ++++++------ .../bootstrap/resource/SecurityConfig.java | 26 ++----- 6 files changed, 76 insertions(+), 130 deletions(-) diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/DiscoveryApplication.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/DiscoveryApplication.java index 32bcdc90b6..4ac445b083 100644 --- a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/DiscoveryApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/DiscoveryApplication.java @@ -7,7 +7,7 @@ import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class DiscoveryApplication { - public static void main(String[] args) { - SpringApplication.run(DiscoveryApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(DiscoveryApplication.class, args); + } } diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java index 3c874bf581..0d03d159a0 100644 --- a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java @@ -15,52 +15,30 @@ import org.springframework.security.config.http.SessionCreationPolicy; @Order(1) public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{ - auth.inMemoryAuthentication().withUser("discUser").password("discPassword").roles("SYSTEM"); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.ALWAYS) - .and() - .requestMatchers() - .antMatchers("/eureka/**") - .and() - .authorizeRequests() - .antMatchers("/eureka/**").hasRole("SYSTEM") - .anyRequest().denyAll() - .and() - .httpBasic() - .and() - .csrf() - .disable(); - } - - @Configuration - //no order tag means this is the last security filter to be evaluated - public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication(); + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("discUser").password("discPassword").roles("SYSTEM"); } - @Override protected void configure(HttpSecurity http) throws Exception { - http - .sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.NEVER) - .and() - .httpBasic() - .disable() - .authorizeRequests() - .antMatchers(HttpMethod.GET, "/").hasRole("ADMIN") - .antMatchers("/info","/health").authenticated() - .anyRequest().denyAll() - .and() - .csrf() - .disable(); + @Override + protected void configure(HttpSecurity http) throws Exception { + http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and().requestMatchers().antMatchers("/eureka/**").and().authorizeRequests().antMatchers("/eureka/**").hasRole("SYSTEM").anyRequest().denyAll().and().httpBasic().and() + .csrf().disable(); + } + + @Configuration + //no order tag means this is the last security filter to be evaluated + public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and().httpBasic().disable().authorizeRequests().antMatchers(HttpMethod.GET, "/").hasRole("ADMIN").antMatchers("/info", "/health").authenticated().anyRequest() + .denyAll().and().csrf().disable(); + } } - } } diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java index a3d2df5357..b5ae1e4e7b 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java @@ -18,23 +18,23 @@ import java.util.List; @EnableZuulProxy @EnableEurekaClient public class GatewayApplication { - public static void main(String[] args) { - SpringApplication.run(GatewayApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(GatewayApplication.class, args); + } - @Autowired(required = false) - private List configurations = new ArrayList<>(); + @Autowired(required = false) + private List configurations = new ArrayList<>(); - @Bean - @LoadBalanced RestTemplate restTemplate(){ - return new RestTemplate(); - } + @Bean + @LoadBalanced + RestTemplate restTemplate() { + return new RestTemplate(); + } - - @Bean - public SpringClientFactory springClientFactory() { - SpringClientFactory factory = new SpringClientFactory(); - factory.setConfigurations(this.configurations); - return factory; - } + @Bean + public SpringClientFactory springClientFactory() { + SpringClientFactory factory = new SpringClientFactory(); + factory.setConfigurations(this.configurations); + return factory; + } } diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java index 0b8923391f..e83933feb0 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java @@ -11,28 +11,14 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication() - .withUser("user").password("password").roles("USER") - .and() - .withUser("admin").password("admin").roles("ADMIN"); - } + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("user").password("password").roles("USER").and().withUser("admin").password("admin").roles("ADMIN"); + } - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .antMatchers("/resource/hello/cloud").permitAll() - .antMatchers("/eureka/**").hasRole("ADMIN") - .anyRequest().authenticated() - .and() - .formLogin() - .and() - .logout().permitAll() - .logoutSuccessUrl("/resource/hello/cloud").permitAll() - .and() - .csrf() - .disable(); - } + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().antMatchers("/resource/hello/cloud").permitAll().antMatchers("/eureka/**").hasRole("ADMIN").anyRequest().authenticated().and().formLogin().and().logout().permitAll().logoutSuccessUrl("/resource/hello/cloud").permitAll() + .and().csrf().disable(); + } } diff --git a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/ResourceApplication.java b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/ResourceApplication.java index e12d43f46b..accef18a14 100644 --- a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/ResourceApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/ResourceApplication.java @@ -11,31 +11,31 @@ import org.springframework.web.bind.annotation.RestController; @EnableEurekaClient @RestController public class ResourceApplication { - public static void main(String[] args) { - SpringApplication.run(ResourceApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(ResourceApplication.class, args); + } - @Value("${resource.returnString}") - private String returnString; + @Value("${resource.returnString}") + private String returnString; - @Value("${resource.user.returnString}") - private String userReturnString; + @Value("${resource.user.returnString}") + private String userReturnString; - @Value("${resource.admin.returnString}") - private String adminReturnString; + @Value("${resource.admin.returnString}") + private String adminReturnString; - @RequestMapping("/hello/cloud") - public String getString() { - return returnString; - } + @RequestMapping("/hello/cloud") + public String getString() { + return returnString; + } - @RequestMapping("/hello/user") - public String getUserString() { - return userReturnString; - } + @RequestMapping("/hello/user") + public String getUserString() { + return userReturnString; + } - @RequestMapping("/hello/admin") - public String getAdminString() { - return adminReturnString; - } + @RequestMapping("/hello/admin") + public String getAdminString() { + return adminReturnString; + } } diff --git a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java index 66d154dafb..8cea8cf080 100644 --- a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java @@ -1,8 +1,6 @@ package com.baeldung.spring.cloud.bootstrap.resource; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; -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; @@ -11,24 +9,8 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Autowired - public void configureGlobal1(AuthenticationManagerBuilder auth) throws Exception { - //try in memory auth with no users to support the case that this will allow for users that are logged in to go anywhere - auth.inMemoryAuthentication(); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .httpBasic() - .disable() - .authorizeRequests() - .antMatchers("/hello/cloud").permitAll() - .antMatchers("/hello/user").hasAnyRole("USER", "ADMIN") - .antMatchers("/hello/admin").hasRole("ADMIN") - .anyRequest().authenticated() - .and() - .csrf() - .disable(); - } + @Override + protected void configure(HttpSecurity http) throws Exception { + http.httpBasic().disable().authorizeRequests().antMatchers("/hello/cloud").permitAll().antMatchers("/hello/user").hasAnyRole("USER", "ADMIN").antMatchers("/hello/admin").hasRole("ADMIN").anyRequest().authenticated().and().csrf().disable(); + } } From 8cfe4cc39f68042981a47fcedb9688a32375177a Mon Sep 17 00:00:00 2001 From: tschiman Date: Mon, 24 Oct 2016 20:42:52 -0600 Subject: [PATCH 04/47] Modify formatting. --- .../config/src/main/resources/application.properties | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties index 5b905929a9..e97a6a4094 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties @@ -6,6 +6,7 @@ spring.cloud.config.server.git.uri=file:///${user.home}/application-config eureka.client.region = default eureka.client.registryFetchIntervalSeconds = 5 eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/ +#Security User Config security.user.name=configUser security.user.password=configPassword security.user.role=SYSTEM \ No newline at end of file From 52def2bf97134bf4c39f7696738cce3864e94f05 Mon Sep 17 00:00:00 2001 From: tschiman Date: Mon, 24 Oct 2016 20:46:02 -0600 Subject: [PATCH 05/47] Modify formatting. --- .../spring/cloud/bootstrap/config/SecurityConfig.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java index 914efe8160..f008dff90e 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java @@ -11,6 +11,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().hasRole("SYSTEM").and().httpBasic().and().csrf().disable(); + http + .authorizeRequests().anyRequest().hasRole("SYSTEM").and() + .httpBasic().and() + .csrf().disable(); } } From 3e7760f047761dd1f433a4f96fb8a8ac2a35b951 Mon Sep 17 00:00:00 2001 From: tschiman Date: Mon, 24 Oct 2016 20:49:43 -0600 Subject: [PATCH 06/47] Modify formatting. --- .../bootstrap/discovery/SecurityConfig.java | 18 +++++++++++++++--- .../bootstrap/gateway/SecurityConfig.java | 15 ++++++++++++--- .../bootstrap/resource/SecurityConfig.java | 9 ++++++++- 3 files changed, 35 insertions(+), 7 deletions(-) diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java index 0d03d159a0..a55508b1e7 100644 --- a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java @@ -22,7 +22,13 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and().requestMatchers().antMatchers("/eureka/**").and().authorizeRequests().antMatchers("/eureka/**").hasRole("SYSTEM").anyRequest().denyAll().and().httpBasic().and() + http + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and() + .requestMatchers().antMatchers("/eureka/**").and() + .authorizeRequests() + .antMatchers("/eureka/**").hasRole("SYSTEM") + .anyRequest().denyAll().and() + .httpBasic().and() .csrf().disable(); } @@ -37,8 +43,14 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and().httpBasic().disable().authorizeRequests().antMatchers(HttpMethod.GET, "/").hasRole("ADMIN").antMatchers("/info", "/health").authenticated().anyRequest() - .denyAll().and().csrf().disable(); + http + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and() + .httpBasic().disable() + .authorizeRequests() + .antMatchers(HttpMethod.GET, "/").hasRole("ADMIN") + .antMatchers("/info", "/health").authenticated() + .anyRequest().denyAll().and() + .csrf().disable(); } } } diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java index e83933feb0..417b61d238 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java @@ -13,12 +13,21 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("user").password("password").roles("USER").and().withUser("admin").password("admin").roles("ADMIN"); + auth.inMemoryAuthentication() + .withUser("user").password("password").roles("USER").and() + .withUser("admin").password("admin").roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().antMatchers("/resource/hello/cloud").permitAll().antMatchers("/eureka/**").hasRole("ADMIN").anyRequest().authenticated().and().formLogin().and().logout().permitAll().logoutSuccessUrl("/resource/hello/cloud").permitAll() - .and().csrf().disable(); + http + .authorizeRequests() + .antMatchers("/resource/hello/cloud").permitAll() + .antMatchers("/eureka/**").hasRole("ADMIN") + .anyRequest().authenticated().and() + .formLogin().and() + .logout().permitAll() + .logoutSuccessUrl("/resource/hello/cloud").permitAll().and() + .csrf().disable(); } } diff --git a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java index 8cea8cf080..813956676e 100644 --- a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java @@ -11,6 +11,13 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http.httpBasic().disable().authorizeRequests().antMatchers("/hello/cloud").permitAll().antMatchers("/hello/user").hasAnyRole("USER", "ADMIN").antMatchers("/hello/admin").hasRole("ADMIN").anyRequest().authenticated().and().csrf().disable(); + http + .httpBasic().disable() + .authorizeRequests() + .antMatchers("/hello/cloud").permitAll() + .antMatchers("/hello/user").hasAnyRole("USER", "ADMIN") + .antMatchers("/hello/admin").hasRole("ADMIN") + .anyRequest().authenticated().and() + .csrf().disable(); } } From b48cf1e1cedeef1ec413133557273ef078a5a90a Mon Sep 17 00:00:00 2001 From: tschiman Date: Mon, 24 Oct 2016 20:49:58 -0600 Subject: [PATCH 07/47] Modify formatting. --- .../config/src/main/resources/application.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties index e97a6a4094..212586f0ea 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties @@ -6,7 +6,7 @@ spring.cloud.config.server.git.uri=file:///${user.home}/application-config eureka.client.region = default eureka.client.registryFetchIntervalSeconds = 5 eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/ -#Security User Config + security.user.name=configUser security.user.password=configPassword security.user.role=SYSTEM \ No newline at end of file From e6b8446dd314980011cfcb4b03545f9d4502be3f Mon Sep 17 00:00:00 2001 From: tschiman Date: Mon, 24 Oct 2016 21:26:14 -0600 Subject: [PATCH 08/47] Modify formatting. --- .../bootstrap/discovery/SecurityConfig.java | 5 -- .../filter/SessionSavingZuulPreFilter.java | 48 +++++++++---------- 2 files changed, 24 insertions(+), 29 deletions(-) diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java index a55508b1e7..b8cb66e3e4 100644 --- a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java @@ -36,11 +36,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { //no order tag means this is the last security filter to be evaluated public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter { - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication(); - } - @Override protected void configure(HttpSecurity http) throws Exception { http diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingZuulPreFilter.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingZuulPreFilter.java index 9a2b5bab74..1c90ba2e12 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingZuulPreFilter.java +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingZuulPreFilter.java @@ -14,34 +14,34 @@ import javax.servlet.http.HttpSession; @Component public class SessionSavingZuulPreFilter extends ZuulFilter { - private Logger log = LoggerFactory.getLogger(this.getClass()); + private Logger log = LoggerFactory.getLogger(this.getClass()); - @Autowired - private SessionRepository repository; + @Autowired + private SessionRepository repository; - @Override public boolean shouldFilter() { - return true; - } + @Override + public boolean shouldFilter() { + return true; + } - @Override - public Object run() { - RequestContext context = RequestContext.getCurrentContext(); + @Override + public Object run() { + RequestContext context = RequestContext.getCurrentContext(); + HttpSession httpSession = context.getRequest().getSession(); + Session session = repository.getSession(httpSession.getId()); - HttpSession httpSession = context.getRequest().getSession(); - Session session = repository.getSession(httpSession.getId()); + context.addZuulRequestHeader("Cookie", "SESSION=" + httpSession.getId()); + log.info("ZuulPreFilter session proxy: {}", session.getId()); + return null; + } - context.addZuulRequestHeader("Cookie", "SESSION=" + httpSession.getId()); + @Override + public String filterType() { + return "pre"; + } - log.info("ZuulPreFilter session proxy: {}", session.getId()); - - return null; - } - - @Override public String filterType() { - return "pre"; - } - - @Override public int filterOrder() { - return 0; - } + @Override + public int filterOrder() { + return 0; + } } From 8564e482e4c6a6a2a925d536e341acae64509ec8 Mon Sep 17 00:00:00 2001 From: tschiman Date: Sat, 5 Nov 2016 09:57:39 -0600 Subject: [PATCH 09/47] BAEL-89 Adding spring session tutorial code. --- pom.xml | 1 + spring-session/jetty-ex/pom.xml | 71 +++++++++++++++++++ .../session/tomcatex/JettyWebApplication.java | 19 +++++ .../session/tomcatex/SecurityConfig.java | 22 ++++++ .../session/tomcatex/SessionConfig.java | 17 +++++ .../src/main/resources/application.properties | 4 ++ spring-session/pom.xml | 20 ++++++ spring-session/tomcat-ex/pom.xml | 71 +++++++++++++++++++ .../session/tomcatex/SecurityConfig.java | 32 +++++++++ .../session/tomcatex/SessionConfig.java | 10 +++ .../tomcatex/TomcatWebApplication.java | 29 ++++++++ .../src/main/resources/application.properties | 2 + 12 files changed, 298 insertions(+) create mode 100644 spring-session/jetty-ex/pom.xml create mode 100644 spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java create mode 100644 spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java create mode 100644 spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java create mode 100644 spring-session/jetty-ex/src/main/resources/application.properties create mode 100644 spring-session/pom.xml create mode 100644 spring-session/tomcat-ex/pom.xml create mode 100644 spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java create mode 100644 spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java create mode 100644 spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java create mode 100644 spring-session/tomcat-ex/src/main/resources/application.properties diff --git a/pom.xml b/pom.xml index eee9f07ab9..466e2fe939 100644 --- a/pom.xml +++ b/pom.xml @@ -122,6 +122,7 @@ spring-thymeleaf spring-zuul spring-mvc-velocity + spring-session jsf xml diff --git a/spring-session/jetty-ex/pom.xml b/spring-session/jetty-ex/pom.xml new file mode 100644 index 0000000000..339821b5fe --- /dev/null +++ b/spring-session/jetty-ex/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + com.baeldung + jetty-ex + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-jetty + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.session + spring-session + 1.2.1.RELEASE + + + org.springframework.boot + spring-boot-starter-data-redis + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java b/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java new file mode 100644 index 0000000000..0da6316560 --- /dev/null +++ b/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@SpringBootApplication +@RestController +public class JettyWebApplication { + public static void main(String[] args) { + SpringApplication.run(JettyWebApplication.class, args); + } + + @RequestMapping + public String helloJetty() { + return "hello Jetty"; + } +} diff --git a/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java new file mode 100644 index 0000000000..3cd2e5e3ca --- /dev/null +++ b/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java @@ -0,0 +1,22 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.context.annotation.Configuration; +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.config.http.SessionCreationPolicy; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.NEVER) + .and() + .authorizeRequests().anyRequest().hasRole("ADMIN").and() + .httpBasic().disable(); + } +} diff --git a/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java b/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java new file mode 100644 index 0000000000..59fdefe30b --- /dev/null +++ b/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; +import org.springframework.session.web.http.HeaderHttpSessionStrategy; +import org.springframework.session.web.http.HttpSessionStrategy; + +@Configuration +@EnableRedisHttpSession +public class SessionConfig extends AbstractHttpSessionApplicationInitializer { + @Bean + public HttpSessionStrategy httpSessionStrategy() { + return new HeaderHttpSessionStrategy(); + } +} diff --git a/spring-session/jetty-ex/src/main/resources/application.properties b/spring-session/jetty-ex/src/main/resources/application.properties new file mode 100644 index 0000000000..902de4e45f --- /dev/null +++ b/spring-session/jetty-ex/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.port=8081 + +spring.redis.host=localhost +spring.redis.port=6379 \ No newline at end of file diff --git a/spring-session/pom.xml b/spring-session/pom.xml new file mode 100644 index 0000000000..1e4bec0014 --- /dev/null +++ b/spring-session/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + spring-session + 1.0.0-SNAPSHOT + + + jetty-ex + tomcat-ex + + \ No newline at end of file diff --git a/spring-session/tomcat-ex/pom.xml b/spring-session/tomcat-ex/pom.xml new file mode 100644 index 0000000000..aed49df5e3 --- /dev/null +++ b/spring-session/tomcat-ex/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + com.baeldung + tomcat-ex + 1.0.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.cloud + spring-cloud-starter-zuul + + + org.springframework.session + spring-session + 1.2.1.RELEASE + + + org.springframework.boot + spring-boot-starter-data-redis + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java new file mode 100644 index 0000000000..2af111fe08 --- /dev/null +++ b/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("user").password("password").roles("USER").and() + .withUser("admin").password("password").roles("ADMIN"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .httpBasic().and() +// .csrf().disable() + .authorizeRequests() + .antMatchers("/").permitAll() + .antMatchers("/tomcat").hasRole("USER") + .antMatchers("/tomcat/admin").hasRole("ADMIN") + .anyRequest().authenticated(); + } +} diff --git a/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java b/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java new file mode 100644 index 0000000000..5afac6cb6b --- /dev/null +++ b/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.context.annotation.Configuration; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; + +@Configuration +@EnableRedisHttpSession +public class SessionConfig extends AbstractHttpSessionApplicationInitializer { +} diff --git a/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java b/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java new file mode 100644 index 0000000000..417aaddf29 --- /dev/null +++ b/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@SpringBootApplication +@RestController +public class TomcatWebApplication { + public static void main(String[] args) { + SpringApplication.run(TomcatWebApplication.class, args); + } + + @RequestMapping + public String helloDefault() { + return "hello default"; + } + + @RequestMapping("/tomcat") + public String helloTomcat() { + return "hello tomcat"; + } + + @RequestMapping("/tomcat/admin") + public String helloTomcatAdmin() { + return "hello tomcat admin"; + } +} diff --git a/spring-session/tomcat-ex/src/main/resources/application.properties b/spring-session/tomcat-ex/src/main/resources/application.properties new file mode 100644 index 0000000000..49886b3b70 --- /dev/null +++ b/spring-session/tomcat-ex/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.redis.host=localhost +spring.redis.port=6379 \ No newline at end of file From dd2885085952dc6c3058e1570f0cb5f8eaf4c0a4 Mon Sep 17 00:00:00 2001 From: tschiman Date: Sat, 5 Nov 2016 10:28:46 -0600 Subject: [PATCH 10/47] BAEL-89 remove apring zuul dependency --- spring-session/tomcat-ex/pom.xml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/spring-session/tomcat-ex/pom.xml b/spring-session/tomcat-ex/pom.xml index aed49df5e3..243413b213 100644 --- a/spring-session/tomcat-ex/pom.xml +++ b/spring-session/tomcat-ex/pom.xml @@ -24,10 +24,6 @@ org.springframework.boot spring-boot-starter-security - - org.springframework.cloud - spring-cloud-starter-zuul - org.springframework.session spring-session From 77c5ffbe872392e808d4f738cb98e57f508df7c4 Mon Sep 17 00:00:00 2001 From: tschiman Date: Sat, 5 Nov 2016 10:35:46 -0600 Subject: [PATCH 11/47] BAEL-89 remove csrf disable --- .../com/baeldung/spring/session/tomcatex/SecurityConfig.java | 3 +-- .../com/baeldung/spring/session/tomcatex/SecurityConfig.java | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java index 3cd2e5e3ca..ef779718cd 100644 --- a/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java +++ b/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java @@ -16,7 +16,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.NEVER) .and() - .authorizeRequests().anyRequest().hasRole("ADMIN").and() - .httpBasic().disable(); + .authorizeRequests().anyRequest().hasRole("ADMIN").and(); } } diff --git a/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java index 2af111fe08..91cd749c4c 100644 --- a/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java +++ b/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java @@ -22,7 +22,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { http .httpBasic().and() -// .csrf().disable() .authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/tomcat").hasRole("USER") From 134c4ca455886dd727e6983bb6eef2b8d22f893f Mon Sep 17 00:00:00 2001 From: tschiman Date: Sat, 5 Nov 2016 10:52:45 -0600 Subject: [PATCH 12/47] BAEL-89 remove csrf disable --- .../com/baeldung/spring/session/tomcatex/SecurityConfig.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java index ef779718cd..202cad27e6 100644 --- a/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java +++ b/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java @@ -16,6 +16,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.NEVER) .and() - .authorizeRequests().anyRequest().hasRole("ADMIN").and(); + .authorizeRequests().anyRequest().hasRole("ADMIN"); } } From f5f771d1365f13b4a4fc794494ea1a9c9bb4f923 Mon Sep 17 00:00:00 2001 From: tschiman Date: Sat, 5 Nov 2016 20:35:52 -0600 Subject: [PATCH 13/47] BAEL-89 modifying the module names and changing the dependencies to be in line with what we would get from start.spring.io --- spring-session/{jetty-ex => jetty-session-demo}/pom.xml | 6 +++--- .../spring/session/tomcatex/JettyWebApplication.java | 5 +++++ .../baeldung/spring/session/tomcatex/SecurityConfig.java | 0 .../com/baeldung/spring/session/tomcatex/SessionConfig.java | 0 .../src/main/resources/application.properties | 0 spring-session/pom.xml | 4 ++-- spring-session/{tomcat-ex => tomcat-session-demo}/pom.xml | 5 ++--- .../baeldung/spring/session/tomcatex/SecurityConfig.java | 0 .../com/baeldung/spring/session/tomcatex/SessionConfig.java | 0 .../spring/session/tomcatex/TomcatWebApplication.java | 0 .../src/main/resources/application.properties | 0 11 files changed, 12 insertions(+), 8 deletions(-) rename spring-session/{jetty-ex => jetty-session-demo}/pom.xml (98%) rename spring-session/{jetty-ex => jetty-session-demo}/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java (85%) rename spring-session/{jetty-ex => jetty-session-demo}/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java (100%) rename spring-session/{jetty-ex => jetty-session-demo}/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java (100%) rename spring-session/{jetty-ex => jetty-session-demo}/src/main/resources/application.properties (100%) rename spring-session/{tomcat-ex => tomcat-session-demo}/pom.xml (98%) rename spring-session/{tomcat-ex => tomcat-session-demo}/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java (100%) rename spring-session/{tomcat-ex => tomcat-session-demo}/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java (100%) rename spring-session/{tomcat-ex => tomcat-session-demo}/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java (100%) rename spring-session/{tomcat-ex => tomcat-session-demo}/src/main/resources/application.properties (100%) diff --git a/spring-session/jetty-ex/pom.xml b/spring-session/jetty-session-demo/pom.xml similarity index 98% rename from spring-session/jetty-ex/pom.xml rename to spring-session/jetty-session-demo/pom.xml index 339821b5fe..717506fbce 100644 --- a/spring-session/jetty-ex/pom.xml +++ b/spring-session/jetty-session-demo/pom.xml @@ -20,9 +20,10 @@ org.springframework.boot spring-boot-starter-jetty + org.springframework.boot - spring-boot-starter-web + spring-boot-starter-data-redis org.springframework.boot @@ -31,11 +32,10 @@ org.springframework.session spring-session - 1.2.1.RELEASE org.springframework.boot - spring-boot-starter-data-redis + spring-boot-starter-web diff --git a/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java similarity index 85% rename from spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java rename to spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java index 0da6316560..2cdc5f99af 100644 --- a/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java @@ -16,4 +16,9 @@ public class JettyWebApplication { public String helloJetty() { return "hello Jetty"; } + + @RequestMapping("/test") + public String lksjdf() { + return ""; + } } diff --git a/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java similarity index 100% rename from spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java rename to spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java diff --git a/spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java similarity index 100% rename from spring-session/jetty-ex/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java rename to spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java diff --git a/spring-session/jetty-ex/src/main/resources/application.properties b/spring-session/jetty-session-demo/src/main/resources/application.properties similarity index 100% rename from spring-session/jetty-ex/src/main/resources/application.properties rename to spring-session/jetty-session-demo/src/main/resources/application.properties diff --git a/spring-session/pom.xml b/spring-session/pom.xml index 1e4bec0014..74561edc59 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -14,7 +14,7 @@ 1.0.0-SNAPSHOT - jetty-ex - tomcat-ex + jetty-session-demo + tomcat-session-demo \ No newline at end of file diff --git a/spring-session/tomcat-ex/pom.xml b/spring-session/tomcat-session-demo/pom.xml similarity index 98% rename from spring-session/tomcat-ex/pom.xml rename to spring-session/tomcat-session-demo/pom.xml index 243413b213..cade029ac8 100644 --- a/spring-session/tomcat-ex/pom.xml +++ b/spring-session/tomcat-session-demo/pom.xml @@ -18,7 +18,7 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-data-redis org.springframework.boot @@ -27,11 +27,10 @@ org.springframework.session spring-session - 1.2.1.RELEASE org.springframework.boot - spring-boot-starter-data-redis + spring-boot-starter-web diff --git a/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java similarity index 100% rename from spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java rename to spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java diff --git a/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java similarity index 100% rename from spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java rename to spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java diff --git a/spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java similarity index 100% rename from spring-session/tomcat-ex/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java rename to spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java diff --git a/spring-session/tomcat-ex/src/main/resources/application.properties b/spring-session/tomcat-session-demo/src/main/resources/application.properties similarity index 100% rename from spring-session/tomcat-ex/src/main/resources/application.properties rename to spring-session/tomcat-session-demo/src/main/resources/application.properties From 9689d4656a78cf14dfe51e288d107b026d5fa867 Mon Sep 17 00:00:00 2001 From: tschiman Date: Sat, 5 Nov 2016 20:38:21 -0600 Subject: [PATCH 14/47] BAEL-89 modifying the maven sub project names --- spring-session/jetty-session-demo/pom.xml | 2 +- spring-session/tomcat-session-demo/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-session/jetty-session-demo/pom.xml b/spring-session/jetty-session-demo/pom.xml index 717506fbce..86a8596862 100644 --- a/spring-session/jetty-session-demo/pom.xml +++ b/spring-session/jetty-session-demo/pom.xml @@ -5,7 +5,7 @@ 4.0.0 com.baeldung - jetty-ex + jetty-session-demo 1.0.0-SNAPSHOT diff --git a/spring-session/tomcat-session-demo/pom.xml b/spring-session/tomcat-session-demo/pom.xml index cade029ac8..805d7bec25 100644 --- a/spring-session/tomcat-session-demo/pom.xml +++ b/spring-session/tomcat-session-demo/pom.xml @@ -5,7 +5,7 @@ 4.0.0 com.baeldung - tomcat-ex + tomcat-session-demo 1.0.0-SNAPSHOT From bde1d12e822e5db5ab198f7d12145717ff0d5ad2 Mon Sep 17 00:00:00 2001 From: Pritam Banerjee Date: Mon, 7 Nov 2016 02:06:51 -0800 Subject: [PATCH 15/47] Updated Wildfly configurations and changed the files: ejb pom and ejb-remote.pom --- ejb/ejb-remote/pom.xml | 18 ++++++++++++++++-- ejb/pom.xml | 4 ++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/ejb/ejb-remote/pom.xml b/ejb/ejb-remote/pom.xml index 14c02edd0e..3661fa5b2c 100755 --- a/ejb/ejb-remote/pom.xml +++ b/ejb/ejb-remote/pom.xml @@ -10,7 +10,7 @@ ejb-remote ejb - ejb-remote + org.jboss.spec.javax.ejb @@ -20,6 +20,20 @@ - ejb-remote + + + org.wildfly.plugins + wildfly-maven-plugin + 1.1.0.Alpha5 + + 127.0.0.1 + 9990 + pritamtest + iamtheki9g + ${build.finalName}.jar + + + + \ No newline at end of file diff --git a/ejb/pom.xml b/ejb/pom.xml index 49ddc694e9..5c54cdcf72 100755 --- a/ejb/pom.xml +++ b/ejb/pom.xml @@ -60,8 +60,8 @@ maven-compiler-plugin 3.1 - 1.7 - 1.7 + 1.8 + 1.8 From 58e704a0b873a965d7c9062e6b37a9c8f4265b5b Mon Sep 17 00:00:00 2001 From: tschiman Date: Sat, 12 Nov 2016 09:30:44 -0700 Subject: [PATCH 16/47] BAEL-89 Spring session breaking out the controller and changing the formatting to be in line with the baeldung standard. --- .../session/tomcatex/JettyWebApplication.java | 13 ---------- .../session/tomcatex/TestController.java | 15 +++++++++++ .../session/tomcatex/TestController.java | 26 +++++++++++++++++++ .../tomcatex/TomcatWebApplication.java | 18 ------------- 4 files changed, 41 insertions(+), 31 deletions(-) create mode 100644 spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java create mode 100644 spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java index 7bbc776eaa..947abc2dff 100644 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/JettyWebApplication.java @@ -2,23 +2,10 @@ package com.baeldung.spring.session.tomcatex; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; @SpringBootApplication -@RestController public class JettyWebApplication { public static void main(String[] args) { SpringApplication.run(JettyWebApplication.class, args); } - - @RequestMapping - public String helloJetty() { - return "hello Jetty"; - } - - @RequestMapping("/test") - public String lksjdf() { - return ""; - } } diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java new file mode 100644 index 0000000000..6350a68041 --- /dev/null +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * Created by tschi on 11/12/2016. + */ +@RestController +public class TestController { + @RequestMapping + public String helloJetty() { + return "hello Jetty"; + } +} diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java new file mode 100644 index 0000000000..c84204c6ee --- /dev/null +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.session.tomcatex; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * Created by tschi on 11/12/2016. + */ +@RestController +public class TestController { + + @RequestMapping + public String helloDefault() { + return "hello default"; + } + + @RequestMapping("/tomcat") + public String helloTomcat() { + return "hello tomcat"; + } + + @RequestMapping("/tomcat/admin") + public String helloTomcatAdmin() { + return "hello tomcat admin"; + } +} diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java index 58c6b807ec..fb4e059dd1 100644 --- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java @@ -2,28 +2,10 @@ package com.baeldung.spring.session.tomcatex; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; @SpringBootApplication -@RestController public class TomcatWebApplication { public static void main(String[] args) { SpringApplication.run(TomcatWebApplication.class, args); } - - @RequestMapping - public String helloDefault() { - return "hello default"; - } - - @RequestMapping("/tomcat") - public String helloTomcat() { - return "hello tomcat"; - } - - @RequestMapping("/tomcat/admin") - public String helloTomcatAdmin() { - return "hello tomcat admin"; - } } From b1d5ae8c3c8ebadf15c093827243a477ecc11efd Mon Sep 17 00:00:00 2001 From: Pritam Banerjee Date: Tue, 15 Nov 2016 23:04:08 -0800 Subject: [PATCH 17/47] setup ejb --- ejb/ejb-remote/pom.xml | 11 ++++++----- ejb/pom.xml | 9 ++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/ejb/ejb-remote/pom.xml b/ejb/ejb-remote/pom.xml index 3661fa5b2c..9f0b07c0e3 100755 --- a/ejb/ejb-remote/pom.xml +++ b/ejb/ejb-remote/pom.xml @@ -12,11 +12,12 @@ - - org.jboss.spec.javax.ejb - jboss-ejb-api_3.2_spec - provided - + + javax + javaee-api + 7.0 + provided + diff --git a/ejb/pom.xml b/ejb/pom.xml index 5c54cdcf72..8176de7936 100755 --- a/ejb/pom.xml +++ b/ejb/pom.xml @@ -36,11 +36,10 @@ - org.jboss.spec - jboss-javaee-7.0 - 1.0.1.Final - pom - import + javax + javaee-api + 7.0 + provided From 7e0bf584a1dedab7e9d038c20e1f22a8299d7891 Mon Sep 17 00:00:00 2001 From: oreva Date: Thu, 17 Nov 2016 13:36:07 +0200 Subject: [PATCH 18/47] Java-based configuration implemented. --- .../CustomWebSecurityConfigurerAdapter.java | 17 -------- .../spring/SecSecurityConfigJava.java | 40 +++++++++++++++++++ ...yConfig.java => SecSecurityConfigXML.java} | 10 ++--- 3 files changed, 45 insertions(+), 22 deletions(-) delete mode 100644 spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java create mode 100644 spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfigJava.java rename spring-security-basic-auth/src/main/java/org/baeldung/spring/{SecSecurityConfig.java => SecSecurityConfigXML.java} (56%) diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java b/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java deleted file mode 100644 index 468c99cb2a..0000000000 --- a/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.security.filter.configuration; - -import org.baeldung.security.filter.CustomFilter; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; - -@Configuration -public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); - } - -} diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfigJava.java b/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfigJava.java new file mode 100644 index 0000000000..8e88c3f099 --- /dev/null +++ b/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfigJava.java @@ -0,0 +1,40 @@ +package org.baeldung.spring; + +import org.baeldung.security.basic.MyBasicAuthenticationEntryPoint; +import org.baeldung.security.filter.CustomFilter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +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.authentication.www.BasicAuthenticationFilter; + +@Configuration +@EnableWebSecurity +@ComponentScan("org.baeldung.security") +public class SecSecurityConfigJava extends WebSecurityConfigurerAdapter { + @Autowired + private MyBasicAuthenticationEntryPoint authenticationEntryPoint; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth + .inMemoryAuthentication() + .withUser("user1").password("user1Pass").authorities("ROLE_USER"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/securityNone").permitAll() + .anyRequest().authenticated() + .and() + .httpBasic() + .authenticationEntryPoint(authenticationEntryPoint); + + http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); + } + +} diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfigXML.java similarity index 56% rename from spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java rename to spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfigXML.java index 4ce80dab9f..a080b624f6 100644 --- a/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfigXML.java @@ -4,12 +4,12 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; -@Configuration -@ImportResource({ "classpath:webSecurityConfig.xml" }) -@ComponentScan("org.baeldung.security") -public class SecSecurityConfig { +//@Configuration +//@ImportResource({ "classpath:webSecurityConfig.xml" }) +//@ComponentScan("org.baeldung.security") +public class SecSecurityConfigXML { - public SecSecurityConfig() { + public SecSecurityConfigXML() { super(); } From c0e721b92e30f486324ad4fe0c6b4d69f68a3ffb Mon Sep 17 00:00:00 2001 From: tschiman Date: Thu, 17 Nov 2016 20:32:05 -0700 Subject: [PATCH 19/47] Merge remote-tracking branch 'upstream/master' # Conflicts: # spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java # spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java --- spring-session/tomcat-session-demo/pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/spring-session/tomcat-session-demo/pom.xml b/spring-session/tomcat-session-demo/pom.xml index 805d7bec25..0a101e73a6 100644 --- a/spring-session/tomcat-session-demo/pom.xml +++ b/spring-session/tomcat-session-demo/pom.xml @@ -32,6 +32,11 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-test + test + From a88c500d8d6862ff1f9d2bd345268a2d98f8605a Mon Sep 17 00:00:00 2001 From: tschiman Date: Thu, 17 Nov 2016 20:32:44 -0700 Subject: [PATCH 20/47] BAEL-89 Adding test dependencies --- spring-session/jetty-session-demo/pom.xml | 5 +++++ .../spring/session/tomcatex/TestController.java | 15 --------------- .../spring/session/tomcatex/SecurityConfig.java | 3 --- .../spring/session/tomcatex/TestController.java | 11 ----------- 4 files changed, 5 insertions(+), 29 deletions(-) delete mode 100644 spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java diff --git a/spring-session/jetty-session-demo/pom.xml b/spring-session/jetty-session-demo/pom.xml index 86a8596862..19f0577d2e 100644 --- a/spring-session/jetty-session-demo/pom.xml +++ b/spring-session/jetty-session-demo/pom.xml @@ -37,6 +37,11 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-test + test + diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java deleted file mode 100644 index 6350a68041..0000000000 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.spring.session.tomcatex; - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * Created by tschi on 11/12/2016. - */ -@RestController -public class TestController { - @RequestMapping - public String helloJetty() { - return "hello Jetty"; - } -} diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java index 3e419b27a2..7476d7305d 100644 --- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java @@ -14,7 +14,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() - .withUser("user").password("password").roles("USER").and() .withUser("admin").password("password").roles("ADMIN"); } @@ -23,8 +22,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { http .httpBasic().and() .authorizeRequests() - .antMatchers("/").permitAll() - .antMatchers("/tomcat").hasRole("USER") .antMatchers("/tomcat/admin").hasRole("ADMIN") .anyRequest().authenticated(); } diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java index 877f29e1d3..9728ff7fc9 100644 --- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java @@ -5,17 +5,6 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { - - @RequestMapping - public String helloDefault() { - return "hello default"; - } - - @RequestMapping("/tomcat") - public String helloTomcat() { - return "hello tomcat"; - } - @RequestMapping("/tomcat/admin") public String helloTomcatAdmin() { return "hello tomcat admin"; From 7f6130c5661009aa1ae8e225b3d14b428e5444c8 Mon Sep 17 00:00:00 2001 From: tschiman Date: Thu, 17 Nov 2016 22:19:49 -0700 Subject: [PATCH 21/47] BAEL-89 Adding test configuration and test classes to demonstrate the code --- ...stController.java => JettyController.java} | 2 +- .../session/jettyex/JettyWebApplication.java | 1 - .../session/jettyex/SecurityConfig.java | 4 +- .../session/tomcatex/SecurityConfig.java | 13 ++- ...tController.java => TomcatController.java} | 2 +- .../tomcatex/TomcatControllerTest.java | 103 ++++++++++++++++++ 6 files changed, 113 insertions(+), 12 deletions(-) rename spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/{TestController.java => JettyController.java} (90%) rename spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/{TestController.java => TomcatController.java} (90%) create mode 100644 spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/TestController.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyController.java similarity index 90% rename from spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/TestController.java rename to spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyController.java index f5c82f2260..308b0a8d51 100644 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/TestController.java +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyController.java @@ -4,7 +4,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController -public class TestController { +public class JettyController { @RequestMapping public String helloJetty() { return "hello Jetty"; diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java index f692d0ff23..ebb2a8e188 100644 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java @@ -2,7 +2,6 @@ package com.baeldung.spring.session.jettyex; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.web.bind.annotation.RestController; @SpringBootApplication public class JettyWebApplication { diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java index 28cdb3cc08..5ce8f9a042 100644 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java @@ -13,9 +13,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http - .sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.NEVER) - .and() + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and() .authorizeRequests().anyRequest().hasRole("ADMIN"); } } diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java index 7476d7305d..0f467dd104 100644 --- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java @@ -13,16 +13,17 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication() - .withUser("admin").password("password").roles("ADMIN"); + auth + .inMemoryAuthentication() + .withUser("admin").password("password").roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http - .httpBasic().and() - .authorizeRequests() - .antMatchers("/tomcat/admin").hasRole("ADMIN") - .anyRequest().authenticated(); + .httpBasic().and() + .authorizeRequests() + .antMatchers("/tomcat/admin").hasRole("ADMIN") + .anyRequest().authenticated(); } } diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatController.java similarity index 90% rename from spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java rename to spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatController.java index 9728ff7fc9..a241158294 100644 --- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatController.java @@ -4,7 +4,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController -public class TestController { +public class TomcatController { @RequestMapping("/tomcat/admin") public String helloTomcatAdmin() { return "hello tomcat admin"; diff --git a/spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java b/spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java new file mode 100644 index 0000000000..5bfb7e9411 --- /dev/null +++ b/spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java @@ -0,0 +1,103 @@ +package com.baeldung.spring.session.tomcatex; + +import org.apache.tomcat.util.codec.binary.Base64; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; +import org.springframework.http.*; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class TomcatControllerTest { + + @Autowired + private TestRestTemplate restTemplate; + @LocalServerPort + private int port; + @Autowired + private JedisConnectionFactory jedisConnectionFactory; + private RedisConnection connection; + + @Before + public void clearRedisData() { + connection = jedisConnectionFactory.getConnection(); + connection.flushAll(); + } + + @Test + public void testRedisIsEmpty() { + Set result = connection.keys("*".getBytes()); + assertEquals(0, result.size()); + } + + @Test + public void testForbiddenToProtectedEndpoint() { + ResponseEntity result = restTemplate.getForEntity("/tomcat/admin", String.class); + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); + } + + @Test + public void testLoginAddsRedisKey() { + ResponseEntity result = makeRequest(); + assertEquals("hello tomcat admin", result.getBody()); //login worked + + Set redisResult = connection.keys("*".getBytes()); + assertTrue(redisResult.size() > 0); //redis was populated with data + } + + @Test //requires that the jetty service is running on port 8081 + public void testFailureAccessingJettyResourceWithTomcatSessionToken() { + //call the jetty server with the token + ResponseEntity jettyResult = restTemplate.getForEntity("http://localhost:8081", String.class); + assertEquals(HttpStatus.UNAUTHORIZED, jettyResult.getStatusCode()); //login worked + } + + @Test //requires that the jetty service is running on port 8081 + public void testAccessingJettyResourceWithTomcatSessionToken() { + //login to get a session token + ResponseEntity result = makeRequest(); + assertEquals("hello tomcat admin", result.getBody()); //login worked + + assertTrue(result.getHeaders().containsKey("Set-Cookie")); + + String setCookieValue = result.getHeaders().get("Set-Cookie").get(0); + String sessionCookie = setCookieValue.split(";")[0]; + String sessionValue = sessionCookie.split("=")[1]; + + //Add session token to headers + HttpHeaders headers = new HttpHeaders(); + headers.add("x-auth-token", sessionValue); + + //call the jetty server with the token + HttpEntity request = new HttpEntity<>(headers); + ResponseEntity jettyResult = restTemplate.exchange("http://localhost:8081", HttpMethod.GET, request, String.class); + assertEquals("hello Jetty", jettyResult.getBody()); //login worked + + } + + private ResponseEntity makeRequest() { + String plainCreds = "admin:password"; + byte[] plainCredsBytes = plainCreds.getBytes(); + byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); + String base64Creds = new String(base64CredsBytes); + + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic " + base64Creds); + + HttpEntity request = new HttpEntity<>(headers); + return restTemplate.exchange("http://localhost:" + port + "/tomcat/admin", HttpMethod.GET, request, String.class); + } + +} \ No newline at end of file From 5f99e5aedd6fc64c4266104c72674b372b7d57e7 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sat, 19 Nov 2016 09:47:17 +0100 Subject: [PATCH 22/47] BAEL-89 - Adding surefire, fixing formatting --- .../spring/session/jettyex/SecurityConfig.java | 4 ++-- spring-session/pom.xml | 1 + spring-session/tomcat-session-demo/pom.xml | 14 ++++++++++++++ .../spring/session/tomcatex/SecurityConfig.java | 12 ++++++------ 4 files changed, 23 insertions(+), 8 deletions(-) diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java index 5ce8f9a042..09f752b261 100644 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java @@ -13,7 +13,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and() - .authorizeRequests().anyRequest().hasRole("ADMIN"); + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and() + .authorizeRequests().anyRequest().hasRole("ADMIN"); } } diff --git a/spring-session/pom.xml b/spring-session/pom.xml index fec6a46af2..3a5965c193 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -19,4 +19,5 @@ jetty-session-demo tomcat-session-demo + \ No newline at end of file diff --git a/spring-session/tomcat-session-demo/pom.xml b/spring-session/tomcat-session-demo/pom.xml index 0a101e73a6..7d52082651 100644 --- a/spring-session/tomcat-session-demo/pom.xml +++ b/spring-session/tomcat-session-demo/pom.xml @@ -66,6 +66,20 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*ControllerTest.java + + + + + + 2.19.1 + \ No newline at end of file diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java index 0f467dd104..691aad3ee5 100644 --- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java @@ -14,16 +14,16 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth - .inMemoryAuthentication() - .withUser("admin").password("password").roles("ADMIN"); + .inMemoryAuthentication() + .withUser("admin").password("password").roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http - .httpBasic().and() - .authorizeRequests() - .antMatchers("/tomcat/admin").hasRole("ADMIN") - .anyRequest().authenticated(); + .httpBasic().and() + .authorizeRequests() + .antMatchers("/tomcat/admin").hasRole("ADMIN") + .anyRequest().authenticated(); } } From 858d14baf308f7e22ddf8d96ddb0587cf106b538 Mon Sep 17 00:00:00 2001 From: oreva Date: Sat, 19 Nov 2016 21:14:40 +0200 Subject: [PATCH 23/47] Reorganized classes according to the last pull request's comments. --- .../CustomWebSecurityConfigurerAdapter.java} | 26 +++++++++---------- ...yConfigXML.java => SecSecurityConfig.java} | 9 +++---- 2 files changed, 17 insertions(+), 18 deletions(-) rename spring-security-basic-auth/src/main/java/org/baeldung/{spring/SecSecurityConfigJava.java => security/filter/configuration/CustomWebSecurityConfigurerAdapter.java} (63%) rename spring-security-basic-auth/src/main/java/org/baeldung/spring/{SecSecurityConfigXML.java => SecSecurityConfig.java} (55%) diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfigJava.java b/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java similarity index 63% rename from spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfigJava.java rename to spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java index 8e88c3f099..1901489305 100644 --- a/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfigJava.java +++ b/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java @@ -1,9 +1,8 @@ -package org.baeldung.spring; +package org.baeldung.security.filter.configuration; import org.baeldung.security.basic.MyBasicAuthenticationEntryPoint; import org.baeldung.security.filter.CustomFilter; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; @@ -13,28 +12,29 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationFi @Configuration @EnableWebSecurity -@ComponentScan("org.baeldung.security") -public class SecSecurityConfigJava extends WebSecurityConfigurerAdapter { +public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Autowired private MyBasicAuthenticationEntryPoint authenticationEntryPoint; @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + public void configureGlobal(AuthenticationManagerBuilder auth) + throws Exception { auth - .inMemoryAuthentication() - .withUser("user1").password("user1Pass").authorities("ROLE_USER"); + .inMemoryAuthentication() + .withUser("user1").password("user1Pass") + .authorities("ROLE_USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() - .antMatchers("/securityNone").permitAll() - .anyRequest().authenticated() - .and() + .antMatchers("/securityNone").permitAll() + .anyRequest().authenticated() + .and() .httpBasic() - .authenticationEntryPoint(authenticationEntryPoint); + .authenticationEntryPoint(authenticationEntryPoint); - http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); + http.addFilterAfter(new CustomFilter(), + BasicAuthenticationFilter.class); } - } diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfigXML.java b/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java similarity index 55% rename from spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfigXML.java rename to spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java index a080b624f6..5aa14c1051 100644 --- a/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfigXML.java +++ b/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -2,14 +2,13 @@ package org.baeldung.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; -//@Configuration +@Configuration +@ComponentScan("org.baeldung.security") //@ImportResource({ "classpath:webSecurityConfig.xml" }) -//@ComponentScan("org.baeldung.security") -public class SecSecurityConfigXML { +public class SecSecurityConfig { - public SecSecurityConfigXML() { + public SecSecurityConfig() { super(); } From a8fb4e11cb24c4572d888fc434d70069fb035e5a Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 20 Nov 2016 11:57:27 +0200 Subject: [PATCH 24/47] Fix FileTest --- .../java/com/baeldung/java/nio2/FileTest.java | 86 ++++++++++--------- 1 file changed, 47 insertions(+), 39 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java index 64fbb4ae25..587f4ab34a 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java @@ -1,64 +1,72 @@ package com.baeldung.java.nio2; +import org.apache.commons.io.FileUtils; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.*; +import java.util.UUID; + import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import java.io.IOException; -import java.nio.file.DirectoryNotEmptyException; -import java.nio.file.FileAlreadyExistsException; -import java.nio.file.Files; -import java.nio.file.NoSuchFileException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.UUID; - -import org.junit.Test; - public class FileTest { - private static final String HOME = System.getProperty("user.home"); + private static final String TEMP_DIR = String.format("%s/temp%s", System.getProperty("user.home"), UUID.randomUUID().toString()); + + @BeforeClass + public static void setup() throws IOException { + Files.createDirectory(Paths.get(TEMP_DIR)); + } + + @AfterClass + public static void cleanup() throws IOException { + FileUtils.deleteDirectory(new File(TEMP_DIR)); + } // checking file or dir @Test public void givenExistentPath_whenConfirmsFileExists_thenCorrect() { - Path p = Paths.get(HOME); + Path p = Paths.get(TEMP_DIR); assertTrue(Files.exists(p)); } @Test public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() { - Path p = Paths.get(HOME + "/inexistent_file.txt"); + Path p = Paths.get(TEMP_DIR + "/inexistent_file.txt"); assertTrue(Files.notExists(p)); } @Test public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() { - Path p = Paths.get(HOME); + Path p = Paths.get(TEMP_DIR); assertFalse(Files.isRegularFile(p)); } @Test public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() { - Path p = Paths.get(HOME); + Path p = Paths.get(TEMP_DIR); assertTrue(Files.isReadable(p)); } @Test public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() { - Path p = Paths.get(HOME); + Path p = Paths.get(System.getProperty("user.home")); assertTrue(Files.isWritable(p)); } @Test public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() { - Path p = Paths.get(HOME); + Path p = Paths.get(System.getProperty("user.home")); assertTrue(Files.isExecutable(p)); } @Test public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException { - Path p1 = Paths.get(HOME); - Path p2 = Paths.get(HOME); + Path p1 = Paths.get(TEMP_DIR); + Path p2 = Paths.get(TEMP_DIR); assertTrue(Files.isSameFile(p1, p2)); } @@ -67,7 +75,7 @@ public class FileTest { @Test public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException { String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt"; - Path p = Paths.get(HOME + "/" + fileName); + Path p = Paths.get(TEMP_DIR + "/" + fileName); assertFalse(Files.exists(p)); Files.createFile(p); assertTrue(Files.exists(p)); @@ -77,7 +85,7 @@ public class FileTest { @Test public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException { String dirName = "myDir_" + UUID.randomUUID().toString(); - Path p = Paths.get(HOME + "/" + dirName); + Path p = Paths.get(TEMP_DIR + "/" + dirName); assertFalse(Files.exists(p)); Files.createDirectory(p); assertTrue(Files.exists(p)); @@ -89,7 +97,7 @@ public class FileTest { @Test(expected = NoSuchFileException.class) public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException { String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir"; - Path p = Paths.get(HOME + "/" + dirName); + Path p = Paths.get(TEMP_DIR + "/" + dirName); assertFalse(Files.exists(p)); Files.createDirectory(p); @@ -97,7 +105,7 @@ public class FileTest { @Test public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException { - Path dir = Paths.get(HOME + "/myDir_" + UUID.randomUUID().toString()); + Path dir = Paths.get(TEMP_DIR + "/myDir_" + UUID.randomUUID().toString()); Path subdir = dir.resolve("subdir"); assertFalse(Files.exists(dir)); assertFalse(Files.exists(subdir)); @@ -110,7 +118,7 @@ public class FileTest { public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException { String prefix = "log_"; String suffix = ".txt"; - Path p = Paths.get(HOME + "/"); + Path p = Paths.get(TEMP_DIR + "/"); p = Files.createTempFile(p, prefix, suffix); // like log_8821081429012075286.txt assertTrue(Files.exists(p)); @@ -119,7 +127,7 @@ public class FileTest { @Test public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException { - Path p = Paths.get(HOME + "/"); + Path p = Paths.get(TEMP_DIR + "/"); p = Files.createTempFile(p, null, null); // like 8600179353689423985.tmp assertTrue(Files.exists(p)); @@ -136,7 +144,7 @@ public class FileTest { // delete file @Test public void givenPath_whenDeletes_thenCorrect() throws IOException { - Path p = Paths.get(HOME + "/fileToDelete.txt"); + Path p = Paths.get(TEMP_DIR + "/fileToDelete.txt"); assertFalse(Files.exists(p)); Files.createFile(p); assertTrue(Files.exists(p)); @@ -147,7 +155,7 @@ public class FileTest { @Test(expected = DirectoryNotEmptyException.class) public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException { - Path dir = Paths.get(HOME + "/emptyDir" + UUID.randomUUID().toString()); + Path dir = Paths.get(TEMP_DIR + "/emptyDir" + UUID.randomUUID().toString()); Files.createDirectory(dir); assertTrue(Files.exists(dir)); Path file = dir.resolve("file.txt"); @@ -160,7 +168,7 @@ public class FileTest { @Test(expected = NoSuchFileException.class) public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException { - Path p = Paths.get(HOME + "/inexistentFile.txt"); + Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt"); assertFalse(Files.exists(p)); Files.delete(p); @@ -168,7 +176,7 @@ public class FileTest { @Test public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException { - Path p = Paths.get(HOME + "/inexistentFile.txt"); + Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt"); assertFalse(Files.exists(p)); Files.deleteIfExists(p); @@ -177,8 +185,8 @@ public class FileTest { // copy file @Test public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException { - Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString()); - Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString()); + Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString()); + Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString()); Files.createDirectory(dir1); Files.createDirectory(dir2); Path file1 = dir1.resolve("filetocopy.txt"); @@ -193,8 +201,8 @@ public class FileTest { @Test(expected = FileAlreadyExistsException.class) public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException { - Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString()); - Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString()); + Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString()); + Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString()); Files.createDirectory(dir1); Files.createDirectory(dir2); Path file1 = dir1.resolve("filetocopy.txt"); @@ -210,8 +218,8 @@ public class FileTest { // moving files @Test public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException { - Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString()); - Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString()); + Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString()); + Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString()); Files.createDirectory(dir1); Files.createDirectory(dir2); Path file1 = dir1.resolve("filetocopy.txt"); @@ -227,8 +235,8 @@ public class FileTest { @Test(expected = FileAlreadyExistsException.class) public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException { - Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString()); - Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString()); + Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString()); + Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString()); Files.createDirectory(dir1); Files.createDirectory(dir2); Path file1 = dir1.resolve("filetocopy.txt"); From 9bf925cfdf9e35537bdfad13171364cd6b1bee99 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 20 Nov 2016 12:09:40 +0200 Subject: [PATCH 25/47] cleanup work --- spring-core/pom.xml | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 798a717d01..84a492bbe4 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -4,14 +4,11 @@ 4.0.0 com.baeldung - dependency-injection + spring-core 0.0.1-SNAPSHOT war - dependency-injection - Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely - Resource, Inject, and Autowired - + spring-core From a7e2e2d6b2d23c17b3635db9c923ebf5d9b47d75 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 20 Nov 2016 17:39:28 +0200 Subject: [PATCH 26/47] Fix JavaFileUnitTest --- .../baeldung/java/io/JavaFileUnitTest.java | 73 +++++++++++-------- 1 file changed, 44 insertions(+), 29 deletions(-) diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java index 4b56a97325..d4b63beaa4 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java @@ -1,7 +1,9 @@ package org.baeldung.java.io; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertTrue; +import org.apache.commons.io.FileUtils; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; import java.io.File; import java.io.IOException; @@ -9,17 +11,29 @@ import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.UUID; -import org.apache.commons.io.FileUtils; -import org.junit.Test; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertTrue; public class JavaFileUnitTest { - // create a file + private static final String TEMP_DIR = "src/test/resources/temp" + UUID.randomUUID().toString(); + + + @BeforeClass + public static void setup() throws IOException { + Files.createDirectory(Paths.get(TEMP_DIR)); + } + + @AfterClass + public static void cleanup() throws IOException { + FileUtils.deleteDirectory(new File(TEMP_DIR)); + } @Test public final void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException { - final File newFile = new File("src/test/resources/newFile_jdk6.txt"); + final File newFile = new File(TEMP_DIR + "/newFile_jdk6.txt"); final boolean success = newFile.createNewFile(); assertTrue(success); @@ -27,48 +41,48 @@ public class JavaFileUnitTest { @Test public final void givenUsingJDK7nio2_whenCreatingFile_thenCorrect() throws IOException { - final Path newFilePath = Paths.get("src/test/resources/newFile_jdk7.txt"); + final Path newFilePath = Paths.get(TEMP_DIR + "/newFile_jdk7.txt"); Files.createFile(newFilePath); } @Test public final void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException { - FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt")); + FileUtils.touch(new File(TEMP_DIR + "/newFile_commonsio.txt")); } @Test public final void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException { - com.google.common.io.Files.touch(new File("src/test/resources/newFile_guava.txt")); + com.google.common.io.Files.touch(new File(TEMP_DIR + "/newFile_guava.txt")); } // move a file @Test public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException { - final File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt"); + final File fileToMove = new File(TEMP_DIR + "/toMoveFile_jdk6.txt"); fileToMove.createNewFile();// .exists(); - final File destDir = new File("src/test/resources/"); + final File destDir = new File(TEMP_DIR + "/"); destDir.mkdir(); - final boolean isMoved = fileToMove.renameTo(new File("src/test/resources/movedFile_jdk6.txt")); + final boolean isMoved = fileToMove.renameTo(new File(TEMP_DIR + "/movedFile_jdk6.txt")); if (!isMoved) { - throw new FileSystemException("src/test/resources/movedFile_jdk6.txt"); + throw new FileSystemException(TEMP_DIR + "/movedFile_jdk6.txt"); } } @Test public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException { - final Path fileToMovePath = Files.createFile(Paths.get("src/test/resources/" + randomAlphabetic(5) + ".txt")); - final Path targetPath = Paths.get("src/main/resources/"); + final Path fileToMovePath = Files.createFile(Paths.get(TEMP_DIR + "/" + randomAlphabetic(5) + ".txt")); + final Path targetPath = Paths.get(TEMP_DIR + "/"); Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName())); } @Test public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException { - final File fileToMove = new File("src/test/resources/fileToMove.txt"); + final File fileToMove = new File(TEMP_DIR + "/fileToMove.txt"); fileToMove.createNewFile(); - final File destDir = new File("src/main/resources/"); + final File destDir = new File(TEMP_DIR + "/temp"); final File targetFile = new File(destDir, fileToMove.getName()); com.google.common.io.Files.createParentDirs(targetFile); com.google.common.io.Files.move(fileToMove, targetFile); @@ -76,23 +90,24 @@ public class JavaFileUnitTest { @Test public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException { - FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt")); - FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/test/resources/fileMoved_apache2.txt")); + FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt")); + FileUtils.moveFile(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/fileMoved_apache2.txt")); } @Test public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException { - FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt")); - FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/main/resources/"), true); + FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt")); + Files.createDirectory(Paths.get(TEMP_DIR + "/temp")); + FileUtils.moveFileToDirectory(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/temp"), true); } // delete a file @Test public final void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException { - new File("src/test/resources/fileToDelete_jdk6.txt").createNewFile(); + new File(TEMP_DIR + "/fileToDelete_jdk6.txt").createNewFile(); - final File fileToDelete = new File("src/test/resources/fileToDelete_jdk6.txt"); + final File fileToDelete = new File(TEMP_DIR + "/fileToDelete_jdk6.txt"); final boolean success = fileToDelete.delete(); assertTrue(success); @@ -100,17 +115,17 @@ public class JavaFileUnitTest { @Test public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException { - Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt")); + Files.createFile(Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt")); - final Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt"); + final Path fileToDeletePath = Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt"); Files.delete(fileToDeletePath); } @Test public final void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException { - FileUtils.touch(new File("src/test/resources/fileToDelete_commonsIo.txt")); + FileUtils.touch(new File(TEMP_DIR + "/fileToDelete_commonsIo.txt")); - final File fileToDelete = FileUtils.getFile("src/test/resources/fileToDelete_commonsIo.txt"); + final File fileToDelete = FileUtils.getFile(TEMP_DIR + "/fileToDelete_commonsIo.txt"); final boolean success = FileUtils.deleteQuietly(fileToDelete); assertTrue(success); @@ -118,9 +133,9 @@ public class JavaFileUnitTest { @Test public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException { - FileUtils.touch(new File("src/test/resources/fileToDelete.txt")); + FileUtils.touch(new File(TEMP_DIR + "/fileToDelete.txt")); - FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt")); + FileUtils.forceDelete(FileUtils.getFile(TEMP_DIR + "/fileToDelete.txt")); } } From 73bbab4ae64efb55d1ece603e6b576e031ba6607 Mon Sep 17 00:00:00 2001 From: Marek Lewandowski Date: Sun, 20 Nov 2016 19:01:42 +0100 Subject: [PATCH 27/47] Update README.md --- spring-core/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-core/README.md b/spring-core/README.md index 5554412c31..53842ecb1a 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Wiring in Spring: @Autowired, @Resource and @Inject](http://www.baeldung.com/spring-annotations-resource-inject-autowire) +- [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory) From 68356256026542836b3501b4dea936ad973fe428 Mon Sep 17 00:00:00 2001 From: Yasser Afifi Date: Sun, 20 Nov 2016 20:20:52 +0000 Subject: [PATCH 28/47] added generics example method and tests --- .../java/com/baeldung/generics/Generics.java | 24 ++++++++++ .../com/baeldung/generics/GenericsTest.java | 46 +++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/generics/Generics.java create mode 100644 core-java/src/test/java/com/baeldung/generics/GenericsTest.java diff --git a/core-java/src/main/java/com/baeldung/generics/Generics.java b/core-java/src/main/java/com/baeldung/generics/Generics.java new file mode 100644 index 0000000000..ce1325687f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/generics/Generics.java @@ -0,0 +1,24 @@ +import java.util.ArrayList; +import java.util.List; + +public class Generics { + + // definition of a generic method + public static List fromArrayToList(T[] a) { + List list = new ArrayList<>(); + for (T t : a) { + list.add(t); + } + return list; + } + + // example of a generic method that has Number as an upper bound for T + public static List fromArrayToListWithUpperBound(T[] a) { + List list = new ArrayList<>(); + for (T t : a) { + list.add(t); + } + return list; + } + +} diff --git a/core-java/src/test/java/com/baeldung/generics/GenericsTest.java b/core-java/src/test/java/com/baeldung/generics/GenericsTest.java new file mode 100644 index 0000000000..7778f8ea81 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/generics/GenericsTest.java @@ -0,0 +1,46 @@ +import java.util.Iterator; +import java.util.List; + +import org.junit.Test; + +public class GenericsTest { + + // testing the generic method with Integer + @Test + public void fromArrayToListIntTest() { + Integer[] intArray = { 1, 2, 3, 4, 5 }; + List list = Generics.fromArrayToList(intArray); + Iterator iterator; + iterator = list.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); + } + } + + // testing the generic method with String + @Test + public void fromArrayToListStringTest() { + String[] stringArray = { "hello1", "hello2", "hello3", "hello4", "hello5" }; + List list = Generics.fromArrayToList(stringArray); + Iterator iterator; + iterator = list.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); + } + } + + // testing the generic method with Number as upper bound with Integer + // if we test fromArrayToListWithUpperBound with any type that doesn't + // extend Number it will fail to compile + @Test + public void fromArrayToListUpperboundIntTest() { + Integer[] intArray = { 1, 2, 3, 4, 5 }; + List list = Generics.fromArrayToListWithUpperBound(intArray); + Iterator iterator; + iterator = list.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); + } + } + +} From 2186f6412677edef05a2700775b4cbbf6ed3b3b6 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sun, 20 Nov 2016 22:35:17 +0100 Subject: [PATCH 29/47] BAEL-376 - java generics code --- .../java/com/baeldung/generics/Generics.java | 31 ++++----- .../com/baeldung/generics/GenericsTest.java | 69 +++++++++---------- 2 files changed, 47 insertions(+), 53 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/generics/Generics.java b/core-java/src/main/java/com/baeldung/generics/Generics.java index ce1325687f..69c7baddd3 100644 --- a/core-java/src/main/java/com/baeldung/generics/Generics.java +++ b/core-java/src/main/java/com/baeldung/generics/Generics.java @@ -1,24 +1,23 @@ +package com.baeldung.generics; + import java.util.ArrayList; +import java.util.Arrays; import java.util.List; public class Generics { - // definition of a generic method - public static List fromArrayToList(T[] a) { - List list = new ArrayList<>(); - for (T t : a) { - list.add(t); - } - return list; - } + // definition of a generic method + public static List fromArrayToList(T[] a) { + List list = new ArrayList<>(); + Arrays.stream(a).forEach(list::add); + return list; + } - // example of a generic method that has Number as an upper bound for T - public static List fromArrayToListWithUpperBound(T[] a) { - List list = new ArrayList<>(); - for (T t : a) { - list.add(t); - } - return list; - } + // example of a generic method that has Number as an upper bound for T + public static List fromArrayToListWithUpperBound(T[] a) { + List list = new ArrayList<>(); + Arrays.stream(a).forEach(list::add); + return list; + } } diff --git a/core-java/src/test/java/com/baeldung/generics/GenericsTest.java b/core-java/src/test/java/com/baeldung/generics/GenericsTest.java index 7778f8ea81..9eb459ccb5 100644 --- a/core-java/src/test/java/com/baeldung/generics/GenericsTest.java +++ b/core-java/src/test/java/com/baeldung/generics/GenericsTest.java @@ -1,46 +1,41 @@ -import java.util.Iterator; -import java.util.List; +package com.baeldung.generics; import org.junit.Test; +import java.util.List; + +import static org.hamcrest.CoreMatchers.hasItems; +import static org.hamcrest.MatcherAssert.assertThat; + public class GenericsTest { - // testing the generic method with Integer - @Test - public void fromArrayToListIntTest() { - Integer[] intArray = { 1, 2, 3, 4, 5 }; - List list = Generics.fromArrayToList(intArray); - Iterator iterator; - iterator = list.iterator(); - while (iterator.hasNext()) { - System.out.println(iterator.next()); - } - } + // testing the generic method with Integer + @Test + public void givenArrayOfIntegers_thanListOfIntegersReturnedOK() { + Integer[] intArray = {1, 2, 3, 4, 5}; + List list = Generics.fromArrayToList(intArray); - // testing the generic method with String - @Test - public void fromArrayToListStringTest() { - String[] stringArray = { "hello1", "hello2", "hello3", "hello4", "hello5" }; - List list = Generics.fromArrayToList(stringArray); - Iterator iterator; - iterator = list.iterator(); - while (iterator.hasNext()) { - System.out.println(iterator.next()); - } - } + assertThat(list, hasItems(intArray)); + } - // testing the generic method with Number as upper bound with Integer - // if we test fromArrayToListWithUpperBound with any type that doesn't - // extend Number it will fail to compile - @Test - public void fromArrayToListUpperboundIntTest() { - Integer[] intArray = { 1, 2, 3, 4, 5 }; - List list = Generics.fromArrayToListWithUpperBound(intArray); - Iterator iterator; - iterator = list.iterator(); - while (iterator.hasNext()) { - System.out.println(iterator.next()); - } - } + // testing the generic method with String + @Test + public void givenArrayOfStrings_thanListOfStringsReturnedOK() { + String[] stringArray = {"hello1", "hello2", "hello3", "hello4", "hello5"}; + List list = Generics.fromArrayToList(stringArray); + + assertThat(list, hasItems(stringArray)); + } + + // testing the generic method with Number as upper bound with Integer + // if we test fromArrayToListWithUpperBound with any type that doesn't + // extend Number it will fail to compile + @Test + public void givenArrayOfIntegersAndNumberUpperBound_thanListOfIntegersReturnedOK() { + Integer[] intArray = {1, 2, 3, 4, 5}; + List list = Generics.fromArrayToListWithUpperBound(intArray); + + assertThat(list, hasItems(intArray)); + } } From 540075ca390a859a1f1bff4966095b3b522dd74b Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Mon, 21 Nov 2016 11:42:13 +0100 Subject: [PATCH 30/47] Add method init for common logic --- .../okhttp/OkHttpFileUploadingLiveTest.java | 26 +++++++++++-------- .../baeldung/okhttp/OkHttpGetLiveTest.java | 25 +++++++++++++----- .../baeldung/okhttp/OkHttpHeaderLiveTest.java | 13 +++++++--- .../baeldung/okhttp/OkHttpMiscLiveTest.java | 11 +++++++- .../okhttp/OkHttpPostingLiveTest.java | 17 +++++++++--- 5 files changed, 67 insertions(+), 25 deletions(-) diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java index d1cc67b99a..d7aff8207a 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java @@ -8,6 +8,7 @@ import java.io.File; import java.io.IOException; import org.baeldung.okhttp.ProgressRequestWrapper; +import org.junit.Before; import org.junit.Test; import okhttp3.Call; @@ -22,10 +23,18 @@ public class OkHttpFileUploadingLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; + OkHttpClient client; + + @Before + public void init() { + + client = new OkHttpClient(); + } + @Test public void whenUploadFile_thenCorrect() throws IOException { - OkHttpClient client = new OkHttpClient(); + client = new OkHttpClient(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -47,7 +56,7 @@ public class OkHttpFileUploadingLiveTest { @Test public void whenGetUploadFileProgress_thenCorrect() throws IOException { - OkHttpClient client = new OkHttpClient(); + client = new OkHttpClient(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -55,17 +64,12 @@ public class OkHttpFileUploadingLiveTest { RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) .build(); + ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> { - ProgressRequestWrapper.ProgressListener listener = new ProgressRequestWrapper.ProgressListener() { + float percentage = 100f * bytesWritten / contentLength; + assertFalse(Float.compare(percentage, 100) > 0); - 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") diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index 632d7577a4..19bfd6d46b 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -6,7 +6,12 @@ import static org.junit.Assert.fail; import java.io.IOException; +import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; import okhttp3.Call; import okhttp3.Callback; @@ -15,17 +20,25 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; -//@RunWith(SpringJUnit4ClassRunner.class) -//@WebAppConfiguration -//@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/api-servlet.xml") +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/api-servlet.xml") public class OkHttpGetLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; + OkHttpClient client; + + @Before + public void init() { + + client = new OkHttpClient(); + } + @Test public void whenGetRequest_thenCorrect() throws IOException { - OkHttpClient client = new OkHttpClient(); + client = new OkHttpClient(); Request request = new Request.Builder() .url(BASE_URL + "/date") @@ -40,7 +53,7 @@ public class OkHttpGetLiveTest { @Test public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException { - OkHttpClient client = new OkHttpClient(); + client = new OkHttpClient(); HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); urlBuilder.addQueryParameter("id", "1"); @@ -60,7 +73,7 @@ public class OkHttpGetLiveTest { @Test public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException { - OkHttpClient client = new OkHttpClient(); + client = new OkHttpClient(); Request request = new Request.Builder() .url(BASE_URL + "/date") diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java index 8eddfcb135..1b73565aa4 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java @@ -2,6 +2,7 @@ package org.baeldung.okhttp; import java.io.IOException; +import org.junit.Before; import org.junit.Test; import okhttp3.Call; @@ -13,10 +14,18 @@ public class OkHttpHeaderLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; + OkHttpClient client; + + @Before + public void init() { + + client = new OkHttpClient(); + } + @Test public void whenSetHeader_thenCorrect() throws IOException { - OkHttpClient client = new OkHttpClient(); + client = new OkHttpClient(); Request request = new Request.Builder() .url(SAMPLE_URL) @@ -43,6 +52,4 @@ public class OkHttpHeaderLiveTest { Response response = call.execute(); response.close(); } - - } diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java index dcdb4e328c..39f66a8024 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -6,6 +6,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,6 +22,14 @@ public class OkHttpMiscLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class); + OkHttpClient client; + + @Before + public void init() { + + client = new OkHttpClient(); + } + @Test public void whenSetRequestTimeout_thenFail() throws IOException { @@ -42,7 +51,7 @@ public class OkHttpMiscLiveTest { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); - OkHttpClient client = new OkHttpClient(); + client = new OkHttpClient(); Request request = new Request.Builder() .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java index 18bd4cdcb3..59844d547a 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java @@ -6,6 +6,7 @@ import static org.junit.Assert.assertThat; import java.io.File; import java.io.IOException; +import org.junit.Before; import org.junit.Test; import okhttp3.Call; @@ -23,10 +24,18 @@ 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"; + OkHttpClient client; + + @Before + public void init() { + + client = new OkHttpClient(); + } + @Test public void whenSendPostRequest_thenCorrect() throws IOException { - OkHttpClient client = new OkHttpClient(); + client = new OkHttpClient(); RequestBody formBody = new FormBody.Builder() .add("username", "test") @@ -49,7 +58,7 @@ public class OkHttpPostingLiveTest { String postBody = "test post"; - OkHttpClient client = new OkHttpClient(); + client = new OkHttpClient(); Request request = new Request.Builder() .url(URL_SECURED_BY_BASIC_AUTHENTICATION) @@ -66,7 +75,7 @@ public class OkHttpPostingLiveTest { @Test public void whenPostJson_thenCorrect() throws IOException { - OkHttpClient client = new OkHttpClient(); + client = new OkHttpClient(); String json = "{\"id\":1,\"name\":\"John\"}"; @@ -86,7 +95,7 @@ public class OkHttpPostingLiveTest { @Test public void whenSendMultipartRequest_thenCorrect() throws IOException { - OkHttpClient client = new OkHttpClient(); + client = new OkHttpClient(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) From e66e9d445f301cdccd370e721eea1e9ab92cc131 Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Mon, 21 Nov 2016 11:43:32 +0100 Subject: [PATCH 31/47] Code improvement --- .../src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index 19bfd6d46b..7a5f598569 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -20,9 +20,6 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/api-servlet.xml") public class OkHttpGetLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; From 652dcd2804f215d5a2fb175d07a8f0b3dc61c603 Mon Sep 17 00:00:00 2001 From: michal_aibin Date: Mon, 21 Nov 2016 12:39:44 +0100 Subject: [PATCH 32/47] URIComponentsBuilder --- .../uribuilder/SpringUriBuilderTest.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderTest.java diff --git a/spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderTest.java b/spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderTest.java new file mode 100644 index 0000000000..4b6a9ba312 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderTest.java @@ -0,0 +1,53 @@ +package org.baeldung.uribuilder; + +import static org.junit.Assert.assertEquals; + +import java.util.Collections; + +import org.junit.Test; +import org.springframework.web.util.UriComponents; +import org.springframework.web.util.UriComponentsBuilder; + +public class SpringUriBuilderTest { + + @Test + public void constructUri() { + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com") + .path("/junit-5").build(); + + assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString()); + } + + @Test + public void constructUriEncoded() { + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com") + .path("/junit 5").build().encode(); + + assertEquals("http://www.baeldung.com/junit%205", uriComponents.toUriString()); + } + + @Test + public void constructUriFromTemplate() { + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com") + .path("/{article-name}").buildAndExpand("junit-5"); + + assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString()); + } + + @Test + public void constructUriWithQueryParameter() { + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.google.com") + .path("/").query("q={keyword}").buildAndExpand("baeldung"); + + assertEquals("http://www.google.com/?q=baeldung", uriComponents.toUriString()); + } + + @Test + public void expandWithRegexVar() { + String template = "/myurl/{name:[a-z]{1,5}}/show"; + UriComponents uriComponents = UriComponentsBuilder.fromUriString(template).build(); + uriComponents = uriComponents.expand(Collections.singletonMap("name", "test")); + + assertEquals("/myurl/test/show", uriComponents.getPath()); + } +} From 4d4afa6ca454b0172260e8cc210e7215442746c3 Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Mon, 21 Nov 2016 13:53:37 +0100 Subject: [PATCH 33/47] Code improvement --- .../src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index 7a5f598569..f077efce0d 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -8,10 +8,6 @@ import java.io.IOException; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; import okhttp3.Call; import okhttp3.Callback; From c1f94aab9265271376ff299f61597496e083ea45 Mon Sep 17 00:00:00 2001 From: James Kerak Date: Mon, 21 Nov 2016 09:12:30 -0500 Subject: [PATCH 34/47] fixing incorrect merge --- .../okhttp/OkHttpFileUploadingLiveTest.java | 5 ----- .../org/baeldung/okhttp/OkHttpGetLiveTest.java | 10 +--------- .../org/baeldung/okhttp/OkHttpHeaderLiveTest.java | 7 ++----- .../org/baeldung/okhttp/OkHttpMiscLiveTest.java | 14 +++++--------- .../org/baeldung/okhttp/OkHttpPostingLiveTest.java | 12 ------------ 5 files changed, 8 insertions(+), 40 deletions(-) diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java index 2f75560e03..d5765b9756 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java @@ -27,15 +27,12 @@ public class OkHttpFileUploadingLiveTest { @Before public void init() { - client = new OkHttpClient(); } @Test public void whenUploadFile_thenCorrect() throws IOException { - client = new OkHttpClient(); - RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", "file.txt", @@ -56,8 +53,6 @@ public class OkHttpFileUploadingLiveTest { @Test public void whenGetUploadFileProgress_thenCorrect() throws IOException { - client = new OkHttpClient(); - RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", "file.txt", diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index f1dce530cd..08d41fe7ab 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -13,6 +13,7 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; + public class OkHttpGetLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; @@ -27,9 +28,6 @@ public class OkHttpGetLiveTest { @Test public void whenGetRequest_thenCorrect() throws IOException { - - client = new OkHttpClient(); - Request request = new Request.Builder() .url(BASE_URL + "/date") .build(); @@ -42,9 +40,6 @@ public class OkHttpGetLiveTest { @Test public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException { - - client = new OkHttpClient(); - HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); urlBuilder.addQueryParameter("id", "1"); @@ -62,9 +57,6 @@ public class OkHttpGetLiveTest { @Test public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException { - - client = new OkHttpClient(); - Request request = new Request.Builder() .url(BASE_URL + "/date") .build(); diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java index 1b73565aa4..8888f7d4a7 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java @@ -24,9 +24,6 @@ public class OkHttpHeaderLiveTest { @Test public void whenSetHeader_thenCorrect() throws IOException { - - client = new OkHttpClient(); - Request request = new Request.Builder() .url(SAMPLE_URL) .addHeader("Content-Type", "application/json") @@ -40,7 +37,7 @@ public class OkHttpHeaderLiveTest { @Test public void whenSetDefaultHeader_thenCorrect() throws IOException { - OkHttpClient client = new OkHttpClient.Builder() + OkHttpClient clientWithInterceptor = new OkHttpClient.Builder() .addInterceptor(new DefaultContentTypeInterceptor("application/json")) .build(); @@ -48,7 +45,7 @@ public class OkHttpHeaderLiveTest { .url(SAMPLE_URL) .build(); - Call call = client.newCall(request); + Call call = clientWithInterceptor.newCall(request); Response response = call.execute(); response.close(); } diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java index 3411f29c40..34e1554908 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -34,8 +34,7 @@ public class OkHttpMiscLiveTest { @Test public void whenSetRequestTimeout_thenFail() throws IOException { - - OkHttpClient client = new OkHttpClient.Builder() + OkHttpClient clientWithTimeout = new OkHttpClient.Builder() .readTimeout(1, TimeUnit.SECONDS) .build(); @@ -43,18 +42,15 @@ public class OkHttpMiscLiveTest { .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. .build(); - Call call = client.newCall(request); + Call call = clientWithTimeout.newCall(request); Response response = call.execute(); response.close(); } @Test(expected = IOException.class) public void whenCancelRequest_thenCorrect() throws IOException { - ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); - client = new OkHttpClient(); - Request request = new Request.Builder() .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. .build(); @@ -85,7 +81,7 @@ public class OkHttpMiscLiveTest { File cacheDirectory = new File("src/test/resources/cache"); Cache cache = new Cache(cacheDirectory, cacheSize); - OkHttpClient client = new OkHttpClient.Builder() + OkHttpClient clientCached = new OkHttpClient.Builder() .cache(cache) .build(); @@ -93,10 +89,10 @@ public class OkHttpMiscLiveTest { .url("http://publicobject.com/helloworld.txt") .build(); - Response response1 = client.newCall(request).execute(); + Response response1 = clientCached.newCall(request).execute(); logResponse(response1); - Response response2 = client.newCall(request).execute(); + Response response2 = clientCached.newCall(request).execute(); logResponse(response2); } diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java index 59844d547a..dce3bb174f 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java @@ -34,9 +34,6 @@ public class OkHttpPostingLiveTest { @Test public void whenSendPostRequest_thenCorrect() throws IOException { - - client = new OkHttpClient(); - RequestBody formBody = new FormBody.Builder() .add("username", "test") .add("password", "test") @@ -55,11 +52,8 @@ public class OkHttpPostingLiveTest { @Test public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException { - String postBody = "test post"; - client = new OkHttpClient(); - Request request = new Request.Builder() .url(URL_SECURED_BY_BASIC_AUTHENTICATION) .addHeader("Authorization", Credentials.basic("test", "test")) @@ -74,9 +68,6 @@ public class OkHttpPostingLiveTest { @Test public void whenPostJson_thenCorrect() throws IOException { - - client = new OkHttpClient(); - String json = "{\"id\":1,\"name\":\"John\"}"; RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); @@ -94,9 +85,6 @@ public class OkHttpPostingLiveTest { @Test public void whenSendMultipartRequest_thenCorrect() throws IOException { - - client = new OkHttpClient(); - RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("username", "test") From a32db2581fb69e44fb117349099134497ec43799 Mon Sep 17 00:00:00 2001 From: Danil Kornishev Date: Mon, 21 Nov 2016 11:36:05 -0500 Subject: [PATCH 35/47] Added example of spring constructor based dependency injection --- spring-constructor-di/pom.xml | 37 +++++++++++++++++++ .../main/java/com/baeldung/spring/Config.java | 24 ++++++++++++ .../com/baeldung/spring/SpringRunner.java | 30 +++++++++++++++ .../java/com/baeldung/spring/domain/Car.java | 24 ++++++++++++ .../com/baeldung/spring/domain/Engine.java | 16 ++++++++ .../baeldung/spring/domain/Transmission.java | 14 +++++++ .../src/main/resources/baeldung.xml | 20 ++++++++++ 7 files changed, 165 insertions(+) create mode 100644 spring-constructor-di/pom.xml create mode 100644 spring-constructor-di/src/main/java/com/baeldung/spring/Config.java create mode 100644 spring-constructor-di/src/main/java/com/baeldung/spring/SpringRunner.java create mode 100644 spring-constructor-di/src/main/java/com/baeldung/spring/domain/Car.java create mode 100644 spring-constructor-di/src/main/java/com/baeldung/spring/domain/Engine.java create mode 100644 spring-constructor-di/src/main/java/com/baeldung/spring/domain/Transmission.java create mode 100644 spring-constructor-di/src/main/resources/baeldung.xml diff --git a/spring-constructor-di/pom.xml b/spring-constructor-di/pom.xml new file mode 100644 index 0000000000..835a1ba4c8 --- /dev/null +++ b/spring-constructor-di/pom.xml @@ -0,0 +1,37 @@ + + + 4.0.0 + + baeldung + baeldung + 1.0-SNAPSHOT + + + + org.springframework + spring-context + 4.2.6.RELEASE + + + javax.inject + javax.inject + 1 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + \ No newline at end of file diff --git a/spring-constructor-di/src/main/java/com/baeldung/spring/Config.java b/spring-constructor-di/src/main/java/com/baeldung/spring/Config.java new file mode 100644 index 0000000000..e7f33c2ad4 --- /dev/null +++ b/spring-constructor-di/src/main/java/com/baeldung/spring/Config.java @@ -0,0 +1,24 @@ +package com.baeldung.spring; + +import com.baeldung.spring.domain.Car; +import com.baeldung.spring.domain.Engine; +import com.baeldung.spring.domain.Transmission; +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; + +@Configuration +@ComponentScan("com.baeldung.spring") +public class Config { + + @Bean + public Engine engine() { + return new Engine("v8", 5); + } + + @Bean + public Transmission transmission() { + return new Transmission("sliding"); + } +} diff --git a/spring-constructor-di/src/main/java/com/baeldung/spring/SpringRunner.java b/spring-constructor-di/src/main/java/com/baeldung/spring/SpringRunner.java new file mode 100644 index 0000000000..e8a74b9482 --- /dev/null +++ b/spring-constructor-di/src/main/java/com/baeldung/spring/SpringRunner.java @@ -0,0 +1,30 @@ +package com.baeldung.spring; + +import com.baeldung.spring.domain.Car; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class SpringRunner { + public static void main(String[] args) { + Car toyota = getCarFromXml(); + + System.out.println(toyota); + + toyota = getCarFromJavaConfig(); + + System.out.println(toyota); + } + + private static Car getCarFromJavaConfig() { + ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); + + return context.getBean(Car.class); + } + + private static Car getCarFromXml() { + ApplicationContext context = new ClassPathXmlApplicationContext("baeldung.xml"); + + return context.getBean(Car.class); + } +} diff --git a/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Car.java b/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Car.java new file mode 100644 index 0000000000..73bcc430c1 --- /dev/null +++ b/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Car.java @@ -0,0 +1,24 @@ +package com.baeldung.spring.domain; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; +import javax.inject.Named; + +@Component +public class Car { + private Engine engine; + private Transmission transmission; + + @Autowired + public Car(Engine engine, Transmission transmission) { + this.engine = engine; + this.transmission = transmission; + } + + @Override + public String toString() { + return String.format("Engine: %s Transmission: %s", engine, transmission); + } +} diff --git a/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Engine.java b/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Engine.java new file mode 100644 index 0000000000..1679692d6d --- /dev/null +++ b/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Engine.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.domain; + +public class Engine { + private String type; + private int volume; + + public Engine(String type, int volume) { + this.type = type; + this.volume = volume; + } + + @Override + public String toString() { + return String.format("%s %d", type, volume); + } +} diff --git a/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Transmission.java b/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Transmission.java new file mode 100644 index 0000000000..47df118020 --- /dev/null +++ b/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Transmission.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.domain; + +public class Transmission { + private String type; + + public Transmission(String type) { + this.type = type; + } + + @Override + public String toString() { + return String.format("%s", type); + } +} diff --git a/spring-constructor-di/src/main/resources/baeldung.xml b/spring-constructor-di/src/main/resources/baeldung.xml new file mode 100644 index 0000000000..7980460dcc --- /dev/null +++ b/spring-constructor-di/src/main/resources/baeldung.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file From 2375eda92c1c218e1dc10a45e6cd3873e992b010 Mon Sep 17 00:00:00 2001 From: Danil Kornishev Date: Mon, 21 Nov 2016 11:43:03 -0500 Subject: [PATCH 36/47] Cleanup --- spring-constructor-di/pom.xml | 55 +++++++++---------- .../main/java/com/baeldung/spring/Config.java | 7 +-- .../java/com/baeldung/spring/domain/Car.java | 3 - 3 files changed, 28 insertions(+), 37 deletions(-) diff --git a/spring-constructor-di/pom.xml b/spring-constructor-di/pom.xml index 835a1ba4c8..27418c9d0c 100644 --- a/spring-constructor-di/pom.xml +++ b/spring-constructor-di/pom.xml @@ -1,37 +1,32 @@ - 4.0.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - baeldung - baeldung - 1.0-SNAPSHOT + baeldung + baeldung + 1.0-SNAPSHOT - - - org.springframework - spring-context - 4.2.6.RELEASE - - - javax.inject - javax.inject - 1 - - + + + org.springframework + spring-context + 4.2.6.RELEASE + + - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + \ No newline at end of file diff --git a/spring-constructor-di/src/main/java/com/baeldung/spring/Config.java b/spring-constructor-di/src/main/java/com/baeldung/spring/Config.java index e7f33c2ad4..661e2cee17 100644 --- a/spring-constructor-di/src/main/java/com/baeldung/spring/Config.java +++ b/spring-constructor-di/src/main/java/com/baeldung/spring/Config.java @@ -1,13 +1,12 @@ package com.baeldung.spring; -import com.baeldung.spring.domain.Car; -import com.baeldung.spring.domain.Engine; -import com.baeldung.spring.domain.Transmission; -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 com.baeldung.spring.domain.Engine; +import com.baeldung.spring.domain.Transmission; + @Configuration @ComponentScan("com.baeldung.spring") public class Config { diff --git a/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Car.java b/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Car.java index 73bcc430c1..96199fcee0 100644 --- a/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Car.java +++ b/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Car.java @@ -3,9 +3,6 @@ package com.baeldung.spring.domain; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import javax.inject.Inject; -import javax.inject.Named; - @Component public class Car { private Engine engine; From 126b7f1fe530121645f55e7060ec19570ee4c822 Mon Sep 17 00:00:00 2001 From: Danil Kornishev Date: Mon, 21 Nov 2016 11:45:11 -0500 Subject: [PATCH 37/47] Cleanup --- spring-constructor-di/src/main/resources/baeldung.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-constructor-di/src/main/resources/baeldung.xml b/spring-constructor-di/src/main/resources/baeldung.xml index 7980460dcc..b3aeef5ee9 100644 --- a/spring-constructor-di/src/main/resources/baeldung.xml +++ b/spring-constructor-di/src/main/resources/baeldung.xml @@ -17,4 +17,4 @@ - \ No newline at end of file + From b8ade6f6da06b4d24d9d1b18bc486188e5795649 Mon Sep 17 00:00:00 2001 From: Marek Lewandowski Date: Mon, 21 Nov 2016 22:01:05 +0100 Subject: [PATCH 38/47] BAEL-453 some improvments, formatting etc. --- .../java/com/baeldung/factorybean/FactoryBeanAppConfig.java | 1 + .../com/baeldung/factorybean/InitializationToolFactory.java | 1 + .../java/com/baeldung/factorybean/NonSingleToolFactory.java | 1 + .../com/baeldung/factorybean/PostConstructToolFactory.java | 1 + .../java/com/baeldung/factorybean/SingleToolFactory.java | 1 + .../src/main/java/com/baeldung/factorybean/Tool.java | 4 +--- .../src/main/java/com/baeldung/factorybean/ToolFactory.java | 1 + .../src/main/java/com/baeldung/factorybean/Worker.java | 4 ++-- .../src/main/resources/factorybean-abstract-spring-ctx.xml | 4 ++-- .../src/main/resources/factorybean-init-spring-ctx.xml | 4 ++-- .../main/resources/factorybean-postconstruct-spring-ctx.xml | 6 +++--- spring-core/src/main/resources/factorybean-spring-ctx.xml | 4 ++-- .../com/baeldung/factorybean/AbstractFactoryBeanTest.java | 1 + .../com/baeldung/factorybean/FactoryBeanInitializeTest.java | 1 + .../test/java/com/baeldung/factorybean/FactoryBeanTest.java | 1 + 15 files changed, 21 insertions(+), 14 deletions(-) diff --git a/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java b/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java index ab36df27cb..40e181b7a7 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java @@ -5,6 +5,7 @@ import org.springframework.context.annotation.Configuration; @Configuration public class FactoryBeanAppConfig { + @Bean public ToolFactory tool() { ToolFactory factory = new ToolFactory(); diff --git a/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java index 6d2fd2564e..15e2b01f49 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java @@ -7,6 +7,7 @@ import org.springframework.beans.factory.InitializingBean; import org.springframework.util.StringUtils; public class InitializationToolFactory implements FactoryBean, InitializingBean { + private int factoryId; private int toolId; private String toolName; diff --git a/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java index c818b775eb..158318649c 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java @@ -3,6 +3,7 @@ package com.baeldung.factorybean; import org.springframework.beans.factory.config.AbstractFactoryBean; public class NonSingleToolFactory extends AbstractFactoryBean { + private int factoryId; private int toolId; private String toolName; diff --git a/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java index 47db05d271..696545a70a 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java @@ -8,6 +8,7 @@ import org.springframework.beans.factory.FactoryBean; import org.springframework.util.StringUtils; public class PostConstructToolFactory implements FactoryBean { + private int factoryId; private int toolId; private String toolName; diff --git a/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java index bc0c2d79c0..37fd978a3c 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java @@ -4,6 +4,7 @@ import org.springframework.beans.factory.config.AbstractFactoryBean; //no need to set singleton property because default value is true public class SingleToolFactory extends AbstractFactoryBean { + private int factoryId; private int toolId; private String toolName; diff --git a/spring-core/src/main/java/com/baeldung/factorybean/Tool.java b/spring-core/src/main/java/com/baeldung/factorybean/Tool.java index a7f7f7681e..2a69cbaf2a 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/Tool.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/Tool.java @@ -1,13 +1,11 @@ package com.baeldung.factorybean; public class Tool { + private int id; private String name; private double price; - public Tool() { - } - public Tool(int id, String name, double price) { this.id = id; this.name = name; diff --git a/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java index ca8f82eadb..5e6385c679 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java @@ -3,6 +3,7 @@ package com.baeldung.factorybean; import org.springframework.beans.factory.FactoryBean; public class ToolFactory implements FactoryBean { + private int factoryId; private int toolId; private String toolName; diff --git a/spring-core/src/main/java/com/baeldung/factorybean/Worker.java b/spring-core/src/main/java/com/baeldung/factorybean/Worker.java index 9a35c0656b..0d1dc5d7d6 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/Worker.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/Worker.java @@ -1,11 +1,11 @@ package com.baeldung.factorybean; public class Worker { + private String number; private Tool tool; - public Worker() { - } + public Worker() {} public Worker(String number, Tool tool) { this.number = number; diff --git a/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml b/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml index 6bce114d9c..33b3051cae 100644 --- a/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml +++ b/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml @@ -1,7 +1,7 @@ + xmlns="http://www.springframework.org/schema/beans" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> diff --git a/spring-core/src/main/resources/factorybean-init-spring-ctx.xml b/spring-core/src/main/resources/factorybean-init-spring-ctx.xml index 47722b6d3d..1ff492e5df 100644 --- a/spring-core/src/main/resources/factorybean-init-spring-ctx.xml +++ b/spring-core/src/main/resources/factorybean-init-spring-ctx.xml @@ -1,7 +1,7 @@ + xmlns="http://www.springframework.org/schema/beans" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> diff --git a/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml b/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml index 94a4f407a8..f34325160f 100644 --- a/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml +++ b/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml @@ -1,8 +1,8 @@ + xmlns:context="http://www.springframework.org/schema/context" + xmlns="http://www.springframework.org/schema/beans" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> diff --git a/spring-core/src/main/resources/factorybean-spring-ctx.xml b/spring-core/src/main/resources/factorybean-spring-ctx.xml index ab0c646bb0..2987b67d94 100644 --- a/spring-core/src/main/resources/factorybean-spring-ctx.xml +++ b/spring-core/src/main/resources/factorybean-spring-ctx.xml @@ -1,7 +1,7 @@ + xmlns="http://www.springframework.org/schema/beans" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> diff --git a/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java b/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java index 790107f114..a7ba6d9a68 100644 --- a/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java +++ b/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java @@ -9,6 +9,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AbstractFactoryBeanTest { + @Test public void testSingleToolFactory() { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-abstract-spring-ctx.xml"); diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java index 673bab6f63..87947b148a 100644 --- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java @@ -5,6 +5,7 @@ import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.support.ClassPathXmlApplicationContext; public class FactoryBeanInitializeTest { + @Test(expected = BeanCreationException.class) public void testInitializationToolFactory() { new ClassPathXmlApplicationContext("classpath:factorybean-init-spring-ctx.xml"); diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java index d06448b63c..f35503794a 100644 --- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java @@ -9,6 +9,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.support.ClassPathXmlApplicationContext; public class FactoryBeanTest { + @Test public void testConstructWorkerByXml() { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-spring-ctx.xml"); From 1ba76d72f08e4e63cc04f3df8b6ca3da8b22a010 Mon Sep 17 00:00:00 2001 From: Parth Joshi Date: Wed, 23 Nov 2016 09:41:02 +0530 Subject: [PATCH 39/47] Changes for mentioning db path... (#857) --- .../spring/service/RawDBDemoGeoIPLocationService.java | 2 +- spring-mvc-xml/src/main/webapp/GeoIpTest.jsp | 4 ++-- .../test/java/com/baeldung/geoip/GeoIpIntegrationTest.java | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java index 0a292ab1e9..af3ce8cfb3 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java @@ -13,7 +13,7 @@ public class RawDBDemoGeoIPLocationService{ private DatabaseReader dbReader; public RawDBDemoGeoIPLocationService() throws IOException { - File database = new File("C:\\Users\\Parth Joshi\\Desktop\\GeoLite2-City.mmdb\\GeoLite2-City.mmdb"); + File database = new File("your-path-to-db-file"); dbReader = new DatabaseReader.Builder(database).build(); } diff --git a/spring-mvc-xml/src/main/webapp/GeoIpTest.jsp b/spring-mvc-xml/src/main/webapp/GeoIpTest.jsp index 431f6162bc..c2a60d5197 100644 --- a/spring-mvc-xml/src/main/webapp/GeoIpTest.jsp +++ b/spring-mvc-xml/src/main/webapp/GeoIpTest.jsp @@ -77,8 +77,8 @@
- - \ No newline at end of file diff --git a/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java b/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java index 72d528095e..2edaa125b7 100644 --- a/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java +++ b/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java @@ -15,10 +15,10 @@ public class GeoIpIntegrationTest { @Test public void givenIP_whenFetchingCity_thenReturnsCityData() throws IOException, GeoIp2Exception { - File database = new File("C:\\Users\\Parth Joshi\\Desktop\\GeoLite2-City.mmdb\\GeoLite2-City.mmdb"); + File database = new File("your-path-to-db-file"); DatabaseReader dbReader = new DatabaseReader.Builder(database).build(); - InetAddress ipAddress = InetAddress.getByName("202.47.112.9"); + InetAddress ipAddress = InetAddress.getByName("your-public-ip"); CityResponse response = dbReader.city(ipAddress); String countryName = response.getCountry().getName(); From 61152915b76d9ec0f59380fb5fdaf97343b0bed5 Mon Sep 17 00:00:00 2001 From: Danil Kornishev Date: Wed, 23 Nov 2016 08:33:57 -0500 Subject: [PATCH 40/47] Moved sprindi examples --- spring-constructor-di/pom.xml | 32 ------------------- .../com/baeldung/constructordi}/Config.java | 8 ++--- .../baeldung/constructordi}/SpringRunner.java | 5 +-- .../baeldung/constructordi}/domain/Car.java | 2 +- .../constructordi}/domain/Engine.java | 2 +- .../constructordi}/domain/Transmission.java | 2 +- .../src/main/resources/baeldung.xml | 6 ++-- 7 files changed, 13 insertions(+), 44 deletions(-) delete mode 100644 spring-constructor-di/pom.xml rename {spring-constructor-di/src/main/java/com/baeldung/spring => spring-core/src/main/java/com/baeldung/constructordi}/Config.java (68%) rename {spring-constructor-di/src/main/java/com/baeldung/spring => spring-core/src/main/java/com/baeldung/constructordi}/SpringRunner.java (90%) rename {spring-constructor-di/src/main/java/com/baeldung/spring => spring-core/src/main/java/com/baeldung/constructordi}/domain/Car.java (92%) rename {spring-constructor-di/src/main/java/com/baeldung/spring => spring-core/src/main/java/com/baeldung/constructordi}/domain/Engine.java (86%) rename {spring-constructor-di/src/main/java/com/baeldung/spring => spring-core/src/main/java/com/baeldung/constructordi}/domain/Transmission.java (81%) rename {spring-constructor-di => spring-core}/src/main/resources/baeldung.xml (71%) diff --git a/spring-constructor-di/pom.xml b/spring-constructor-di/pom.xml deleted file mode 100644 index 27418c9d0c..0000000000 --- a/spring-constructor-di/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - 4.0.0 - - baeldung - baeldung - 1.0-SNAPSHOT - - - - org.springframework - spring-context - 4.2.6.RELEASE - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - - - \ No newline at end of file diff --git a/spring-constructor-di/src/main/java/com/baeldung/spring/Config.java b/spring-core/src/main/java/com/baeldung/constructordi/Config.java similarity index 68% rename from spring-constructor-di/src/main/java/com/baeldung/spring/Config.java rename to spring-core/src/main/java/com/baeldung/constructordi/Config.java index 661e2cee17..07568018f3 100644 --- a/spring-constructor-di/src/main/java/com/baeldung/spring/Config.java +++ b/spring-core/src/main/java/com/baeldung/constructordi/Config.java @@ -1,14 +1,14 @@ -package com.baeldung.spring; +package com.baeldung.constructordi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import com.baeldung.spring.domain.Engine; -import com.baeldung.spring.domain.Transmission; +import com.baeldung.constructordi.domain.Engine; +import com.baeldung.constructordi.domain.Transmission; @Configuration -@ComponentScan("com.baeldung.spring") +@ComponentScan("com.baeldung.constructordi") public class Config { @Bean diff --git a/spring-constructor-di/src/main/java/com/baeldung/spring/SpringRunner.java b/spring-core/src/main/java/com/baeldung/constructordi/SpringRunner.java similarity index 90% rename from spring-constructor-di/src/main/java/com/baeldung/spring/SpringRunner.java rename to spring-core/src/main/java/com/baeldung/constructordi/SpringRunner.java index e8a74b9482..623739f036 100644 --- a/spring-constructor-di/src/main/java/com/baeldung/spring/SpringRunner.java +++ b/spring-core/src/main/java/com/baeldung/constructordi/SpringRunner.java @@ -1,10 +1,11 @@ -package com.baeldung.spring; +package com.baeldung.constructordi; -import com.baeldung.spring.domain.Car; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; +import com.baeldung.constructordi.domain.Car; + public class SpringRunner { public static void main(String[] args) { Car toyota = getCarFromXml(); diff --git a/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Car.java b/spring-core/src/main/java/com/baeldung/constructordi/domain/Car.java similarity index 92% rename from spring-constructor-di/src/main/java/com/baeldung/spring/domain/Car.java rename to spring-core/src/main/java/com/baeldung/constructordi/domain/Car.java index 96199fcee0..9f68ba5cd9 100644 --- a/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Car.java +++ b/spring-core/src/main/java/com/baeldung/constructordi/domain/Car.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.domain; +package com.baeldung.constructordi.domain; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Engine.java b/spring-core/src/main/java/com/baeldung/constructordi/domain/Engine.java similarity index 86% rename from spring-constructor-di/src/main/java/com/baeldung/spring/domain/Engine.java rename to spring-core/src/main/java/com/baeldung/constructordi/domain/Engine.java index 1679692d6d..f2987988eb 100644 --- a/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Engine.java +++ b/spring-core/src/main/java/com/baeldung/constructordi/domain/Engine.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.domain; +package com.baeldung.constructordi.domain; public class Engine { private String type; diff --git a/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Transmission.java b/spring-core/src/main/java/com/baeldung/constructordi/domain/Transmission.java similarity index 81% rename from spring-constructor-di/src/main/java/com/baeldung/spring/domain/Transmission.java rename to spring-core/src/main/java/com/baeldung/constructordi/domain/Transmission.java index 47df118020..85271e1f2a 100644 --- a/spring-constructor-di/src/main/java/com/baeldung/spring/domain/Transmission.java +++ b/spring-core/src/main/java/com/baeldung/constructordi/domain/Transmission.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.domain; +package com.baeldung.constructordi.domain; public class Transmission { private String type; diff --git a/spring-constructor-di/src/main/resources/baeldung.xml b/spring-core/src/main/resources/baeldung.xml similarity index 71% rename from spring-constructor-di/src/main/resources/baeldung.xml rename to spring-core/src/main/resources/baeldung.xml index b3aeef5ee9..d84492f1d4 100644 --- a/spring-constructor-di/src/main/resources/baeldung.xml +++ b/spring-core/src/main/resources/baeldung.xml @@ -3,17 +3,17 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> - + - + - + From 2edb881680cf1354cc6c5e04b361482cbc9166ae Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 23 Nov 2016 16:39:52 +0200 Subject: [PATCH 41/47] compilation fix --- .../baeldung/okhttp/OkHttpGetLiveTest.java | 24 ++++++++----------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index 08d41fe7ab..034833da0d 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -1,11 +1,14 @@ package org.baeldung.okhttp; -import okhttp3.*; -import org.junit.Test; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; import java.io.IOException; + import org.junit.Before; import org.junit.Test; + import okhttp3.Call; import okhttp3.Callback; import okhttp3.HttpUrl; @@ -13,7 +16,6 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; - public class OkHttpGetLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; @@ -23,14 +25,12 @@ public class OkHttpGetLiveTest { @Before public void init() { - client = new OkHttpClient(); + client = new OkHttpClient(); } @Test public void whenGetRequest_thenCorrect() throws IOException { - Request request = new Request.Builder() - .url(BASE_URL + "/date") - .build(); + Request request = new Request.Builder().url(BASE_URL + "/date").build(); Call call = client.newCall(request); Response response = call.execute(); @@ -45,9 +45,7 @@ public class OkHttpGetLiveTest { String url = urlBuilder.build().toString(); - Request request = new Request.Builder() - .url(url) - .build(); + Request request = new Request.Builder().url(url).build(); Call call = client.newCall(request); Response response = call.execute(); @@ -57,9 +55,7 @@ public class OkHttpGetLiveTest { @Test public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException { - Request request = new Request.Builder() - .url(BASE_URL + "/date") - .build(); + Request request = new Request.Builder().url(BASE_URL + "/date").build(); Call call = client.newCall(request); @@ -69,7 +65,7 @@ public class OkHttpGetLiveTest { } public void onFailure(Call call, IOException e) { - fail(); + fail(); } }); From 19b4155ef3ae733a30b54f5c27d73221e068ba03 Mon Sep 17 00:00:00 2001 From: seemamani Date: Thu, 24 Nov 2016 00:04:27 +0530 Subject: [PATCH 42/47] Added a Java file on combining collections (#849) BAEL-35 Added a Java file on combining collections --- .../CollectionsConcatenateUnitTest.java | 116 ++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java diff --git a/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java new file mode 100644 index 0000000000..3ee08767bd --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java @@ -0,0 +1,116 @@ +package org.baeldung.java.collections; + +import static java.util.Arrays.asList; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.Assert; +import org.junit.Test; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +public class CollectionsConcatenateUnitTest { + + @Test + public void givenUsingJava8_whenConcatenatingUsingConcat_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + Collection collectionC = asList("W", "X"); + + Stream combinedStream = Stream.concat(Stream.concat(collectionA.stream(), collectionB.stream()), collectionC.stream()); + Collection collectionCombined = combinedStream.collect(Collectors.toList()); + + Assert.assertEquals(asList("S", "T", "U", "V", "W", "X"), collectionCombined); + } + + @Test + public void givenUsingJava8_whenConcatenatingUsingflatMap_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + + Stream combinedStream = Stream.of(collectionA, collectionB).flatMap(Collection::stream); + Collection collectionCombined = combinedStream.collect(Collectors.toList()); + + Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined); + } + + @Test + public void givenUsingGuava_whenConcatenatingUsingIterables_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + + Iterable combinedIterables = Iterables.unmodifiableIterable(Iterables.concat(collectionA, collectionB)); + Collection collectionCombined = Lists.newArrayList(combinedIterables); + + Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined); + } + + @Test + public void givenUsingJava7_whenConcatenatingUsingIterables_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + + Iterable combinedIterables = concat(collectionA, collectionB); + Collection collectionCombined = makeListFromIterable(combinedIterables); + Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined); + } + + public static Iterable concat(Iterable list1, Iterable list2) { + return new Iterable() { + public Iterator iterator() { + return new Iterator() { + protected Iterator listIterator = list1.iterator(); + protected Boolean checkedHasNext; + protected E nextValue; + private boolean startTheSecond; + + public void theNext() { + if (listIterator.hasNext()) { + checkedHasNext = true; + nextValue = listIterator.next(); + } else if (startTheSecond) + checkedHasNext = false; + else { + startTheSecond = true; + listIterator = list2.iterator(); + theNext(); + } + } + + public boolean hasNext() { + if (checkedHasNext == null) + theNext(); + return checkedHasNext; + } + + public E next() { + if (!hasNext()) + throw new NoSuchElementException(); + checkedHasNext = null; + return nextValue; + } + + public void remove() { + listIterator.remove(); + } + }; + } + }; + } + + public static List makeListFromIterable(Iterable iter) { + List list = new ArrayList(); + for (E item : iter) { + list.add(item); + } + return list; + } +} From 5f9ef96503b23e4981a12f1a10226769aac994a7 Mon Sep 17 00:00:00 2001 From: gitterjim-I Date: Wed, 23 Nov 2016 20:57:39 +0000 Subject: [PATCH 43/47] manual authentication demo integration (#836) * manual authentication demo integration * apply eclipse and security formatting rules * add content to readme file, for manual authentication demo --- spring-security-client/README.MD | 11 ++- .../java/org/baeldung/config/MvcConfig.java | 2 + .../org/baeldung/config/MvcConfigManual.java | 22 +++++ .../config/RegistrationController.java | 92 +++++++++++++++++++ .../org/baeldung/config/SecurityConfig.java | 2 + .../config/WebSecurityConfigManual.java | 35 +++++++ .../src/main/resources/templates/hello.html | 15 +++ .../src/main/resources/templates/home.html | 15 +++ .../src/main/resources/templates/login.html | 21 +++++ .../templates/registrationError.html | 1 + .../templates/registrationSuccess.html | 15 +++ 11 files changed, 230 insertions(+), 1 deletion(-) create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/home.html create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/login.html create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationError.html create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationSuccess.html diff --git a/spring-security-client/README.MD b/spring-security-client/README.MD index 5ac974203b..0b0af7ffe1 100644 --- a/spring-security-client/README.MD +++ b/spring-security-client/README.MD @@ -1,2 +1,11 @@ -###The Course +========= +## Spring Security Authentication/Authorization Example Project + +##The Course The "REST With Spring" Classes: http://github.learnspringsecurity.com + +### Relevant Articles: +- [Spring Security Manual Authentication](http://www.baeldung.com/spring-security-authentication) + +### Build the Project +mvn clean install diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java index 9ade60e54c..259433f6ae 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java @@ -8,9 +8,11 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.context.annotation.Profile; @Configuration @EnableWebMvc +@Profile("!manual") public class MvcConfig extends WebMvcConfigurerAdapter { public MvcConfig() { diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java new file mode 100644 index 0000000000..d80527c30a --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java @@ -0,0 +1,22 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +@Configuration +@EnableWebMvc +@Profile("manual") +public class MvcConfigManual extends WebMvcConfigurerAdapter { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/home").setViewName("home"); + registry.addViewController("/").setViewName("home"); + registry.addViewController("/hello").setViewName("hello"); + registry.addViewController("/login").setViewName("login"); + } + +} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java new file mode 100644 index 0000000000..025001ac44 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java @@ -0,0 +1,92 @@ +package org.baeldung.config; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.WebAuthenticationDetails; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.context.annotation.Profile; + +/** + * Manually authenticate a user using Spring Security / Spring Web MVC' (upon successful account registration) + * (http://stackoverflow.com/questions/4664893/how-to-manually-set-an-authenticated-user-in-spring-security-springmvc) + * + * @author jim clayson + */ +@Controller +@Profile("manual") +public class RegistrationController { + private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class); + + @Autowired + AuthenticationManager authenticationManager; + + /** + * For demo purposes this need only be a GET request method + * + * @param request + * @param response + * @return The view. Page confirming either successful registration (and/or + * successful authentication) or failed registration. + */ + @RequestMapping(value = "/register", method = RequestMethod.GET) + public String registerAndAuthenticate(HttpServletRequest request, HttpServletResponse response) { + logger.debug("registerAndAuthenticate: attempt to register, application should manually authenticate."); + + // Mocked values. Potentially could come from an HTML registration form, + // in which case this mapping would match on an HTTP POST, rather than a GET + String username = "user"; + String password = "password"; + + String view = "registrationSuccess"; + + if (requestQualifiesForManualAuthentication()) { + try { + authenticate(username, password, request, response); + logger.debug("registerAndAuthenticate: authentication completed."); + } catch (BadCredentialsException bce) { + logger.debug("Authentication failure: bad credentials"); + bce.printStackTrace(); + view = "systemError"; // assume a low-level error, since the registration + // form would have been successfully validated + } + } + + return view; + } + + private boolean requestQualifiesForManualAuthentication() { + // Some processing to determine that the user requires a Spring Security-recognized, + // application-directed login e.g. successful account registration. + return true; + } + + private void authenticate(String username, String password, HttpServletRequest request, HttpServletResponse response) throws BadCredentialsException { + logger.debug("attempting to authenticated, manually ... "); + + // create and populate the token + AbstractAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password); + authToken.setDetails(new WebAuthenticationDetails(request)); + + // This call returns an authentication object, which holds principle and user credentials + Authentication authentication = this.authenticationManager.authenticate(authToken); + + // The security context holds the authentication object, and is stored + // in thread local scope. + SecurityContextHolder.getContext().setAuthentication(authentication); + + logger.debug("User should now be authenticated."); + } + +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java index bd6c56d38a..153cc67661 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java @@ -6,9 +6,11 @@ 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.context.annotation.Profile; @Configuration @EnableWebSecurity +@Profile("!manual") public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java new file mode 100644 index 0000000000..180a53deba --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java @@ -0,0 +1,35 @@ +package org.baeldung.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +@Profile("manual") +public class WebSecurityConfigManual extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http + .authorizeRequests() + .antMatchers("/", "/home", "/register").permitAll() + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login").permitAll() + .and() + .logout().permitAll(); + // @formatter:on + } + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); + } +} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html new file mode 100644 index 0000000000..b37731b0ed --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html @@ -0,0 +1,15 @@ + + + + Hello World! + + +

Hello [[${#httpServletRequest.remoteUser}]]!

+
+ +
+

Click here to go to the home page.

+ + + \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/home.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/home.html new file mode 100644 index 0000000000..6dbdf491c6 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/home.html @@ -0,0 +1,15 @@ + + + + Spring Security Example + + +

Welcome!

+ +

Click here to see a greeting.

+

Click here to send a dummy registration request, where the application logs you in.

+ + \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/login.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/login.html new file mode 100644 index 0000000000..3f28efac69 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/login.html @@ -0,0 +1,21 @@ + + + + Spring Security Example + + +
+ Invalid username and password. +
+
+ You have been logged out. +
+
+
+
+
+
+

Click here to go to the home page.

+ + \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationError.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationError.html new file mode 100644 index 0000000000..756cc2390d --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationError.html @@ -0,0 +1 @@ +Registration could not be completed at this time. Please try again later or contact support! \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationSuccess.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationSuccess.html new file mode 100644 index 0000000000..b1c4336f2f --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationSuccess.html @@ -0,0 +1,15 @@ + + + + Registration Success! + + +

Registration succeeded. You have been logged in by the system. Welcome [[${#httpServletRequest.remoteUser}]]!

+
+ +
+

Click here to go to the home page.

+ + + \ No newline at end of file From 15d398cbbb4d2e363000224ae7d83aa5e6a96071 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Thu, 24 Nov 2016 08:04:37 -0600 Subject: [PATCH 44/47] Update 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 783bbb2ef4..e96a8d0392 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -12,3 +12,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [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) +- [Geolocation by IP in Java](http://www.baeldung.com/geolocation-by-ip-with-maxmind) From cdb6dfd79e4c185804adc220d9a221a24f0b9e7b Mon Sep 17 00:00:00 2001 From: Egima profile Date: Fri, 25 Nov 2016 18:48:26 +0300 Subject: [PATCH 45/47] asyncronous channel apis (#839) * 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 * requested changes made * added project for nio2 * standardized exception based tests * fixed exception based tests * removed redundant files * added network interface project * used UUID other than timestamps * fixed network interface tests * removed filetest change * made changes to NIO2 FileTest names * added project for asyncronous channel apis * added project for NIO2 advanced filesystems APIS --- .../java/nio2/visitor/FileSearchExample.java | 60 ++++++++ .../java/nio2/visitor/FileVisitorImpl.java | 30 ++++ .../nio2/watcher/DirectoryWatcherExample.java | 25 ++++ .../java/nio2/async/AsyncEchoClient.java | 82 +++++++++++ .../java/nio2/async/AsyncEchoServer.java | 79 +++++++++++ .../java/nio2/async/AsyncEchoServer2.java | 100 ++++++++++++++ .../java/nio2/async/AsyncEchoTest.java | 36 +++++ .../java/nio2/async/AsyncFileTest.java | 130 ++++++++++++++++++ .../nio2/attributes/BasicAttribsTest.java | 68 +++++++++ 9 files changed, 610 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java create mode 100644 core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java create mode 100644 core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java create mode 100644 core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java create mode 100644 core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java create mode 100644 core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java create mode 100644 core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java create mode 100644 core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java create mode 100644 core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java diff --git a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java new file mode 100644 index 0000000000..15910abf9b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java @@ -0,0 +1,60 @@ +package com.baeldung.java.nio2.visitor; + +import static java.nio.file.FileVisitResult.CONTINUE; +import static java.nio.file.FileVisitResult.TERMINATE; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.FileVisitor; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributes; + +public class FileSearchExample implements FileVisitor { + private static String FILE_NAME; + private static Path START_DIR; + + public FileSearchExample(String fileName, Path startingDir) { + FILE_NAME = fileName; + START_DIR = startingDir; + } + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + return CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + String fileName = file.getFileName().toString(); + if (FILE_NAME.equals(fileName)) { + System.out.println("File found: " + file.toString()); + return TERMINATE; + } + return CONTINUE; + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { + System.out.println("Failed to access file: " + file.toString()); + return CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + boolean finishedSearch = Files.isSameFile(dir, START_DIR); + if (finishedSearch) { + System.out.println("File:" + FILE_NAME + " not found"); + return TERMINATE; + } + return CONTINUE; + } + + public static void main(String[] args) throws IOException { + Path startingDir = Paths.get("C:/Users/new/Desktop"); + FileSearchExample crawler = new FileSearchExample("hibernate.txt", startingDir); + Files.walkFileTree(startingDir, crawler); + } + +} diff --git a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java new file mode 100644 index 0000000000..360d6d0689 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java @@ -0,0 +1,30 @@ +package com.baeldung.java.nio2.visitor; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.FileVisitor; +import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; + +public class FileVisitorImpl implements FileVisitor { + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { + return null; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { + return null; + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) { + return null; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) { + return null; + } +} diff --git a/core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java b/core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java new file mode 100644 index 0000000000..ffc58a1c50 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java @@ -0,0 +1,25 @@ +package com.baeldung.java.nio2.watcher; + +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; + +public class DirectoryWatcherExample { + public static void main(String[] args) throws IOException, InterruptedException { + WatchService watchService = FileSystems.getDefault().newWatchService(); + Path path = Paths.get(System.getProperty("user.home")); + path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); + WatchKey key; + while ((key = watchService.take()) != null) { + for (WatchEvent event : key.pollEvents()) { + System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + "."); + } + key.reset(); + } + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java new file mode 100644 index 0000000000..ea35130f49 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java @@ -0,0 +1,82 @@ +package com.baeldung.java.nio2.async; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousSocketChannel; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +public class AsyncEchoClient { + private AsynchronousSocketChannel client; + private Future future; + private static AsyncEchoClient instance; + + private AsyncEchoClient() { + try { + client = AsynchronousSocketChannel.open(); + InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999); + future = client.connect(hostAddress); + start(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static AsyncEchoClient getInstance() { + if (instance == null) + instance = new AsyncEchoClient(); + return instance; + } + + private void start() { + try { + future.get(); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + } + + public String sendMessage(String message) { + byte[] byteMsg = new String(message).getBytes(); + ByteBuffer buffer = ByteBuffer.wrap(byteMsg); + Future writeResult = client.write(buffer); + + while (!writeResult.isDone()) { + // do nothing + } + buffer.flip(); + Future readResult = client.read(buffer); + while (!readResult.isDone()) { + + } + String echo = new String(buffer.array()).trim(); + buffer.clear(); + return echo; + } + + public void stop() { + try { + client.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws IOException { + AsyncEchoClient client = AsyncEchoClient.getInstance(); + client.start(); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String line = null; + System.out.println("Message to server:"); + while ((line = br.readLine()) != null) { + String response = client.sendMessage(line); + System.out.println("response from server: " + response); + System.out.println("Message to server:"); + } + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java new file mode 100644 index 0000000000..0e58cb5f10 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java @@ -0,0 +1,79 @@ +package com.baeldung.java.nio2.async; + +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousServerSocketChannel; +import java.nio.channels.AsynchronousSocketChannel; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +public class AsyncEchoServer { + private AsynchronousServerSocketChannel serverChannel; + private Future acceptResult; + private AsynchronousSocketChannel clientChannel; + + public AsyncEchoServer() { + try { + serverChannel = AsynchronousServerSocketChannel.open(); + InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999); + serverChannel.bind(hostAddress); + acceptResult = serverChannel.accept(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void runServer() { + try { + clientChannel = acceptResult.get(); + if ((clientChannel != null) && (clientChannel.isOpen())) { + while (true) { + + ByteBuffer buffer = ByteBuffer.allocate(32); + Future readResult = clientChannel.read(buffer); + + while (!readResult.isDone()) { + // do nothing + } + + buffer.flip(); + String message = new String(buffer.array()).trim(); + if (message.equals("bye")) { + break; // while loop + } + buffer = ByteBuffer.wrap(new String(message).getBytes()); + Future writeResult = clientChannel.write(buffer); + while (!writeResult.isDone()) { + // do nothing + } + buffer.clear(); + + } // while() + + clientChannel.close(); + serverChannel.close(); + + } + } catch (InterruptedException | ExecutionException | IOException e) { + e.printStackTrace(); + } + + } + + public static void main(String[] args) { + AsyncEchoServer server = new AsyncEchoServer(); + server.runServer(); + } + 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 = AsyncEchoServer.class.getCanonicalName(); + + ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className); + + return builder.start(); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java new file mode 100644 index 0000000000..03ce233ce9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java @@ -0,0 +1,100 @@ +package com.baeldung.java.nio2.async; + +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousServerSocketChannel; +import java.nio.channels.AsynchronousSocketChannel; +import java.nio.channels.CompletionHandler; +import java.util.HashMap; +import java.util.Map; + +public class AsyncEchoServer2 { + private AsynchronousServerSocketChannel serverChannel; + private AsynchronousSocketChannel clientChannel; + + public AsyncEchoServer2() { + try { + serverChannel = AsynchronousServerSocketChannel.open(); + InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999); + serverChannel.bind(hostAddress); + while (true) { + + serverChannel.accept(null, new CompletionHandler() { + + @Override + public void completed(AsynchronousSocketChannel result, Object attachment) { + if (serverChannel.isOpen()) + serverChannel.accept(null, this); + clientChannel = result; + if ((clientChannel != null) && (clientChannel.isOpen())) { + ReadWriteHandler handler = new ReadWriteHandler(); + ByteBuffer buffer = ByteBuffer.allocate(32); + Map readInfo = new HashMap<>(); + readInfo.put("action", "read"); + readInfo.put("buffer", buffer); + clientChannel.read(buffer, readInfo, handler); + } + } + + @Override + public void failed(Throwable exc, Object attachment) { + // process error + } + }); + try { + System.in.read(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + class ReadWriteHandler implements CompletionHandler> { + + @Override + public void completed(Integer result, Map attachment) { + Map actionInfo = attachment; + String action = (String) actionInfo.get("action"); + if ("read".equals(action)) { + ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer"); + buffer.flip(); + actionInfo.put("action", "write"); + clientChannel.write(buffer, actionInfo, this); + buffer.clear(); + } else if ("write".equals(action)) { + ByteBuffer buffer = ByteBuffer.allocate(32); + actionInfo.put("action", "read"); + actionInfo.put("buffer", buffer); + clientChannel.read(buffer, actionInfo, this); + } + + } + + @Override + public void failed(Throwable exc, Map attachment) { + + } + + } + + + public static void main(String[] args) { + new AsyncEchoServer2(); + } + + 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 = AsyncEchoServer2.class.getCanonicalName(); + + ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className); + + return builder.start(); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java new file mode 100644 index 0000000000..7ac388fb09 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java @@ -0,0 +1,36 @@ +package com.baeldung.java.nio2.async; + +import static org.junit.Assert.*; + +import java.io.IOException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class AsyncEchoTest { + + Process server; + AsyncEchoClient client; + + @Before + public void setup() throws IOException, InterruptedException { + server = AsyncEchoServer2.start(); + client = AsyncEchoClient.getInstance(); + } + + @Test + public void givenServerClient_whenServerEchosMessage_thenCorrect() { + String resp1 = client.sendMessage("hello"); + String resp2 = client.sendMessage("world"); + assertEquals("hello", resp1); + assertEquals("world", resp2); + } + + @After + public void teardown() throws IOException { + server.destroy(); + client.stop(); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java new file mode 100644 index 0000000000..db30d32210 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java @@ -0,0 +1,130 @@ +package com.baeldung.java.nio2.async; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.net.URI; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousFileChannel; +import java.nio.channels.CompletionHandler; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.UUID; +import java.util.concurrent.Future; + +import org.junit.Test; + +public class AsyncFileTest { + @Test + public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException { + Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString())); + AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ); + + ByteBuffer buffer = ByteBuffer.allocate(1024); + + Future operation = fileChannel.read(buffer, 0); + + while (!operation.isDone()) + ; + + String fileContent = new String(buffer.array()).trim(); + buffer.clear(); + + assertEquals(fileContent, "baeldung.com"); + } + + @Test + public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException { + Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString())); + AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ); + + ByteBuffer buffer = ByteBuffer.allocate(1024); + + fileChannel.read(buffer, 0, buffer, new CompletionHandler() { + + @Override + public void completed(Integer result, ByteBuffer attachment) { + // result is number of bytes read + // attachment is the buffer + + } + + @Override + public void failed(Throwable exc, ByteBuffer attachment) { + + } + }); + } + + @Test + public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException { + String fileName = UUID.randomUUID().toString(); + Path path = Paths.get(fileName); + AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,StandardOpenOption.DELETE_ON_CLOSE); + + ByteBuffer buffer = ByteBuffer.allocate(1024); + long position = 0; + + buffer.put("hello world".getBytes()); + buffer.flip(); + + Future operation = fileChannel.write(buffer, position); + buffer.clear(); + + while (!operation.isDone()) { + + } + + String content = readContent(path); + assertEquals("hello world", content); + } + + @Test + public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException { + String fileName = UUID.randomUUID().toString(); + Path path = Paths.get(fileName); + AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,StandardOpenOption.DELETE_ON_CLOSE); + + + ByteBuffer buffer = ByteBuffer.allocate(1024); + buffer.put("hello world".getBytes()); + buffer.flip(); + + fileChannel.write(buffer, 0, buffer, new CompletionHandler() { + + @Override + public void completed(Integer result, ByteBuffer attachment) { + // result is number of bytes written + // attachment is the buffer + + } + + @Override + public void failed(Throwable exc, ByteBuffer attachment) { + + } + }); + } + + public static String readContent(Path file) { + AsynchronousFileChannel fileChannel = null; + try { + fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + ByteBuffer buffer = ByteBuffer.allocate(1024); + + Future operation = fileChannel.read(buffer, 0); + + while (!operation.isDone()) + ; + + String fileContent = new String(buffer.array()).trim(); + buffer.clear(); + return fileContent; + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java new file mode 100644 index 0000000000..dcc24c6415 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java @@ -0,0 +1,68 @@ +package com.baeldung.java.nio2.attributes; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributeView; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileTime; + +import org.junit.Before; +import org.junit.Test; + +public class BasicAttribsTest { + private static final String HOME = System.getProperty("user.home"); + BasicFileAttributes basicAttribs; + + @Before + public void setup() throws IOException { + Path home = Paths.get(HOME); + BasicFileAttributeView basicView = Files.getFileAttributeView(home, BasicFileAttributeView.class); + basicAttribs = basicView.readAttributes(); + } + + @Test + public void givenFileTimes_whenComparesThem_ThenCorrect() { + FileTime created = basicAttribs.creationTime(); + FileTime modified = basicAttribs.lastModifiedTime(); + FileTime accessed = basicAttribs.lastAccessTime(); + + assertTrue(0 > created.compareTo(accessed)); + assertTrue(0 < modified.compareTo(created)); + assertTrue(0 == created.compareTo(created)); + } + + @Test + public void givenPath_whenGetsFileSize_thenCorrect() { + long size = basicAttribs.size(); + assertTrue(size > 0); + } + + @Test + public void givenPath_whenChecksIfDirectory_thenCorrect() { + boolean isDir = basicAttribs.isDirectory(); + assertTrue(isDir); + } + + @Test + public void givenPath_whenChecksIfFile_thenCorrect() { + boolean isFile = basicAttribs.isRegularFile(); + assertFalse(isFile); + } + + @Test + public void givenPath_whenChecksIfSymLink_thenCorrect() { + boolean isSymLink = basicAttribs.isSymbolicLink(); + assertFalse(isSymLink); + } + + @Test + public void givenPath_whenChecksIfOther_thenCorrect() { + boolean isOther = basicAttribs.isOther(); + assertFalse(isOther); + } +} From 5b738313e8524ea44113cb1bf7c9aca0f4c34ddf Mon Sep 17 00:00:00 2001 From: Alex Theedom Date: Sat, 26 Nov 2016 17:43:54 +0000 Subject: [PATCH 46/47] Add Spring MVC form and binding example --- spring-mvc-forms/pom.xml | 99 +++++++++++++++++++ .../ApplicationConfiguration.java | 29 ++++++ .../configuration/WebInitializer.java | 47 +++++++++ .../controller/EmployeeController.java | 41 ++++++++ .../springmvcforms/domain/Employee.java | 46 +++++++++ .../webapp/WEB-INF/views/employeeHome.jsp | 33 +++++++ .../webapp/WEB-INF/views/employeeView.jsp | 24 +++++ .../src/main/webapp/WEB-INF/views/error.jsp | 20 ++++ 8 files changed, 339 insertions(+) create mode 100644 spring-mvc-forms/pom.xml create mode 100644 spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java create mode 100644 spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java create mode 100644 spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java create mode 100644 spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Employee.java create mode 100644 spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeHome.jsp create mode 100644 spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeView.jsp create mode 100644 spring-mvc-forms/src/main/webapp/WEB-INF/views/error.jsp diff --git a/spring-mvc-forms/pom.xml b/spring-mvc-forms/pom.xml new file mode 100644 index 0000000000..370fd7feb2 --- /dev/null +++ b/spring-mvc-forms/pom.xml @@ -0,0 +1,99 @@ + + + + 4.0.0 + com.baeldung + 0.1-SNAPSHOT + spring-mvc-forms + + spring-mvc-forms + war + + + + org.springframework + spring-webmvc + ${springframework.version} + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + + javax.servlet.jsp + javax.servlet.jsp-api + ${javax.servlet.jsp-api.version} + + + + javax.servlet + jstl + ${jstl.version} + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + + + + + + spring-mvc-forms + + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven-compiler-plugin.source} + ${maven-compiler-plugin.source} + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + src/main/webapp + spring-mvc-forms + false + ${deploy-path} + + + + + + spring-mvc-forms + + + + + + 4.0.6.RELEASE + 2.4 + 1.2 + 2.3.1 + 3.1.0 + 3.5.1 + 1.8 + 5.1.1.Final + enter-location-of-server + + + + diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java new file mode 100644 index 0000000000..998f070c02 --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.springmvcforms.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "com.baeldung.springmvcforms") +class ApplicationConfiguration extends WebMvcConfigurerAdapter { + + @Override + public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Bean + public InternalResourceViewResolver jspViewResolver() { + InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setPrefix("/WEB-INF/views/"); + bean.setSuffix(".jsp"); + return bean; + } + +} diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java new file mode 100644 index 0000000000..c602ea6454 --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java @@ -0,0 +1,47 @@ +package com.baeldung.springmvcforms.configuration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +public class WebInitializer implements WebApplicationInitializer { + + public void onStartup(ServletContext container) throws ServletException { + + AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); + ctx.register(ApplicationConfiguration.class); + ctx.setServletContext(container); + + // Manage the lifecycle of the root application context + container.addListener(new ContextLoaderListener(ctx)); + + ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx)); + + servlet.setLoadOnStartup(1); + servlet.addMapping("/"); + } +// @Override +// public void onStartup(ServletContext container) { +// // Create the 'root' Spring application context +// AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); +// rootContext.register(ServiceConfig.class, JPAConfig.class, SecurityConfig.class); +// +// // Manage the lifecycle of the root application context +// container.addListener(new ContextLoaderListener(rootContext)); +// +// // Create the dispatcher servlet's Spring application context +// AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext(); +// dispatcherServlet.register(MvcConfig.class); +// +// // Register and map the dispatcher servlet +// ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet)); +// dispatcher.setLoadOnStartup(1); +// dispatcher.addMapping("/"); +// +// } +} diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java new file mode 100644 index 0000000000..3ece77bb18 --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java @@ -0,0 +1,41 @@ +package com.baeldung.springmvcforms.controller; + +import com.baeldung.springmvcforms.domain.Employee; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.ModelAndView; + +import javax.validation.Valid; +import java.util.HashMap; +import java.util.Map; + +@Controller +public class EmployeeController { + + Map employeeMap = new HashMap<>(); + + @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 = "/addEmployee", method = RequestMethod.POST) + public String submit(@Valid @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-forms/src/main/java/com/baeldung/springmvcforms/domain/Employee.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Employee.java new file mode 100644 index 0000000000..23cb72b3dc --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Employee.java @@ -0,0 +1,46 @@ +package com.baeldung.springmvcforms.domain; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +public class Employee { + + private long id; + + @NotNull + @Size(min = 5) + private String name; + + @NotNull + @Size(min = 7) + private String contactNumber; + + public Employee() { + super(); + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getContactNumber() { + return contactNumber; + } + + public void setContactNumber(final String contactNumber) { + this.contactNumber = contactNumber; + } + +} diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeHome.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeHome.jsp new file mode 100644 index 0000000000..5ed572000a --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeHome.jsp @@ -0,0 +1,33 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +Form Example - Register an Employee + + +

Welcome, Enter The Employee Details

+ + + + + + + + + + + + + + + + + + +
Name
Id
Contact Number
+
+ + + + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeView.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeView.jsp new file mode 100644 index 0000000000..1457bc5fc8 --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeView.jsp @@ -0,0 +1,24 @@ +<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> + + +Spring MVC Form Handling + + + +

Submitted Employee Information

+ + + + + + + + + + + + + +
Name :${name}
ID :${id}
Contact Number :${contactNumber}
+ + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/error.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/error.jsp new file mode 100644 index 0000000000..8f3d83af17 --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/error.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +SpringMVCExample + + + +

Pleas enter the correct details

+ + + + +
Retry
+ + + + \ No newline at end of file From 6cca0522517816a98ffbc883992d11e537b68c03 Mon Sep 17 00:00:00 2001 From: Alex Theedom Date: Sat, 26 Nov 2016 18:33:20 +0000 Subject: [PATCH 47/47] Add Spring MVC form and binding example --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index b8d0303160..77cf615a98 100644 --- a/pom.xml +++ b/pom.xml @@ -109,6 +109,7 @@ spring-katharsis spring-mockito spring-mvc-java + spring-mvc-forms spring-mvc-no-xml spring-mvc-tiles spring-mvc-velocity