From 22207e646b504c269c0484e1883fa8b9de5a80c8 Mon Sep 17 00:00:00 2001 From: Pritam Banerjee Date: Sat, 15 Oct 2016 14:40:20 -0700 Subject: [PATCH 01/74] 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/74] 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/74] 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/74] 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/74] 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/74] 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 858d14baf308f7e22ddf8d96ddb0587cf106b538 Mon Sep 17 00:00:00 2001 From: oreva Date: Sat, 19 Nov 2016 21:14:40 +0200 Subject: [PATCH 07/74] 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 08/74] 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 09/74] 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 10/74] 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 11/74] 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 12/74] 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 13/74] 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 2186f6412677edef05a2700775b4cbbf6ed3b3b6 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sun, 20 Nov 2016 22:35:17 +0100 Subject: [PATCH 14/74] 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 15/74] 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 16/74] Code improvement --- .../src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index 19bfd6d46b..7a5f598569 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -20,9 +20,6 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/api-servlet.xml") public class OkHttpGetLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; From 652dcd2804f215d5a2fb175d07a8f0b3dc61c603 Mon Sep 17 00:00:00 2001 From: michal_aibin Date: Mon, 21 Nov 2016 12:39:44 +0100 Subject: [PATCH 17/74] URIComponentsBuilder --- .../uribuilder/SpringUriBuilderTest.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderTest.java diff --git a/spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderTest.java b/spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderTest.java new file mode 100644 index 0000000000..4b6a9ba312 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderTest.java @@ -0,0 +1,53 @@ +package org.baeldung.uribuilder; + +import static org.junit.Assert.assertEquals; + +import java.util.Collections; + +import org.junit.Test; +import org.springframework.web.util.UriComponents; +import org.springframework.web.util.UriComponentsBuilder; + +public class SpringUriBuilderTest { + + @Test + public void constructUri() { + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com") + .path("/junit-5").build(); + + assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString()); + } + + @Test + public void constructUriEncoded() { + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com") + .path("/junit 5").build().encode(); + + assertEquals("http://www.baeldung.com/junit%205", uriComponents.toUriString()); + } + + @Test + public void constructUriFromTemplate() { + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com") + .path("/{article-name}").buildAndExpand("junit-5"); + + assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString()); + } + + @Test + public void constructUriWithQueryParameter() { + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.google.com") + .path("/").query("q={keyword}").buildAndExpand("baeldung"); + + assertEquals("http://www.google.com/?q=baeldung", uriComponents.toUriString()); + } + + @Test + public void expandWithRegexVar() { + String template = "/myurl/{name:[a-z]{1,5}}/show"; + UriComponents uriComponents = UriComponentsBuilder.fromUriString(template).build(); + uriComponents = uriComponents.expand(Collections.singletonMap("name", "test")); + + assertEquals("/myurl/test/show", uriComponents.getPath()); + } +} From 77240dc024831aa643e0c2c885e09e92c15fbf7a Mon Sep 17 00:00:00 2001 From: DianeDuan Date: Mon, 21 Nov 2016 20:41:33 +0800 Subject: [PATCH 18/74] 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 19/74] 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 20/74] 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 21/74] 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 22/74] 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 23/74] 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 24/74] 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 25/74] 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 26/74] 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 27/74] 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 28/74] 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 29/74] 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 30/74] manual authentication demo integration (#836) * manual authentication demo integration * apply eclipse and security formatting rules * add content to readme file, for manual authentication demo --- spring-security-client/README.MD | 11 ++- .../java/org/baeldung/config/MvcConfig.java | 2 + .../org/baeldung/config/MvcConfigManual.java | 22 +++++ .../config/RegistrationController.java | 92 +++++++++++++++++++ .../org/baeldung/config/SecurityConfig.java | 2 + .../config/WebSecurityConfigManual.java | 35 +++++++ .../src/main/resources/templates/hello.html | 15 +++ .../src/main/resources/templates/home.html | 15 +++ .../src/main/resources/templates/login.html | 21 +++++ .../templates/registrationError.html | 1 + .../templates/registrationSuccess.html | 15 +++ 11 files changed, 230 insertions(+), 1 deletion(-) create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/home.html create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/login.html create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationError.html create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationSuccess.html diff --git a/spring-security-client/README.MD b/spring-security-client/README.MD index 5ac974203b..0b0af7ffe1 100644 --- a/spring-security-client/README.MD +++ b/spring-security-client/README.MD @@ -1,2 +1,11 @@ -###The Course +========= +## Spring Security Authentication/Authorization Example Project + +##The Course The "REST With Spring" Classes: http://github.learnspringsecurity.com + +### Relevant Articles: +- [Spring Security Manual Authentication](http://www.baeldung.com/spring-security-authentication) + +### Build the Project +mvn clean install diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java index 9ade60e54c..259433f6ae 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java @@ -8,9 +8,11 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.context.annotation.Profile; @Configuration @EnableWebMvc +@Profile("!manual") public class MvcConfig extends WebMvcConfigurerAdapter { public MvcConfig() { diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java new file mode 100644 index 0000000000..d80527c30a --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java @@ -0,0 +1,22 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +@Configuration +@EnableWebMvc +@Profile("manual") +public class MvcConfigManual extends WebMvcConfigurerAdapter { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/home").setViewName("home"); + registry.addViewController("/").setViewName("home"); + registry.addViewController("/hello").setViewName("hello"); + registry.addViewController("/login").setViewName("login"); + } + +} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java new file mode 100644 index 0000000000..025001ac44 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java @@ -0,0 +1,92 @@ +package org.baeldung.config; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.WebAuthenticationDetails; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.context.annotation.Profile; + +/** + * Manually authenticate a user using Spring Security / Spring Web MVC' (upon successful account registration) + * (http://stackoverflow.com/questions/4664893/how-to-manually-set-an-authenticated-user-in-spring-security-springmvc) + * + * @author jim clayson + */ +@Controller +@Profile("manual") +public class RegistrationController { + private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class); + + @Autowired + AuthenticationManager authenticationManager; + + /** + * For demo purposes this need only be a GET request method + * + * @param request + * @param response + * @return The view. Page confirming either successful registration (and/or + * successful authentication) or failed registration. + */ + @RequestMapping(value = "/register", method = RequestMethod.GET) + public String registerAndAuthenticate(HttpServletRequest request, HttpServletResponse response) { + logger.debug("registerAndAuthenticate: attempt to register, application should manually authenticate."); + + // Mocked values. Potentially could come from an HTML registration form, + // in which case this mapping would match on an HTTP POST, rather than a GET + String username = "user"; + String password = "password"; + + String view = "registrationSuccess"; + + if (requestQualifiesForManualAuthentication()) { + try { + authenticate(username, password, request, response); + logger.debug("registerAndAuthenticate: authentication completed."); + } catch (BadCredentialsException bce) { + logger.debug("Authentication failure: bad credentials"); + bce.printStackTrace(); + view = "systemError"; // assume a low-level error, since the registration + // form would have been successfully validated + } + } + + return view; + } + + private boolean requestQualifiesForManualAuthentication() { + // Some processing to determine that the user requires a Spring Security-recognized, + // application-directed login e.g. successful account registration. + return true; + } + + private void authenticate(String username, String password, HttpServletRequest request, HttpServletResponse response) throws BadCredentialsException { + logger.debug("attempting to authenticated, manually ... "); + + // create and populate the token + AbstractAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password); + authToken.setDetails(new WebAuthenticationDetails(request)); + + // This call returns an authentication object, which holds principle and user credentials + Authentication authentication = this.authenticationManager.authenticate(authToken); + + // The security context holds the authentication object, and is stored + // in thread local scope. + SecurityContextHolder.getContext().setAuthentication(authentication); + + logger.debug("User should now be authenticated."); + } + +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java index bd6c56d38a..153cc67661 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java @@ -6,9 +6,11 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.context.annotation.Profile; @Configuration @EnableWebSecurity +@Profile("!manual") public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java new file mode 100644 index 0000000000..180a53deba --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java @@ -0,0 +1,35 @@ +package org.baeldung.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +@Profile("manual") +public class WebSecurityConfigManual extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http + .authorizeRequests() + .antMatchers("/", "/home", "/register").permitAll() + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login").permitAll() + .and() + .logout().permitAll(); + // @formatter:on + } + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); + } +} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html new file mode 100644 index 0000000000..b37731b0ed --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html @@ -0,0 +1,15 @@ + + + + Hello World! + + +

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

+
+ +
+

Click here to go to the home page.

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

Welcome!

+ +

Click here to see a greeting.

+

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

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

Click here to go to the home page.

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

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

+
+ +
+

Click here to go to the home page.

+ + + \ No newline at end of file From 9cd64f8d19864cc6340714efd388604d13440be2 Mon Sep 17 00:00:00 2001 From: tschiman Date: Wed, 23 Nov 2016 16:07:28 -0700 Subject: [PATCH 31/74] BAEL-89 Trimming down to one application that uses spring boot and demonstrating spring session in the unit tests. --- spring-session/jetty-session-demo/pom.xml | 76 ------------- .../session/jettyex/JettyController.java | 12 -- .../session/jettyex/SecurityConfig.java | 19 ---- .../spring/session/jettyex/SessionConfig.java | 17 --- .../src/main/resources/application.properties | 3 - spring-session/pom.xml | 71 ++++++++++-- .../spring/session}/SecurityConfig.java | 4 +- .../spring/session}/SessionConfig.java | 2 +- .../spring/session/SessionController.java} | 8 +- .../session/SessionWebApplication.java} | 6 +- .../src/main/resources/application.properties | 0 .../spring/session/SessionControllerTest.java | 87 +++++++++++++++ spring-session/tomcat-session-demo/pom.xml | 71 ------------ .../tomcatex/TomcatWebApplication.java | 11 -- .../tomcatex/TomcatControllerTest.java | 103 ------------------ 15 files changed, 157 insertions(+), 333 deletions(-) delete mode 100644 spring-session/jetty-session-demo/pom.xml delete mode 100644 spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyController.java delete mode 100644 spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java delete mode 100644 spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SessionConfig.java delete mode 100644 spring-session/jetty-session-demo/src/main/resources/application.properties rename spring-session/{tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex => src/main/java/com/baeldung/spring/session}/SecurityConfig.java (90%) rename spring-session/{tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex => src/main/java/com/baeldung/spring/session}/SessionConfig.java (88%) rename spring-session/{tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatController.java => src/main/java/com/baeldung/spring/session/SessionController.java} (55%) rename spring-session/{jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java => src/main/java/com/baeldung/spring/session/SessionWebApplication.java} (57%) rename spring-session/{tomcat-session-demo => }/src/main/resources/application.properties (100%) create mode 100644 spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java delete mode 100644 spring-session/tomcat-session-demo/pom.xml delete mode 100644 spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java delete mode 100644 spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java diff --git a/spring-session/jetty-session-demo/pom.xml b/spring-session/jetty-session-demo/pom.xml deleted file mode 100644 index 19f0577d2e..0000000000 --- a/spring-session/jetty-session-demo/pom.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - 4.0.0 - - com.baeldung - jetty-session-demo - 1.0.0-SNAPSHOT - - - org.springframework.boot - spring-boot-starter-parent - 1.4.0.RELEASE - - - - - - org.springframework.boot - spring-boot-starter-jetty - - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.session - spring-session - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.cloud - spring-cloud-dependencies - Brixton.RELEASE - pom - import - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 1.8 - 1.8 - - - - - \ No newline at end of file diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyController.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyController.java deleted file mode 100644 index 308b0a8d51..0000000000 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyController.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.spring.session.jettyex; - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class JettyController { - @RequestMapping - public String helloJetty() { - return "hello Jetty"; - } -} \ No newline at end of file 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 deleted file mode 100644 index 5ce8f9a042..0000000000 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.spring.session.jettyex; - -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.http.SessionCreationPolicy; - -@Configuration -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and() - .authorizeRequests().anyRequest().hasRole("ADMIN"); - } -} diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SessionConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SessionConfig.java deleted file mode 100644 index 735ae7fb43..0000000000 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SessionConfig.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.spring.session.jettyex; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; -import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; -import org.springframework.session.web.http.HeaderHttpSessionStrategy; -import org.springframework.session.web.http.HttpSessionStrategy; - -@Configuration -@EnableRedisHttpSession -public class SessionConfig extends AbstractHttpSessionApplicationInitializer { - @Bean - public HttpSessionStrategy httpSessionStrategy() { - return new HeaderHttpSessionStrategy(); - } -} diff --git a/spring-session/jetty-session-demo/src/main/resources/application.properties b/spring-session/jetty-session-demo/src/main/resources/application.properties deleted file mode 100644 index 7f81672eda..0000000000 --- a/spring-session/jetty-session-demo/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -server.port=8081 -spring.redis.host=localhost -spring.redis.port=6379 \ No newline at end of file diff --git a/spring-session/pom.xml b/spring-session/pom.xml index fec6a46af2..cf6fc71be2 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -4,19 +4,68 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - spring-session 1.0.0-SNAPSHOT pom - - jetty-session-demo - tomcat-session-demo - + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.session + spring-session + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.RELEASE + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + + + + \ No newline at end of file diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/src/main/java/com/baeldung/spring/session/SecurityConfig.java similarity index 90% rename from spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java rename to spring-session/src/main/java/com/baeldung/spring/session/SecurityConfig.java index 0f467dd104..beaa4da0fe 100644 --- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java +++ b/spring-session/src/main/java/com/baeldung/spring/session/SecurityConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.session.tomcatex; +package com.baeldung.spring.session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; @@ -23,7 +23,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { http .httpBasic().and() .authorizeRequests() - .antMatchers("/tomcat/admin").hasRole("ADMIN") + .antMatchers("/").hasRole("ADMIN") .anyRequest().authenticated(); } } diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java b/spring-session/src/main/java/com/baeldung/spring/session/SessionConfig.java similarity index 88% rename from spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java rename to spring-session/src/main/java/com/baeldung/spring/session/SessionConfig.java index 5afac6cb6b..5a9bc9ff28 100644 --- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java +++ b/spring-session/src/main/java/com/baeldung/spring/session/SessionConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.session.tomcatex; +package com.baeldung.spring.session; import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatController.java b/spring-session/src/main/java/com/baeldung/spring/session/SessionController.java similarity index 55% rename from spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatController.java rename to spring-session/src/main/java/com/baeldung/spring/session/SessionController.java index a241158294..224196d8a0 100644 --- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatController.java +++ b/spring-session/src/main/java/com/baeldung/spring/session/SessionController.java @@ -1,12 +1,12 @@ -package com.baeldung.spring.session.tomcatex; +package com.baeldung.spring.session; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController -public class TomcatController { - @RequestMapping("/tomcat/admin") +public class SessionController { + @RequestMapping("/") public String helloTomcatAdmin() { - return "hello tomcat admin"; + return "hello admin"; } } diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java b/spring-session/src/main/java/com/baeldung/spring/session/SessionWebApplication.java similarity index 57% rename from spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java rename to spring-session/src/main/java/com/baeldung/spring/session/SessionWebApplication.java index ebb2a8e188..3c605be3a6 100644 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java +++ b/spring-session/src/main/java/com/baeldung/spring/session/SessionWebApplication.java @@ -1,11 +1,11 @@ -package com.baeldung.spring.session.jettyex; +package com.baeldung.spring.session; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class JettyWebApplication { +public class SessionWebApplication { public static void main(String[] args) { - SpringApplication.run(JettyWebApplication.class, args); + SpringApplication.run(SessionWebApplication.class, args); } } diff --git a/spring-session/tomcat-session-demo/src/main/resources/application.properties b/spring-session/src/main/resources/application.properties similarity index 100% rename from spring-session/tomcat-session-demo/src/main/resources/application.properties rename to spring-session/src/main/resources/application.properties diff --git a/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java b/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java new file mode 100644 index 0000000000..5775710410 --- /dev/null +++ b/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java @@ -0,0 +1,87 @@ +package com.baeldung.spring.session; + +import org.apache.tomcat.util.codec.binary.Base64; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; +import org.springframework.http.*; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class SessionControllerTest { + + @Autowired + private TestRestTemplate restTemplate; + @Autowired + private JedisConnectionFactory jedisConnectionFactory; + + private RedisConnection connection; + + @Before + public void clearRedisData() { + connection = jedisConnectionFactory.getConnection(); + connection.flushAll(); + } + + @Test + public void testRedisIsEmpty() { + Set result = connection.keys("*".getBytes()); + assertEquals(0, result.size()); + } + + @Test + public void testUnauthenticatedCantAccess() { + ResponseEntity result = restTemplate.getForEntity("/", String.class); + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); + } + + @Test + public void testRedisControlsSession() { + ResponseEntity result = restTemplate.exchange("/", HttpMethod.GET, makeAuthRequest(), String.class); + assertEquals("hello admin", result.getBody()); //login worked + + Set redisResult = connection.keys("*".getBytes()); + assertTrue(redisResult.size() > 0); //redis is populated with session data + + String sessionCookie = result.getHeaders().get("Set-Cookie").get(0).split(";")[0]; + result = restTemplate.exchange("/", HttpMethod.GET, makeRequestWithCookie(sessionCookie), String.class); + assertEquals("hello admin", result.getBody()); //access with session works worked + + connection.flushAll(); //clear all keys in redis + + result = restTemplate.exchange("/", HttpMethod.GET, makeRequestWithCookie(sessionCookie), String.class); + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());//access denied after sessions are removed in redis + + } + + private HttpEntity makeRequestWithCookie(String sessionCookie) { + HttpHeaders headers = new HttpHeaders(); + headers.add("Cookie", sessionCookie); + + return new HttpEntity<>(headers); + } + + private HttpEntity makeAuthRequest() { + String plainCreds = "admin:password"; + byte[] plainCredsBytes = plainCreds.getBytes(); + byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); + String base64Creds = new String(base64CredsBytes); + + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic " + base64Creds); + + return new HttpEntity<>(headers); + } + +} \ No newline at end of file diff --git a/spring-session/tomcat-session-demo/pom.xml b/spring-session/tomcat-session-demo/pom.xml deleted file mode 100644 index 0a101e73a6..0000000000 --- a/spring-session/tomcat-session-demo/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - - com.baeldung - tomcat-session-demo - 1.0.0-SNAPSHOT - - - org.springframework.boot - spring-boot-starter-parent - 1.4.0.RELEASE - - - - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.session - spring-session - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.cloud - spring-cloud-dependencies - Brixton.RELEASE - pom - import - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 1.8 - 1.8 - - - - - \ No newline at end of file diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java deleted file mode 100644 index fb4e059dd1..0000000000 --- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.spring.session.tomcatex; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class TomcatWebApplication { - public static void main(String[] args) { - SpringApplication.run(TomcatWebApplication.class, args); - } -} diff --git a/spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java b/spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java deleted file mode 100644 index 5bfb7e9411..0000000000 --- a/spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.baeldung.spring.session.tomcatex; - -import org.apache.tomcat.util.codec.binary.Base64; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.embedded.LocalServerPort; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.data.redis.connection.RedisConnection; -import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; -import org.springframework.http.*; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.Set; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class TomcatControllerTest { - - @Autowired - private TestRestTemplate restTemplate; - @LocalServerPort - private int port; - @Autowired - private JedisConnectionFactory jedisConnectionFactory; - private RedisConnection connection; - - @Before - public void clearRedisData() { - connection = jedisConnectionFactory.getConnection(); - connection.flushAll(); - } - - @Test - public void testRedisIsEmpty() { - Set result = connection.keys("*".getBytes()); - assertEquals(0, result.size()); - } - - @Test - public void testForbiddenToProtectedEndpoint() { - ResponseEntity result = restTemplate.getForEntity("/tomcat/admin", String.class); - assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); - } - - @Test - public void testLoginAddsRedisKey() { - ResponseEntity result = makeRequest(); - assertEquals("hello tomcat admin", result.getBody()); //login worked - - Set redisResult = connection.keys("*".getBytes()); - assertTrue(redisResult.size() > 0); //redis was populated with data - } - - @Test //requires that the jetty service is running on port 8081 - public void testFailureAccessingJettyResourceWithTomcatSessionToken() { - //call the jetty server with the token - ResponseEntity jettyResult = restTemplate.getForEntity("http://localhost:8081", String.class); - assertEquals(HttpStatus.UNAUTHORIZED, jettyResult.getStatusCode()); //login worked - } - - @Test //requires that the jetty service is running on port 8081 - public void testAccessingJettyResourceWithTomcatSessionToken() { - //login to get a session token - ResponseEntity result = makeRequest(); - assertEquals("hello tomcat admin", result.getBody()); //login worked - - assertTrue(result.getHeaders().containsKey("Set-Cookie")); - - String setCookieValue = result.getHeaders().get("Set-Cookie").get(0); - String sessionCookie = setCookieValue.split(";")[0]; - String sessionValue = sessionCookie.split("=")[1]; - - //Add session token to headers - HttpHeaders headers = new HttpHeaders(); - headers.add("x-auth-token", sessionValue); - - //call the jetty server with the token - HttpEntity request = new HttpEntity<>(headers); - ResponseEntity jettyResult = restTemplate.exchange("http://localhost:8081", HttpMethod.GET, request, String.class); - assertEquals("hello Jetty", jettyResult.getBody()); //login worked - - } - - private ResponseEntity makeRequest() { - String plainCreds = "admin:password"; - byte[] plainCredsBytes = plainCreds.getBytes(); - byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); - String base64Creds = new String(base64CredsBytes); - - HttpHeaders headers = new HttpHeaders(); - headers.add("Authorization", "Basic " + base64Creds); - - HttpEntity request = new HttpEntity<>(headers); - return restTemplate.exchange("http://localhost:" + port + "/tomcat/admin", HttpMethod.GET, request, String.class); - } - -} \ No newline at end of file From 15d398cbbb4d2e363000224ae7d83aa5e6a96071 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Thu, 24 Nov 2016 08:04:37 -0600 Subject: [PATCH 32/74] Update README.md --- spring-mvc-xml/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index 783bbb2ef4..e96a8d0392 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -12,3 +12,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout) - [Basic Forms with Spring MVC](http://www.baeldung.com/spring-mvc-form-tutorial) - [Returning Image/Media Data with Spring MVC](http://www.baeldung.com/spring-mvc-image-media-data) +- [Geolocation by IP in Java](http://www.baeldung.com/geolocation-by-ip-with-maxmind) From cdb6dfd79e4c185804adc220d9a221a24f0b9e7b Mon Sep 17 00:00:00 2001 From: Egima profile Date: Fri, 25 Nov 2016 18:48:26 +0300 Subject: [PATCH 33/74] asyncronous channel apis (#839) * made changes to java reflection * removed redundant method makeSound in Animal abstract class * added project for play-framework article * added project for regex * changed regex project from own model to core-java * added project for routing in play * made changes to regex project * refactored code for REST API with Play project * refactored student store indexing to zero base * added unit tests, removed bad names * added NIO Selector project under core-java module * requested changes made * added project for nio2 * standardized exception based tests * fixed exception based tests * removed redundant files * added network interface project * used UUID other than timestamps * fixed network interface tests * removed filetest change * made changes to NIO2 FileTest names * added project for asyncronous channel apis * added project for NIO2 advanced filesystems APIS --- .../java/nio2/visitor/FileSearchExample.java | 60 ++++++++ .../java/nio2/visitor/FileVisitorImpl.java | 30 ++++ .../nio2/watcher/DirectoryWatcherExample.java | 25 ++++ .../java/nio2/async/AsyncEchoClient.java | 82 +++++++++++ .../java/nio2/async/AsyncEchoServer.java | 79 +++++++++++ .../java/nio2/async/AsyncEchoServer2.java | 100 ++++++++++++++ .../java/nio2/async/AsyncEchoTest.java | 36 +++++ .../java/nio2/async/AsyncFileTest.java | 130 ++++++++++++++++++ .../nio2/attributes/BasicAttribsTest.java | 68 +++++++++ 9 files changed, 610 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java create mode 100644 core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java create mode 100644 core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java create mode 100644 core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java create mode 100644 core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java create mode 100644 core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java create mode 100644 core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java create mode 100644 core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java create mode 100644 core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java diff --git a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java new file mode 100644 index 0000000000..15910abf9b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java @@ -0,0 +1,60 @@ +package com.baeldung.java.nio2.visitor; + +import static java.nio.file.FileVisitResult.CONTINUE; +import static java.nio.file.FileVisitResult.TERMINATE; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.FileVisitor; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributes; + +public class FileSearchExample implements FileVisitor { + private static String FILE_NAME; + private static Path START_DIR; + + public FileSearchExample(String fileName, Path startingDir) { + FILE_NAME = fileName; + START_DIR = startingDir; + } + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + return CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + String fileName = file.getFileName().toString(); + if (FILE_NAME.equals(fileName)) { + System.out.println("File found: " + file.toString()); + return TERMINATE; + } + return CONTINUE; + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { + System.out.println("Failed to access file: " + file.toString()); + return CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + boolean finishedSearch = Files.isSameFile(dir, START_DIR); + if (finishedSearch) { + System.out.println("File:" + FILE_NAME + " not found"); + return TERMINATE; + } + return CONTINUE; + } + + public static void main(String[] args) throws IOException { + Path startingDir = Paths.get("C:/Users/new/Desktop"); + FileSearchExample crawler = new FileSearchExample("hibernate.txt", startingDir); + Files.walkFileTree(startingDir, crawler); + } + +} diff --git a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java new file mode 100644 index 0000000000..360d6d0689 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java @@ -0,0 +1,30 @@ +package com.baeldung.java.nio2.visitor; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.FileVisitor; +import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; + +public class FileVisitorImpl implements FileVisitor { + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { + return null; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { + return null; + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) { + return null; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) { + return null; + } +} diff --git a/core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java b/core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java new file mode 100644 index 0000000000..ffc58a1c50 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java @@ -0,0 +1,25 @@ +package com.baeldung.java.nio2.watcher; + +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; + +public class DirectoryWatcherExample { + public static void main(String[] args) throws IOException, InterruptedException { + WatchService watchService = FileSystems.getDefault().newWatchService(); + Path path = Paths.get(System.getProperty("user.home")); + path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); + WatchKey key; + while ((key = watchService.take()) != null) { + for (WatchEvent event : key.pollEvents()) { + System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + "."); + } + key.reset(); + } + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java new file mode 100644 index 0000000000..ea35130f49 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java @@ -0,0 +1,82 @@ +package com.baeldung.java.nio2.async; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousSocketChannel; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +public class AsyncEchoClient { + private AsynchronousSocketChannel client; + private Future future; + private static AsyncEchoClient instance; + + private AsyncEchoClient() { + try { + client = AsynchronousSocketChannel.open(); + InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999); + future = client.connect(hostAddress); + start(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static AsyncEchoClient getInstance() { + if (instance == null) + instance = new AsyncEchoClient(); + return instance; + } + + private void start() { + try { + future.get(); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + } + + public String sendMessage(String message) { + byte[] byteMsg = new String(message).getBytes(); + ByteBuffer buffer = ByteBuffer.wrap(byteMsg); + Future writeResult = client.write(buffer); + + while (!writeResult.isDone()) { + // do nothing + } + buffer.flip(); + Future readResult = client.read(buffer); + while (!readResult.isDone()) { + + } + String echo = new String(buffer.array()).trim(); + buffer.clear(); + return echo; + } + + public void stop() { + try { + client.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws IOException { + AsyncEchoClient client = AsyncEchoClient.getInstance(); + client.start(); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String line = null; + System.out.println("Message to server:"); + while ((line = br.readLine()) != null) { + String response = client.sendMessage(line); + System.out.println("response from server: " + response); + System.out.println("Message to server:"); + } + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java new file mode 100644 index 0000000000..0e58cb5f10 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java @@ -0,0 +1,79 @@ +package com.baeldung.java.nio2.async; + +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousServerSocketChannel; +import java.nio.channels.AsynchronousSocketChannel; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +public class AsyncEchoServer { + private AsynchronousServerSocketChannel serverChannel; + private Future acceptResult; + private AsynchronousSocketChannel clientChannel; + + public AsyncEchoServer() { + try { + serverChannel = AsynchronousServerSocketChannel.open(); + InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999); + serverChannel.bind(hostAddress); + acceptResult = serverChannel.accept(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void runServer() { + try { + clientChannel = acceptResult.get(); + if ((clientChannel != null) && (clientChannel.isOpen())) { + while (true) { + + ByteBuffer buffer = ByteBuffer.allocate(32); + Future readResult = clientChannel.read(buffer); + + while (!readResult.isDone()) { + // do nothing + } + + buffer.flip(); + String message = new String(buffer.array()).trim(); + if (message.equals("bye")) { + break; // while loop + } + buffer = ByteBuffer.wrap(new String(message).getBytes()); + Future writeResult = clientChannel.write(buffer); + while (!writeResult.isDone()) { + // do nothing + } + buffer.clear(); + + } // while() + + clientChannel.close(); + serverChannel.close(); + + } + } catch (InterruptedException | ExecutionException | IOException e) { + e.printStackTrace(); + } + + } + + public static void main(String[] args) { + AsyncEchoServer server = new AsyncEchoServer(); + server.runServer(); + } + public static Process start() throws IOException, InterruptedException { + String javaHome = System.getProperty("java.home"); + String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; + String classpath = System.getProperty("java.class.path"); + String className = AsyncEchoServer.class.getCanonicalName(); + + ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className); + + return builder.start(); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java new file mode 100644 index 0000000000..03ce233ce9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java @@ -0,0 +1,100 @@ +package com.baeldung.java.nio2.async; + +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousServerSocketChannel; +import java.nio.channels.AsynchronousSocketChannel; +import java.nio.channels.CompletionHandler; +import java.util.HashMap; +import java.util.Map; + +public class AsyncEchoServer2 { + private AsynchronousServerSocketChannel serverChannel; + private AsynchronousSocketChannel clientChannel; + + public AsyncEchoServer2() { + try { + serverChannel = AsynchronousServerSocketChannel.open(); + InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999); + serverChannel.bind(hostAddress); + while (true) { + + serverChannel.accept(null, new CompletionHandler() { + + @Override + public void completed(AsynchronousSocketChannel result, Object attachment) { + if (serverChannel.isOpen()) + serverChannel.accept(null, this); + clientChannel = result; + if ((clientChannel != null) && (clientChannel.isOpen())) { + ReadWriteHandler handler = new ReadWriteHandler(); + ByteBuffer buffer = ByteBuffer.allocate(32); + Map readInfo = new HashMap<>(); + readInfo.put("action", "read"); + readInfo.put("buffer", buffer); + clientChannel.read(buffer, readInfo, handler); + } + } + + @Override + public void failed(Throwable exc, Object attachment) { + // process error + } + }); + try { + System.in.read(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + class ReadWriteHandler implements CompletionHandler> { + + @Override + public void completed(Integer result, Map attachment) { + Map actionInfo = attachment; + String action = (String) actionInfo.get("action"); + if ("read".equals(action)) { + ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer"); + buffer.flip(); + actionInfo.put("action", "write"); + clientChannel.write(buffer, actionInfo, this); + buffer.clear(); + } else if ("write".equals(action)) { + ByteBuffer buffer = ByteBuffer.allocate(32); + actionInfo.put("action", "read"); + actionInfo.put("buffer", buffer); + clientChannel.read(buffer, actionInfo, this); + } + + } + + @Override + public void failed(Throwable exc, Map attachment) { + + } + + } + + + public static void main(String[] args) { + new AsyncEchoServer2(); + } + + public static Process start() throws IOException, InterruptedException { + String javaHome = System.getProperty("java.home"); + String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; + String classpath = System.getProperty("java.class.path"); + String className = AsyncEchoServer2.class.getCanonicalName(); + + ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className); + + return builder.start(); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java new file mode 100644 index 0000000000..7ac388fb09 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java @@ -0,0 +1,36 @@ +package com.baeldung.java.nio2.async; + +import static org.junit.Assert.*; + +import java.io.IOException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class AsyncEchoTest { + + Process server; + AsyncEchoClient client; + + @Before + public void setup() throws IOException, InterruptedException { + server = AsyncEchoServer2.start(); + client = AsyncEchoClient.getInstance(); + } + + @Test + public void givenServerClient_whenServerEchosMessage_thenCorrect() { + String resp1 = client.sendMessage("hello"); + String resp2 = client.sendMessage("world"); + assertEquals("hello", resp1); + assertEquals("world", resp2); + } + + @After + public void teardown() throws IOException { + server.destroy(); + client.stop(); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java new file mode 100644 index 0000000000..db30d32210 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java @@ -0,0 +1,130 @@ +package com.baeldung.java.nio2.async; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.net.URI; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousFileChannel; +import java.nio.channels.CompletionHandler; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.UUID; +import java.util.concurrent.Future; + +import org.junit.Test; + +public class AsyncFileTest { + @Test + public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException { + Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString())); + AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ); + + ByteBuffer buffer = ByteBuffer.allocate(1024); + + Future operation = fileChannel.read(buffer, 0); + + while (!operation.isDone()) + ; + + String fileContent = new String(buffer.array()).trim(); + buffer.clear(); + + assertEquals(fileContent, "baeldung.com"); + } + + @Test + public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException { + Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString())); + AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ); + + ByteBuffer buffer = ByteBuffer.allocate(1024); + + fileChannel.read(buffer, 0, buffer, new CompletionHandler() { + + @Override + public void completed(Integer result, ByteBuffer attachment) { + // result is number of bytes read + // attachment is the buffer + + } + + @Override + public void failed(Throwable exc, ByteBuffer attachment) { + + } + }); + } + + @Test + public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException { + String fileName = UUID.randomUUID().toString(); + Path path = Paths.get(fileName); + AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,StandardOpenOption.DELETE_ON_CLOSE); + + ByteBuffer buffer = ByteBuffer.allocate(1024); + long position = 0; + + buffer.put("hello world".getBytes()); + buffer.flip(); + + Future operation = fileChannel.write(buffer, position); + buffer.clear(); + + while (!operation.isDone()) { + + } + + String content = readContent(path); + assertEquals("hello world", content); + } + + @Test + public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException { + String fileName = UUID.randomUUID().toString(); + Path path = Paths.get(fileName); + AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,StandardOpenOption.DELETE_ON_CLOSE); + + + ByteBuffer buffer = ByteBuffer.allocate(1024); + buffer.put("hello world".getBytes()); + buffer.flip(); + + fileChannel.write(buffer, 0, buffer, new CompletionHandler() { + + @Override + public void completed(Integer result, ByteBuffer attachment) { + // result is number of bytes written + // attachment is the buffer + + } + + @Override + public void failed(Throwable exc, ByteBuffer attachment) { + + } + }); + } + + public static String readContent(Path file) { + AsynchronousFileChannel fileChannel = null; + try { + fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + ByteBuffer buffer = ByteBuffer.allocate(1024); + + Future operation = fileChannel.read(buffer, 0); + + while (!operation.isDone()) + ; + + String fileContent = new String(buffer.array()).trim(); + buffer.clear(); + return fileContent; + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java new file mode 100644 index 0000000000..dcc24c6415 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java @@ -0,0 +1,68 @@ +package com.baeldung.java.nio2.attributes; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributeView; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileTime; + +import org.junit.Before; +import org.junit.Test; + +public class BasicAttribsTest { + private static final String HOME = System.getProperty("user.home"); + BasicFileAttributes basicAttribs; + + @Before + public void setup() throws IOException { + Path home = Paths.get(HOME); + BasicFileAttributeView basicView = Files.getFileAttributeView(home, BasicFileAttributeView.class); + basicAttribs = basicView.readAttributes(); + } + + @Test + public void givenFileTimes_whenComparesThem_ThenCorrect() { + FileTime created = basicAttribs.creationTime(); + FileTime modified = basicAttribs.lastModifiedTime(); + FileTime accessed = basicAttribs.lastAccessTime(); + + assertTrue(0 > created.compareTo(accessed)); + assertTrue(0 < modified.compareTo(created)); + assertTrue(0 == created.compareTo(created)); + } + + @Test + public void givenPath_whenGetsFileSize_thenCorrect() { + long size = basicAttribs.size(); + assertTrue(size > 0); + } + + @Test + public void givenPath_whenChecksIfDirectory_thenCorrect() { + boolean isDir = basicAttribs.isDirectory(); + assertTrue(isDir); + } + + @Test + public void givenPath_whenChecksIfFile_thenCorrect() { + boolean isFile = basicAttribs.isRegularFile(); + assertFalse(isFile); + } + + @Test + public void givenPath_whenChecksIfSymLink_thenCorrect() { + boolean isSymLink = basicAttribs.isSymbolicLink(); + assertFalse(isSymLink); + } + + @Test + public void givenPath_whenChecksIfOther_thenCorrect() { + boolean isOther = basicAttribs.isOther(); + assertFalse(isOther); + } +} From 5b738313e8524ea44113cb1bf7c9aca0f4c34ddf Mon Sep 17 00:00:00 2001 From: Alex Theedom Date: Sat, 26 Nov 2016 17:43:54 +0000 Subject: [PATCH 34/74] Add Spring MVC form and binding example --- spring-mvc-forms/pom.xml | 99 +++++++++++++++++++ .../ApplicationConfiguration.java | 29 ++++++ .../configuration/WebInitializer.java | 47 +++++++++ .../controller/EmployeeController.java | 41 ++++++++ .../springmvcforms/domain/Employee.java | 46 +++++++++ .../webapp/WEB-INF/views/employeeHome.jsp | 33 +++++++ .../webapp/WEB-INF/views/employeeView.jsp | 24 +++++ .../src/main/webapp/WEB-INF/views/error.jsp | 20 ++++ 8 files changed, 339 insertions(+) create mode 100644 spring-mvc-forms/pom.xml create mode 100644 spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java create mode 100644 spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java create mode 100644 spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java create mode 100644 spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Employee.java create mode 100644 spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeHome.jsp create mode 100644 spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeView.jsp create mode 100644 spring-mvc-forms/src/main/webapp/WEB-INF/views/error.jsp diff --git a/spring-mvc-forms/pom.xml b/spring-mvc-forms/pom.xml new file mode 100644 index 0000000000..370fd7feb2 --- /dev/null +++ b/spring-mvc-forms/pom.xml @@ -0,0 +1,99 @@ + + + + 4.0.0 + com.baeldung + 0.1-SNAPSHOT + spring-mvc-forms + + spring-mvc-forms + war + + + + org.springframework + spring-webmvc + ${springframework.version} + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + + javax.servlet.jsp + javax.servlet.jsp-api + ${javax.servlet.jsp-api.version} + + + + javax.servlet + jstl + ${jstl.version} + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + + + + + + spring-mvc-forms + + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven-compiler-plugin.source} + ${maven-compiler-plugin.source} + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + src/main/webapp + spring-mvc-forms + false + ${deploy-path} + + + + + + spring-mvc-forms + + + + + + 4.0.6.RELEASE + 2.4 + 1.2 + 2.3.1 + 3.1.0 + 3.5.1 + 1.8 + 5.1.1.Final + enter-location-of-server + + + + diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java new file mode 100644 index 0000000000..998f070c02 --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.springmvcforms.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "com.baeldung.springmvcforms") +class ApplicationConfiguration extends WebMvcConfigurerAdapter { + + @Override + public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Bean + public InternalResourceViewResolver jspViewResolver() { + InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setPrefix("/WEB-INF/views/"); + bean.setSuffix(".jsp"); + return bean; + } + +} diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java new file mode 100644 index 0000000000..c602ea6454 --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java @@ -0,0 +1,47 @@ +package com.baeldung.springmvcforms.configuration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +public class WebInitializer implements WebApplicationInitializer { + + public void onStartup(ServletContext container) throws ServletException { + + AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); + ctx.register(ApplicationConfiguration.class); + ctx.setServletContext(container); + + // Manage the lifecycle of the root application context + container.addListener(new ContextLoaderListener(ctx)); + + ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx)); + + servlet.setLoadOnStartup(1); + servlet.addMapping("/"); + } +// @Override +// public void onStartup(ServletContext container) { +// // Create the 'root' Spring application context +// AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); +// rootContext.register(ServiceConfig.class, JPAConfig.class, SecurityConfig.class); +// +// // Manage the lifecycle of the root application context +// container.addListener(new ContextLoaderListener(rootContext)); +// +// // Create the dispatcher servlet's Spring application context +// AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext(); +// dispatcherServlet.register(MvcConfig.class); +// +// // Register and map the dispatcher servlet +// ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet)); +// dispatcher.setLoadOnStartup(1); +// dispatcher.addMapping("/"); +// +// } +} diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java new file mode 100644 index 0000000000..3ece77bb18 --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java @@ -0,0 +1,41 @@ +package com.baeldung.springmvcforms.controller; + +import com.baeldung.springmvcforms.domain.Employee; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.ModelAndView; + +import javax.validation.Valid; +import java.util.HashMap; +import java.util.Map; + +@Controller +public class EmployeeController { + + Map employeeMap = new HashMap<>(); + + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } + + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { + return employeeMap.get(Id); + } + + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("id", employee.getId()); + employeeMap.put(employee.getId(), employee); + return "employeeView"; + } + +} diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Employee.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Employee.java new file mode 100644 index 0000000000..23cb72b3dc --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Employee.java @@ -0,0 +1,46 @@ +package com.baeldung.springmvcforms.domain; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +public class Employee { + + private long id; + + @NotNull + @Size(min = 5) + private String name; + + @NotNull + @Size(min = 7) + private String contactNumber; + + public Employee() { + super(); + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getContactNumber() { + return contactNumber; + } + + public void setContactNumber(final String contactNumber) { + this.contactNumber = contactNumber; + } + +} diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeHome.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeHome.jsp new file mode 100644 index 0000000000..5ed572000a --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeHome.jsp @@ -0,0 +1,33 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +Form Example - Register an Employee + + +

Welcome, Enter The Employee Details

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

Submitted Employee Information

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

Pleas enter the correct details

+ + + + +
Retry
+ + + + \ No newline at end of file From 6cca0522517816a98ffbc883992d11e537b68c03 Mon Sep 17 00:00:00 2001 From: Alex Theedom Date: Sat, 26 Nov 2016 18:33:20 +0000 Subject: [PATCH 35/74] Add Spring MVC form and binding example --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index b8d0303160..77cf615a98 100644 --- a/pom.xml +++ b/pom.xml @@ -109,6 +109,7 @@ spring-katharsis spring-mockito spring-mvc-java + spring-mvc-forms spring-mvc-no-xml spring-mvc-tiles spring-mvc-velocity From 361874d0d6beb8c00a41e0ca86668fa8189b029a Mon Sep 17 00:00:00 2001 From: DianeDuan Date: Sun, 27 Nov 2016 12:23:51 +0800 Subject: [PATCH 36/74] simplify demos --- .../factorybean/FactoryBeanAppConfig.java | 11 +-- .../InitializationToolFactory.java | 67 ------------------ .../factorybean/NonSingleToolFactory.java | 20 +----- .../factorybean/PostConstructToolFactory.java | 68 ------------------- .../factorybean/SingleToolFactory.java | 20 +----- .../java/com/baeldung/factorybean/Tool.java | 22 +----- .../com/baeldung/factorybean/ToolFactory.java | 20 +----- .../java/com/baeldung/factorybean/Worker.java | 30 -------- .../factorybean-abstract-spring-ctx.xml | 24 ------- .../resources/factorybean-init-spring-ctx.xml | 17 ----- .../factorybean-postconstruct-spring-ctx.xml | 20 ------ .../main/resources/factorybean-spring-ctx.xml | 7 -- .../factorybean/AbstractFactoryBeanTest.java | 42 ++++++------ .../FactoryBeanInitializeTest.java | 17 ----- .../FactoryBeanJavaConfigTest.java | 27 ++++++++ .../baeldung/factorybean/FactoryBeanTest.java | 39 ----------- .../factorybean/FactoryBeanXmlConfigTest.java | 27 ++++++++ 17 files changed, 84 insertions(+), 394 deletions(-) delete mode 100644 spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java delete mode 100644 spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java delete mode 100644 spring-core/src/main/java/com/baeldung/factorybean/Worker.java delete mode 100644 spring-core/src/main/resources/factorybean-init-spring-ctx.xml delete mode 100644 spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml delete mode 100644 spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java create mode 100644 spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java delete mode 100644 spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java create mode 100644 spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.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 index ab36df27cb..51e24b6266 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java @@ -6,20 +6,15 @@ import org.springframework.context.annotation.Configuration; @Configuration public class FactoryBeanAppConfig { @Bean - public ToolFactory tool() { + public ToolFactory toolFactory() { 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; + public Tool tool() throws Exception { + return toolFactory().getObject(); } } diff --git a/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java deleted file mode 100644 index 6d2fd2564e..0000000000 --- a/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java +++ /dev/null @@ -1,67 +0,0 @@ -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; - private int toolId; - private String toolName; - private double toolPrice; - - @Override - public void afterPropertiesSet() throws Exception { - checkArgument(!StringUtils.isEmpty(toolName), "tool name cannot be empty"); - checkArgument(toolPrice >= 0, "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 index c818b775eb..7d3a6617c0 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java @@ -5,8 +5,6 @@ import org.springframework.beans.factory.config.AbstractFactoryBean; public class NonSingleToolFactory extends AbstractFactoryBean { private int factoryId; private int toolId; - private String toolName; - private double toolPrice; public NonSingleToolFactory() { setSingleton(false); @@ -19,7 +17,7 @@ public class NonSingleToolFactory extends AbstractFactoryBean { @Override protected Tool createInstance() throws Exception { - return new Tool(toolId, toolName, toolPrice); + return new Tool(toolId); } public int getFactoryId() { @@ -37,20 +35,4 @@ public class NonSingleToolFactory extends AbstractFactoryBean { 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 deleted file mode 100644 index 47db05d271..0000000000 --- a/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java +++ /dev/null @@ -1,68 +0,0 @@ -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; - private int toolId; - private String toolName; - private double toolPrice; - - @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() { - checkArgument(!StringUtils.isEmpty(toolName), "tool name cannot be empty"); - checkArgument(toolPrice >= 0, "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 index bc0c2d79c0..5d54900c2d 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java @@ -6,8 +6,6 @@ import org.springframework.beans.factory.config.AbstractFactoryBean; public class SingleToolFactory extends AbstractFactoryBean { private int factoryId; private int toolId; - private String toolName; - private double toolPrice; @Override public Class getObjectType() { @@ -16,7 +14,7 @@ public class SingleToolFactory extends AbstractFactoryBean { @Override protected Tool createInstance() throws Exception { - return new Tool(toolId, toolName, toolPrice); + return new Tool(toolId); } public int getFactoryId() { @@ -34,20 +32,4 @@ public class SingleToolFactory extends AbstractFactoryBean { 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 index a7f7f7681e..be56745b3d 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/Tool.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/Tool.java @@ -2,16 +2,12 @@ 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) { + public Tool(int id) { this.id = id; - this.name = name; - this.price = price; } public int getId() { @@ -21,20 +17,4 @@ public class Tool { 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 index ca8f82eadb..cddf17d337 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java @@ -5,12 +5,10 @@ import org.springframework.beans.factory.FactoryBean; public class ToolFactory implements FactoryBean { private int factoryId; private int toolId; - private String toolName; - private double toolPrice; @Override public Tool getObject() throws Exception { - return new Tool(toolId, toolName, toolPrice); + return new Tool(toolId); } @Override @@ -38,20 +36,4 @@ public class ToolFactory implements FactoryBean { 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 deleted file mode 100644 index 9a35c0656b..0000000000 --- a/spring-core/src/main/java/com/baeldung/factorybean/Worker.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.factorybean; - -public class Worker { - private String number; - private Tool tool; - - 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 index 6bce114d9c..fe914f79ba 100644 --- a/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml +++ b/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml @@ -6,34 +6,10 @@ - - - - - - - - - - - - - - - - - - - - - - - -
\ 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 deleted file mode 100644 index 47722b6d3d..0000000000 --- a/spring-core/src/main/resources/factorybean-init-spring-ctx.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - \ 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 deleted file mode 100644 index 94a4f407a8..0000000000 --- a/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - \ 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 index ab0c646bb0..e0d4aa4fec 100644 --- a/spring-core/src/main/resources/factorybean-spring-ctx.xml +++ b/spring-core/src/main/resources/factorybean-spring-ctx.xml @@ -6,12 +6,5 @@ - - - - - - -
\ 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 index 790107f114..aa6d7c2cd2 100644 --- a/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java +++ b/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java @@ -4,32 +4,36 @@ 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; +import javax.annotation.Resource; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath:factorybean-abstract-spring-ctx.xml" }) public class AbstractFactoryBeanTest { + + @Resource(name = "singleTool") + private Tool tool1; + @Resource(name = "singleTool") + private Tool tool2; + @Resource(name = "nonSingleTool") + private Tool tool3; + @Resource(name = "nonSingleTool") + private Tool tool4; + @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()); + assertThat(tool1.getId(), equalTo(1)); + assertTrue(tool1 == tool2); } @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()); + assertThat(tool3.getId(), equalTo(2)); + assertThat(tool4.getId(), equalTo(2)); + assertTrue(tool3 != tool4); } } diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java deleted file mode 100644 index 673bab6f63..0000000000 --- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java +++ /dev/null @@ -1,17 +0,0 @@ -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 = BeanCreationException.class) - public void testInitializationToolFactory() { - new ClassPathXmlApplicationContext("classpath:factorybean-init-spring-ctx.xml"); - } - - @Test(expected = BeanCreationException.class) - public void testPostConstructToolFactory() { - new ClassPathXmlApplicationContext("classpath:factorybean-postconstruct-spring-ctx.xml"); - } -} diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java new file mode 100644 index 0000000000..1bd1f3d234 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java @@ -0,0 +1,27 @@ +package com.baeldung.factorybean; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + +import javax.annotation.Resource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = FactoryBeanAppConfig.class) +public class FactoryBeanJavaConfigTest { + + @Resource + private Tool tool; + @Resource(name = "&toolFactory") + private ToolFactory toolFactory; + + @Test + public void testConstructWorkerByJava() { + assertThat(tool.getId(), equalTo(2)); + assertThat(toolFactory.getFactoryId(), equalTo(7070)); + } +} diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java deleted file mode 100644 index d06448b63c..0000000000 --- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java +++ /dev/null @@ -1,39 +0,0 @@ -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)); - } -} diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java new file mode 100644 index 0000000000..b479b231d9 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java @@ -0,0 +1,27 @@ +package com.baeldung.factorybean; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + +import javax.annotation.Resource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath:factorybean-spring-ctx.xml" }) +public class FactoryBeanXmlConfigTest { + + @Resource + private Tool tool; + @Resource(name = "&tool") + private ToolFactory toolFactory; + + @Test + public void testConstructWorkerByXml() { + assertThat(tool.getId(), equalTo(1)); + assertThat(toolFactory.getFactoryId(), equalTo(9090)); + } +} From b451fcfc02ed7e5d6bf30c77a2a3b1666029bfc8 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Sun, 27 Nov 2016 10:43:50 +0100 Subject: [PATCH 37/74] Reformat CustomWebSecurityConfigurerAdapter --- .../CustomWebSecurityConfigurerAdapter.java | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) 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 index 1901489305..db304edb36 100644 --- 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 @@ -13,28 +13,27 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationFi @Configuration @EnableWebSecurity public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { + @Autowired private MyBasicAuthenticationEntryPoint authenticationEntryPoint; @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) - throws Exception { - auth - .inMemoryAuthentication() - .withUser("user1").password("user1Pass") - .authorities("ROLE_USER"); + 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); + .antMatchers("/securityNone").permitAll() + .anyRequest().authenticated() + .and() + .httpBasic() + .authenticationEntryPoint(authenticationEntryPoint); http.addFilterAfter(new CustomFilter(), - BasicAuthenticationFilter.class); + BasicAuthenticationFilter.class); } } From fc64b7ed46b3daebe30a7c72f032765a0e21741d Mon Sep 17 00:00:00 2001 From: Hector Romero Date: Sun, 27 Nov 2016 06:18:12 -0600 Subject: [PATCH 38/74] BAEL-7: Join and Split Collections from and to String --- .../CollectionsToAndFromStringUnitTest.java | 110 ++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 core-java/src/test/java/org/baeldung/java/collections/CollectionsToAndFromStringUnitTest.java diff --git a/core-java/src/test/java/org/baeldung/java/collections/CollectionsToAndFromStringUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/CollectionsToAndFromStringUnitTest.java new file mode 100644 index 0000000000..5f4b3b417f --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/collections/CollectionsToAndFromStringUnitTest.java @@ -0,0 +1,110 @@ +package org.baeldung.java.collections; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.junit.Test; + +public class CollectionsToAndFromStringUnitTest { + @Test + public void whenConvertArrayToString_thenConverted() { + String[] colors = new String[] { "Red", "Blue", "Green", "Yellow" }; + String result = Arrays.stream(colors).collect(Collectors.joining(", ")); + + assertEquals(result, "Red, Blue, Green, Yellow"); + } + + @Test + public void whenConvertListToString_thenConverted() { + List directions = Arrays.asList("Left", "Right", "Top", "Bottom"); + String result = directions.stream().collect(Collectors.joining(", ")); + + assertEquals(result, "Left, Right, Top, Bottom"); + } + + @Test + public void whenConvertMapToString_thenConverted() { + Map users = new HashMap<>(); + users.put(1, "John Doe"); + users.put(2, "Paul Smith"); + users.put(3, "Susan Anderson"); + + String result = users.entrySet().stream() + .map(entry -> entry.getKey() + " = " + entry.getValue()) + .collect(Collectors.joining(", ")); + + assertEquals(result, "1 = John Doe, 2 = Paul Smith, 3 = Susan Anderson"); + } + + @Test + public void whenConvertNestedListToString_thenConverted() { + List> nested = new ArrayList<>(); + nested.add(Arrays.asList("Left", "Right", "Top", "Bottom")); + nested.add(Arrays.asList("Red", "Blue", "Green", "Yellow")); + + String result = nested.stream() + .map(nextList -> nextList.stream() + .collect(Collectors.joining("-"))) + .collect(Collectors.joining("; ")); + + assertEquals(result, "Left-Right-Top-Bottom; Red-Blue-Green-Yellow"); + } + + @Test + public void whenConvertListToStringAndSkipNull_thenConverted() { + List fruits = Arrays.asList("Apple", "Orange", null, "Grape"); + String result = fruits.stream() + .filter(next -> next != null) + .collect(Collectors.joining(", ")); + + assertEquals(result, "Apple, Orange, Grape"); + } + + @Test + public void whenConvertStringToArray_thenConverted() { + String colors = "Red, Blue, Green, Yellow"; + String[] result = colors.split(", "); + + assertArrayEquals(result, new String[] { "Red", "Blue", "Green", "Yellow" }); + } + + @Test + public void whenConvertStringToList_thenConverted() { + String colors = "Left, Right, Top, Bottom"; + List result = Arrays.asList(colors.split(", ")); + + assertTrue(result.equals(Arrays.asList("Left", "Right", "Top", "Bottom"))); + } + + @Test + public void whenConvertStringToMap_thenConverted() { + String users = "1 = John Doe, 2 = Paul Smith, 3 = Susan Anderson"; + + Map result = Arrays.stream(users.split(", ")) + .map(next -> next.split(" = ")) + .collect(Collectors.toMap(entry -> Integer.parseInt(entry[0]), entry -> entry[1])); + + assertEquals(result.get(1), "John Doe"); + assertEquals(result.get(2), "Paul Smith"); + assertEquals(result.get(3), "Susan Anderson"); + } + + @Test + public void whenConvertListToStringMultipleSeparators_thenConverted() { + String fruits = "Apple. , Orange, Grape. Lemon"; + + List result = Arrays.stream(fruits.split("[,|.]")) + .map(String::trim).filter(next -> !next.isEmpty()) + .collect(Collectors.toList()); + + assertTrue(result.equals(Arrays.asList("Apple", "Orange", "Grape", "Lemon"))); + } +} From 678e47dc1a9313cc3586c72bc17d094fe0ff9aaf Mon Sep 17 00:00:00 2001 From: pivovarit Date: Sun, 27 Nov 2016 18:26:14 +0100 Subject: [PATCH 39/74] Refactor CollectionsConcatenateUnitTest --- .../CollectionsConcatenateUnitTest.java | 36 ++++++++----------- 1 file changed, 15 insertions(+), 21 deletions(-) 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 index 3ee08767bd..0d913db1bd 100644 --- a/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java @@ -1,21 +1,15 @@ 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; +import org.junit.Assert; +import org.junit.Test; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; public class CollectionsConcatenateUnitTest { @@ -63,16 +57,16 @@ public class CollectionsConcatenateUnitTest { Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined); } - public static Iterable concat(Iterable list1, Iterable list2) { + public static Iterable concat(Iterable i1, Iterable i2) { return new Iterable() { public Iterator iterator() { return new Iterator() { - protected Iterator listIterator = list1.iterator(); - protected Boolean checkedHasNext; - protected E nextValue; + Iterator listIterator = i1.iterator(); + Boolean checkedHasNext; + E nextValue; private boolean startTheSecond; - public void theNext() { + void theNext() { if (listIterator.hasNext()) { checkedHasNext = true; nextValue = listIterator.next(); @@ -80,7 +74,7 @@ public class CollectionsConcatenateUnitTest { checkedHasNext = false; else { startTheSecond = true; - listIterator = list2.iterator(); + listIterator = i2.iterator(); theNext(); } } @@ -107,7 +101,7 @@ public class CollectionsConcatenateUnitTest { } public static List makeListFromIterable(Iterable iter) { - List list = new ArrayList(); + List list = new ArrayList<>(); for (E item : iter) { list.add(item); } From aecc8503f235e90b5421d4044b64d3e1238dfa09 Mon Sep 17 00:00:00 2001 From: tschiman Date: Sun, 27 Nov 2016 16:02:24 -0700 Subject: [PATCH 40/74] BAEL-89 Some final code changes for the article --- spring-session/pom.xml | 2 +- .../java/com/baeldung/spring/session/SessionController.java | 2 +- .../java/com/baeldung/spring/session/SessionControllerTest.java | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/spring-session/pom.xml b/spring-session/pom.xml index cf6fc71be2..848fdfc405 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -6,7 +6,7 @@ spring-session 1.0.0-SNAPSHOT - pom + jar org.springframework.boot diff --git a/spring-session/src/main/java/com/baeldung/spring/session/SessionController.java b/spring-session/src/main/java/com/baeldung/spring/session/SessionController.java index 224196d8a0..ac0479afed 100644 --- a/spring-session/src/main/java/com/baeldung/spring/session/SessionController.java +++ b/spring-session/src/main/java/com/baeldung/spring/session/SessionController.java @@ -6,7 +6,7 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class SessionController { @RequestMapping("/") - public String helloTomcatAdmin() { + public String helloAdmin() { return "hello admin"; } } diff --git a/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java b/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java index 5775710410..42d12112a2 100644 --- a/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java +++ b/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java @@ -83,5 +83,4 @@ public class SessionControllerTest { return new HttpEntity<>(headers); } - } \ No newline at end of file From 977333c9a312759d1dd537434001bef6f4ed869a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Garc=C3=ADa=20Heredero?= Date: Mon, 28 Nov 2016 18:43:10 +0100 Subject: [PATCH 41/74] BAEL-228 (#863) * Update HtmlUnitAndJUnitTest.java * Update HtmlUnitWebScraping.java * Update HtmlUnitAndSpringTest.java * Create message.html * Update HtmlUnitAndJUnitTest.java * Delete HtmlUnitAndSpringIntegrationTest.java * Delete HtmlUnitTest.java --- .../webapp/WEB-INF/templates/message.html | 15 ++++ .../htmlunit/HtmlUnitAndJUnitTest.java | 31 ++++++++ .../HtmlUnitAndSpringIntegrationTest.java | 72 ------------------- .../htmlunit/HtmlUnitAndSpringTest.java | 61 ++++++++++++++++ .../com/baeldung/htmlunit/HtmlUnitTest.java | 21 ------ .../htmlunit/HtmlUnitWebScraping.java | 46 ++++++------ 6 files changed, 131 insertions(+), 115 deletions(-) create mode 100644 spring-mvc-java/src/main/webapp/WEB-INF/templates/message.html create mode 100644 spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java delete mode 100644 spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java create mode 100644 spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java delete mode 100644 spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/templates/message.html b/spring-mvc-java/src/main/webapp/WEB-INF/templates/message.html new file mode 100644 index 0000000000..291e8312ae --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/templates/message.html @@ -0,0 +1,15 @@ + + + + + + +
+ Message: + +
+ + + + diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java new file mode 100644 index 0000000000..8395a49581 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.htmlunit; + +import org.junit.Assert; +import org.junit.Test; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlPage; + +public class HtmlUnitAndJUnitTest { + + @Before + public void init() throws Exception { + webClient = new WebClient(); + } + + @After + public void close() throws Exception { + webClient.close(); + } + + @Test + public void givenAClient_whenEnteringBaeldung_thenPageTitleIsOk() + throws Exception { + webClient.getOptions().setThrowExceptionOnScriptError(false); + HtmlPage page = webClient.getPage("http://www.baeldung.com/"); + Assert.assertEquals( + "Baeldung | Java, Spring and Web Development tutorials", + page.getTitleText()); + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java deleted file mode 100644 index 406975b6cc..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.htmlunit; - -import java.io.IOException; -import java.net.MalformedURLException; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; -import org.springframework.web.context.WebApplicationContext; - -import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; -import com.gargoylesoftware.htmlunit.WebClient; -import com.gargoylesoftware.htmlunit.html.HtmlForm; -import com.gargoylesoftware.htmlunit.html.HtmlPage; -import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; -import com.gargoylesoftware.htmlunit.html.HtmlTextInput; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { TestConfig.class }) -public class HtmlUnitAndSpringIntegrationTest { - - @Autowired - private WebApplicationContext wac; - - private WebClient webClient; - - @Before - public void setup() { - webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build(); - } - - // - - @Test - @Ignore("Related view message.html does not exist check MessageController") - public void givenAMessage_whenSent_thenItShows() throws FailingHttpStatusCodeException, MalformedURLException, IOException { - final String text = "Hello world!"; - final HtmlPage page = webClient.getPage("http://localhost/message/showForm"); - System.out.println(page.asXml()); - - final HtmlTextInput messageText = page.getHtmlElementById("message"); - messageText.setValueAttribute(text); - - final HtmlForm form = page.getForms().get(0); - final HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit"); - final HtmlPage newPage = submit.click(); - - final String receivedText = newPage.getHtmlElementById("received").getTextContent(); - - Assert.assertEquals(receivedText, text); - System.out.println(newPage.asXml()); - } - - @Test - public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { - try (final WebClient client = new WebClient()) { - webClient.getOptions().setThrowExceptionOnScriptError(false); - - final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); - Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); - } - } - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java new file mode 100644 index 0000000000..45e441f47f --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java @@ -0,0 +1,61 @@ +package com.baeldung.htmlunit; + +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; +import org.springframework.web.context.WebApplicationContext; + +import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlForm; +import com.gargoylesoftware.htmlunit.html.HtmlPage; +import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; +import com.gargoylesoftware.htmlunit.html.HtmlTextInput; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { TestConfig.class }) +public class HtmlUnitAndSpringTest { + + @Autowired + private WebApplicationContext wac; + + private WebClient webClient; + + @Before + public void setup() { + webClient = MockMvcWebClientBuilder + .webAppContextSetup(wac).build(); + } + + @Test + public void givenAMessage_whenSent_thenItShows() throws Exception { + String text = "Hello world!"; + HtmlPage page; + + String url = "http://localhost/message/showForm"; + page = webClient.getPage(url); + + HtmlTextInput messageText = page.getHtmlElementById("message"); + messageText.setValueAttribute(text); + + HtmlForm form = page.getForms().get(0); + HtmlSubmitInput submit = form.getOneHtmlElementByAttribute( + "input", "type", "submit"); + HtmlPage newPage = submit.click(); + + String receivedText = newPage.getHtmlElementById("received") + .getTextContent(); + + Assert.assertEquals(receivedText, text); + } +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java deleted file mode 100644 index 6a7e961eb1..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.htmlunit; - -import org.junit.Assert; -import org.junit.Test; - -import com.gargoylesoftware.htmlunit.WebClient; -import com.gargoylesoftware.htmlunit.html.HtmlPage; - -public class HtmlUnitTest { - - @Test - public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { - try (final WebClient webClient = new WebClient()) { - webClient.getOptions().setThrowExceptionOnScriptError(false); - - final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); - Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); - } - } - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java index 9919d7571d..f97bedddef 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java @@ -5,36 +5,38 @@ import java.util.List; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlHeading1; -import com.gargoylesoftware.htmlunit.html.HtmlHeading2; import com.gargoylesoftware.htmlunit.html.HtmlPage; public class HtmlUnitWebScraping { - public static void main(final String[] args) throws Exception { - try (final WebClient webClient = new WebClient()) { + private WebClient webClient; - webClient.getOptions().setCssEnabled(false); - webClient.getOptions().setJavaScriptEnabled(false); + @Before + public void init() throws Exception { + webClient = new WebClient(); + } - final HtmlPage page = webClient.getPage("http://www.baeldung.com/full_archive"); - final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath("(//ul[@class='car-monthlisting']/li)[1]/a").get(0); + @After + public void close() throws Exception { + webClient.close(); + } - System.out.println("Entering: " + latestPostLink.getHrefAttribute()); + @Test + public void givenBaeldungArchive_whenRetrievingArticle_thenHasH1() + throws Exception { + webClient.getOptions().setCssEnabled(false); + webClient.getOptions().setJavaScriptEnabled(false); - final HtmlPage postPage = latestPostLink.click(); + String url = "http://www.baeldung.com/full_archive"; + HtmlPage page = webClient.getPage(url); + String xpath = "(//ul[@class='car-monthlisting']/li)[1]/a"; + HtmlAnchor latestPostLink + = (HtmlAnchor) page.getByXPath(xpath).get(0); + HtmlPage postPage = latestPostLink.click(); - final HtmlHeading1 heading1 = (HtmlHeading1) postPage.getByXPath("//h1").get(0); - System.out.println("Title: " + heading1.getTextContent()); - - final List headings2 = (List) postPage.getByXPath("//h2"); - - final StringBuilder sb = new StringBuilder(heading1.getTextContent()); - for (final HtmlHeading2 h2 : headings2) { - sb.append("\n").append(h2.getTextContent()); - } - - System.out.println(sb.toString()); - } - } + List h1 + = (List) postPage.getByXPath("//h1"); + Assert.assertTrue(h1.size() > 0); + } } From cc34a10bc298701b49b66d3f0a2afb913cde1af7 Mon Sep 17 00:00:00 2001 From: maibin Date: Mon, 28 Nov 2016 18:55:33 +0100 Subject: [PATCH 42/74] @Async and Spring Security (#864) --- spring-security-rest/pom.xml | 695 +++++++++--------- .../web/controller/AsyncController.java | 24 + .../src/main/webapp/WEB-INF/api-servlet.xml | 6 +- .../src/main/webapp/WEB-INF/web.xml | 87 +-- .../org/baeldung/web/AsyncControllerTest.java | 51 ++ .../java/org/baeldung/web/TestConfig.java | 9 + 6 files changed, 485 insertions(+), 387 deletions(-) create mode 100644 spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java create mode 100644 spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerTest.java diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 60f3ed41d1..df000d0df5 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -1,393 +1,400 @@ - 4.0.0 - com.baeldung - spring-security-rest - 0.1-SNAPSHOT + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + spring-security-rest + 0.1-SNAPSHOT - spring-security-rest - war + spring-security-rest + war - + - + - - org.springframework.security - spring-security-web - ${org.springframework.security.version} - - - org.springframework.security - spring-security-config - ${org.springframework.security.version} - + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + - + - - org.springframework - spring-core - ${org.springframework.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-context - ${org.springframework.version} - - - org.springframework - spring-jdbc - ${org.springframework.version} - - - org.springframework - spring-beans - ${org.springframework.version} - - - org.springframework - spring-aop - ${org.springframework.version} - - - org.springframework - spring-tx - ${org.springframework.version} - - - org.springframework - spring-expression - ${org.springframework.version} - + + org.springframework + spring-core + ${org.springframework.version} + + + commons-logging + commons-logging + + + + + org.springframework + spring-context + ${org.springframework.version} + + + org.springframework + spring-jdbc + ${org.springframework.version} + + + org.springframework + spring-beans + ${org.springframework.version} + + + org.springframework + spring-aop + ${org.springframework.version} + + + org.springframework + spring-tx + ${org.springframework.version} + + + org.springframework + spring-expression + ${org.springframework.version} + - - org.springframework - spring-web - ${org.springframework.version} - - - org.springframework - spring-webmvc - ${org.springframework.version} - + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + - - - org.springframework.hateoas - spring-hateoas - ${org.springframework.hateoas.version} - + + + org.springframework.hateoas + spring-hateoas + ${org.springframework.hateoas.version} + - + - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - provided - + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + - - javax.servlet - jstl - ${jstl.version} - runtime - + + javax.servlet + jstl + ${jstl.version} + runtime + - - javax.validation - validation-api - ${javax.validation.version} - + + javax.validation + validation-api + ${javax.validation.version} + - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + - - - com.google.guava - guava - ${guava.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - + + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - - - org.springframework - spring-test - ${org.springframework.version} - test - + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + - - org.springframework.security - spring-security-test - ${org.springframework.security.version} - test - + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + org.springframework.security + spring-security-test + ${org.springframework.security.version} + test + - - com.jayway.restassured - rest-assured - ${rest-assured.version} - test - - - commons-logging - commons-logging - - - + + com.jayway.restassured + rest-assured + ${rest-assured.version} + test + + + commons-logging + commons-logging + + + - - junit - junit - ${junit.version} - test - + + junit + junit + ${junit.version} + test + - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + - - org.mockito - mockito-core - ${mockito.version} - test - + + org.mockito + mockito-core + ${mockito.version} + test + - - - io.springfox - springfox-swagger2 - ${springfox-swagger.version} - + + + io.springfox + springfox-swagger2 + ${springfox-swagger.version} + - - io.springfox - springfox-swagger-ui - ${springfox-swagger.version} - + + io.springfox + springfox-swagger-ui + ${springfox-swagger.version} + - + + + commons-fileupload + commons-fileupload + 1.3.2 + - - spring-security-rest - - - src/main/resources - true - - + - + + spring-security-rest + + + src/main/resources + true + + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - + - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*LiveTest.java - - - - - - + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - - jetty8x - embedded - - - - - - - 8082 - - - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*LiveTest.java + + + + + + - + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + + jetty8x + embedded + + + + + + + 8082 + + + + - + - - - live - - - - org.codehaus.cargo - cargo-maven2-plugin - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - + - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*LiveTest.java - - - cargo - - - - - + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + - - - - - - - - - 4.2.5.RELEASE - 4.0.4.RELEASE - 0.19.0.RELEASE + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + - - 4.3.11.Final - 5.1.38 + +
+ + - - 1.7.13 - 1.1.3 - - 5.2.2.Final - 3.0.1 - 1.1.0.Final - 1.2 - 2.7.8 + + + 4.2.5.RELEASE + 4.0.4.RELEASE + 0.19.0.RELEASE - - 19.0 - 3.4 + + 4.3.11.Final + 5.1.38 - - 1.3 - 4.12 - 1.10.19 - 2.9.0 + + 1.7.13 + 1.1.3 - - 2.4.0 + + 5.2.2.Final + 3.0.1 + 1.1.0.Final + 1.2 + 2.7.8 - 4.4.1 - 4.5 + + 19.0 + 3.4 - 2.9.0 + + 1.3 + 4.12 + 1.10.19 + 2.9.0 - - 3.5.1 - 2.6 - 2.19.1 - 1.4.18 + + 2.4.0 - + 4.4.1 + 4.5 + + 2.9.0 + + + 3.5.1 + 2.6 + 2.19.1 + 1.4.18 + + diff --git a/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java b/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java new file mode 100644 index 0000000000..bc59b4226a --- /dev/null +++ b/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java @@ -0,0 +1,24 @@ +package org.baeldung.web.controller; + +import java.util.concurrent.Callable; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.multipart.MultipartFile; + +@Controller +public class AsyncController { + + @RequestMapping(method = RequestMethod.POST, value = "/upload") + public Callable processUpload(final MultipartFile file) { + + return new Callable() { + public Boolean call() throws Exception { + // ... + return true; + } + }; + } + +} diff --git a/spring-security-rest/src/main/webapp/WEB-INF/api-servlet.xml b/spring-security-rest/src/main/webapp/WEB-INF/api-servlet.xml index 4ba9642448..5a68371f6c 100644 --- a/spring-security-rest/src/main/webapp/WEB-INF/api-servlet.xml +++ b/spring-security-rest/src/main/webapp/WEB-INF/api-servlet.xml @@ -1,6 +1,10 @@ + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"> + + + \ No newline at end of file diff --git a/spring-security-rest/src/main/webapp/WEB-INF/web.xml b/spring-security-rest/src/main/webapp/WEB-INF/web.xml index 3af8709dab..c030a9dd63 100644 --- a/spring-security-rest/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-rest/src/main/webapp/WEB-INF/web.xml @@ -1,54 +1,57 @@ - + http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" + id="WebApp_ID" version="3.0"> - Spring MVC Application + Spring MVC Application - - - contextClass - + + + contextClass + org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - contextConfigLocation - org.baeldung.spring - + + + contextConfigLocation + org.baeldung.spring + - - org.springframework.web.context.ContextLoaderListener - + + org.springframework.web.context.ContextLoaderListener + - - - api - org.springframework.web.servlet.DispatcherServlet - - throwExceptionIfNoHandlerFound - true - - - - api - /api/* - + + + api + org.springframework.web.servlet.DispatcherServlet + + throwExceptionIfNoHandlerFound + true + + + + api + /api/* + - - - springSecurityFilterChain - org.springframework.web.filter.DelegatingFilterProxy - - - springSecurityFilterChain - /* - + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + REQUEST + ASYNC + - - - + + + \ No newline at end of file diff --git a/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerTest.java b/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerTest.java new file mode 100644 index 0000000000..37122ed836 --- /dev/null +++ b/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerTest.java @@ -0,0 +1,51 @@ +package org.baeldung.web; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.baeldung.spring.ClientWebConfig; +import org.baeldung.spring.SecurityJavaConfig; +import org.baeldung.spring.WebConfig; +import org.baeldung.web.controller.AsyncController; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class}) +public class AsyncControllerTest { + + @Autowired + WebApplicationContext wac; + @Autowired + MockHttpSession session; + + @Mock + AsyncController controller; + + private MockMvc mockMvc; + + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); + } + + @Test + public void testProcessUpload() throws Exception { + MockMultipartFile jsonFile = new MockMultipartFile("json", "", "application/json", + "{\"json\": \"someValue\"}".getBytes()); + mockMvc.perform(MockMvcRequestBuilders.fileUpload("/upload").file(jsonFile)).andExpect(status().isOk()); + } + +} diff --git a/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java b/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java index 8b55841508..bdce37dd10 100644 --- a/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java +++ b/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java @@ -1,10 +1,19 @@ package org.baeldung.web; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.web.multipart.MultipartResolver; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; @Configuration @ComponentScan({ "org.baeldung.web" }) public class TestConfig { + @Bean + public MultipartResolver multipartResolver() { + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + return multipartResolver; + } + } \ No newline at end of file From 6082ac9c9ecba721a04f092872250c42c5bc89b1 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Mon, 28 Nov 2016 19:12:29 +0100 Subject: [PATCH 43/74] Fix test --- .../baeldung/file/FileOperationsUnitTest.java | 23 ++++++++----------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java b/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java index 3319716dc6..16d0cb570b 100644 --- a/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java +++ b/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java @@ -1,11 +1,12 @@ package com.baeldung.file; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import org.apache.commons.io.FileUtils; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; + +import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; @@ -14,12 +15,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; -import org.apache.commons.io.FileUtils; -import org.hamcrest.CoreMatchers; -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; - public class FileOperationsUnitTest { @Test @@ -58,9 +53,9 @@ public class FileOperationsUnitTest { @Test public void givenURLName_whenUsingURL_thenFileData() throws IOException { - String expectedData = "Baeldung"; + String expectedData = "Example Domain"; - URL urlObject = new URL("http://www.baeldung.com/"); + URL urlObject = new URL("http://www.example.com/"); URLConnection urlConnection = urlObject.openConnection(); From 2ca24a31fd39e72f582d173d848a3a4956d486f6 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Mon, 28 Nov 2016 19:31:43 +0100 Subject: [PATCH 44/74] Refactor tests --- .../java/nio2/attributes/BasicAttribsTest.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java index dcc24c6415..8fc01ef85b 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java @@ -1,7 +1,7 @@ package com.baeldung.java.nio2.attributes; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.BeforeClass; +import org.junit.Test; import java.io.IOException; import java.nio.file.Files; @@ -11,15 +11,15 @@ import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class BasicAttribsTest { private static final String HOME = System.getProperty("user.home"); - BasicFileAttributes basicAttribs; + private static BasicFileAttributes basicAttribs; - @Before - public void setup() throws IOException { + @BeforeClass + public static void setup() throws IOException { Path home = Paths.get(HOME); BasicFileAttributeView basicView = Files.getFileAttributeView(home, BasicFileAttributeView.class); basicAttribs = basicView.readAttributes(); From d07891bfc8099b16515622fb81af6ec3cd1aeb73 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Mon, 28 Nov 2016 19:33:43 +0100 Subject: [PATCH 45/74] Fix test --- .../baeldung/java/nio2/attributes/BasicAttribsTest.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java index 8fc01ef85b..05686e79c0 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java @@ -31,9 +31,10 @@ public class BasicAttribsTest { FileTime modified = basicAttribs.lastModifiedTime(); FileTime accessed = basicAttribs.lastAccessTime(); - assertTrue(0 > created.compareTo(accessed)); - assertTrue(0 < modified.compareTo(created)); - assertTrue(0 == created.compareTo(created)); + System.out.println("Created: " + created); + System.out.println("Modified: " + modified); + System.out.println("Accessed: " + accessed); + } @Test From 13dbf6603b3ffaeaeae1f5e321fb890857fa5340 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Mon, 28 Nov 2016 19:43:15 +0100 Subject: [PATCH 46/74] Fix tests --- core-java/.gitignore | 1 - .../java/nio2/async/AsyncFileTest.java | 25 ++++++++----------- core-java/src/test/resources/file.txt | 1 + 3 files changed, 12 insertions(+), 15 deletions(-) create mode 100644 core-java/src/test/resources/file.txt diff --git a/core-java/.gitignore b/core-java/.gitignore index 6ecc6405c2..bb70a5d3eb 100644 --- a/core-java/.gitignore +++ b/core-java/.gitignore @@ -13,4 +13,3 @@ *.ear # Files generated by integration tests -*.txt \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java index db30d32210..948c93ff0b 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java @@ -1,6 +1,6 @@ package com.baeldung.java.nio2.async; -import static org.junit.Assert.assertEquals; +import org.junit.Test; import java.io.IOException; import java.net.URI; @@ -11,22 +11,22 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.UUID; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class AsyncFileTest { @Test - public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException { - Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString())); + public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException { + Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString())); AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ); ByteBuffer buffer = ByteBuffer.allocate(1024); Future operation = fileChannel.read(buffer, 0); - while (!operation.isDone()) - ; + operation.get(); String fileContent = new String(buffer.array()).trim(); buffer.clear(); @@ -36,7 +36,7 @@ public class AsyncFileTest { @Test public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException { - Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString())); + Path path = Paths.get(URI.create(AsyncFileTest.class.getResource("/file.txt").toString())); AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ); ByteBuffer buffer = ByteBuffer.allocate(1024); @@ -58,7 +58,7 @@ public class AsyncFileTest { } @Test - public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException { + public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException { String fileName = UUID.randomUUID().toString(); Path path = Paths.get(fileName); AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,StandardOpenOption.DELETE_ON_CLOSE); @@ -72,9 +72,7 @@ public class AsyncFileTest { Future operation = fileChannel.write(buffer, position); buffer.clear(); - while (!operation.isDone()) { - - } + operation.get(); String content = readContent(path); assertEquals("hello world", content); @@ -107,7 +105,7 @@ public class AsyncFileTest { }); } - public static String readContent(Path file) { + public static String readContent(Path file) throws ExecutionException, InterruptedException { AsynchronousFileChannel fileChannel = null; try { fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ); @@ -120,8 +118,7 @@ public class AsyncFileTest { Future operation = fileChannel.read(buffer, 0); - while (!operation.isDone()) - ; + operation.get(); String fileContent = new String(buffer.array()).trim(); buffer.clear(); diff --git a/core-java/src/test/resources/file.txt b/core-java/src/test/resources/file.txt new file mode 100644 index 0000000000..558d8bbf35 --- /dev/null +++ b/core-java/src/test/resources/file.txt @@ -0,0 +1 @@ +baeldung.com \ No newline at end of file From 88a8d5838f8b0dd15cadea9564879c403a22946c Mon Sep 17 00:00:00 2001 From: pivovarit Date: Mon, 28 Nov 2016 19:43:30 +0100 Subject: [PATCH 47/74] Revert .gitignore --- core-java/.gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/.gitignore b/core-java/.gitignore index bb70a5d3eb..6ecc6405c2 100644 --- a/core-java/.gitignore +++ b/core-java/.gitignore @@ -13,3 +13,4 @@ *.ear # Files generated by integration tests +*.txt \ No newline at end of file From 333d3bc1226787a45fe3113d8f7999db76e738e7 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Mon, 28 Nov 2016 22:15:24 +0100 Subject: [PATCH 48/74] Refactor AsyncEchoServer2 --- .../java/nio2/async/AsyncEchoServer2.java | 15 +++++++-------- .../baeldung/java/nio2/async/AsyncFileTest.java | 2 +- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java index 03ce233ce9..172d8036de 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java @@ -58,19 +58,18 @@ public class AsyncEchoServer2 { @Override public void completed(Integer result, Map attachment) { - Map actionInfo = attachment; - String action = (String) actionInfo.get("action"); + String action = (String) attachment.get("action"); if ("read".equals(action)) { - ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer"); + ByteBuffer buffer = (ByteBuffer) attachment.get("buffer"); buffer.flip(); - actionInfo.put("action", "write"); - clientChannel.write(buffer, actionInfo, this); + attachment.put("action", "write"); + clientChannel.write(buffer, attachment, this); buffer.clear(); } else if ("write".equals(action)) { ByteBuffer buffer = ByteBuffer.allocate(32); - actionInfo.put("action", "read"); - actionInfo.put("buffer", buffer); - clientChannel.read(buffer, actionInfo, this); + attachment.put("action", "read"); + attachment.put("buffer", buffer); + clientChannel.read(buffer, attachment, this); } } diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java index 948c93ff0b..fcffc524b1 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java @@ -60,7 +60,7 @@ public class AsyncFileTest { @Test public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException { String fileName = UUID.randomUUID().toString(); - Path path = Paths.get(fileName); + Path path = Paths.get(Paths.get(HOME)); AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,StandardOpenOption.DELETE_ON_CLOSE); ByteBuffer buffer = ByteBuffer.allocate(1024); From 602e98c6c3352148044924b5d702db3d59bd8349 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Mon, 28 Nov 2016 22:18:22 +0100 Subject: [PATCH 49/74] Fix AsyncFileTest --- .../java/com/baeldung/java/nio2/async/AsyncFileTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java index fcffc524b1..b03acf83ca 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java @@ -59,9 +59,9 @@ public class AsyncFileTest { @Test public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException { - String fileName = UUID.randomUUID().toString(); - Path path = Paths.get(Paths.get(HOME)); - AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,StandardOpenOption.DELETE_ON_CLOSE); + String fileName = "temp"; + Path path = Paths.get(fileName); + AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE); ByteBuffer buffer = ByteBuffer.allocate(1024); long position = 0; From 6e6c3e6e80ed1d145b783eed277d174c2b8e1708 Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 28 Nov 2016 23:35:30 +0200 Subject: [PATCH 50/74] move rest template test --- .../web/controller/MyFooController.java | 76 ++++++++ .../main/java/org/baeldung/web/dto/Foo.java | 6 + .../exception/ResourceNotFoundException.java | 8 + .../src/main/webapp/WEB-INF/api-servlet.xml | 8 +- .../client/RestTemplateBasicLiveTest.java | 173 +++++++++++++++++- 5 files changed, 262 insertions(+), 9 deletions(-) create mode 100644 spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java create mode 100644 spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java b/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java new file mode 100644 index 0000000000..f19ddca435 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java @@ -0,0 +1,76 @@ +package org.baeldung.web.controller; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletResponse; + +import org.baeldung.web.dto.Foo; +import org.baeldung.web.exception.ResourceNotFoundException; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +@Controller +@RequestMapping(value = "/myfoos") +public class MyFooController { + + private final Map myfoos; + + public MyFooController() { + super(); + myfoos = new HashMap(); + myfoos.put(1L, new Foo(1L, "sample foo")); + } + + // API - read + + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public Collection findAll() { + return myfoos.values(); + } + + @RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = { "application/json" }) + @ResponseBody + public Foo findById(@PathVariable final long id) { + final Foo foo = myfoos.get(id); + if (foo == null) { + throw new ResourceNotFoundException(); + } + return foo; + } + + // API - write + + @RequestMapping(method = RequestMethod.PUT, value = "/{id}") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) { + myfoos.put(id, foo); + return foo; + } + + @RequestMapping(method = RequestMethod.POST) + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo createFoo(@RequestBody final Foo foo, HttpServletResponse response) { + myfoos.put(foo.getId(), foo); + response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentRequest().path("/" + foo.getId()).toUriString()); + return foo; + } + + @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void deleteById(@PathVariable final long id) { + myfoos.remove(id); + } + +} diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java b/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java index 774d547464..240b368b50 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java +++ b/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java @@ -11,6 +11,12 @@ public class Foo { super(); } + public Foo(final String name) { + super(); + + this.name = name; + } + public Foo(final long id, final String name) { super(); diff --git a/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java b/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java new file mode 100644 index 0000000000..aab737b6ec --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java @@ -0,0 +1,8 @@ +package org.baeldung.web.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException { +} diff --git a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml index 21136b62c6..0f80990c16 100644 --- a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml +++ b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml @@ -8,7 +8,7 @@ - + + @@ -43,6 +44,11 @@ + + + + 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 e4321e163f..a47c60e9d8 100644 --- a/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -1,28 +1,42 @@ package org.baeldung.client; +import static org.apache.commons.codec.binary.Base64.encodeBase64; 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 static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.IOException; +import java.net.URI; +import java.util.Arrays; +import java.util.Set; import org.baeldung.web.dto.Foo; import org.junit.Before; import org.junit.Test; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RequestCallback; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Charsets; public class RestTemplateBasicLiveTest { private RestTemplate restTemplate; - private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos"; + private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/myfoos"; @Before public void beforeTest() { @@ -33,19 +47,19 @@ public class RestTemplateBasicLiveTest { @Test public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { - ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); + final 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); + final 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(), is(notNull())); + final ObjectMapper mapper = new ObjectMapper(); + final JsonNode root = mapper.readTree(response.getBody()); + final JsonNode name = root.path("name"); + assertThat(name.asText(), notNullValue()); } @Test @@ -56,4 +70,147 @@ public class RestTemplateBasicLiveTest { assertThat(foo.getId(), is(1L)); } + // HEAD, OPTIONS + + @Test + public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { + final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); + + assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); + } + + // POST + + @Test + public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() { + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + final Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class); + assertThat(foo, notNullValue()); + assertThat(foo.getName(), is("bar")); + } + + @Test + public void givenFooService_whenPostForLocation_thenCreatedLocationIsReturned() { + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + final URI location = restTemplate.postForLocation(fooResourceUrl, request); + assertThat(location, notNullValue()); + } + + @Test + public void givenFooService_whenPostResource_thenResourceIsCreated() { + final RestTemplate template = new RestTemplate(); + + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + + final ResponseEntity response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + final Foo foo = response.getBody(); + assertThat(foo, notNullValue()); + assertThat(foo.getName(), is("bar")); + } + + @Test + public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() { + final Set optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl); + final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD }; + + assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods))); + } + + // PUT + + @Test + public void givenFooService_whenPutExistingEntity_thenItIsUpdated() { + final RestTemplate template = new RestTemplate(); + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + // Create Resource + final ResponseEntity createResponse = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + + // Update Resource + final Foo updatedInstance = new Foo("newName"); + updatedInstance.setId(createResponse.getBody().getId()); + final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody().getId(); + final HttpEntity requestUpdate = new HttpEntity<>(updatedInstance, headers); + template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class); + + // Check that Resource was updated + final ResponseEntity updateResponse = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + final Foo foo = updateResponse.getBody(); + assertThat(foo.getName(), is(updatedInstance.getName())); + } + + @Test + public void givenFooService_whenPutExistingEntityWithCallback_thenItIsUpdated() { + final RestTemplate template = new RestTemplate(); + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + // Create entity + ResponseEntity response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + + // Update entity + final Foo updatedInstance = new Foo("newName"); + updatedInstance.setId(response.getBody().getId()); + final String resourceUrl = fooResourceUrl + '/' + response.getBody().getId(); + template.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null); + + // Check that entity was updated + response = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + final Foo foo = response.getBody(); + assertThat(foo.getName(), is(updatedInstance.getName())); + } + + // DELETE + + @Test + public void givenFooService_whenCallDelete_thenEntityIsRemoved() { + final Foo foo = new Foo("remove me"); + final ResponseEntity response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + + final String entityUrl = fooResourceUrl + "/" + response.getBody().getId(); + restTemplate.delete(entityUrl); + try { + restTemplate.getForEntity(entityUrl, Foo.class); + fail(); + } catch (final HttpClientErrorException ex) { + assertThat(ex.getStatusCode(), is(HttpStatus.NOT_FOUND)); + } + } + + // + + private HttpHeaders prepareBasicAuthHeaders() { + final HttpHeaders headers = new HttpHeaders(); + final String encodedLogPass = getBase64EncodedLogPass(); + headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass); + return headers; + } + + private String getBase64EncodedLogPass() { + final String logPass = "user1:user1Pass"; + final byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII)); + return new String(authHeaderBytes, Charsets.US_ASCII); + } + + private RequestCallback requestCallback(final Foo updatedInstance) { + return clientHttpRequest -> { + final ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(clientHttpRequest.getBody(), updatedInstance); + clientHttpRequest.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + clientHttpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass()); + }; + } + + // Simply setting restTemplate timeout using ClientHttpRequestFactory + + ClientHttpRequestFactory getSimpleClientHttpRequestFactory() { + final int timeout = 5; + final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); + clientHttpRequestFactory.setConnectTimeout(timeout * 1000); + return clientHttpRequestFactory; + } } From 753c71a399a304fe4b0aece6a4d7f7e84db50186 Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 28 Nov 2016 23:35:58 +0200 Subject: [PATCH 51/74] cleanup --- .../okhttp/OkHttpFileUploadingLiveTest.java | 46 +++++------- .../baeldung/okhttp/OkHttpGetLiveTest.java | 31 ++++---- .../baeldung/okhttp/OkHttpMiscLiveTest.java | 72 +++++++++---------- .../okhttp/OkHttpPostingLiveTest.java | 68 +++++++----------- .../web/test/RequestMappingLiveTest.java | 3 +- 5 files changed, 91 insertions(+), 129 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 d5765b9756..71fc755321 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java @@ -1,5 +1,6 @@ package org.baeldung.okhttp; +import static org.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; @@ -7,10 +8,6 @@ import static org.junit.Assert.assertThat; import java.io.File; import java.io.IOException; -import org.baeldung.okhttp.ProgressRequestWrapper; -import org.junit.Before; -import org.junit.Test; - import okhttp3.Call; import okhttp3.MediaType; import okhttp3.MultipartBody; @@ -19,33 +16,29 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; +import org.junit.Before; +import org.junit.Test; + public class OkHttpFileUploadingLiveTest { - private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; OkHttpClient client; @Before public void init() { - client = new OkHttpClient(); + client = new OkHttpClient(); } @Test public void whenUploadFile_thenCorrect() throws IOException { - RequestBody requestBody = new MultipartBody.Builder() - .setType(MultipartBody.FORM) - .addFormDataPart("file", "file.txt", - RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) - .build(); + final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build(); - Request request = new Request.Builder() - .url(BASE_URL + "/users/upload") - .post(requestBody) - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(requestBody).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } @@ -53,25 +46,18 @@ public class OkHttpFileUploadingLiveTest { @Test public void whenGetUploadFileProgress_thenCorrect() throws IOException { - RequestBody requestBody = new MultipartBody.Builder() - .setType(MultipartBody.FORM) - .addFormDataPart("file", "file.txt", - RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) - .build(); + final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build(); - ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> { + final ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> { - float percentage = 100f * bytesWritten / contentLength; + final float percentage = (100f * bytesWritten) / contentLength; assertFalse(Float.compare(percentage, 100) > 0); }); - Request request = new Request.Builder() - .url(BASE_URL + "/users/upload") - .post(countingBody) - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(countingBody).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); 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 034833da0d..fc78899da1 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -1,14 +1,12 @@ package org.baeldung.okhttp; +import static org.baeldung.client.Consts.APPLICATION_PORT; 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; @@ -16,9 +14,12 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; +import org.junit.Before; +import org.junit.Test; + public class OkHttpGetLiveTest { - private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; OkHttpClient client; @@ -30,40 +31,42 @@ public class OkHttpGetLiveTest { @Test public void whenGetRequest_thenCorrect() throws IOException { - Request request = new Request.Builder().url(BASE_URL + "/date").build(); + final Request request = new Request.Builder().url(BASE_URL + "/date").build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } @Test public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException { - HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); + final HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); urlBuilder.addQueryParameter("id", "1"); - String url = urlBuilder.build().toString(); + final String url = urlBuilder.build().toString(); - Request request = new Request.Builder().url(url).build(); + final Request request = new Request.Builder().url(url).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } @Test public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException { - Request request = new Request.Builder().url(BASE_URL + "/date").build(); + final Request request = new Request.Builder().url(BASE_URL + "/date").build(); - Call call = client.newCall(request); + final Call call = client.newCall(request); call.enqueue(new Callback() { + @Override public void onResponse(Call call, Response response) throws IOException { System.out.println("OK"); } + @Override public void onFailure(Call call, IOException e) { fail(); } 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 34e1554908..e6b3cc87b0 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -1,27 +1,27 @@ package org.baeldung.okhttp; -import okhttp3.*; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.baeldung.client.Consts.APPLICATION_PORT; + import java.io.File; import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + import okhttp3.Cache; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class OkHttpMiscLiveTest { - private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class); OkHttpClient client; @@ -29,31 +29,27 @@ public class OkHttpMiscLiveTest { @Before public void init() { - client = new OkHttpClient(); + client = new OkHttpClient(); } @Test public void whenSetRequestTimeout_thenFail() throws IOException { - OkHttpClient clientWithTimeout = new OkHttpClient.Builder() - .readTimeout(1, TimeUnit.SECONDS) - .build(); + final OkHttpClient clientWithTimeout = new OkHttpClient.Builder().readTimeout(1, TimeUnit.SECONDS).build(); - Request request = new Request.Builder() - .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. + .build(); - Call call = clientWithTimeout.newCall(request); - Response response = call.execute(); + final Call call = clientWithTimeout.newCall(request); + final Response response = call.execute(); response.close(); } @Test(expected = IOException.class) public void whenCancelRequest_thenCorrect() throws IOException { - ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); + final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); - Request request = new Request.Builder() - .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. + .build(); final int seconds = 1; final long startNanos = System.nanoTime(); @@ -63,42 +59,38 @@ public class OkHttpMiscLiveTest { // Schedule a job to cancel the call in 1 second. executor.schedule(() -> { - logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f); + logger.debug("Canceling call: " + ((System.nanoTime() - startNanos) / 1e9f)); call.cancel(); - logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f); + logger.debug("Canceled call: " + ((System.nanoTime() - startNanos) / 1e9f)); }, seconds, TimeUnit.SECONDS); - logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f); - Response response = call.execute(); - logger.debug("Call completed: " + (System.nanoTime() - startNanos) / 1e9f, response); + logger.debug("Executing call: " + ((System.nanoTime() - startNanos) / 1e9f)); + final Response response = call.execute(); + logger.debug("Call completed: " + ((System.nanoTime() - startNanos) / 1e9f), response); } @Test - public void whenSetResponseCache_thenCorrect() throws IOException { + public void whenSetResponseCache_thenCorrect() throws IOException { - int cacheSize = 10 * 1024 * 1024; // 10 MiB - File cacheDirectory = new File("src/test/resources/cache"); - Cache cache = new Cache(cacheDirectory, cacheSize); + final int cacheSize = 10 * 1024 * 1024; // 10 MiB + final File cacheDirectory = new File("src/test/resources/cache"); + final Cache cache = new Cache(cacheDirectory, cacheSize); - OkHttpClient clientCached = new OkHttpClient.Builder() - .cache(cache) - .build(); + final OkHttpClient clientCached = new OkHttpClient.Builder().cache(cache).build(); - Request request = new Request.Builder() - .url("http://publicobject.com/helloworld.txt") - .build(); + final Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build(); - Response response1 = clientCached.newCall(request).execute(); + final Response response1 = clientCached.newCall(request).execute(); logResponse(response1); - Response response2 = clientCached.newCall(request).execute(); + final Response response2 = clientCached.newCall(request).execute(); logResponse(response2); } private void logResponse(Response response) throws IOException { - logger.debug("Response response: " + response); + logger.debug("Response response: " + response); logger.debug("Response cache response: " + response.cacheResponse()); logger.debug("Response network response: " + response.networkResponse()); logger.debug("Response responseBody: " + response.body().string()); diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java index dce3bb174f..cbe5ff885c 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java @@ -1,14 +1,12 @@ package org.baeldung.okhttp; +import static org.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.Matchers.equalTo; 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; import okhttp3.Credentials; import okhttp3.FormBody; @@ -19,9 +17,12 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; +import org.junit.Before; +import org.junit.Test; + public class OkHttpPostingLiveTest { - private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; OkHttpClient client; @@ -29,77 +30,56 @@ public class OkHttpPostingLiveTest { @Before public void init() { - client = new OkHttpClient(); + client = new OkHttpClient(); } @Test public void whenSendPostRequest_thenCorrect() throws IOException { - RequestBody formBody = new FormBody.Builder() - .add("username", "test") - .add("password", "test") - .build(); + final RequestBody formBody = new FormBody.Builder().add("username", "test").add("password", "test").build(); - Request request = new Request.Builder() - .url(BASE_URL + "/users") - .post(formBody) - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/users").post(formBody).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } @Test public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException { - String postBody = "test post"; + final String postBody = "test post"; - Request request = new Request.Builder() - .url(URL_SECURED_BY_BASIC_AUTHENTICATION) - .addHeader("Authorization", Credentials.basic("test", "test")) - .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody)) - .build(); + final Request request = new Request.Builder().url(URL_SECURED_BY_BASIC_AUTHENTICATION).addHeader("Authorization", Credentials.basic("test", "test")).post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody)).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } @Test public void whenPostJson_thenCorrect() throws IOException { - String json = "{\"id\":1,\"name\":\"John\"}"; + final String json = "{\"id\":1,\"name\":\"John\"}"; - RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); + final RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); - Request request = new Request.Builder() - .url(BASE_URL + "/users/detail") - .post(body) - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } @Test public void whenSendMultipartRequest_thenCorrect() throws IOException { - RequestBody requestBody = new MultipartBody.Builder() - .setType(MultipartBody.FORM) - .addFormDataPart("username", "test") - .addFormDataPart("password", "test") - .addFormDataPart("file", "file.txt", - RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) - .build(); + final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("username", "test").addFormDataPart("password", "test") + .addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build(); - Request request = new Request.Builder() - .url(BASE_URL + "/users/multipart") - .post(requestBody) - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/users/multipart").post(requestBody).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } diff --git a/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java b/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java index 3155b5cda9..7828df7304 100644 --- a/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java @@ -1,5 +1,6 @@ package org.baeldung.web.test; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import org.junit.Test; @@ -31,7 +32,7 @@ public class RequestMappingLiveTest { @Test public void givenAcceptHeader_whenGetFoos_thenOk() { - RestAssured.given().accept("application/json").get(BASE_URI + "foos").then().assertThat().body(equalTo("Get some Foos with Header New")); + RestAssured.given().accept("application/json").get(BASE_URI + "foos").then().assertThat().body(containsString("Get some Foos with Header New")); } @Test From 73ac10fb96cd17bd5a69604c96b6b648d0321828 Mon Sep 17 00:00:00 2001 From: Hector Romero Date: Sun, 27 Nov 2016 06:18:12 -0600 Subject: [PATCH 52/74] BAEL-7: More examples for Join and Split Collections --- .../JoinSplitCollectionsUnitTest.java | 154 ++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java diff --git a/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java new file mode 100644 index 0000000000..b4dd0e46b1 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java @@ -0,0 +1,154 @@ +package org.baeldung.java.collections; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.Test; + +public class JoinSplitCollectionsUnitTest { + + @Test + public void whenJoiningTwoArrays_thenJoined() { + String[] animals1 = new String[] { "Dog", "Cat" }; + String[] animals2 = new String[] { "Bird", "Cow" }; + String[] result = Stream.concat(Arrays.stream(animals1), Arrays.stream(animals2)) + .toArray(size -> new String[size]); + + assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" }); + } + + @Test + public void whenJoiningTwoListsWithFilter_thenJoined() { + List list1 = Arrays.asList(7, 8, 11); + List list2 = Arrays.asList(9, 12, 10); + List result = Stream.concat(list1.stream(), list2.stream()).filter(next -> next <= 10) + .collect(Collectors.toList()); + + assertTrue(result.equals(Arrays.asList(7, 8, 9, 10))); + } + + @Test + public void whenConvertArrayToString_thenConverted() { + String[] colors = new String[] { "Red", "Blue", "Green", "Yellow" }; + String result = Arrays.stream(colors) + .collect(Collectors.joining(", ")); + + assertEquals(result, "Red, Blue, Green, Yellow"); + } + + @Test + public void whenConvertListToString_thenConverted() { + List directions = Arrays.asList("Left", "Right", "Top", "Bottom"); + String result = directions.stream() + .collect(Collectors.joining(", ")); + + assertEquals(result, "Left, Right, Top, Bottom"); + } + + @Test + public void whenConvertMapToString_thenConverted() { + Map users = new HashMap<>(); + users.put(1, "John Doe"); + users.put(2, "Paul Smith"); + users.put(3, "Susan Anderson"); + + String result = users.entrySet().stream().map(entry -> entry.getKey() + " = " + entry.getValue()) + .collect(Collectors.joining(", ")); + + assertEquals(result, "1 = John Doe, 2 = Paul Smith, 3 = Susan Anderson"); + } + + @Test + public void whenConvertNestedListToString_thenConverted() { + List> nested = new ArrayList<>(); + nested.add(Arrays.asList("Left", "Right", "Top", "Bottom")); + nested.add(Arrays.asList("Red", "Blue", "Green", "Yellow")); + + String result = nested.stream() + .map(nextList -> nextList.stream() + .collect(Collectors.joining("-"))) + .collect(Collectors.joining("; ")); + + assertEquals(result, "Left-Right-Top-Bottom; Red-Blue-Green-Yellow"); + } + + @Test + public void whenConvertListToStringAndSkipNull_thenConverted() { + List fruits = Arrays.asList("Apple", "Orange", null, "Grape"); + String result = fruits.stream() + .filter(next -> next != null) + .collect(Collectors.joining(", ")); + + assertEquals(result, "Apple, Orange, Grape"); + } + + @Test + public void whenSplitListGroupOddEven_thenConverted() { + List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + Map> result = list.stream() + .collect(Collectors.partitioningBy(number -> number % 2 == 0)); + + assertTrue(result.get(true).equals(Arrays.asList(2, 4, 6, 8, 10))); + assertTrue(result.get(false).equals(Arrays.asList(1, 3, 5, 7, 9))); + } + +@Test +public void whenSplitArrayByWordLength_thenConverted() { + String[] words = new String[]{"bye", "cold", "it", "and", "my", "word"}; + Map> result = Arrays.stream(words) + .collect(Collectors.groupingBy(word -> word.length())); + + assertTrue(result.get(2).equals(Arrays.asList("it", "my"))); + assertTrue(result.get(3).equals(Arrays.asList("bye", "and"))); + assertTrue(result.get(4).equals(Arrays.asList("cold", "word"))); +} + + @Test + public void whenConvertStringToArray_thenConverted() { + String colors = "Red, Blue, Green, Yellow"; + String[] result = colors.split(", "); + + assertArrayEquals(result, new String[] { "Red", "Blue", "Green", "Yellow" }); + } + + @Test + public void whenConvertStringToList_thenConverted() { + String colors = "Left, Right, Top, Bottom"; + List result = Arrays.asList(colors.split(", ")); + + assertTrue(result.equals(Arrays.asList("Left", "Right", "Top", "Bottom"))); + } + + @Test + public void whenConvertStringToMap_thenConverted() { + String users = "1 = John Doe, 2 = Paul Smith, 3 = Susan Anderson"; + + Map result = Arrays.stream(users.split(", ")) + .map(next -> next.split(" = ")) + .collect(Collectors.toMap(entry -> Integer.parseInt(entry[0]), entry -> entry[1])); + + assertEquals(result.get(1), "John Doe"); + assertEquals(result.get(2), "Paul Smith"); + assertEquals(result.get(3), "Susan Anderson"); + } + + @Test + public void whenConvertListToStringMultipleSeparators_thenConverted() { + String fruits = "Apple. , Orange, Grape. Lemon"; + + List result = Arrays.stream(fruits.split("[,|.]")) + .map(String::trim).filter(next -> !next.isEmpty()) + .collect(Collectors.toList()); + + assertTrue(result.equals(Arrays.asList("Apple", "Orange", "Grape", "Lemon"))); + } +} From 3af165fb1143e2c25c851c5f161f7ed1295d8a8d Mon Sep 17 00:00:00 2001 From: maverick Date: Tue, 29 Nov 2016 19:32:12 +0530 Subject: [PATCH 53/74] For Sorting Article --- .../src/test/java/org/baeldung/java/sorting/JavaSorting.java | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java diff --git a/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java b/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java new file mode 100644 index 0000000000..2e15a3576f --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java @@ -0,0 +1,5 @@ +package org.baeldung.java.sorting; + +public class JavaSorting { + +} From 751a3ca19f08278f4c19d19eb9b287581dd72db2 Mon Sep 17 00:00:00 2001 From: maverick Date: Tue, 29 Nov 2016 19:36:59 +0530 Subject: [PATCH 54/74] Changes for sorting article --- .../org/baeldung/java/sorting/Employee.java | 58 +++++ .../baeldung/java/sorting/JavaSorting.java | 216 ++++++++++++++++++ 2 files changed, 274 insertions(+) create mode 100644 core-java/src/test/java/org/baeldung/java/sorting/Employee.java diff --git a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java new file mode 100644 index 0000000000..768ee8f397 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java @@ -0,0 +1,58 @@ +package org.baeldung.java.sorting; + +public class Employee implements Comparable { + + private String name; + private int age; + private double salary; + + public Employee(String name, int age, double salary) { + this.name = name; + this.age = age; + this.salary = salary; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + + @Override + public boolean equals(Object obj) { + return ((Employee) obj).getName().equals(getName()); + } + + @Override + public int compareTo(Object o) { + Employee e = (Employee) o; + return getName().compareTo(e.getName()); + } + + @Override + public String toString() { + return new StringBuffer() + .append("(").append(getName()) + .append(getAge()).append(",") + .append(getSalary()).append(")").toString(); + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java b/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java index 2e15a3576f..1ae7bcbbb0 100644 --- a/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java +++ b/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java @@ -1,5 +1,221 @@ package org.baeldung.java.sorting; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.commons.lang3.ArrayUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.manipulation.Sortable; + +import com.google.common.primitives.Ints; + public class JavaSorting { + + private int [] toSort; + private int [] sortedInts; + private int [] sortedRangeInts; +// private Integer [] integers; +// private Integer [] sortedIntegers; +// private List integersList; +// private List sortedIntegersList; + private Employee[] employees; + private Employee[] employeesSorted; + private Employee[] employeesSortedByAge; + private HashMap map; + + @Before + public void initVariables () { + + toSort = new int[] + { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; + sortedInts = new int[] + {1, 5, 7, 66, 88, 89, 123, 200, 255}; + sortedRangeInts = new int[] + {5, 1, 89, 7, 88, 200, 255, 123, 66}; + +// integers = new Integer[] +// { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; +// sortedIntegers = new Integer[] +// {1, 5, 7, 66, 88, 89, 123, 200, 255}; +// +// integersList = Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }); +// sortedIntegersList = Arrays.asList(new Integer[] {1, 5, 7, 66, 88, 89, 123, 200, 255}); + + employees = new Employee[] { + new Employee("John", 23, 5000), + new Employee("Steve", 26, 6000), + new Employee("Frank", 33, 7000), + new Employee("Earl", 43, 10000), + new Employee("Jessica", 23, 4000), + new Employee("Pearl", 33, 6000)}; + employeesSorted = new Employee[] { + new Employee("Earl", 43, 10000), + new Employee("Frank", 33, 70000), + new Employee("Jessica", 23, 4000), + new Employee("John", 23, 5000), + new Employee("Pearl", 33, 4000), + new Employee("Steve", 26, 6000)}; + employeesSortedByAge = new Employee[] { + new Employee("John", 23, 5000), + new Employee("Jessica", 23, 4000), + new Employee("Steve", 26, 6000), + new Employee("Frank", 33, 70000), + new Employee("Pearl", 33, 4000), + new Employee("Earl", 43, 10000)}; + + HashMap map = new HashMap<>(); + map.put(55, "John"); + map.put(22, "Apple"); + map.put(66, "Earl"); + map.put(77, "Pearl"); + map.put(12, "George"); + map.put(6, "Rocky"); + + } + + @Test + public void givenIntArray_whenUsingSort_thenSortedArray() { + Arrays.sort(toSort); + + assertTrue(Arrays.equals(toSort, sortedInts)); + } + + @Test + public void givenIntegerArray_whenUsingSort_thenSortedArray() { + Integer [] integers = ArrayUtils.toObject(toSort); + Arrays.sort(integers, new Comparator() { + @Override + public int compare(Integer a, Integer b) { + return a - b; + } + }); + + assertTrue(Arrays.equals(integers, ArrayUtils.toObject(sortedInts))); + } + + @Test + public void givenArray_whenUsingSortWithLambdas_thenSortedArray() { + Integer [] integersToSort = ArrayUtils.toObject(toSort); + Arrays.sort(integersToSort, (a, b) -> { + return a - b; + }); + + assertTrue(Arrays.equals(integersToSort, ArrayUtils.toObject(sortedInts))); + } + + @Test + public void givenEmpArray_SortEmpArray_thenSortedArrayinNaturalOrder() { + Arrays.sort(employees); + + assertTrue(Arrays.equals(employees, employeesSorted)); + } + + + @Test + public void givenIntArray_whenUsingRangeSort_thenRangeSortedArray() { + Arrays.sort(toSort, 3, 7); + + assertTrue(Arrays.equals(toSort, sortedRangeInts)); + } + + @Test + public void givenIntArray_whenUsingParallelSort_thenParallelSortedArray() { + Arrays.parallelSort(toSort); + + assertTrue(Arrays.equals(toSort, sortedInts)); + } + + + + @Test + public void givenArrayObjects_whenUsingComparing_thenSortedArrayObjects() { + List employeesList = Arrays.asList(employees); + + employeesList.sort(Comparator.comparing(Employee::getAge));//.thenComparing(Employee::getName)); + + assertTrue(Arrays.equals(employeesList.toArray(), employeesSortedByAge)); + } + + @Test + public void givenList_whenUsingSort_thenSortedList() { + List toSortList = Ints.asList(toSort); + Collections.sort(toSortList); + + assertTrue(Arrays.equals(toSortList.toArray(), + ArrayUtils.toObject(sortedInts))); + } + + @Test + public void givenMap_whenSortingByKeys_thenSortedMap() { + Integer[] sortedKeys = new Integer[] { 6, 12, 22, 55, 66, 77 }; + + List> entries = new ArrayList<>(map.entrySet()); + Collections.sort(entries, new Comparator>() { + @Override + public int compare(Entry o1, Entry o2) { + return o1.getKey().compareTo(o2.getKey()); + } + }); + HashMap sortedMap = new LinkedHashMap<>(); + for (Map.Entry entry : entries) { + sortedMap.put(entry.getKey(), entry.getValue()); + } + + assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys)); + } + + @Test + public void givenMap_whenSortingByValues_thenSortedMap() { + String[] sortedValues = new String[] + { "Apple", "Earl", "George", "John", "Pearl", "Rocky" }; + + List> entries = new ArrayList<>(map.entrySet()); + Collections.sort(entries, new Comparator>() { + @Override + public int compare(Entry o1, Entry o2) { + return o1.getValue().compareTo(o2.getValue()); + } + }); + HashMap sortedMap = new LinkedHashMap<>(); + for (Map.Entry entry : entries) { + sortedMap.put(entry.getKey(), entry.getValue()); + } + + assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues)); + } + + + + + + + @Test + public void givenSet_whenUsingSort_thenSortedSet() { + HashSet integersSet = new LinkedHashSet<>(Ints.asList(toSort)); + HashSet descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(new Integer[] + {255, 200, 123, 89, 88, 66, 7, 5, 1})); + + ArrayList list = new ArrayList(integersSet); + Collections.sort(list, (i1, i2) -> { + return i2 - i1; + }); + integersSet = new LinkedHashSet<>(list); + + assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray())); + } + + } From b6403fc1f0e5018fc7211f1fe4d79545db8d3d34 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Tue, 29 Nov 2016 15:54:58 +0100 Subject: [PATCH 55/74] BAEL-89 - excluding integration test --- spring-session/pom.xml | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/spring-session/pom.xml b/spring-session/pom.xml index 848fdfc405..49329af345 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -12,7 +12,8 @@ org.springframework.boot spring-boot-starter-parent 1.4.0.RELEASE - + + @@ -66,6 +67,19 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*ControllerTest.java + + + + + 2.19.1 + \ No newline at end of file From 7676697c4cbefcd227fcb684d53a77d2992f0524 Mon Sep 17 00:00:00 2001 From: Diane Duan Date: Wed, 30 Nov 2016 00:41:30 +0800 Subject: [PATCH 56/74] BAEL-453: How to use the Spring FactoryBean - use custom bean name (#866) * custom bean name * @Autowire --- .../com/baeldung/factorybean/FactoryBeanAppConfig.java | 7 +------ .../baeldung/factorybean/FactoryBeanJavaConfigTest.java | 6 ++++-- .../com/baeldung/factorybean/FactoryBeanXmlConfigTest.java | 3 ++- 3 files changed, 7 insertions(+), 9 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 02eef57e3d..f0cfadcab1 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java @@ -6,16 +6,11 @@ import org.springframework.context.annotation.Configuration; @Configuration public class FactoryBeanAppConfig { - @Bean + @Bean(name = "tool") public ToolFactory toolFactory() { ToolFactory factory = new ToolFactory(); factory.setFactoryId(7070); factory.setToolId(2); return factory; } - - @Bean - public Tool tool() throws Exception { - return toolFactory().getObject(); - } } diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java index 1bd1f3d234..700d8050c7 100644 --- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java @@ -7,6 +7,8 @@ import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -14,9 +16,9 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration(classes = FactoryBeanAppConfig.class) public class FactoryBeanJavaConfigTest { - @Resource + @Autowired private Tool tool; - @Resource(name = "&toolFactory") + @Resource(name = "&tool") private ToolFactory toolFactory; @Test diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java index b479b231d9..8ba1129b30 100644 --- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java @@ -7,6 +7,7 @@ import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -14,7 +15,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration(locations = { "classpath:factorybean-spring-ctx.xml" }) public class FactoryBeanXmlConfigTest { - @Resource + @Autowired private Tool tool; @Resource(name = "&tool") private ToolFactory toolFactory; From 0e3b7fe17c866e3a6279642c294770c88fde0ddc Mon Sep 17 00:00:00 2001 From: pivovarit Date: Tue, 29 Nov 2016 17:43:17 +0100 Subject: [PATCH 57/74] Formatting --- .../factorybean/FactoryBeanJavaConfigTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java index 700d8050c7..706aa0a63f 100644 --- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java @@ -1,23 +1,23 @@ package com.baeldung.factorybean; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertThat; - -import javax.annotation.Resource; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import javax.annotation.Resource; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = FactoryBeanAppConfig.class) public class FactoryBeanJavaConfigTest { @Autowired private Tool tool; + @Resource(name = "&tool") private ToolFactory toolFactory; From 211d7699423c91f5a23f590302f35fdac79cfbd6 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Tue, 29 Nov 2016 18:02:19 +0100 Subject: [PATCH 58/74] Refactor FileSearchExample --- .../java/nio2/visitor/FileSearchExample.java | 26 ++++++++----------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java index 15910abf9b..62c6954e1a 100644 --- a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java +++ b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java @@ -1,23 +1,19 @@ package com.baeldung.java.nio2.visitor; +import java.io.IOException; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; + import static java.nio.file.FileVisitResult.CONTINUE; import static java.nio.file.FileVisitResult.TERMINATE; -import java.io.IOException; -import java.nio.file.FileVisitResult; -import java.nio.file.FileVisitor; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.attribute.BasicFileAttributes; - public class FileSearchExample implements FileVisitor { - private static String FILE_NAME; - private static Path START_DIR; + private final String fileName; + private final Path startDir; public FileSearchExample(String fileName, Path startingDir) { - FILE_NAME = fileName; - START_DIR = startingDir; + this.fileName = fileName; + startDir = startingDir; } @Override @@ -28,7 +24,7 @@ public class FileSearchExample implements FileVisitor { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String fileName = file.getFileName().toString(); - if (FILE_NAME.equals(fileName)) { + if (this.fileName.equals(fileName)) { System.out.println("File found: " + file.toString()); return TERMINATE; } @@ -43,9 +39,9 @@ public class FileSearchExample implements FileVisitor { @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { - boolean finishedSearch = Files.isSameFile(dir, START_DIR); + boolean finishedSearch = Files.isSameFile(dir, startDir); if (finishedSearch) { - System.out.println("File:" + FILE_NAME + " not found"); + System.out.println("File:" + fileName + " not found"); return TERMINATE; } return CONTINUE; From 7194d8b84a78c62eb3ddbed06104eeb8007e0b15 Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 30 Nov 2016 09:05:06 +0200 Subject: [PATCH 59/74] cleanup work --- .../baeldung/java/sorting/JavaSorting.java | 129 +++++++----------- 1 file changed, 47 insertions(+), 82 deletions(-) diff --git a/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java b/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java index 1ae7bcbbb0..72730aeb8b 100644 --- a/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java +++ b/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java @@ -17,64 +17,42 @@ import java.util.Map.Entry; import org.apache.commons.lang3.ArrayUtils; import org.junit.Before; import org.junit.Test; -import org.junit.runner.manipulation.Sortable; import com.google.common.primitives.Ints; public class JavaSorting { - - private int [] toSort; - private int [] sortedInts; - private int [] sortedRangeInts; -// private Integer [] integers; -// private Integer [] sortedIntegers; -// private List integersList; -// private List sortedIntegersList; + + private int[] toSort; + private int[] sortedInts; + private int[] sortedRangeInts; + // private Integer [] integers; + // private Integer [] sortedIntegers; + // private List integersList; + // private List sortedIntegersList; private Employee[] employees; private Employee[] employeesSorted; private Employee[] employeesSortedByAge; private HashMap map; - + @Before - public void initVariables () { - - toSort = new int[] - { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; - sortedInts = new int[] - {1, 5, 7, 66, 88, 89, 123, 200, 255}; - sortedRangeInts = new int[] - {5, 1, 89, 7, 88, 200, 255, 123, 66}; - -// integers = new Integer[] -// { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; -// sortedIntegers = new Integer[] -// {1, 5, 7, 66, 88, 89, 123, 200, 255}; -// -// integersList = Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }); -// sortedIntegersList = Arrays.asList(new Integer[] {1, 5, 7, 66, 88, 89, 123, 200, 255}); - - employees = new Employee[] { - new Employee("John", 23, 5000), - new Employee("Steve", 26, 6000), - new Employee("Frank", 33, 7000), - new Employee("Earl", 43, 10000), - new Employee("Jessica", 23, 4000), - new Employee("Pearl", 33, 6000)}; - employeesSorted = new Employee[] { - new Employee("Earl", 43, 10000), - new Employee("Frank", 33, 70000), - new Employee("Jessica", 23, 4000), - new Employee("John", 23, 5000), - new Employee("Pearl", 33, 4000), - new Employee("Steve", 26, 6000)}; - employeesSortedByAge = new Employee[] { - new Employee("John", 23, 5000), - new Employee("Jessica", 23, 4000), - new Employee("Steve", 26, 6000), - new Employee("Frank", 33, 70000), - new Employee("Pearl", 33, 4000), - new Employee("Earl", 43, 10000)}; - + public void initVariables() { + + toSort = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; + sortedInts = new int[] { 1, 5, 7, 66, 88, 89, 123, 200, 255 }; + sortedRangeInts = new int[] { 5, 1, 89, 7, 88, 200, 255, 123, 66 }; + + // integers = new Integer[] + // { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; + // sortedIntegers = new Integer[] + // {1, 5, 7, 66, 88, 89, 123, 200, 255}; + // + // integersList = Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }); + // sortedIntegersList = Arrays.asList(new Integer[] {1, 5, 7, 66, 88, 89, 123, 200, 255}); + + employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }; + employeesSorted = new Employee[] { new Employee("Earl", 43, 10000), new Employee("Frank", 33, 70000), new Employee("Jessica", 23, 4000), new Employee("John", 23, 5000), new Employee("Pearl", 33, 4000), new Employee("Steve", 26, 6000) }; + employeesSortedByAge = new Employee[] { new Employee("John", 23, 5000), new Employee("Jessica", 23, 4000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 70000), new Employee("Pearl", 33, 4000), new Employee("Earl", 43, 10000) }; + HashMap map = new HashMap<>(); map.put(55, "John"); map.put(22, "Apple"); @@ -84,7 +62,7 @@ public class JavaSorting { map.put(6, "Rocky"); } - + @Test public void givenIntArray_whenUsingSort_thenSortedArray() { Arrays.sort(toSort); @@ -94,24 +72,24 @@ public class JavaSorting { @Test public void givenIntegerArray_whenUsingSort_thenSortedArray() { - Integer [] integers = ArrayUtils.toObject(toSort); + Integer[] integers = ArrayUtils.toObject(toSort); Arrays.sort(integers, new Comparator() { @Override public int compare(Integer a, Integer b) { return a - b; } }); - + assertTrue(Arrays.equals(integers, ArrayUtils.toObject(sortedInts))); } @Test public void givenArray_whenUsingSortWithLambdas_thenSortedArray() { - Integer [] integersToSort = ArrayUtils.toObject(toSort); + Integer[] integersToSort = ArrayUtils.toObject(toSort); Arrays.sort(integersToSort, (a, b) -> { return a - b; }); - + assertTrue(Arrays.equals(integersToSort, ArrayUtils.toObject(sortedInts))); } @@ -122,39 +100,35 @@ public class JavaSorting { assertTrue(Arrays.equals(employees, employeesSorted)); } - @Test public void givenIntArray_whenUsingRangeSort_thenRangeSortedArray() { Arrays.sort(toSort, 3, 7); - + assertTrue(Arrays.equals(toSort, sortedRangeInts)); } - - @Test - public void givenIntArray_whenUsingParallelSort_thenParallelSortedArray() { + + @Test + public void givenIntArray_whenUsingParallelSort_thenArraySorted() { Arrays.parallelSort(toSort); - + assertTrue(Arrays.equals(toSort, sortedInts)); } - - @Test public void givenArrayObjects_whenUsingComparing_thenSortedArrayObjects() { List employeesList = Arrays.asList(employees); - - employeesList.sort(Comparator.comparing(Employee::getAge));//.thenComparing(Employee::getName)); + + employeesList.sort(Comparator.comparing(Employee::getAge));// .thenComparing(Employee::getName)); assertTrue(Arrays.equals(employeesList.toArray(), employeesSortedByAge)); } - + @Test public void givenList_whenUsingSort_thenSortedList() { List toSortList = Ints.asList(toSort); Collections.sort(toSortList); - assertTrue(Arrays.equals(toSortList.toArray(), - ArrayUtils.toObject(sortedInts))); + assertTrue(Arrays.equals(toSortList.toArray(), ArrayUtils.toObject(sortedInts))); } @Test @@ -172,14 +146,13 @@ public class JavaSorting { for (Map.Entry entry : entries) { sortedMap.put(entry.getKey(), entry.getValue()); } - + assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys)); } @Test public void givenMap_whenSortingByValues_thenSortedMap() { - String[] sortedValues = new String[] - { "Apple", "Earl", "George", "John", "Pearl", "Rocky" }; + String[] sortedValues = new String[] { "Apple", "Earl", "George", "John", "Pearl", "Rocky" }; List> entries = new ArrayList<>(map.entrySet()); Collections.sort(entries, new Comparator>() { @@ -192,30 +165,22 @@ public class JavaSorting { for (Map.Entry entry : entries) { sortedMap.put(entry.getKey(), entry.getValue()); } - + assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues)); } - - - - - @Test public void givenSet_whenUsingSort_thenSortedSet() { HashSet integersSet = new LinkedHashSet<>(Ints.asList(toSort)); - HashSet descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(new Integer[] - {255, 200, 123, 89, 88, 66, 7, 5, 1})); - + HashSet descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(new Integer[] { 255, 200, 123, 89, 88, 66, 7, 5, 1 })); + ArrayList list = new ArrayList(integersSet); Collections.sort(list, (i1, i2) -> { return i2 - i1; }); integersSet = new LinkedHashSet<>(list); - + assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray())); } - - } From f354f9e3057481c76c10a1e2aa127d3abb95b329 Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 30 Nov 2016 09:05:38 +0200 Subject: [PATCH 60/74] minor formatting work --- .../com/baeldung/hashing/SHA256Hashing.java | 19 +++++++------------ .../java/nio2/visitor/FileVisitorImpl.java | 4 ++-- .../com/baeldung/generics/GenericsTest.java | 6 +++--- .../baeldung/hashing/SHA256HashingTest.java | 4 +--- .../java/conversion/StringConversionTest.java | 3 +-- .../java/nio2/async/AsyncEchoServer.java | 1 + .../java/nio2/async/AsyncEchoServer2.java | 1 - .../java/nio2/async/AsyncFileTest.java | 3 +-- .../baeldung/java/io/JavaFileUnitTest.java | 1 - .../org/baeldung/java/sorting/Employee.java | 15 ++++++--------- 10 files changed, 22 insertions(+), 35 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/hashing/SHA256Hashing.java b/core-java/src/main/java/com/baeldung/hashing/SHA256Hashing.java index 9c8fc86e7a..4fa164cadc 100644 --- a/core-java/src/main/java/com/baeldung/hashing/SHA256Hashing.java +++ b/core-java/src/main/java/com/baeldung/hashing/SHA256Hashing.java @@ -1,6 +1,5 @@ package com.baeldung.hashing; - import com.google.common.hash.Hashing; import org.apache.commons.codec.digest.DigestUtils; import org.bouncycastle.util.encoders.Hex; @@ -11,17 +10,14 @@ import java.security.NoSuchAlgorithmException; public class SHA256Hashing { - public static String HashWithJavaMessageDigest(final String originalString) - throws NoSuchAlgorithmException { + public static String HashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException { final MessageDigest digest = MessageDigest.getInstance("SHA-256"); - final byte[] encodedhash = digest.digest( - originalString.getBytes(StandardCharsets.UTF_8)); + final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); return bytesToHex(encodedhash); } public static String HashWithGuava(final String originalString) { - final String sha256hex = Hashing.sha256().hashString( - originalString, StandardCharsets.UTF_8).toString(); + final String sha256hex = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString(); return sha256hex; } @@ -30,11 +26,9 @@ public class SHA256Hashing { return sha256hex; } - public static String HashWithBouncyCastle(final String originalString) - throws NoSuchAlgorithmException { + public static String HashWithBouncyCastle(final String originalString) throws NoSuchAlgorithmException { final MessageDigest digest = MessageDigest.getInstance("SHA-256"); - final byte[] hash = digest.digest( - originalString.getBytes(StandardCharsets.UTF_8)); + final byte[] hash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); final String sha256hex = new String(Hex.encode(hash)); return sha256hex; } @@ -43,7 +37,8 @@ public class SHA256Hashing { StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); - if(hex.length() == 1) hexString.append('0'); + if (hex.length() == 1) + hexString.append('0'); hexString.append(hex); } return hexString.toString(); diff --git a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java index 360d6d0689..ee9fb23856 100644 --- a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java +++ b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java @@ -19,12 +19,12 @@ public class FileVisitorImpl implements FileVisitor { } @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) { + public FileVisitResult visitFileFailed(Path file, IOException exc) { return null; } @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) { + public FileVisitResult postVisitDirectory(Path dir, IOException exc) { return null; } } 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 9eb459ccb5..3f0dc46b75 100644 --- a/core-java/src/test/java/com/baeldung/generics/GenericsTest.java +++ b/core-java/src/test/java/com/baeldung/generics/GenericsTest.java @@ -12,7 +12,7 @@ public class GenericsTest { // testing the generic method with Integer @Test public void givenArrayOfIntegers_thanListOfIntegersReturnedOK() { - Integer[] intArray = {1, 2, 3, 4, 5}; + Integer[] intArray = { 1, 2, 3, 4, 5 }; List list = Generics.fromArrayToList(intArray); assertThat(list, hasItems(intArray)); @@ -21,7 +21,7 @@ public class GenericsTest { // testing the generic method with String @Test public void givenArrayOfStrings_thanListOfStringsReturnedOK() { - String[] stringArray = {"hello1", "hello2", "hello3", "hello4", "hello5"}; + String[] stringArray = { "hello1", "hello2", "hello3", "hello4", "hello5" }; List list = Generics.fromArrayToList(stringArray); assertThat(list, hasItems(stringArray)); @@ -32,7 +32,7 @@ public class GenericsTest { // extend Number it will fail to compile @Test public void givenArrayOfIntegersAndNumberUpperBound_thanListOfIntegersReturnedOK() { - Integer[] intArray = {1, 2, 3, 4, 5}; + Integer[] intArray = { 1, 2, 3, 4, 5 }; List list = Generics.fromArrayToListWithUpperBound(intArray); assertThat(list, hasItems(intArray)); diff --git a/core-java/src/test/java/com/baeldung/hashing/SHA256HashingTest.java b/core-java/src/test/java/com/baeldung/hashing/SHA256HashingTest.java index dc496d589b..ce77b824d8 100644 --- a/core-java/src/test/java/com/baeldung/hashing/SHA256HashingTest.java +++ b/core-java/src/test/java/com/baeldung/hashing/SHA256HashingTest.java @@ -4,12 +4,10 @@ import org.junit.Test; import static org.junit.Assert.*; - public class SHA256HashingTest { private static String originalValue = "abc123"; - private static String hashedValue = - "6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090"; + private static String hashedValue = "6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090"; @Test public void testHashWithJavaMessageDigest() throws Exception { diff --git a/core-java/src/test/java/com/baeldung/java/conversion/StringConversionTest.java b/core-java/src/test/java/com/baeldung/java/conversion/StringConversionTest.java index 09cacd0a29..9a4ac053af 100644 --- a/core-java/src/test/java/com/baeldung/java/conversion/StringConversionTest.java +++ b/core-java/src/test/java/com/baeldung/java/conversion/StringConversionTest.java @@ -119,8 +119,7 @@ public class StringConversionTest { int afterConvCalendarDay = 03; Month afterConvCalendarMonth = Month.DECEMBER; int afterConvCalendarYear = 2007; - LocalDateTime afterConvDate - = new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str); + LocalDateTime afterConvDate = new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str); assertEquals(afterConvDate.getDayOfMonth(), afterConvCalendarDay); assertEquals(afterConvDate.getMonth(), afterConvCalendarMonth); diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java index 0e58cb5f10..31f2357468 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java @@ -66,6 +66,7 @@ public class AsyncEchoServer { AsyncEchoServer server = new AsyncEchoServer(); server.runServer(); } + public static Process start() throws IOException, InterruptedException { String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java index 172d8036de..ff4ebe08b2 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java @@ -81,7 +81,6 @@ public class AsyncEchoServer2 { } - public static void main(String[] args) { new AsyncEchoServer2(); } diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java index b03acf83ca..42cbe2a753 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java @@ -82,8 +82,7 @@ public class AsyncFileTest { public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException { String fileName = UUID.randomUUID().toString(); Path path = Paths.get(fileName); - AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,StandardOpenOption.DELETE_ON_CLOSE); - + AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE); ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put("hello world".getBytes()); 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 d4b63beaa4..6d972611f1 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 @@ -20,7 +20,6 @@ public class JavaFileUnitTest { 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)); diff --git a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java index 768ee8f397..477092bfcb 100644 --- a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java +++ b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java @@ -1,14 +1,14 @@ package org.baeldung.java.sorting; public class Employee implements Comparable { - + private String name; private int age; private double salary; public Employee(String name, int age, double salary) { - this.name = name; - this.age = age; + this.name = name; + this.age = age; this.salary = salary; } @@ -35,7 +35,7 @@ public class Employee implements Comparable { public void setSalary(double salary) { this.salary = salary; } - + @Override public boolean equals(Object obj) { return ((Employee) obj).getName().equals(getName()); @@ -46,13 +46,10 @@ public class Employee implements Comparable { Employee e = (Employee) o; return getName().compareTo(e.getName()); } - + @Override public String toString() { - return new StringBuffer() - .append("(").append(getName()) - .append(getAge()).append(",") - .append(getSalary()).append(")").toString(); + return new StringBuffer().append("(").append(getName()).append(getAge()).append(",").append(getSalary()).append(")").toString(); } } From ac89a21ee265f830d5dd8083d9e3cfa54da7cf71 Mon Sep 17 00:00:00 2001 From: gitterjim-I Date: Wed, 30 Nov 2016 22:19:49 +0000 Subject: [PATCH 61/74] update to ltest spring boot version (#859) * manual authentication demo integration * apply eclipse and security formatting rules * add content to readme file, for manual authentication demo * update spring boot version to 1.4.2 --- .../spring-security-thymeleaf-authentication/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml index cdbe0946f4..9f819d11c5 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml @@ -13,7 +13,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.3.RELEASE + 1.4.2.RELEASE From aa6850134118dc5a7c36b8b860de902e939cb09c Mon Sep 17 00:00:00 2001 From: Egima profile Date: Thu, 1 Dec 2016 11:55:20 +0300 Subject: [PATCH 62/74] merged formatting changes and removed while loops in asynchronous client (#870) * made changes to java reflection * removed redundant method makeSound in Animal abstract class * added project for play-framework article * added project for regex * changed regex project from own model to core-java * added project for routing in play * made changes to regex project * refactored code for REST API with Play project * refactored student store indexing to zero base * added unit tests, removed bad names * added NIO Selector project under core-java module * requested changes made * added project for nio2 * standardized exception based tests * fixed exception based tests * removed redundant files * added network interface project * used UUID other than timestamps * fixed network interface tests * removed filetest change * made changes to NIO2 FileTest names * added project for asyncronous channel apis * added project for NIO2 advanced filesystems APIS * merge conflicts * merged changes to asyncfiletest with future get API * removed while loops from async client and server * added project for java8 optional * fixed merge conflicts in spring-core --- .../java/nio2/visitor/FileSearchExample.java | 2 +- .../java/nio2/visitor/FileVisitorImpl.java | 2 +- .../com/baeldung/java_8_features/Person.java | 39 ++++ .../java/nio2/async/AsyncEchoClient.java | 11 +- .../java/nio2/async/AsyncEchoServer.java | 14 +- .../java/nio2/async/AsyncEchoServer2.java | 2 +- .../java/nio2/async/AsyncFileTest.java | 2 +- .../nio2/attributes/BasicAttribsTest.java | 2 +- .../baeldung/java8/optional/OptionalTest.java | 211 ++++++++++++++++++ .../factorybean/FactoryBeanAppConfig.java | 2 +- .../FactoryBeanJavaConfigTest.java | 2 +- .../factorybean/FactoryBeanXmlConfigTest.java | 2 +- 12 files changed, 270 insertions(+), 21 deletions(-) create mode 100644 core-java/src/main/java/com/baeldung/java_8_features/Person.java create mode 100644 core-java/src/test/java/com/baeldung/java8/optional/OptionalTest.java diff --git a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java index 62c6954e1a..b1b790f541 100644 --- a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java +++ b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java @@ -53,4 +53,4 @@ public class FileSearchExample implements FileVisitor { Files.walkFileTree(startingDir, crawler); } -} +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java index ee9fb23856..aa769b5091 100644 --- a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java +++ b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java @@ -27,4 +27,4 @@ public class FileVisitorImpl implements FileVisitor { public FileVisitResult postVisitDirectory(Path dir, IOException exc) { return null; } -} +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/java_8_features/Person.java b/core-java/src/main/java/com/baeldung/java_8_features/Person.java new file mode 100644 index 0000000000..82b6819699 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java_8_features/Person.java @@ -0,0 +1,39 @@ +package com.baeldung.java_8_features; + +import java.util.Optional; + +public class Person { + private String name; + private int age; + private String password; + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + public Optional getName() { + return Optional.ofNullable(name); + } + + public void setName(String name) { + this.name = name; + } + + public Optional getAge() { + return Optional.ofNullable(age); + } + + public void setAge(int age) { + this.age = age; + } + + public void setPassword(String password) { + this.password = password; + } + + public Optional getPassword() { + return Optional.ofNullable(password); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java index ea35130f49..d64fbc763e 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java @@ -45,14 +45,13 @@ public class AsyncEchoClient { ByteBuffer buffer = ByteBuffer.wrap(byteMsg); Future writeResult = client.write(buffer); - while (!writeResult.isDone()) { - // do nothing - } + //run some code + writeResult.get(); buffer.flip(); Future readResult = client.read(buffer); - while (!readResult.isDone()) { - - } + + //run some code + readResult.get(); String echo = new String(buffer.array()).trim(); buffer.clear(); return echo; diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java index 31f2357468..5c3d204863 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java @@ -34,9 +34,9 @@ public class AsyncEchoServer { ByteBuffer buffer = ByteBuffer.allocate(32); Future readResult = clientChannel.read(buffer); - while (!readResult.isDone()) { - // do nothing - } + //do some computation + + readResult.get(); buffer.flip(); String message = new String(buffer.array()).trim(); @@ -45,9 +45,9 @@ public class AsyncEchoServer { } buffer = ByteBuffer.wrap(new String(message).getBytes()); Future writeResult = clientChannel.write(buffer); - while (!writeResult.isDone()) { - // do nothing - } + + //do some computation + writeResult.get(); buffer.clear(); } // while() @@ -77,4 +77,4 @@ public class AsyncEchoServer { return builder.start(); } -} +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java index ff4ebe08b2..a7432da464 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java @@ -95,4 +95,4 @@ public class AsyncEchoServer2 { return builder.start(); } -} +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java index 42cbe2a753..4395017e63 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java @@ -123,4 +123,4 @@ public class AsyncFileTest { buffer.clear(); return fileContent; } -} +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java index 05686e79c0..24097542d0 100644 --- a/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java @@ -66,4 +66,4 @@ public class BasicAttribsTest { boolean isOther = basicAttribs.isOther(); assertFalse(isOther); } -} +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java8/optional/OptionalTest.java b/core-java/src/test/java/com/baeldung/java8/optional/OptionalTest.java new file mode 100644 index 0000000000..cd092fdd70 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java8/optional/OptionalTest.java @@ -0,0 +1,211 @@ +package com.baeldung.java8.optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; +import com.baeldung.java_8_features.Person; + +import org.junit.Test; + +public class OptionalTest { + // creating Optional + @Test + public void whenCreatesEmptyOptional_thenCorrect() { + Optional empty = Optional.empty(); + assertFalse(empty.isPresent()); + } + + @Test + public void givenNonNull_whenCreatesNonNullable_thenCorrect() { + String name = "baeldung"; + Optional.of(name); + } + + @Test(expected = NullPointerException.class) + public void givenNull_whenThrowsErrorOnCreate_thenCorrect() { + String name = null; + Optional opt = Optional.of(name); + } + + @Test + public void givenNonNull_whenCreatesOptional_thenCorrect() { + String name = "baeldung"; + Optional opt = Optional.of(name); + assertEquals("Optional[baeldung]", opt.toString()); + } + + @Test + public void givenNonNull_whenCreatesNullable_thenCorrect() { + String name = "baeldung"; + Optional opt = Optional.ofNullable(name); + assertEquals("Optional[baeldung]", opt.toString()); + } + + @Test + public void givenNull_whenCreatesNullable_thenCorrect() { + String name = null; + Optional opt = Optional.ofNullable(name); + assertEquals("Optional.empty", opt.toString()); + } + // Checking Value With isPresent() + + @Test + public void givenOptional_whenIsPresentWorks_thenCorrect() { + Optional opt = Optional.of("Baeldung"); + assertTrue(opt.isPresent()); + + opt = Optional.ofNullable(null); + assertFalse(opt.isPresent()); + } + + // Condition Action With ifPresent() + @Test + public void givenOptional_whenIfPresentWorks_thenCorrect() { + Optional opt = Optional.of("baeldung"); + opt.ifPresent(name -> System.out.println(name.length())); + opt.ifPresent(String::length); + } + + // returning Value With get() + @Test + public void givenOptional_whenGetsValue_thenCorrect() { + Optional opt = Optional.of("baeldung"); + String name = opt.get(); + assertEquals("baeldung", name); + } + + @Test(expected = NoSuchElementException.class) + public void givenOptionalWithNull_whenGetThrowsException_thenCorrect() { + Optional opt = Optional.ofNullable(null); + String name = opt.get(); + } + + // Conditional Return With filter() + @Test + public void whenOptionalFilterWorks_thenCorrect() { + Integer year = 2016; + Optional yearOptional = Optional.of(year); + boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent(); + assertTrue(is2016); + boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent(); + assertFalse(is2017); + } + + // Transforming Value With map() + @Test + public void givenOptional_whenMapWorks_thenCorrect() { + List companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple"); + Optional> listOptional = Optional.of(companyNames); + + int size = listOptional.map(list -> list.size()).get(); + assertEquals(6, size); + } + + @Test + public void givenOptional_whenMapWorks_thenCorrect2() { + String name = "baeldung"; + Optional nameOptional = Optional.of(name); + + int len = nameOptional.map(s -> s.length()).get(); + assertEquals(8, len); + } + + @Test + public void givenOptional_whenMapWorksWithFilter_thenCorrect() { + String password = " password "; + Optional passOpt = Optional.of(password); + boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent(); + assertFalse(correctPassword); + + correctPassword = passOpt.map(pass -> pass.trim()).filter(pass -> pass.equals("password")).isPresent(); + assertTrue(correctPassword); + } + + // Transforming Value With flatMap() + @Test + public void givenOptional_whenFlatMapWorks_thenCorrect2() { + Person person = new Person("john", 26); + Optional personOptional = Optional.of(person); + + Optional> nameOptionalWrapper = personOptional.map(p -> p.getName()); + Optional nameOptional = nameOptionalWrapper.get(); + String name1 = nameOptional.get(); + assertEquals("john", name1); + + String name = personOptional.flatMap(p -> p.getName()).get(); + assertEquals("john", name); + } + + @Test + public void givenOptional_whenFlatMapWorksWithFilter_thenCorrect() { + Person person = new Person("john", 26); + person.setPassword("password"); + Optional personOptional = Optional.of(person); + + String password = personOptional.flatMap(p -> p.getPassword()).filter(cleanPass -> cleanPass.equals("password")).get(); + assertEquals("password", password); + } + + // Default Value With orElse + @Test + public void whenOrElseWorks_thenCorrect() { + String nullName = null; + String name = Optional.ofNullable(nullName).orElse("john"); + assertEquals("john", name); + } + + // Default Value With orElseGet + @Test + public void whenOrElseGetWorks_thenCorrect() { + String nullName = null; + String name = Optional.ofNullable(nullName).orElseGet(() -> "john"); + assertEquals("john", name); + + name = Optional.ofNullable(nullName).orElseGet(() -> { + return "doe"; + }); + assertEquals("doe", name); + + } + + @Test + public void whenOrElseGetAndOrElseOverlap_thenCorrect() { + String text = null; + System.out.println("Using orElseGet:"); + String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); + assertEquals("Default Value", defaultText); + + System.out.println("Using orElse:"); + defaultText = Optional.ofNullable(text).orElse(getMyDefault()); + assertEquals("Default Value", defaultText); + } + + @Test + public void whenOrElseGetAndOrElseDiffer_thenCorrect() { + String text = "Text present"; + System.out.println("Using orElseGet:"); + String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); + assertEquals("Text present", defaultText); + + System.out.println("Using orElse:"); + defaultText = Optional.ofNullable(text).orElse(getMyDefault()); + assertEquals("Text present", defaultText); + } + + // Exceptions With orElseThrow + @Test(expected = IllegalArgumentException.class) + public void whenOrElseThrowWorks_thenCorrect() { + String nullName = null; + String name = Optional.ofNullable(nullName).orElseThrow(IllegalArgumentException::new); + } + + public String getMyDefault() { + System.out.println("Getting default value..."); + return "Default Value"; + } +} 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 f0cfadcab1..e5e6d2ec05 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java @@ -13,4 +13,4 @@ public class FactoryBeanAppConfig { factory.setToolId(2); return factory; } -} +} \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java index 706aa0a63f..c725f786dc 100644 --- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java @@ -26,4 +26,4 @@ public class FactoryBeanJavaConfigTest { assertThat(tool.getId(), equalTo(2)); assertThat(toolFactory.getFactoryId(), equalTo(7070)); } -} +} \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java index 8ba1129b30..443515f872 100644 --- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java @@ -25,4 +25,4 @@ public class FactoryBeanXmlConfigTest { assertThat(tool.getId(), equalTo(1)); assertThat(toolFactory.getFactoryId(), equalTo(9090)); } -} +} \ No newline at end of file From d705d1de9b9b40d7167f5d4501aacba2453a6b55 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 1 Dec 2016 12:53:06 +0200 Subject: [PATCH 63/74] upgrade dependencies --- xstream/pom.xml | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/xstream/pom.xml b/xstream/pom.xml index f505019d71..7af8efa659 100644 --- a/xstream/pom.xml +++ b/xstream/pom.xml @@ -11,25 +11,25 @@ com.thoughtworks.xstream xstream - 1.4.5 + ${xstream.version} org.codehaus.jettison jettison - 1.3.7 + ${jettison.version} junit junit - 4.12 + ${junit.version} log4j log4j - 1.2.17 + ${log4j.version} @@ -38,7 +38,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.5.1 + ${maven-compiler-plugin.version} 1.8 1.8 @@ -47,4 +47,17 @@ + + 1.4.9 + 1.3.8 + + 1.2.17 + + 4.12 + + + 3.6.0 + + + \ No newline at end of file From 215dde6f9214efdb28343943efe3b500afaeddaf Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 1 Dec 2016 13:07:39 +0200 Subject: [PATCH 64/74] upgrade dependencies --- xmlunit2/pom.xml | 64 +++++++++++++++++++++++++++++------------------- 1 file changed, 39 insertions(+), 25 deletions(-) diff --git a/xmlunit2/pom.xml b/xmlunit2/pom.xml index c80e3f37b2..d4364292d6 100644 --- a/xmlunit2/pom.xml +++ b/xmlunit2/pom.xml @@ -5,42 +5,56 @@ xmlunit2 1.0 XMLUnit-2 - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 7 - 7 - - - - + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + junit junit - 4.3 + ${junit.version} test org.hamcrest hamcrest-all - 1.3 + ${hamcrest.version} - - org.xmlunit - xmlunit-matchers - 2.2.1 - + + org.xmlunit + xmlunit-matchers + ${xmlunit.version} + - - org.xmlunit - xmlunit-core - 2.2.1 - + + org.xmlunit + xmlunit-core + ${xmlunit.version} + + + + + + 4.12 + 1.3 + 2.3.0 + + + 3.6.0 + + From f46e18a3533d06aa94081ace3c0baa78424981dc Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 1 Dec 2016 13:27:21 +0200 Subject: [PATCH 65/74] upgrade dependencies --- xml/pom.xml | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/xml/pom.xml b/xml/pom.xml index d204eea45f..4230350ed9 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -12,32 +12,32 @@ dom4j dom4j - 1.6.1 + ${dom4j.version} jaxen jaxen - 1.1.6 + ${jaxen.version} org.jdom jdom2 - 2.0.6 + ${jdom2.version} commons-io commons-io - 2.4 + ${commons-io.version} org.apache.commons commons-collections4 - 4.0 + ${commons-collections4.version} @@ -90,20 +90,21 @@ + 1.6.1 + 1.1.6 + 2.0.6 + 2.5 + 4.1 - 19.0 - 3.4 + 3.5 4.12 - 3.5.1 - 2.6 + 3.6.0 2.19.1 - 2.7 - 1.4.18 From de33c9ce0b77d04287fd97116b83aa25e7c8f719 Mon Sep 17 00:00:00 2001 From: Hector Romero Date: Thu, 1 Dec 2016 08:16:25 -0600 Subject: [PATCH 66/74] BAEL-7: Use Collection interface --- .../JoinSplitCollectionsUnitTest.java | 94 ++++++++++++------- 1 file changed, 59 insertions(+), 35 deletions(-) diff --git a/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java index b4dd0e46b1..66e037b457 100644 --- a/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java @@ -6,9 +6,11 @@ import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -25,14 +27,25 @@ public class JoinSplitCollectionsUnitTest { assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" }); } + + @Test + public void whenJoiningTwoCollections_thenJoined() { + Collection collection1 = Arrays.asList(7, 8, 9); + Collection collection2 = Arrays.asList(10, 11, 12); + Collection result = Stream.concat(collection1.stream(), collection2.stream()) + .collect(Collectors.toList()); + + assertTrue(result.equals(Arrays.asList(7, 8, 9, 10, 11, 12))); + } @Test - public void whenJoiningTwoListsWithFilter_thenJoined() { - List list1 = Arrays.asList(7, 8, 11); - List list2 = Arrays.asList(9, 12, 10); - List result = Stream.concat(list1.stream(), list2.stream()).filter(next -> next <= 10) + public void whenJoiningTwoCollectionsWithFilter_thenJoined() { + Collection collection1 = Arrays.asList(7, 8, 11); + Collection collection2 = Arrays.asList(9, 12, 10); + Collection result = Stream.concat(collection1.stream(), collection2.stream()) + .filter(next -> next <= 10) .collect(Collectors.toList()); - + assertTrue(result.equals(Arrays.asList(7, 8, 9, 10))); } @@ -46,11 +59,11 @@ public class JoinSplitCollectionsUnitTest { } @Test - public void whenConvertListToString_thenConverted() { - List directions = Arrays.asList("Left", "Right", "Top", "Bottom"); + public void whenConvertCollectionToString_thenConverted() { + Collection directions = Arrays.asList("Left", "Right", "Top", "Bottom"); String result = directions.stream() .collect(Collectors.joining(", ")); - + assertEquals(result, "Left, Right, Top, Bottom"); } @@ -68,49 +81,60 @@ public class JoinSplitCollectionsUnitTest { } @Test - public void whenConvertNestedListToString_thenConverted() { - List> nested = new ArrayList<>(); + public void whenConvertNestedCollectionToString_thenConverted() { + Collection> nested = new ArrayList<>(); nested.add(Arrays.asList("Left", "Right", "Top", "Bottom")); nested.add(Arrays.asList("Red", "Blue", "Green", "Yellow")); - + String result = nested.stream() .map(nextList -> nextList.stream() .collect(Collectors.joining("-"))) .collect(Collectors.joining("; ")); - + assertEquals(result, "Left-Right-Top-Bottom; Red-Blue-Green-Yellow"); } @Test - public void whenConvertListToStringAndSkipNull_thenConverted() { - List fruits = Arrays.asList("Apple", "Orange", null, "Grape"); + public void whenConvertCollectionToStringAndSkipNull_thenConverted() { + Collection fruits = Arrays.asList("Apple", "Orange", null, "Grape"); String result = fruits.stream() .filter(next -> next != null) .collect(Collectors.joining(", ")); - + assertEquals(result, "Apple, Orange, Grape"); } @Test - public void whenSplitListGroupOddEven_thenConverted() { - List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - Map> result = list.stream() - .collect(Collectors.partitioningBy(number -> number % 2 == 0)); + public void whenSplitCollectionHalf_thenConverted() { + Collection numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + Collection result1 = new ArrayList<>(); + Collection result2 = new ArrayList<>(); + AtomicInteger count = new AtomicInteger(); + int midpoint = Math.round(numbers.size() / 2); - assertTrue(result.get(true).equals(Arrays.asList(2, 4, 6, 8, 10))); - assertTrue(result.get(false).equals(Arrays.asList(1, 3, 5, 7, 9))); + numbers.forEach(next -> { + int index = count.getAndIncrement(); + if(index < midpoint){ + result1.add(next); + }else{ + result2.add(next); + } + }); + + assertTrue(result1.equals(Arrays.asList(1, 2, 3, 4, 5))); + assertTrue(result2.equals(Arrays.asList(6, 7, 8, 9, 10))); } -@Test -public void whenSplitArrayByWordLength_thenConverted() { - String[] words = new String[]{"bye", "cold", "it", "and", "my", "word"}; - Map> result = Arrays.stream(words) - .collect(Collectors.groupingBy(word -> word.length())); - - assertTrue(result.get(2).equals(Arrays.asList("it", "my"))); - assertTrue(result.get(3).equals(Arrays.asList("bye", "and"))); - assertTrue(result.get(4).equals(Arrays.asList("cold", "word"))); -} + @Test + public void whenSplitArrayByWordLength_thenConverted() { + String[] words = new String[]{"bye", "cold", "it", "and", "my", "word"}; + Map> result = Arrays.stream(words) + .collect(Collectors.groupingBy(word -> word.length())); + + assertTrue(result.get(2).equals(Arrays.asList("it", "my"))); + assertTrue(result.get(3).equals(Arrays.asList("bye", "and"))); + assertTrue(result.get(4).equals(Arrays.asList("cold", "word"))); + } @Test public void whenConvertStringToArray_thenConverted() { @@ -121,9 +145,9 @@ public void whenSplitArrayByWordLength_thenConverted() { } @Test - public void whenConvertStringToList_thenConverted() { + public void whenConvertStringToCollection_thenConverted() { String colors = "Left, Right, Top, Bottom"; - List result = Arrays.asList(colors.split(", ")); + Collection result = Arrays.asList(colors.split(", ")); assertTrue(result.equals(Arrays.asList("Left", "Right", "Top", "Bottom"))); } @@ -142,10 +166,10 @@ public void whenSplitArrayByWordLength_thenConverted() { } @Test - public void whenConvertListToStringMultipleSeparators_thenConverted() { + public void whenConvertCollectionToStringMultipleSeparators_thenConverted() { String fruits = "Apple. , Orange, Grape. Lemon"; - List result = Arrays.stream(fruits.split("[,|.]")) + Collection result = Arrays.stream(fruits.split("[,|.]")) .map(String::trim).filter(next -> !next.isEmpty()) .collect(Collectors.toList()); From 5750a3a064b9883a9872bac2a976e9b83217363c Mon Sep 17 00:00:00 2001 From: Marek Lewandowski Date: Thu, 1 Dec 2016 22:34:40 +0100 Subject: [PATCH 67/74] Update README.md --- spring-core/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spring-core/README.md b/spring-core/README.md index 53842ecb1a..f05ba9384f 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -1,3 +1,5 @@ ### 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) +- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) + From 6df8e9000e5bdffd4a3f561358e8d44c0281075a Mon Sep 17 00:00:00 2001 From: Tuan Date: Fri, 2 Dec 2016 05:46:56 +0700 Subject: [PATCH 68/74] PR (#843) * remove else condition * remove else condition * spring retry introduction * remove else condition * remove spring retry, format code --- aspectj/pom.xml | 8 +++++--- aspectj/src/main/java/com/baeldung/aspectj/Account.java | 8 ++++---- .../src/main/java/com/baeldung/aspectj/AccountAspect.aj | 5 ++--- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/aspectj/pom.xml b/aspectj/pom.xml index 2a1cff11c8..1c409483ec 100644 --- a/aspectj/pom.xml +++ b/aspectj/pom.xml @@ -98,13 +98,14 @@ compile - test-compile + test-compile - + + --> diff --git a/aspectj/src/main/java/com/baeldung/aspectj/Account.java b/aspectj/src/main/java/com/baeldung/aspectj/Account.java index 59cab72ebf..bc9ca375aa 100644 --- a/aspectj/src/main/java/com/baeldung/aspectj/Account.java +++ b/aspectj/src/main/java/com/baeldung/aspectj/Account.java @@ -4,10 +4,10 @@ public class Account { int balance = 20; public boolean withdraw(int amount) { - if (balance - amount > 0) { - balance = balance - amount; - return true; - } else + if (balance < amount) { return false; + } + balance = balance - amount; + return true; } } diff --git a/aspectj/src/main/java/com/baeldung/aspectj/AccountAspect.aj b/aspectj/src/main/java/com/baeldung/aspectj/AccountAspect.aj index 2ddf03192b..8423c1da97 100644 --- a/aspectj/src/main/java/com/baeldung/aspectj/AccountAspect.aj +++ b/aspectj/src/main/java/com/baeldung/aspectj/AccountAspect.aj @@ -16,12 +16,11 @@ public aspect AccountAspect { } boolean around(int amount, Account account) : callWithDraw(amount, account) { - if (account.balance - amount >= MIN_BALANCE) - return proceed(amount, account); - else { + if (account.balance < amount) { logger.info("Withdrawal Rejected!"); return false; } + return proceed(amount, account); } after(int amount, Account balance) : callWithDraw(amount, balance) { From f1043d3b526da61f16b8744cfb249de59173ceab Mon Sep 17 00:00:00 2001 From: Hector Romero Date: Fri, 2 Dec 2016 03:47:24 -0600 Subject: [PATCH 69/74] BAEL-7: Small tweaks --- .../java/collections/JoinSplitCollectionsUnitTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java index 66e037b457..7e43fef9fa 100644 --- a/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java @@ -23,7 +23,7 @@ public class JoinSplitCollectionsUnitTest { String[] animals1 = new String[] { "Dog", "Cat" }; String[] animals2 = new String[] { "Bird", "Cow" }; String[] result = Stream.concat(Arrays.stream(animals1), Arrays.stream(animals2)) - .toArray(size -> new String[size]); + .toArray(String[]::new); assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" }); } @@ -170,7 +170,8 @@ public class JoinSplitCollectionsUnitTest { String fruits = "Apple. , Orange, Grape. Lemon"; Collection result = Arrays.stream(fruits.split("[,|.]")) - .map(String::trim).filter(next -> !next.isEmpty()) + .map(String::trim) + .filter(next -> !next.isEmpty()) .collect(Collectors.toList()); assertTrue(result.equals(Arrays.asList("Apple", "Orange", "Grape", "Lemon"))); From 09741a0edd66aca6c0acc045ce127403716ff0a9 Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 2 Dec 2016 13:20:28 +0200 Subject: [PATCH 70/74] update dependencies --- wicket/pom.xml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/wicket/pom.xml b/wicket/pom.xml index 929f723c2c..8b81ea4be8 100644 --- a/wicket/pom.xml +++ b/wicket/pom.xml @@ -9,11 +9,10 @@ 1.0-SNAPSHOT WicketIntro - 7.4.0 + 7.5.0 9.2.13.v20150730 - 2.5 4.12 - 3.5.1 + 3.6.0 2.6 UTF-8 From 125756eaffd1ada4c6778fab84a1216484d9164e Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 2 Dec 2016 13:28:53 +0200 Subject: [PATCH 71/74] cleanup pom --- testing/pom.xml | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/testing/pom.xml b/testing/pom.xml index aa523d95ef..1bdc5c87f0 100644 --- a/testing/pom.xml +++ b/testing/pom.xml @@ -5,17 +5,23 @@ mutation-testing 0.1-SNAPSHOT mutation-testing + + + 1.1.10 + 4.12 + 0.7.7.201606060606 + org.pitest pitest-parent - 1.1.10 + ${pitest.version} pom junit junit - 4.9 + ${junit.version} @@ -23,7 +29,7 @@ org.pitest pitest-maven - 1.1.10 + ${pitest.version} com.baeldung.testing.mutation.* @@ -36,7 +42,7 @@ org.jacoco jacoco-maven-plugin - 0.7.7.201606060606 + ${jacoco.version} From 9c7b0550d2d31e49a87c992c83627097c0b8a5aa Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 2 Dec 2016 13:56:34 +0200 Subject: [PATCH 72/74] update dependencies --- spring-zuul/pom.xml | 26 ++++---------------------- spring-zuul/spring-zuul-ui/pom.xml | 2 +- 2 files changed, 5 insertions(+), 23 deletions(-) diff --git a/spring-zuul/pom.xml b/spring-zuul/pom.xml index 75ff467527..2107892667 100644 --- a/spring-zuul/pom.xml +++ b/spring-zuul/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.3.RELEASE + 1.4.2.RELEASE @@ -65,36 +65,18 @@ - 4.2.5.RELEASE - 4.0.4.RELEASE - - - - 2.7.2 - - - 1.7.12 - 1.1.3 + 1.2.3.RELEASE - 19.0 - 3.3.2 + 3.5 - 1.3 - 4.11 - 1.10.19 - - 4.4 - 4.4 - 2.9.0 - 3.5.1 + 3.6.0 2.6 2.19.1 - 1.4.18 diff --git a/spring-zuul/spring-zuul-ui/pom.xml b/spring-zuul/spring-zuul-ui/pom.xml index 99df27f2f9..f337ed32ba 100644 --- a/spring-zuul/spring-zuul-ui/pom.xml +++ b/spring-zuul/spring-zuul-ui/pom.xml @@ -17,7 +17,7 @@ org.springframework.cloud spring-cloud-starter-zuul - 1.0.4.RELEASE + ${spring-cloud.version} @@ -158,52 +158,52 @@ org.apache.derby derby - 10.12.1.1 + ${derby.version} org.apache.derby derbyclient - 10.12.1.1 + ${derby.version} org.apache.derby derbynet - 10.12.1.1 + ${derby.version} org.apache.derby derbytools - 10.12.1.1 + ${derby.version} taglibs standard - 1.1.2 + ${taglibs-standard.version} org.springframework.security spring-security-taglibs - 4.1.3.RELEASE + ${org.springframework.security.version} javax.servlet.jsp.jstl jstl-api - 1.2 + ${jstl-api.version} org.springframework.boot spring-boot-test - 1.4.1.RELEASE + ${spring-boot.version} org.springframework.boot spring-boot - 1.4.1.RELEASE + ${spring-boot.version} javax.servlet javax.servlet-api - 3.1.0 + ${javax.servlet.version} @@ -288,44 +288,39 @@ - 4.1.3.RELEASE - 4.3.2.RELEASE - 3.20.0-GA + 4.2.0.RELEASE + 4.3.4.RELEASE + 1.4.2.RELEASE + 3.21.0-GA - 5.2.2.Final - 5.1.38 - 1.10.2.RELEASE - 1.4.192 - - - 1.7.13 - 1.1.3 - + 5.2.5.Final + 5.1.40 + 1.10.5.RELEASE + 1.4.193 + 10.13.1.1 + - 5.2.2.Final - + 5.3.3.Final + 2.2.5 + 1.1.2 + 1.2 + 3.1.0 + 19.0 - 3.4 - + 3.5 + 1.4.01 + 1.3 4.12 1.10.19 - 4.4.1 - 4.5 - - 2.9.0 - - 3.5.1 + 3.6.0 2.6 2.19.1 - 2.7 - 1.4.18 - From c05a61b91bba0bd5b7d7fe077cc850aacda51a4e Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 2 Dec 2016 21:19:15 +0200 Subject: [PATCH 74/74] upgrade dependencies --- spring-thymeleaf/pom.xml | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index e59ce77e57..b387539aa1 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -8,22 +8,27 @@ 1.8 - 4.3.3.RELEASE - 3.0.1 + 4.3.4.RELEASE + 4.2.0.RELEASE + 3.1.0 - 1.7.12 - 1.1.3 + 1.7.21 + 1.1.7 - 3.0.1.RELEASE + 3.0.2.RELEASE + 2.1.2 1.1.0.Final - 5.1.2.Final + 5.3.3.Final + 5.2.5.Final + 4.12 - 3.5.1 + 3.6.0 2.6 2.19.1 - 1.4.18 + 1.6.1 + 2.2 @@ -49,12 +54,12 @@ org.springframework.security spring-security-web - 4.1.3.RELEASE + ${springframework-security.version} org.springframework.security spring-security-config - 4.1.3.RELEASE + ${springframework-security.version} @@ -71,7 +76,7 @@ nz.net.ultraq.thymeleaf thymeleaf-layout-dialect - 2.0.4 + ${thymeleaf-layout-dialect.version} @@ -112,14 +117,14 @@ org.hibernate hibernate-validator - ${org.hibernate-version} + ${hibernate-validator.version} org.springframework spring-test - 4.1.3.RELEASE + ${org.springframework-version} test @@ -127,7 +132,7 @@ org.springframework.security spring-security-test - 4.1.3.RELEASE + ${springframework-security.version} test @@ -135,7 +140,7 @@ junit junit - 4.12 + ${junit.version} test @@ -194,7 +199,7 @@ org.apache.tomcat.maven tomcat7-maven-plugin - 2.0 + ${tomcat7-maven-plugin.version} tomcat-run