From 22207e646b504c269c0484e1883fa8b9de5a80c8 Mon Sep 17 00:00:00 2001 From: Pritam Banerjee Date: Sat, 15 Oct 2016 14:40:20 -0700 Subject: [PATCH 01/38] 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 bde1d12e822e5db5ab198f7d12145717ff0d5ad2 Mon Sep 17 00:00:00 2001 From: Pritam Banerjee Date: Mon, 7 Nov 2016 02:06:51 -0800 Subject: [PATCH 02/38] 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 dd6946585f5212c1bc6461360496e436c24c2a0c Mon Sep 17 00:00:00 2001 From: Diane Duan Date: Mon, 14 Nov 2016 14:53:12 +0800 Subject: [PATCH 03/38] core-java Properties class demos --- .../baeldung/properties/DefaultListDemo.java | 23 ++++++++ .../com/baeldung/properties/LoadDemo.java | 26 +++++++++ .../baeldung/properties/OperationsDemo.java | 57 +++++++++++++++++++ .../com/baeldung/properties/StoreDemo.java | 30 ++++++++++ core-java/src/main/resources/app.properties | 3 + core-java/src/main/resources/catalog | 3 + .../src/main/resources/default.properties | 4 ++ core-java/src/main/resources/icons.xml | 8 +++ 8 files changed, 154 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/properties/DefaultListDemo.java create mode 100644 core-java/src/main/java/com/baeldung/properties/LoadDemo.java create mode 100644 core-java/src/main/java/com/baeldung/properties/OperationsDemo.java create mode 100644 core-java/src/main/java/com/baeldung/properties/StoreDemo.java create mode 100644 core-java/src/main/resources/app.properties create mode 100644 core-java/src/main/resources/catalog create mode 100644 core-java/src/main/resources/default.properties create mode 100644 core-java/src/main/resources/icons.xml diff --git a/core-java/src/main/java/com/baeldung/properties/DefaultListDemo.java b/core-java/src/main/java/com/baeldung/properties/DefaultListDemo.java new file mode 100644 index 0000000000..758bd2a71b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/properties/DefaultListDemo.java @@ -0,0 +1,23 @@ +package com.baeldung.properties; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Properties; + +public class DefaultListDemo { + public static void main(String[] args) throws IOException { + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String defaultConfigPath = rootPath + "default.properties"; + String appConfigPath = rootPath + "app.properties"; + + Properties defaultProps = new Properties(); + defaultProps.load(new FileInputStream(defaultConfigPath)); + + Properties appProps = new Properties(defaultProps); + appProps.load(new FileInputStream(appConfigPath)); + + System.out.println(appProps.getProperty("name")); + System.out.println(appProps.getProperty("version")); + System.out.println(appProps.getProperty("site")); + } +} diff --git a/core-java/src/main/java/com/baeldung/properties/LoadDemo.java b/core-java/src/main/java/com/baeldung/properties/LoadDemo.java new file mode 100644 index 0000000000..3a75113b79 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/properties/LoadDemo.java @@ -0,0 +1,26 @@ +package com.baeldung.properties; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Properties; + +public class LoadDemo { + public static void main(String[] args) throws IOException { + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + String catalogConfigPath = rootPath + "catalog"; + String iconConfigPath = rootPath + "icons.xml"; + + // load from properties file which use .properties as the suffix + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + // load from properties file which not use .properties as the suffix + Properties catalogProps = new Properties(); + catalogProps.load(new FileInputStream(catalogConfigPath)); + + // load from XML file + Properties iconProps = new Properties(); + iconProps.loadFromXML(new FileInputStream(iconConfigPath)); + } +} diff --git a/core-java/src/main/java/com/baeldung/properties/OperationsDemo.java b/core-java/src/main/java/com/baeldung/properties/OperationsDemo.java new file mode 100644 index 0000000000..c33caf877c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/properties/OperationsDemo.java @@ -0,0 +1,57 @@ +package com.baeldung.properties; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Enumeration; +import java.util.Properties; + +public class OperationsDemo { + public static void main(String[] args) throws IOException { + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + // retrieve values + String appVersion = appProps.getProperty("version"); + String appName = appProps.getProperty("name", "defaultName"); + String appGroup = appProps.getProperty("group", "baeldung"); + String appDownloadAddr = appProps.getProperty("downloadAddr"); + System.out.println(appVersion); + System.out.println(appName); + System.out.println(appGroup); + System.out.println(appDownloadAddr); + + // set values + appProps.setProperty("name", "NewAppName"); + appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); + appName = appProps.getProperty("name"); + appDownloadAddr = appProps.getProperty("downloadAddr"); + System.out.println("new app name: " + appName); + System.out.println("new app downloadAddr: " + appDownloadAddr); + + // remove a key-value pair + System.out.println("before removal, version is: " + appProps.getProperty("version")); + appProps.remove("version"); + System.out.println("after removal, version is: " + appProps.getProperty("version")); + + // list all key-value pairs + appProps.list(System.out); + + // get an enumeration of all values + Enumeration valueEnumeration = appProps.elements(); + while (valueEnumeration.hasMoreElements()) { + System.out.println(valueEnumeration.nextElement()); + } + + // get an enumeration of all keys + Enumeration keyEnumeration = appProps.keys(); + while (keyEnumeration.hasMoreElements()) { + System.out.println(keyEnumeration.nextElement()); + } + + // get the count of key-value pairs + int size = appProps.size(); + System.out.println(size); + } +} diff --git a/core-java/src/main/java/com/baeldung/properties/StoreDemo.java b/core-java/src/main/java/com/baeldung/properties/StoreDemo.java new file mode 100644 index 0000000000..e8a7892c40 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/properties/StoreDemo.java @@ -0,0 +1,30 @@ +package com.baeldung.properties; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Properties; + +public class StoreDemo { + public static void main(String[] args) throws IOException { + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + + // load the original properties + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + // update property list + appProps.setProperty("name", "NewAppName"); + appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); + + // store new property list in properties file + String newAppConfigPropertiesFile = rootPath + "newApp.properties"; + appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file"); + + // store new property list in XML file + String newAppConfigXmlFile = rootPath + "newApp.xml"; + appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file"); + } +} diff --git a/core-java/src/main/resources/app.properties b/core-java/src/main/resources/app.properties new file mode 100644 index 0000000000..ff6174ec2a --- /dev/null +++ b/core-java/src/main/resources/app.properties @@ -0,0 +1,3 @@ +version=1.0 +name=TestApp +date=2016-11-12 \ No newline at end of file diff --git a/core-java/src/main/resources/catalog b/core-java/src/main/resources/catalog new file mode 100644 index 0000000000..488513d0ce --- /dev/null +++ b/core-java/src/main/resources/catalog @@ -0,0 +1,3 @@ +c1=files +c2=images +c3=videos \ No newline at end of file diff --git a/core-java/src/main/resources/default.properties b/core-java/src/main/resources/default.properties new file mode 100644 index 0000000000..df1bab371c --- /dev/null +++ b/core-java/src/main/resources/default.properties @@ -0,0 +1,4 @@ +site=www.google.com +name=DefaultAppName +topic=Properties +category=core-java \ No newline at end of file diff --git a/core-java/src/main/resources/icons.xml b/core-java/src/main/resources/icons.xml new file mode 100644 index 0000000000..0db7b2699a --- /dev/null +++ b/core-java/src/main/resources/icons.xml @@ -0,0 +1,8 @@ + + + + xml example + icon1.jpg + icon2.jpg + icon3.jpg + \ No newline at end of file From d2e52b4368c49d4072daed7d32157adecc5f4faa Mon Sep 17 00:00:00 2001 From: Diane Duan Date: Tue, 15 Nov 2016 12:37:17 +0800 Subject: [PATCH 04/38] add unit tests --- .../baeldung/properties/OperationsDemo.java | 57 ----------- .../com/baeldung/properties/StoreDemo.java | 30 ------ .../PropertiesDefaultListTest.java} | 17 +++- .../properties/PropertiesLoadTest.java} | 14 ++- .../properties/PropertiesOperationsTest.java | 97 +++++++++++++++++++ .../properties/PropertiesStoreTest.java | 51 ++++++++++ .../{main => test}/resources/app.properties | 0 .../src/{main => test}/resources/catalog | 0 .../resources/default.properties | 0 .../src/{main => test}/resources/icons.xml | 0 10 files changed, 170 insertions(+), 96 deletions(-) delete mode 100644 core-java/src/main/java/com/baeldung/properties/OperationsDemo.java delete mode 100644 core-java/src/main/java/com/baeldung/properties/StoreDemo.java rename core-java/src/{main/java/com/baeldung/properties/DefaultListDemo.java => test/java/com/baeldung/properties/PropertiesDefaultListTest.java} (55%) rename core-java/src/{main/java/com/baeldung/properties/LoadDemo.java => test/java/com/baeldung/properties/PropertiesLoadTest.java} (74%) create mode 100644 core-java/src/test/java/com/baeldung/properties/PropertiesOperationsTest.java create mode 100644 core-java/src/test/java/com/baeldung/properties/PropertiesStoreTest.java rename core-java/src/{main => test}/resources/app.properties (100%) rename core-java/src/{main => test}/resources/catalog (100%) rename core-java/src/{main => test}/resources/default.properties (100%) rename core-java/src/{main => test}/resources/icons.xml (100%) diff --git a/core-java/src/main/java/com/baeldung/properties/OperationsDemo.java b/core-java/src/main/java/com/baeldung/properties/OperationsDemo.java deleted file mode 100644 index c33caf877c..0000000000 --- a/core-java/src/main/java/com/baeldung/properties/OperationsDemo.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.properties; - -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Enumeration; -import java.util.Properties; - -public class OperationsDemo { - public static void main(String[] args) throws IOException { - String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); - String appConfigPath = rootPath + "app.properties"; - Properties appProps = new Properties(); - appProps.load(new FileInputStream(appConfigPath)); - - // retrieve values - String appVersion = appProps.getProperty("version"); - String appName = appProps.getProperty("name", "defaultName"); - String appGroup = appProps.getProperty("group", "baeldung"); - String appDownloadAddr = appProps.getProperty("downloadAddr"); - System.out.println(appVersion); - System.out.println(appName); - System.out.println(appGroup); - System.out.println(appDownloadAddr); - - // set values - appProps.setProperty("name", "NewAppName"); - appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); - appName = appProps.getProperty("name"); - appDownloadAddr = appProps.getProperty("downloadAddr"); - System.out.println("new app name: " + appName); - System.out.println("new app downloadAddr: " + appDownloadAddr); - - // remove a key-value pair - System.out.println("before removal, version is: " + appProps.getProperty("version")); - appProps.remove("version"); - System.out.println("after removal, version is: " + appProps.getProperty("version")); - - // list all key-value pairs - appProps.list(System.out); - - // get an enumeration of all values - Enumeration valueEnumeration = appProps.elements(); - while (valueEnumeration.hasMoreElements()) { - System.out.println(valueEnumeration.nextElement()); - } - - // get an enumeration of all keys - Enumeration keyEnumeration = appProps.keys(); - while (keyEnumeration.hasMoreElements()) { - System.out.println(keyEnumeration.nextElement()); - } - - // get the count of key-value pairs - int size = appProps.size(); - System.out.println(size); - } -} diff --git a/core-java/src/main/java/com/baeldung/properties/StoreDemo.java b/core-java/src/main/java/com/baeldung/properties/StoreDemo.java deleted file mode 100644 index e8a7892c40..0000000000 --- a/core-java/src/main/java/com/baeldung/properties/StoreDemo.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.properties; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Properties; - -public class StoreDemo { - public static void main(String[] args) throws IOException { - String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); - String appConfigPath = rootPath + "app.properties"; - - // load the original properties - Properties appProps = new Properties(); - appProps.load(new FileInputStream(appConfigPath)); - - // update property list - appProps.setProperty("name", "NewAppName"); - appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); - - // store new property list in properties file - String newAppConfigPropertiesFile = rootPath + "newApp.properties"; - appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file"); - - // store new property list in XML file - String newAppConfigXmlFile = rootPath + "newApp.xml"; - appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file"); - } -} diff --git a/core-java/src/main/java/com/baeldung/properties/DefaultListDemo.java b/core-java/src/test/java/com/baeldung/properties/PropertiesDefaultListTest.java similarity index 55% rename from core-java/src/main/java/com/baeldung/properties/DefaultListDemo.java rename to core-java/src/test/java/com/baeldung/properties/PropertiesDefaultListTest.java index 758bd2a71b..704bb19759 100644 --- a/core-java/src/main/java/com/baeldung/properties/DefaultListDemo.java +++ b/core-java/src/test/java/com/baeldung/properties/PropertiesDefaultListTest.java @@ -1,11 +1,18 @@ package com.baeldung.properties; +import org.junit.Test; + import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; -public class DefaultListDemo { - public static void main(String[] args) throws IOException { +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + +public class PropertiesDefaultListTest { + @Test + public void testDefaultList() throws IOException { String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); String defaultConfigPath = rootPath + "default.properties"; String appConfigPath = rootPath + "app.properties"; @@ -16,8 +23,8 @@ public class DefaultListDemo { Properties appProps = new Properties(defaultProps); appProps.load(new FileInputStream(appConfigPath)); - System.out.println(appProps.getProperty("name")); - System.out.println(appProps.getProperty("version")); - System.out.println(appProps.getProperty("site")); + assertThat(appProps.getProperty("name"), equalTo("TestApp")); + assertThat(appProps.getProperty("version"), equalTo("1.0")); + assertThat(appProps.getProperty("site"), equalTo("www.google.com")); } } diff --git a/core-java/src/main/java/com/baeldung/properties/LoadDemo.java b/core-java/src/test/java/com/baeldung/properties/PropertiesLoadTest.java similarity index 74% rename from core-java/src/main/java/com/baeldung/properties/LoadDemo.java rename to core-java/src/test/java/com/baeldung/properties/PropertiesLoadTest.java index 3a75113b79..bcf386bd0f 100644 --- a/core-java/src/main/java/com/baeldung/properties/LoadDemo.java +++ b/core-java/src/test/java/com/baeldung/properties/PropertiesLoadTest.java @@ -1,15 +1,17 @@ package com.baeldung.properties; +import org.junit.Test; + import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; -public class LoadDemo { - public static void main(String[] args) throws IOException { +public class PropertiesLoadTest { + @Test + public void testLoadFromPropertiesFiles() throws IOException { String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); String appConfigPath = rootPath + "app.properties"; String catalogConfigPath = rootPath + "catalog"; - String iconConfigPath = rootPath + "icons.xml"; // load from properties file which use .properties as the suffix Properties appProps = new Properties(); @@ -18,8 +20,12 @@ public class LoadDemo { // load from properties file which not use .properties as the suffix Properties catalogProps = new Properties(); catalogProps.load(new FileInputStream(catalogConfigPath)); + } - // load from XML file + @Test + public void testLoadFromXmlFile() throws IOException { + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String iconConfigPath = rootPath + "icons.xml"; Properties iconProps = new Properties(); iconProps.loadFromXML(new FileInputStream(iconConfigPath)); } diff --git a/core-java/src/test/java/com/baeldung/properties/PropertiesOperationsTest.java b/core-java/src/test/java/com/baeldung/properties/PropertiesOperationsTest.java new file mode 100644 index 0000000000..20aa64c385 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/properties/PropertiesOperationsTest.java @@ -0,0 +1,97 @@ +package com.baeldung.properties; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import org.junit.Before; +import org.junit.Test; +import org.testng.annotations.BeforeClass; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +public class PropertiesOperationsTest { + private Properties appProps; + + @Before + public void beforeClass() throws IOException { + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + } + + @Test + public void testGetProperties() { + String appVersion = appProps.getProperty("version"); + String appName = appProps.getProperty("name", "defaultName"); + String appGroup = appProps.getProperty("group", "baeldung"); + String appDownloadAddr = appProps.getProperty("downloadAddr"); + + assertThat(appVersion, equalTo("1.0")); + assertThat(appName, equalTo("TestApp")); + assertThat(appGroup, equalTo("baeldung")); + assertThat(appDownloadAddr, equalTo(null)); + } + + @Test + public void testSetProperties() { + appProps.setProperty("name", "NewAppName"); + appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); + + String appName = appProps.getProperty("name"); + String appDownloadAddr = appProps.getProperty("downloadAddr"); + + assertThat(appName, equalTo("NewAppName")); + assertThat(appDownloadAddr, equalTo("www.baeldung.com/downloads")); + } + + @Test + public void testRemoveProperties() { + String versionBeforeRemoval = appProps.getProperty("version"); + assertThat(versionBeforeRemoval, equalTo("1.0")); + + appProps.remove("version"); + + String versionAfterRemoval = appProps.getProperty("version"); + assertThat(versionAfterRemoval, equalTo(null)); + } + + @Test + public void testGetEnumerationOfValues() { + Enumeration valueEnumeration = appProps.elements(); + List values = Lists.newArrayList(); + while (valueEnumeration.hasMoreElements()) { + String val = String.valueOf(valueEnumeration.nextElement()); + values.add(val); + } + assertArrayEquals(new String[] {"1.0", "2016-11-12", "TestApp"}, values.toArray()); + } + + @Test + public void testGetEnumerationOfKeys() { + Enumeration keyEnumeration = appProps.keys(); + List keys = Lists.newArrayList(); + while (keyEnumeration.hasMoreElements()) { + String key = String.valueOf(keyEnumeration.nextElement()); + keys.add(key); + } + assertArrayEquals(new String[] {"version", "date", "name"}, keys.toArray()); + } + + @Test + public void testGetSize() { + int size = appProps.size(); + assertThat(size, equalTo(3)); + } +} diff --git a/core-java/src/test/java/com/baeldung/properties/PropertiesStoreTest.java b/core-java/src/test/java/com/baeldung/properties/PropertiesStoreTest.java new file mode 100644 index 0000000000..582fdb3808 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/properties/PropertiesStoreTest.java @@ -0,0 +1,51 @@ +package com.baeldung.properties; + +import org.junit.Before; +import org.junit.Test; +import org.testng.annotations.BeforeClass; + +import java.io.*; +import java.util.Properties; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + +public class PropertiesStoreTest { + private static Properties appProps = new Properties(); + + @Before + public void before() throws IOException { + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + + // load the original properties + appProps.load(new FileInputStream(appConfigPath)); + + // update property list + appProps.setProperty("name", "NewAppName"); + appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); + } + + @Test + public void testStoreToPropertiesFile() throws IOException { + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String newAppConfigPropertiesFile = rootPath + "newApp.properties"; + appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file"); + + + Properties verifyProps = new Properties(); + verifyProps.load(new FileInputStream(newAppConfigPropertiesFile)); + assertThat(verifyProps.getProperty("name"), equalTo("NewAppName")); + } + + @Test + public void testStoreToXmlFile() throws IOException { + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String newAppConfigXmlFile = rootPath + "newApp.xml"; + appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file"); + + Properties verifyProps = new Properties(); + verifyProps.loadFromXML(new FileInputStream(newAppConfigXmlFile)); + assertThat(verifyProps.getProperty("downloadAddr"), equalTo("www.baeldung.com/downloads")); + } +} diff --git a/core-java/src/main/resources/app.properties b/core-java/src/test/resources/app.properties similarity index 100% rename from core-java/src/main/resources/app.properties rename to core-java/src/test/resources/app.properties diff --git a/core-java/src/main/resources/catalog b/core-java/src/test/resources/catalog similarity index 100% rename from core-java/src/main/resources/catalog rename to core-java/src/test/resources/catalog diff --git a/core-java/src/main/resources/default.properties b/core-java/src/test/resources/default.properties similarity index 100% rename from core-java/src/main/resources/default.properties rename to core-java/src/test/resources/default.properties diff --git a/core-java/src/main/resources/icons.xml b/core-java/src/test/resources/icons.xml similarity index 100% rename from core-java/src/main/resources/icons.xml rename to core-java/src/test/resources/icons.xml From b1d5ae8c3c8ebadf15c093827243a477ecc11efd Mon Sep 17 00:00:00 2001 From: Pritam Banerjee Date: Tue, 15 Nov 2016 23:04:08 -0800 Subject: [PATCH 05/38] 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 06/38] 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 205a84d8345a51544876be572fc2805b1ada7c4f Mon Sep 17 00:00:00 2001 From: eugenp Date: Fri, 18 Nov 2016 13:26:34 +0200 Subject: [PATCH 07/38] major upgrades --- spring-mvc-java/pom.xml | 4 ++-- spring-security-rest-full/pom.xml | 20 +++++++------------ .../persistence/dao/MyUserPredicate.java | 8 ++++---- .../dao/MyUserPredicatesBuilder.java | 2 +- .../persistence/dao/MyUserRepository.java | 2 +- .../web/controller/UserController.java | 4 ++-- 6 files changed, 17 insertions(+), 23 deletions(-) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 011de70ad2..8e2db044a6 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -248,8 +248,8 @@ - 4.2.5.RELEASE - 4.0.4.RELEASE + 4.3.4.RELEASE + 4.2.0.RELEASE 2.1.4.RELEASE 2.7.8 diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index 957a349d3c..ab354d51a7 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.8.RELEASE + 1.4.2.RELEASE @@ -109,14 +109,12 @@ - com.mysema.querydsl + com.querydsl querydsl-apt - ${querydsl.version} - com.mysema.querydsl + com.querydsl querydsl-jpa - ${querydsl.version} @@ -161,7 +159,6 @@ xml-apis xml-apis - ${xml-apis.version} org.javassist @@ -358,7 +355,7 @@ target/generated-sources/java - com.mysema.query.apt.jpa.JPAAnnotationProcessor + com.querydsl.apt.jpa.JPAAnnotationProcessor @@ -467,16 +464,13 @@ - 4.2.5.RELEASE - 4.0.4.RELEASE 4.3.11.Final - 5.1.38 - 1.8.2.RELEASE + 5.1.40 2.0.0 - 3.6.2 + 4.1.4 2.7.8 @@ -505,7 +499,7 @@ 2.9.0 - 3.5.1 + 3.6.0 2.6 2.19.1 1.4.18 diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java index 7a00e7490c..63ae35ec1f 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java @@ -3,10 +3,10 @@ package org.baeldung.persistence.dao; import org.baeldung.persistence.model.MyUser; import org.baeldung.web.util.SearchCriteria; -import com.mysema.query.types.expr.BooleanExpression; -import com.mysema.query.types.path.NumberPath; -import com.mysema.query.types.path.PathBuilder; -import com.mysema.query.types.path.StringPath; +import com.querydsl.core.types.dsl.BooleanExpression; +import com.querydsl.core.types.dsl.NumberPath; +import com.querydsl.core.types.dsl.PathBuilder; +import com.querydsl.core.types.dsl.StringPath; public class MyUserPredicate { diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java index 5e08bde273..caee59c1ec 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java @@ -5,7 +5,7 @@ import java.util.List; import org.baeldung.web.util.SearchCriteria; -import com.mysema.query.types.expr.BooleanExpression; +import com.querydsl.core.types.dsl.BooleanExpression; public final class MyUserPredicatesBuilder { private final List params; diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java index db3627817a..029b57016b 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java @@ -7,7 +7,7 @@ import org.springframework.data.querydsl.QueryDslPredicateExecutor; import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; import org.springframework.data.querydsl.binding.QuerydslBindings; -import com.mysema.query.types.path.StringPath; +import com.querydsl.core.types.dsl.StringPath; public interface MyUserRepository extends JpaRepository, QueryDslPredicateExecutor, QuerydslBinderCustomizer { @Override diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java index cf46e35e57..d20423ddc0 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java @@ -29,8 +29,8 @@ import org.springframework.web.bind.annotation.ResponseStatus; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; -import com.mysema.query.types.Predicate; -import com.mysema.query.types.expr.BooleanExpression; +import com.querydsl.core.types.Predicate; +import com.querydsl.core.types.dsl.BooleanExpression; import cz.jirutka.rsql.parser.RSQLParser; import cz.jirutka.rsql.parser.ast.Node; From 42946ddbac3869a755ed48ccd6bbd9ff2e186bd8 Mon Sep 17 00:00:00 2001 From: eugenp Date: Fri, 18 Nov 2016 13:41:33 +0200 Subject: [PATCH 08/38] cleanup work --- spring-security-rest-full/.springBeans | 19 +++++++++++ .../example/spring/AnotherBootApp.java | 17 ---------- .../spring/SecurityWithoutCsrfConfig.java | 2 +- .../client/RestTemplateBasicLiveTest.java | 34 +++++++++++++++++++ .../csrf/CsrfDisabledIntegrationTest.java | 2 +- .../csrf/CsrfEnabledIntegrationTest.java | 1 + .../SecurityWithCsrfConfig.java | 2 +- .../LoggerInterceptorIntegrationTest.java | 2 +- ...essionTimerInterceptorIntegrationTest.java | 2 +- .../UserInterceptorIntegrationTest.java | 2 +- 10 files changed, 60 insertions(+), 23 deletions(-) create mode 100644 spring-security-rest-full/.springBeans delete mode 100644 spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java rename spring-security-rest-full/src/main/java/org/baeldung/{ => security}/spring/SecurityWithoutCsrfConfig.java (98%) create mode 100644 spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java rename spring-security-rest-full/src/test/java/org/baeldung/security/{csrf => spring}/SecurityWithCsrfConfig.java (98%) diff --git a/spring-security-rest-full/.springBeans b/spring-security-rest-full/.springBeans new file mode 100644 index 0000000000..f100c6afbe --- /dev/null +++ b/spring-security-rest-full/.springBeans @@ -0,0 +1,19 @@ + + + 1 + + + + + + + java:org.baeldung.security.spring.SecurityWithoutCsrfConfig + + + src/main/webapp/WEB-INF/api-servlet.xml + java:org.baeldung.spring.Application + java:org.baeldung.security.spring.SecurityWithCsrfConfig + + + + diff --git a/spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java b/spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java deleted file mode 100644 index 445a70f29c..0000000000 --- a/spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.example.spring; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@EnableScheduling -@EnableAutoConfiguration -@ComponentScan("org.baeldung") -public class AnotherBootApp extends WebMvcConfigurerAdapter { - - public static void main(final String[] args) { - SpringApplication.run(AnotherBootApp.class, args); - } -} \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java similarity index 98% rename from spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java rename to spring-security-rest-full/src/main/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java index aeb2428326..f1a78d1472 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package org.baeldung.security.spring; import org.baeldung.web.error.CustomAccessDeniedHandler; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java new file mode 100644 index 0000000000..3516e5161d --- /dev/null +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -0,0 +1,34 @@ +package org.baeldung.client; + +import static org.baeldung.Consts.APPLICATION_PORT; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.io.IOException; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +public class RestTemplateBasicLiveTest { + + private RestTemplate restTemplate; + private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-security-rest-full/auth/foos"; + + @Before + public void beforeTest() { + restTemplate = new RestTemplate(); + } + + // GET + + @Test + public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { + final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl, String.class); + + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + +} diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java index 63efd870cd..e06461fc2c 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java @@ -4,8 +4,8 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.baeldung.security.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.WebConfig; import org.junit.Test; import org.springframework.http.MediaType; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java index b04644f847..939b745de8 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -4,6 +4,7 @@ import static org.springframework.security.test.web.servlet.request.SecurityMock import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.baeldung.security.spring.SecurityWithCsrfConfig; import org.baeldung.spring.PersistenceConfig; import org.baeldung.spring.WebConfig; import org.junit.Test; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java b/spring-security-rest-full/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java similarity index 98% rename from spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java rename to spring-security-rest-full/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java index ae4a655265..97ae1f1dd2 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.security.csrf; +package org.baeldung.security.spring; import org.baeldung.web.error.CustomAccessDeniedHandler; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java index 99b391eda1..7dcaec5a12 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java @@ -3,8 +3,8 @@ package org.baeldung.web.interceptor; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.baeldung.security.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.WebConfig; import org.junit.Before; import org.junit.Test; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java index 662fc997f9..d62fab0670 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java @@ -5,8 +5,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import javax.servlet.http.HttpSession; +import org.baeldung.security.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.WebConfig; import org.junit.Before; import org.junit.Test; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java index 0e8f7c98ed..f995f86145 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java @@ -1,7 +1,7 @@ package org.baeldung.web.interceptor; +import org.baeldung.security.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.WebConfig; import org.junit.Before; import org.junit.Test; From 30171ef89bcd5e0e919263fcb66ffa9c9960cbea Mon Sep 17 00:00:00 2001 From: eugenp Date: Fri, 18 Nov 2016 14:01:31 +0200 Subject: [PATCH 09/38] upgrades --- spring-rest/pom.xml | 80 ++++++++++++++----- .../java/org/baeldung/config/Application.java | 22 +++++ .../java/org/baeldung/config/WebConfig.java | 9 +-- .../src/main/resources/application.properties | 2 + .../test/java/org/baeldung/client/Consts.java | 5 ++ .../client/RestTemplateBasicLiveTest.java | 21 ++++- ...=> RedirectControllerIntegrationTest.java} | 16 ++-- ... => ExampleControllerIntegrationTest.java} | 2 +- 8 files changed, 121 insertions(+), 36 deletions(-) create mode 100644 spring-rest/src/main/java/org/baeldung/config/Application.java create mode 100644 spring-rest/src/main/resources/application.properties create mode 100644 spring-rest/src/test/java/org/baeldung/client/Consts.java rename {spring-security-rest-full => spring-rest}/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java (51%) rename spring-rest/src/test/java/org/baeldung/web/controller/redirect/{RedirectControllerTest.java => RedirectControllerIntegrationTest.java} (78%) rename spring-rest/src/test/java/org/baeldung/web/controller/status/{ExampleControllerTest.java => ExampleControllerIntegrationTest.java} (96%) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 6580f5ecc7..3c23f1bca7 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung spring-rest @@ -9,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.5.RELEASE + 1.4.2.RELEASE @@ -24,6 +25,10 @@ org.springframework.boot spring-boot-starter-actuator + + org.springframework.boot + spring-boot-devtools + @@ -49,7 +54,7 @@ commons-fileupload commons-fileupload - 1.3.1 + 1.3.2 @@ -73,9 +78,9 @@ - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + com.thoughtworks.xstream @@ -94,7 +99,7 @@ org.apache.commons commons-lang3 - 3.2.1 + 3.5 @@ -157,16 +162,21 @@ - com.jayway.restassured - rest-assured - ${rest-assured.version} - + com.jayway.restassured + rest-assured + ${rest-assured.version} + - + com.google.protobuf protobuf-java - 2.6.1 + 3.1.0 + + + com.googlecode.protobuf-java-format + protobuf-java-format + 1.4 @@ -206,7 +216,8 @@ maven-surefire-plugin - **/*LiveTest.java + **/*IntegrationTest.java + **/*LiveTest.java @@ -240,6 +251,36 @@ + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*IntegrationTest.java + + + + + + + + + + live @@ -292,6 +333,7 @@ + @@ -299,13 +341,13 @@ 4.3.11.Final - 5.1.39 + 5.1.40 5.2.2.Final - 19.0 + 20.0 3.4 @@ -323,7 +365,7 @@ 1.1.3 - 3.5.1 + 3.6.0 2.6 2.19.1 1.6.0 @@ -332,7 +374,8 @@ 3.4.1 - + + org.codehaus.mojo @@ -345,4 +388,5 @@ + diff --git a/spring-rest/src/main/java/org/baeldung/config/Application.java b/spring-rest/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..f7b74659c8 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,22 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.web.filter.ShallowEtagHeaderFilter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@EnableAutoConfiguration +@ComponentScan("org.baeldung") +public class Application extends WebMvcConfigurerAdapter { + + public static void main(final String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { + return new ShallowEtagHeaderFilter(); + } +} \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java index d116148f09..1516e9915c 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java @@ -17,9 +17,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter /* * Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml - * */ - @Configuration @EnableWebMvc @ComponentScan({ "org.baeldung.web" }) @@ -33,13 +31,14 @@ public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(final List> messageConverters) { - messageConverters.add(createXmlHttpMessageConverter()); - // messageConverters.add(new MappingJackson2HttpMessageConverter()); - final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.indentOutput(true).dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm")); messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); // messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); + + messageConverters.add(createXmlHttpMessageConverter()); + // messageConverters.add(new MappingJackson2HttpMessageConverter()); + messageConverters.add(new ProtobufHttpMessageConverter()); messageConverters.add(new KryoHttpMessageConverter()); super.configureMessageConverters(messageConverters); diff --git a/spring-rest/src/main/resources/application.properties b/spring-rest/src/main/resources/application.properties new file mode 100644 index 0000000000..300589f561 --- /dev/null +++ b/spring-rest/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port= 8082 +server.context-path=/spring-rest \ No newline at end of file diff --git a/spring-rest/src/test/java/org/baeldung/client/Consts.java b/spring-rest/src/test/java/org/baeldung/client/Consts.java new file mode 100644 index 0000000000..b40561d9c3 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/client/Consts.java @@ -0,0 +1,5 @@ +package org.baeldung.client; + +public interface Consts { + int APPLICATION_PORT = 8082; +} diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java similarity index 51% rename from spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java rename to spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java index 3516e5161d..9e968b94f3 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -1,6 +1,6 @@ package org.baeldung.client; -import static org.baeldung.Consts.APPLICATION_PORT; +import static org.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @@ -12,10 +12,13 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + public class RestTemplateBasicLiveTest { private RestTemplate restTemplate; - private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-security-rest-full/auth/foos"; + private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos"; @Before public void beforeTest() { @@ -26,9 +29,19 @@ public class RestTemplateBasicLiveTest { @Test public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { - final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl, String.class); - + ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } + + @Test + public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException { + ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode root = mapper.readTree(response.getBody()); + JsonNode name = root.path("name"); + assertThat(name.asText(), equalTo("bar")); + } } diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java similarity index 78% rename from spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerTest.java rename to spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java index cafaff7b07..b31bfcf5ec 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java @@ -1,6 +1,6 @@ package org.baeldung.web.controller.redirect; -import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash; @@ -24,7 +24,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("file:src/main/webapp/WEB-INF/api-servlet.xml") @WebAppConfiguration -public class RedirectControllerTest { +public class RedirectControllerIntegrationTest { private MockMvc mockMvc; @@ -38,30 +38,30 @@ public class RedirectControllerTest { @Test public void whenRedirectOnUrlWithUsingXMLConfig_thenStatusRedirectionAndRedirectedOnUrl() throws Exception { - mockMvc.perform(get("/redirectWithXMLConfig")).andExpect(status().is3xxRedirection()).andExpect(view().name("RedirectedUrl")).andExpect(model().attribute("attribute", is("redirectWithXMLConfig"))) + mockMvc.perform(get("/redirectWithXMLConfig")).andExpect(status().is3xxRedirection()).andExpect(view().name("RedirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithXMLConfig"))) .andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithXMLConfig")); } @Test public void whenRedirectOnUrlWithUsingRedirectPrefix_thenStatusRedirectionAndRedirectedOnUrl() throws Exception { - mockMvc.perform(get("/redirectWithRedirectPrefix")).andExpect(status().is3xxRedirection()).andExpect(view().name("redirect:/redirectedUrl")).andExpect(model().attribute("attribute", is("redirectWithRedirectPrefix"))) + mockMvc.perform(get("/redirectWithRedirectPrefix")).andExpect(status().is3xxRedirection()).andExpect(view().name("redirect:/redirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithRedirectPrefix"))) .andExpect(redirectedUrl("/redirectedUrl?attribute=redirectWithRedirectPrefix")); } @Test public void whenRedirectOnUrlWithUsingRedirectAttributes_thenStatusRedirectionAndRedirectedOnUrlAndAddedAttributeToFlashScope() throws Exception { - mockMvc.perform(get("/redirectWithRedirectAttributes")).andExpect(status().is3xxRedirection()).andExpect(flash().attribute("flashAttribute", is("redirectWithRedirectAttributes"))) - .andExpect(model().attribute("attribute", is("redirectWithRedirectAttributes"))).andExpect(model().attribute("flashAttribute", is(nullValue()))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectAttributes")); + mockMvc.perform(get("/redirectWithRedirectAttributes")).andExpect(status().is3xxRedirection()).andExpect(flash().attribute("flashAttribute", equalTo("redirectWithRedirectAttributes"))) + .andExpect(model().attribute("attribute", equalTo("redirectWithRedirectAttributes"))).andExpect(model().attribute("flashAttribute", equalTo(nullValue()))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectAttributes")); } @Test public void whenRedirectOnUrlWithUsingRedirectView_thenStatusRedirectionAndRedirectedOnUrlAndAddedAttributeToFlashScope() throws Exception { - mockMvc.perform(get("/redirectWithRedirectView")).andExpect(status().is3xxRedirection()).andExpect(model().attribute("attribute", is("redirectWithRedirectView"))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectView")); + mockMvc.perform(get("/redirectWithRedirectView")).andExpect(status().is3xxRedirection()).andExpect(model().attribute("attribute", equalTo("redirectWithRedirectView"))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectView")); } @Test public void whenRedirectOnUrlWithUsingForwardPrefix_thenStatusOkAndForwardedOnUrl() throws Exception { - mockMvc.perform(get("/forwardWithForwardPrefix")).andExpect(status().isOk()).andExpect(view().name("forward:/redirectedUrl")).andExpect(model().attribute("attribute", is("redirectWithForwardPrefix"))).andExpect(forwardedUrl("/redirectedUrl")); + mockMvc.perform(get("/forwardWithForwardPrefix")).andExpect(status().isOk()).andExpect(view().name("forward:/redirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithForwardPrefix"))).andExpect(forwardedUrl("/redirectedUrl")); } } diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java similarity index 96% rename from spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java rename to spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java index c50e1b4f43..e29bef501e 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java @@ -18,7 +18,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) @WebAppConfiguration -public class ExampleControllerTest { +public class ExampleControllerIntegrationTest { private MockMvc mockMvc; From 12de46529d7f37333b2cf862e3a4be929d7dd395 Mon Sep 17 00:00:00 2001 From: eugenp Date: Fri, 18 Nov 2016 14:10:21 +0200 Subject: [PATCH 10/38] cleanup work --- .../java/org/baeldung/config/Application.java | 6 ------ .../main/java/org/baeldung/config/WebConfig.java | 2 +- .../baeldung/web/controller/FooController.java | 3 +-- .../client/RestTemplateBasicLiveTest.java | 16 ++++++++++++++-- 4 files changed, 16 insertions(+), 11 deletions(-) diff --git a/spring-rest/src/main/java/org/baeldung/config/Application.java b/spring-rest/src/main/java/org/baeldung/config/Application.java index f7b74659c8..077213b04d 100644 --- a/spring-rest/src/main/java/org/baeldung/config/Application.java +++ b/spring-rest/src/main/java/org/baeldung/config/Application.java @@ -2,9 +2,7 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; -import org.springframework.web.filter.ShallowEtagHeaderFilter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @EnableAutoConfiguration @@ -15,8 +13,4 @@ public class Application extends WebMvcConfigurerAdapter { SpringApplication.run(Application.class, args); } - @Bean - public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { - return new ShallowEtagHeaderFilter(); - } } \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java index 1516e9915c..39c1252c4f 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java @@ -36,7 +36,7 @@ public class WebConfig extends WebMvcConfigurerAdapter { messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); // messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); - messageConverters.add(createXmlHttpMessageConverter()); + // messageConverters.add(createXmlHttpMessageConverter()); // messageConverters.add(new MappingJackson2HttpMessageConverter()); messageConverters.add(new ProtobufHttpMessageConverter()); diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java index dd1e3ca222..21ba3c6d13 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java @@ -1,7 +1,6 @@ package org.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import org.baeldung.web.dto.Foo; import org.baeldung.web.dto.FooProtos; @@ -26,7 +25,7 @@ public class FooController { @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { - return new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); + return new Foo(id, randomAlphabetic(4)); } // API - write diff --git a/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java index 9e968b94f3..e4321e163f 100644 --- a/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -2,10 +2,14 @@ package org.baeldung.client; import static org.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Matchers.notNull; import java.io.IOException; +import org.baeldung.web.dto.Foo; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpStatus; @@ -41,7 +45,15 @@ public class RestTemplateBasicLiveTest { ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(response.getBody()); JsonNode name = root.path("name"); - assertThat(name.asText(), equalTo("bar")); + assertThat(name.asText(), is(notNull())); } - + + @Test + public void givenResourceUrl_whenRetrievingResource_thenCorrect() throws IOException { + final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); + + assertThat(foo.getName(), notNullValue()); + assertThat(foo.getId(), is(1L)); + } + } From 6d8a11f0a6245f2f70b23aa189545b110a5ba08f Mon Sep 17 00:00:00 2001 From: Prashant Khanal Date: Fri, 18 Nov 2016 11:15:38 -0800 Subject: [PATCH 11/38] @Qualifier annotation removed --- .../java/com/baeldung/spring/controllers/MailController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java b/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java index 768a0f8e7b..286a661b65 100644 --- a/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java @@ -26,6 +26,7 @@ import java.util.Set; @Controller @RequestMapping("/mail") public class MailController { + @Autowired public EmailServiceImpl emailService; @@ -33,7 +34,6 @@ public class MailController { private String attachmentPath; @Autowired - @Qualifier("templateSimpleMessage") public SimpleMailMessage template; private static final Map> labels; From 224a3a8a42e2c005fa77adee45f362cb6ada5ae9 Mon Sep 17 00:00:00 2001 From: Parth Joshi Date: Sat, 19 Nov 2016 03:32:52 +0530 Subject: [PATCH 12/38] GeoIp Article PR (#789) * GEO Ip Article first commit. * Changes in controller and flow as per review by Kevin. * Removed this file from spring-mvc-java as I had worked on spring-mvc-xml and this was commited by mistake. * Some fix in service usage as i was initializing service, intializing the db in the each requests. * Changes for Integration Testing Config. Renaming the test file for the same purpose. * Removed integration profile. --- spring-mvc-xml/pom.xml | 7 +- .../controller/GeoIPTestController.java | 28 +++++++ .../java/com/baeldung/spring/form/GeoIP.java | 56 +++++++++++++ .../RawDBDemoGeoIPLocationService.java | 29 +++++++ spring-mvc-xml/src/main/webapp/GeoIpTest.jsp | 84 +++++++++++++++++++ .../baeldung/geoip/GeoIpIntegrationTest.java | 31 +++++++ 6 files changed, 234 insertions(+), 1 deletion(-) create mode 100644 spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java create mode 100644 spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java create mode 100644 spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java create mode 100644 spring-mvc-xml/src/main/webapp/GeoIpTest.jsp create mode 100644 spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 849699cfae..ca51a56633 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -112,6 +112,11 @@ commons-io 2.2 + + com.maxmind.geoip2 + geoip2 + 2.8.0 + @@ -146,7 +151,7 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java new file mode 100644 index 0000000000..16de4e56f5 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.controller; + +import java.io.IOException; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.spring.form.GeoIP; +import com.baeldung.spring.service.RawDBDemoGeoIPLocationService; + +@Controller +public class GeoIPTestController { + private RawDBDemoGeoIPLocationService locationService; + public GeoIPTestController() throws IOException { + locationService + = new RawDBDemoGeoIPLocationService(); + } + @RequestMapping(value="/GeoIPTest", method = RequestMethod.POST) + @ResponseBody + public GeoIP getLocation( + @RequestParam(value="ipAddress", required=true) String ipAddress) throws Exception { + + return locationService.getLocation(ipAddress); + } +} diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java new file mode 100644 index 0000000000..19f56867a1 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java @@ -0,0 +1,56 @@ +package com.baeldung.spring.form; + +public class GeoIP { + private String ipAddress; + private String city; + private String latitude; + private String longitude; + + public GeoIP() { + + } + + public GeoIP(String ipAddress) { + this.ipAddress = ipAddress; + } + + public GeoIP(String ipAddress, String city, String latitude, String longitude) { + this.ipAddress = ipAddress; + this.city = city; + this.latitude = latitude; + this.longitude = longitude; + } + + public String getIpAddress() { + return ipAddress; + } + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getLatitude() { + return latitude; + } + + public void setLatitude(String latitude) { + this.latitude = latitude; + } + + public String getLongitude() { + return longitude; + } + + public void setLongitude(String longitude) { + this.longitude = longitude; + } + +} 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 new file mode 100644 index 0000000000..0a292ab1e9 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.service; + +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; + +import com.baeldung.spring.form.GeoIP; +import com.maxmind.geoip2.DatabaseReader; +import com.maxmind.geoip2.exception.GeoIp2Exception; +import com.maxmind.geoip2.model.CityResponse; + +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"); + dbReader = new DatabaseReader.Builder(database).build(); + } + + public GeoIP getLocation(String ip) throws IOException, GeoIp2Exception { + InetAddress ipAddress = InetAddress.getByName(ip); + CityResponse response = dbReader.city(ipAddress); + + String cityName = response.getCity().getName(); + String latitude = response.getLocation().getLatitude().toString(); + String longitude = response.getLocation().getLongitude().toString(); + return new GeoIP(ip, cityName, latitude, longitude); + } +} diff --git a/spring-mvc-xml/src/main/webapp/GeoIpTest.jsp b/spring-mvc-xml/src/main/webapp/GeoIpTest.jsp new file mode 100644 index 0000000000..431f6162bc --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/GeoIpTest.jsp @@ -0,0 +1,84 @@ + + + + +Geo IP Test + + + + + + + + +
+ + + +
+ +
+ +
+ + + + \ 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 new file mode 100644 index 0000000000..72d528095e --- /dev/null +++ b/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.geoip; + +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; + +import org.junit.Test; + +import com.maxmind.geoip2.DatabaseReader; +import com.maxmind.geoip2.exception.GeoIp2Exception; +import com.maxmind.geoip2.model.CityResponse; + + +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"); + DatabaseReader dbReader = new DatabaseReader.Builder(database).build(); + + InetAddress ipAddress = InetAddress.getByName("202.47.112.9"); + CityResponse response = dbReader.city(ipAddress); + + String countryName = response.getCountry().getName(); + String cityName = response.getCity().getName(); + String postal = response.getPostal().getCode(); + String state = response.getLeastSpecificSubdivision().getName(); + + } + +} From da66ba895517026dc147bc23e0fab945298b2b5a Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 19 Nov 2016 08:30:42 +0200 Subject: [PATCH 13/38] Remove unnecessary comments --- .../java/com/baeldung/spring/controllers/MailController.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java b/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java index 286a661b65..ff828ca9ec 100644 --- a/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java @@ -20,9 +20,6 @@ import java.util.Iterator; import java.util.Map; import java.util.Set; -/** - * Created by Olga on 7/20/2016. - */ @Controller @RequestMapping("/mail") public class MailController { From 5f99e5aedd6fc64c4266104c72674b372b7d57e7 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sat, 19 Nov 2016 09:47:17 +0100 Subject: [PATCH 14/38] 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 15/38] 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 42fc383518761be292e36041cc3d0f81f27ed7b2 Mon Sep 17 00:00:00 2001 From: DianeDuan Date: Sun, 20 Nov 2016 10:52:09 +0800 Subject: [PATCH 16/38] FactoryBean example code --- .../factorybean/FactoryBeanAppConfig.java | 25 +++++++ .../InitializationToolFactory.java | 68 ++++++++++++++++++ .../factorybean/NonSingleToolFactory.java | 56 +++++++++++++++ .../factorybean/PostConstructToolFactory.java | 69 +++++++++++++++++++ .../factorybean/SingleToolFactory.java | 53 ++++++++++++++ .../java/com/baeldung/factorybean/Tool.java | 40 +++++++++++ .../com/baeldung/factorybean/ToolFactory.java | 57 +++++++++++++++ .../java/com/baeldung/factorybean/Worker.java | 30 ++++++++ .../factorybean-abstract-spring-ctx.xml | 39 +++++++++++ .../resources/factorybean-init-spring-ctx.xml | 17 +++++ .../factorybean-postconstruct-spring-ctx.xml | 20 ++++++ .../main/resources/factorybean-spring-ctx.xml | 17 +++++ .../factorybean/AbstractFactoryBeanTest.java | 35 ++++++++++ .../FactoryBeanInitializeTest.java | 17 +++++ .../baeldung/factorybean/FactoryBeanTest.java | 39 +++++++++++ 15 files changed, 582 insertions(+) create mode 100644 spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java create mode 100644 spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java create mode 100644 spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java create mode 100644 spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java create mode 100644 spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java create mode 100644 spring-core/src/main/java/com/baeldung/factorybean/Tool.java create mode 100644 spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java create mode 100644 spring-core/src/main/java/com/baeldung/factorybean/Worker.java create mode 100644 spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml create mode 100644 spring-core/src/main/resources/factorybean-init-spring-ctx.xml create mode 100644 spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml create mode 100644 spring-core/src/main/resources/factorybean-spring-ctx.xml create mode 100644 spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java create mode 100644 spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java create mode 100644 spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java diff --git a/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java b/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java new file mode 100644 index 0000000000..ab36df27cb --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java @@ -0,0 +1,25 @@ +package com.baeldung.factorybean; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class FactoryBeanAppConfig { + @Bean + public ToolFactory tool() { + ToolFactory factory = new ToolFactory(); + factory.setFactoryId(7070); + factory.setToolId(2); + factory.setToolName("wrench"); + factory.setToolPrice(3.7); + return factory; + } + + @Bean + public Worker worker() throws Exception { + Worker worker = new Worker(); + worker.setNumber("1002"); + worker.setTool(tool().getObject()); + return worker; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java new file mode 100644 index 0000000000..925ba2d8e4 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java @@ -0,0 +1,68 @@ +package com.baeldung.factorybean; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; + +public class InitializationToolFactory implements FactoryBean, InitializingBean { + private int factoryId;// standard setters and getters + private int toolId;// standard setters and getters + private String toolName;// standard setters and getters + private double toolPrice;// standard setters and getters + + @Override + public void afterPropertiesSet() throws Exception { + if (toolName == null || toolName.equals("")) { + throw new IllegalArgumentException("tool name cannot be empty"); + } + if (toolPrice < 0) { + throw new IllegalArgumentException("tool price should not be less than 0"); + } + } + + @Override + public Tool getObject() throws Exception { + return new Tool(toolId, toolName, toolPrice); + } + + @Override + public Class getObjectType() { + return Tool.class; + } + + @Override + public boolean isSingleton() { + return false; + } + + public int getFactoryId() { + return factoryId; + } + + public void setFactoryId(int factoryId) { + this.factoryId = factoryId; + } + + public int getToolId() { + return toolId; + } + + public void setToolId(int toolId) { + this.toolId = toolId; + } + + public String getToolName() { + return toolName; + } + + public void setToolName(String toolName) { + this.toolName = toolName; + } + + public double getToolPrice() { + return toolPrice; + } + + public void setToolPrice(double toolPrice) { + this.toolPrice = toolPrice; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java new file mode 100644 index 0000000000..0cd80eab41 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java @@ -0,0 +1,56 @@ +package com.baeldung.factorybean; + +import org.springframework.beans.factory.config.AbstractFactoryBean; + +public class NonSingleToolFactory extends AbstractFactoryBean { + private int factoryId;// standard setters and getters + private int toolId;// standard setters and getters + private String toolName;// standard setters and getters + private double toolPrice;// standard setters and getters + + public NonSingleToolFactory() { + setSingleton(false); + } + + @Override + public Class getObjectType() { + return Tool.class; + } + + @Override + protected Tool createInstance() throws Exception { + return new Tool(toolId, toolName, toolPrice); + } + + public int getFactoryId() { + return factoryId; + } + + public void setFactoryId(int factoryId) { + this.factoryId = factoryId; + } + + public int getToolId() { + return toolId; + } + + public void setToolId(int toolId) { + this.toolId = toolId; + } + + public String getToolName() { + return toolName; + } + + public void setToolName(String toolName) { + this.toolName = toolName; + } + + public double getToolPrice() { + return toolPrice; + } + + public void setToolPrice(double toolPrice) { + this.toolPrice = toolPrice; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java new file mode 100644 index 0000000000..8298f6f4db --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java @@ -0,0 +1,69 @@ +package com.baeldung.factorybean; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.FactoryBean; + +public class PostConstructToolFactory implements FactoryBean { + private int factoryId;// standard setters and getters + private int toolId;// standard setters and getters + private String toolName;// standard setters and getters + private double toolPrice;// standard setters and getters + + @Override + public Tool getObject() throws Exception { + return new Tool(toolId, toolName, toolPrice); + } + + @Override + public Class getObjectType() { + return Tool.class; + } + + @Override + public boolean isSingleton() { + return false; + } + + @PostConstruct + public void checkParams() { + if (toolName == null || toolName.equals("")) { + throw new IllegalArgumentException("tool name cannot be empty"); + } + if (toolPrice < 0) { + throw new IllegalArgumentException("tool price should not be less than 0"); + } + } + + public int getFactoryId() { + return factoryId; + } + + public void setFactoryId(int factoryId) { + this.factoryId = factoryId; + } + + public int getToolId() { + return toolId; + } + + public void setToolId(int toolId) { + this.toolId = toolId; + } + + public String getToolName() { + return toolName; + } + + public void setToolName(String toolName) { + this.toolName = toolName; + } + + public double getToolPrice() { + return toolPrice; + } + + public void setToolPrice(double toolPrice) { + this.toolPrice = toolPrice; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java new file mode 100644 index 0000000000..94d68ef113 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java @@ -0,0 +1,53 @@ +package com.baeldung.factorybean; + +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;// standard setters and getters + private int toolId;// standard setters and getters + private String toolName;// standard setters and getters + private double toolPrice;// standard setters and getters + + @Override + public Class getObjectType() { + return Tool.class; + } + + @Override + protected Tool createInstance() throws Exception { + return new Tool(toolId, toolName, toolPrice); + } + + public int getFactoryId() { + return factoryId; + } + + public void setFactoryId(int factoryId) { + this.factoryId = factoryId; + } + + public int getToolId() { + return toolId; + } + + public void setToolId(int toolId) { + this.toolId = toolId; + } + + public String getToolName() { + return toolName; + } + + public void setToolName(String toolName) { + this.toolName = toolName; + } + + public double getToolPrice() { + return toolPrice; + } + + public void setToolPrice(double toolPrice) { + this.toolPrice = toolPrice; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/Tool.java b/spring-core/src/main/java/com/baeldung/factorybean/Tool.java new file mode 100644 index 0000000000..abdd074e9a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/Tool.java @@ -0,0 +1,40 @@ +package com.baeldung.factorybean; + +public class Tool { + private int id;// standard setters and getters + private String name;// standard setters and getters + private double price;// standard setters and getters + + public Tool() { + } + + public Tool(int id, String name, double price) { + this.id = id; + this.name = name; + this.price = price; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java new file mode 100644 index 0000000000..9b2f7fa42e --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java @@ -0,0 +1,57 @@ +package com.baeldung.factorybean; + +import org.springframework.beans.factory.FactoryBean; + +public class ToolFactory implements FactoryBean { + private int factoryId;// standard setters and getters + private int toolId;// standard setters and getters + private String toolName;// standard setters and getters + private double toolPrice;// standard setters and getters + + @Override + public Tool getObject() throws Exception { + return new Tool(toolId, toolName, toolPrice); + } + + @Override + public Class getObjectType() { + return Tool.class; + } + + @Override + public boolean isSingleton() { + return false; + } + + public int getFactoryId() { + return factoryId; + } + + public void setFactoryId(int factoryId) { + this.factoryId = factoryId; + } + + public int getToolId() { + return toolId; + } + + public void setToolId(int toolId) { + this.toolId = toolId; + } + + public String getToolName() { + return toolName; + } + + public void setToolName(String toolName) { + this.toolName = toolName; + } + + public double getToolPrice() { + return toolPrice; + } + + public void setToolPrice(double toolPrice) { + this.toolPrice = toolPrice; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/Worker.java b/spring-core/src/main/java/com/baeldung/factorybean/Worker.java new file mode 100644 index 0000000000..070322a5f9 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/Worker.java @@ -0,0 +1,30 @@ +package com.baeldung.factorybean; + +public class Worker { + private String number;// standard setters and getters + private Tool tool;// standard setters and getters + + public Worker() { + } + + public Worker(String number, Tool tool) { + this.number = number; + this.tool = tool; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } + + public Tool getTool() { + return tool; + } + + public void setTool(Tool tool) { + this.tool = tool; + } +} diff --git a/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml b/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml new file mode 100644 index 0000000000..2f34e2e1cf --- /dev/null +++ b/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-core/src/main/resources/factorybean-init-spring-ctx.xml b/spring-core/src/main/resources/factorybean-init-spring-ctx.xml new file mode 100644 index 0000000000..f5835c1e70 --- /dev/null +++ b/spring-core/src/main/resources/factorybean-init-spring-ctx.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml b/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml new file mode 100644 index 0000000000..81e02a0b35 --- /dev/null +++ b/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-core/src/main/resources/factorybean-spring-ctx.xml b/spring-core/src/main/resources/factorybean-spring-ctx.xml new file mode 100644 index 0000000000..800e489ba0 --- /dev/null +++ b/spring-core/src/main/resources/factorybean-spring-ctx.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java b/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java new file mode 100644 index 0000000000..790107f114 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java @@ -0,0 +1,35 @@ +package com.baeldung.factorybean; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +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"); + + Worker worker1 = (Worker) context.getBean("worker1"); + Worker worker2 = (Worker) context.getBean("worker2"); + + assertThat(worker1.getNumber(), equalTo("50001")); + assertThat(worker2.getNumber(), equalTo("50002")); + assertTrue(worker1.getTool() == worker2.getTool()); + } + + @Test + public void testNonSingleToolFactory() { + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-abstract-spring-ctx.xml"); + + Worker worker3 = (Worker) context.getBean("worker3"); + Worker worker4 = (Worker) context.getBean("worker4"); + + assertThat(worker3.getNumber(), equalTo("50003")); + assertThat(worker4.getNumber(), equalTo("50004")); + assertTrue(worker3.getTool() != worker4.getTool()); + } +} diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java new file mode 100644 index 0000000000..851c15a3ec --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java @@ -0,0 +1,17 @@ +package com.baeldung.factorybean; + +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class FactoryBeanInitializeTest { + @Test(expected = Exception.class) + public void testInitializationToolFactory() { + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-init-spring-ctx.xml"); + } + + @Test(expected = Exception.class) + public void testPostConstructToolFactory() { + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-postconstruct-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 new file mode 100644 index 0000000000..d06448b63c --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java @@ -0,0 +1,39 @@ +package com.baeldung.factorybean; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + +import org.junit.Test; +import org.springframework.context.ApplicationContext; +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"); + + Worker worker = (Worker) context.getBean("worker"); + assertThat(worker.getNumber(), equalTo("1001")); + assertThat(worker.getTool().getId(), equalTo(1)); + assertThat(worker.getTool().getName(), equalTo("screwdriver")); + assertThat(worker.getTool().getPrice(), equalTo(1.5)); + + ToolFactory toolFactory = (ToolFactory) context.getBean("&tool"); + assertThat(toolFactory.getFactoryId(), equalTo(9090)); + } + + @Test + public void testConstructWorkerByJava() { + ApplicationContext context = new AnnotationConfigApplicationContext(FactoryBeanAppConfig.class); + + Worker worker = (Worker) context.getBean("worker"); + assertThat(worker.getNumber(), equalTo("1002")); + assertThat(worker.getTool().getId(), equalTo(2)); + assertThat(worker.getTool().getName(), equalTo("wrench")); + assertThat(worker.getTool().getPrice(), equalTo(3.7)); + + ToolFactory toolFactory = (ToolFactory) context.getBean("&tool"); + assertThat(toolFactory.getFactoryId(), equalTo(7070)); + } +} From d13f7b9ed83abfc1317d503958e179f20d872f8a Mon Sep 17 00:00:00 2001 From: DianeDuan Date: Sun, 20 Nov 2016 11:22:42 +0800 Subject: [PATCH 17/38] delete last topic code --- .../properties/PropertiesDefaultListTest.java | 30 ------ .../properties/PropertiesLoadTest.java | 32 ------ .../properties/PropertiesOperationsTest.java | 97 ------------------- .../properties/PropertiesStoreTest.java | 51 ---------- core-java/src/test/resources/app.properties | 3 - core-java/src/test/resources/catalog | 3 - .../src/test/resources/default.properties | 4 - core-java/src/test/resources/icons.xml | 8 -- 8 files changed, 228 deletions(-) delete mode 100644 core-java/src/test/java/com/baeldung/properties/PropertiesDefaultListTest.java delete mode 100644 core-java/src/test/java/com/baeldung/properties/PropertiesLoadTest.java delete mode 100644 core-java/src/test/java/com/baeldung/properties/PropertiesOperationsTest.java delete mode 100644 core-java/src/test/java/com/baeldung/properties/PropertiesStoreTest.java delete mode 100644 core-java/src/test/resources/app.properties delete mode 100644 core-java/src/test/resources/catalog delete mode 100644 core-java/src/test/resources/default.properties delete mode 100644 core-java/src/test/resources/icons.xml diff --git a/core-java/src/test/java/com/baeldung/properties/PropertiesDefaultListTest.java b/core-java/src/test/java/com/baeldung/properties/PropertiesDefaultListTest.java deleted file mode 100644 index 704bb19759..0000000000 --- a/core-java/src/test/java/com/baeldung/properties/PropertiesDefaultListTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.properties; - -import org.junit.Test; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Properties; - -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertThat; - -public class PropertiesDefaultListTest { - @Test - public void testDefaultList() throws IOException { - String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); - String defaultConfigPath = rootPath + "default.properties"; - String appConfigPath = rootPath + "app.properties"; - - Properties defaultProps = new Properties(); - defaultProps.load(new FileInputStream(defaultConfigPath)); - - Properties appProps = new Properties(defaultProps); - appProps.load(new FileInputStream(appConfigPath)); - - assertThat(appProps.getProperty("name"), equalTo("TestApp")); - assertThat(appProps.getProperty("version"), equalTo("1.0")); - assertThat(appProps.getProperty("site"), equalTo("www.google.com")); - } -} diff --git a/core-java/src/test/java/com/baeldung/properties/PropertiesLoadTest.java b/core-java/src/test/java/com/baeldung/properties/PropertiesLoadTest.java deleted file mode 100644 index bcf386bd0f..0000000000 --- a/core-java/src/test/java/com/baeldung/properties/PropertiesLoadTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.properties; - -import org.junit.Test; - -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Properties; - -public class PropertiesLoadTest { - @Test - public void testLoadFromPropertiesFiles() throws IOException { - String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); - String appConfigPath = rootPath + "app.properties"; - String catalogConfigPath = rootPath + "catalog"; - - // load from properties file which use .properties as the suffix - Properties appProps = new Properties(); - appProps.load(new FileInputStream(appConfigPath)); - - // load from properties file which not use .properties as the suffix - Properties catalogProps = new Properties(); - catalogProps.load(new FileInputStream(catalogConfigPath)); - } - - @Test - public void testLoadFromXmlFile() throws IOException { - String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); - String iconConfigPath = rootPath + "icons.xml"; - Properties iconProps = new Properties(); - iconProps.loadFromXML(new FileInputStream(iconConfigPath)); - } -} diff --git a/core-java/src/test/java/com/baeldung/properties/PropertiesOperationsTest.java b/core-java/src/test/java/com/baeldung/properties/PropertiesOperationsTest.java deleted file mode 100644 index 20aa64c385..0000000000 --- a/core-java/src/test/java/com/baeldung/properties/PropertiesOperationsTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.baeldung.properties; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import org.junit.Before; -import org.junit.Test; -import org.testng.annotations.BeforeClass; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Enumeration; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -public class PropertiesOperationsTest { - private Properties appProps; - - @Before - public void beforeClass() throws IOException { - String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); - String appConfigPath = rootPath + "app.properties"; - appProps = new Properties(); - appProps.load(new FileInputStream(appConfigPath)); - } - - @Test - public void testGetProperties() { - String appVersion = appProps.getProperty("version"); - String appName = appProps.getProperty("name", "defaultName"); - String appGroup = appProps.getProperty("group", "baeldung"); - String appDownloadAddr = appProps.getProperty("downloadAddr"); - - assertThat(appVersion, equalTo("1.0")); - assertThat(appName, equalTo("TestApp")); - assertThat(appGroup, equalTo("baeldung")); - assertThat(appDownloadAddr, equalTo(null)); - } - - @Test - public void testSetProperties() { - appProps.setProperty("name", "NewAppName"); - appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); - - String appName = appProps.getProperty("name"); - String appDownloadAddr = appProps.getProperty("downloadAddr"); - - assertThat(appName, equalTo("NewAppName")); - assertThat(appDownloadAddr, equalTo("www.baeldung.com/downloads")); - } - - @Test - public void testRemoveProperties() { - String versionBeforeRemoval = appProps.getProperty("version"); - assertThat(versionBeforeRemoval, equalTo("1.0")); - - appProps.remove("version"); - - String versionAfterRemoval = appProps.getProperty("version"); - assertThat(versionAfterRemoval, equalTo(null)); - } - - @Test - public void testGetEnumerationOfValues() { - Enumeration valueEnumeration = appProps.elements(); - List values = Lists.newArrayList(); - while (valueEnumeration.hasMoreElements()) { - String val = String.valueOf(valueEnumeration.nextElement()); - values.add(val); - } - assertArrayEquals(new String[] {"1.0", "2016-11-12", "TestApp"}, values.toArray()); - } - - @Test - public void testGetEnumerationOfKeys() { - Enumeration keyEnumeration = appProps.keys(); - List keys = Lists.newArrayList(); - while (keyEnumeration.hasMoreElements()) { - String key = String.valueOf(keyEnumeration.nextElement()); - keys.add(key); - } - assertArrayEquals(new String[] {"version", "date", "name"}, keys.toArray()); - } - - @Test - public void testGetSize() { - int size = appProps.size(); - assertThat(size, equalTo(3)); - } -} diff --git a/core-java/src/test/java/com/baeldung/properties/PropertiesStoreTest.java b/core-java/src/test/java/com/baeldung/properties/PropertiesStoreTest.java deleted file mode 100644 index 582fdb3808..0000000000 --- a/core-java/src/test/java/com/baeldung/properties/PropertiesStoreTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.properties; - -import org.junit.Before; -import org.junit.Test; -import org.testng.annotations.BeforeClass; - -import java.io.*; -import java.util.Properties; - -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertThat; - -public class PropertiesStoreTest { - private static Properties appProps = new Properties(); - - @Before - public void before() throws IOException { - String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); - String appConfigPath = rootPath + "app.properties"; - - // load the original properties - appProps.load(new FileInputStream(appConfigPath)); - - // update property list - appProps.setProperty("name", "NewAppName"); - appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); - } - - @Test - public void testStoreToPropertiesFile() throws IOException { - String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); - String newAppConfigPropertiesFile = rootPath + "newApp.properties"; - appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file"); - - - Properties verifyProps = new Properties(); - verifyProps.load(new FileInputStream(newAppConfigPropertiesFile)); - assertThat(verifyProps.getProperty("name"), equalTo("NewAppName")); - } - - @Test - public void testStoreToXmlFile() throws IOException { - String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); - String newAppConfigXmlFile = rootPath + "newApp.xml"; - appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file"); - - Properties verifyProps = new Properties(); - verifyProps.loadFromXML(new FileInputStream(newAppConfigXmlFile)); - assertThat(verifyProps.getProperty("downloadAddr"), equalTo("www.baeldung.com/downloads")); - } -} diff --git a/core-java/src/test/resources/app.properties b/core-java/src/test/resources/app.properties deleted file mode 100644 index ff6174ec2a..0000000000 --- a/core-java/src/test/resources/app.properties +++ /dev/null @@ -1,3 +0,0 @@ -version=1.0 -name=TestApp -date=2016-11-12 \ No newline at end of file diff --git a/core-java/src/test/resources/catalog b/core-java/src/test/resources/catalog deleted file mode 100644 index 488513d0ce..0000000000 --- a/core-java/src/test/resources/catalog +++ /dev/null @@ -1,3 +0,0 @@ -c1=files -c2=images -c3=videos \ No newline at end of file diff --git a/core-java/src/test/resources/default.properties b/core-java/src/test/resources/default.properties deleted file mode 100644 index df1bab371c..0000000000 --- a/core-java/src/test/resources/default.properties +++ /dev/null @@ -1,4 +0,0 @@ -site=www.google.com -name=DefaultAppName -topic=Properties -category=core-java \ No newline at end of file diff --git a/core-java/src/test/resources/icons.xml b/core-java/src/test/resources/icons.xml deleted file mode 100644 index 0db7b2699a..0000000000 --- a/core-java/src/test/resources/icons.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - xml example - icon1.jpg - icon2.jpg - icon3.jpg - \ No newline at end of file From a8fb4e11cb24c4572d888fc434d70069fb035e5a Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 20 Nov 2016 11:57:27 +0200 Subject: [PATCH 18/38] 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 19/38] 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 20/38] 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 21/38] 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 22/38] 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 23/38] 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 24/38] 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 25/38] 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 77240dc024831aa643e0c2c885e09e92c15fbf7a Mon Sep 17 00:00:00 2001 From: DianeDuan Date: Mon, 21 Nov 2016 20:41:33 +0800 Subject: [PATCH 26/38] delete extra comments and variable assignments, use guava precondition for check --- spring-core/pom.xml | 5 +++++ .../InitializationToolFactory.java | 19 +++++++++---------- .../factorybean/NonSingleToolFactory.java | 8 ++++---- .../factorybean/PostConstructToolFactory.java | 19 +++++++++---------- .../factorybean/SingleToolFactory.java | 8 ++++---- .../java/com/baeldung/factorybean/Tool.java | 6 +++--- .../com/baeldung/factorybean/ToolFactory.java | 8 ++++---- .../java/com/baeldung/factorybean/Worker.java | 4 ++-- .../factorybean-abstract-spring-ctx.xml | 4 ++-- .../resources/factorybean-init-spring-ctx.xml | 4 ++-- .../factorybean-postconstruct-spring-ctx.xml | 4 ++-- .../main/resources/factorybean-spring-ctx.xml | 4 ++-- .../FactoryBeanInitializeTest.java | 5 ++--- 13 files changed, 50 insertions(+), 48 deletions(-) diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 798a717d01..e8ab8b00c4 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -50,6 +50,11 @@ 4.12 test + + com.google.guava + guava + 20.0 + 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 925ba2d8e4..6d2fd2564e 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java @@ -1,22 +1,21 @@ package com.baeldung.factorybean; +import static com.google.common.base.Preconditions.checkArgument; + import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; +import org.springframework.util.StringUtils; public class InitializationToolFactory implements FactoryBean, InitializingBean { - private int factoryId;// standard setters and getters - private int toolId;// standard setters and getters - private String toolName;// standard setters and getters - private double toolPrice;// standard setters and getters + private int factoryId; + private int toolId; + private String toolName; + private double toolPrice; @Override public void afterPropertiesSet() throws Exception { - if (toolName == null || toolName.equals("")) { - throw new IllegalArgumentException("tool name cannot be empty"); - } - if (toolPrice < 0) { - throw new IllegalArgumentException("tool price should not be less than 0"); - } + checkArgument(!StringUtils.isEmpty(toolName), "tool name cannot be empty"); + checkArgument(toolPrice >= 0, "tool price should not be less than 0"); } @Override 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 0cd80eab41..c818b775eb 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java @@ -3,10 +3,10 @@ package com.baeldung.factorybean; import org.springframework.beans.factory.config.AbstractFactoryBean; public class NonSingleToolFactory extends AbstractFactoryBean { - private int factoryId;// standard setters and getters - private int toolId;// standard setters and getters - private String toolName;// standard setters and getters - private double toolPrice;// standard setters and getters + private int factoryId; + private int toolId; + private String toolName; + private double toolPrice; public NonSingleToolFactory() { setSingleton(false); 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 8298f6f4db..47db05d271 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java @@ -1,14 +1,17 @@ package com.baeldung.factorybean; +import static com.google.common.base.Preconditions.checkArgument; + import javax.annotation.PostConstruct; import org.springframework.beans.factory.FactoryBean; +import org.springframework.util.StringUtils; public class PostConstructToolFactory implements FactoryBean { - private int factoryId;// standard setters and getters - private int toolId;// standard setters and getters - private String toolName;// standard setters and getters - private double toolPrice;// standard setters and getters + private int factoryId; + private int toolId; + private String toolName; + private double toolPrice; @Override public Tool getObject() throws Exception { @@ -27,12 +30,8 @@ public class PostConstructToolFactory implements FactoryBean { @PostConstruct public void checkParams() { - if (toolName == null || toolName.equals("")) { - throw new IllegalArgumentException("tool name cannot be empty"); - } - if (toolPrice < 0) { - throw new IllegalArgumentException("tool price should not be less than 0"); - } + checkArgument(!StringUtils.isEmpty(toolName), "tool name cannot be empty"); + checkArgument(toolPrice >= 0, "tool price should not be less than 0"); } public int getFactoryId() { 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 94d68ef113..bc0c2d79c0 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java @@ -4,10 +4,10 @@ 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;// standard setters and getters - private int toolId;// standard setters and getters - private String toolName;// standard setters and getters - private double toolPrice;// standard setters and getters + private int factoryId; + private int toolId; + private String toolName; + private double toolPrice; @Override public Class getObjectType() { 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 abdd074e9a..a7f7f7681e 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/Tool.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/Tool.java @@ -1,9 +1,9 @@ package com.baeldung.factorybean; public class Tool { - private int id;// standard setters and getters - private String name;// standard setters and getters - private double price;// standard setters and getters + private int id; + private String name; + private double price; public Tool() { } 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 9b2f7fa42e..ca8f82eadb 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java @@ -3,10 +3,10 @@ package com.baeldung.factorybean; import org.springframework.beans.factory.FactoryBean; public class ToolFactory implements FactoryBean { - private int factoryId;// standard setters and getters - private int toolId;// standard setters and getters - private String toolName;// standard setters and getters - private double toolPrice;// standard setters and getters + private int factoryId; + private int toolId; + private String toolName; + private double toolPrice; @Override public Tool getObject() throws Exception { 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 070322a5f9..9a35c0656b 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/Worker.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/Worker.java @@ -1,8 +1,8 @@ package com.baeldung.factorybean; public class Worker { - private String number;// standard setters and getters - private Tool tool;// standard setters and getters + private String number; + private Tool tool; public Worker() { } 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 2f34e2e1cf..6bce114d9c 100644 --- a/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml +++ b/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml @@ -1,6 +1,6 @@ - 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 f5835c1e70..47722b6d3d 100644 --- a/spring-core/src/main/resources/factorybean-init-spring-ctx.xml +++ b/spring-core/src/main/resources/factorybean-init-spring-ctx.xml @@ -1,6 +1,6 @@ - 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 81e02a0b35..94a4f407a8 100644 --- a/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml +++ b/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml @@ -1,7 +1,7 @@ - diff --git a/spring-core/src/main/resources/factorybean-spring-ctx.xml b/spring-core/src/main/resources/factorybean-spring-ctx.xml index 800e489ba0..ab0c646bb0 100644 --- a/spring-core/src/main/resources/factorybean-spring-ctx.xml +++ b/spring-core/src/main/resources/factorybean-spring-ctx.xml @@ -1,6 +1,6 @@ - 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 851c15a3ec..848eea216a 100644 --- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java @@ -1,17 +1,16 @@ package com.baeldung.factorybean; import org.junit.Test; -import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class FactoryBeanInitializeTest { @Test(expected = Exception.class) public void testInitializationToolFactory() { - ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-init-spring-ctx.xml"); + new ClassPathXmlApplicationContext("classpath:factorybean-init-spring-ctx.xml"); } @Test(expected = Exception.class) public void testPostConstructToolFactory() { - ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-postconstruct-spring-ctx.xml"); + new ClassPathXmlApplicationContext("classpath:factorybean-postconstruct-spring-ctx.xml"); } } From 4d4afa6ca454b0172260e8cc210e7215442746c3 Mon Sep 17 00:00:00 2001 From: Ivan Paolillo Date: Mon, 21 Nov 2016 13:53:37 +0100 Subject: [PATCH 27/38] 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 e84957c768eace2e933a935d6c76d87bc251fcd8 Mon Sep 17 00:00:00 2001 From: DianeDuan Date: Mon, 21 Nov 2016 21:51:20 +0800 Subject: [PATCH 28/38] change expect exception in ut --- .../com/baeldung/factorybean/FactoryBeanInitializeTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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 848eea216a..673bab6f63 100644 --- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java @@ -1,15 +1,16 @@ package com.baeldung.factorybean; import org.junit.Test; +import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.support.ClassPathXmlApplicationContext; public class FactoryBeanInitializeTest { - @Test(expected = Exception.class) + @Test(expected = BeanCreationException.class) public void testInitializationToolFactory() { new ClassPathXmlApplicationContext("classpath:factorybean-init-spring-ctx.xml"); } - @Test(expected = Exception.class) + @Test(expected = BeanCreationException.class) public void testPostConstructToolFactory() { new ClassPathXmlApplicationContext("classpath:factorybean-postconstruct-spring-ctx.xml"); } From c1f94aab9265271376ff299f61597496e083ea45 Mon Sep 17 00:00:00 2001 From: James Kerak Date: Mon, 21 Nov 2016 09:12:30 -0500 Subject: [PATCH 29/38] 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 30/38] 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 31/38] 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 32/38] 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 33/38] 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 34/38] 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 35/38] 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 36/38] 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 37/38] 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 38/38] 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