diff --git a/core-java/pom.xml b/core-java/pom.xml index 17d9c2ce64..c3a9611682 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -49,7 +49,7 @@ org.bouncycastle bcprov-jdk15on - 1.55 + ${bouncycastle.version} @@ -134,7 +134,7 @@ commons-codec commons-codec - 1.10 + ${commons-codec.version} @@ -338,6 +338,8 @@ 19.0 3.4 + 1.55 + 1.10 1.3 diff --git a/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceTest.java b/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceTest.java deleted file mode 100644 index 4a8ef57b8f..0000000000 --- a/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceTest.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.baeldung.java.networking.interfaces; - -import static org.junit.Assert.*; - -import java.net.InetAddress; -import java.net.InterfaceAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.util.Enumeration; -import java.util.List; - -import org.junit.Test; - -public class NetworkInterfaceTest { - @Test - public void givenName_whenReturnsNetworkInterface_thenCorrect() throws SocketException { - NetworkInterface nif = NetworkInterface.getByName("lo"); - assertNotNull(nif); - } - - @Test - public void givenInExistentName_whenReturnsNull_thenCorrect() throws SocketException { - NetworkInterface nif = NetworkInterface.getByName("inexistent_name"); - assertNull(nif); - } - - @Test - public void givenIP_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException { - byte[] ip = new byte[] { 127, 0, 0, 1 }; - NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByAddress(ip)); - assertNotNull(nif); - } - - @Test - public void givenHostName_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException { - NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByName("localhost")); - assertNotNull(nif); - } - - @Test - public void givenLocalHost_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException { - NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); - assertNotNull(nif); - } - - @Test - public void givenLoopBack_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException { - NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLoopbackAddress()); - assertNotNull(nif); - } - - @Test - public void givenIndex_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException { - NetworkInterface nif = NetworkInterface.getByIndex(0); - assertNotNull(nif); - } - - @Test - public void givenInterface_whenReturnsInetAddresses_thenCorrect() throws SocketException, UnknownHostException { - NetworkInterface nif = NetworkInterface.getByName("lo"); - Enumeration addressEnum = nif.getInetAddresses(); - InetAddress address = addressEnum.nextElement(); - assertEquals("127.0.0.1", address.getHostAddress()); - } - - @Test - public void givenInterface_whenReturnsInterfaceAddresses_thenCorrect() throws SocketException, UnknownHostException { - NetworkInterface nif = NetworkInterface.getByName("lo"); - - List addressEnum = nif.getInterfaceAddresses(); - InterfaceAddress address = addressEnum.get(0); - InetAddress localAddress = address.getAddress(); - InetAddress broadCastAddress = address.getBroadcast(); - assertEquals("127.0.0.1", localAddress.getHostAddress()); - assertEquals("127.255.255.255", broadCastAddress.getHostAddress()); - } - - @Test - public void givenInterface_whenChecksIfLoopback_thenCorrect() throws SocketException, UnknownHostException { - NetworkInterface nif = NetworkInterface.getByName("lo"); - assertTrue(nif.isLoopback()); - } - - @Test - public void givenInterface_whenChecksIfUp_thenCorrect() throws SocketException, UnknownHostException { - NetworkInterface nif = NetworkInterface.getByName("lo"); - assertTrue(nif.isUp()); - } - - @Test - public void givenInterface_whenChecksIfPointToPoint_thenCorrect() throws SocketException, UnknownHostException { - NetworkInterface nif = NetworkInterface.getByName("lo"); - assertFalse(nif.isPointToPoint()); - } - - @Test - public void givenInterface_whenChecksIfVirtual_thenCorrect() throws SocketException, UnknownHostException { - NetworkInterface nif = NetworkInterface.getByName("lo"); - assertFalse(nif.isVirtual()); - } - - @Test - public void givenInterface_whenChecksMulticastSupport_thenCorrect() throws SocketException, UnknownHostException { - NetworkInterface nif = NetworkInterface.getByName("lo"); - assertTrue(nif.supportsMulticast()); - } - - @Test - public void givenInterface_whenGetsMacAddress_thenCorrect() throws SocketException, UnknownHostException { - NetworkInterface nif = NetworkInterface.getByName("lo"); - byte[] bytes = nif.getHardwareAddress(); - assertNotNull(bytes); - } - - @Test - public void givenInterface_whenGetsMTU_thenCorrect() throws SocketException, UnknownHostException { - NetworkInterface nif = NetworkInterface.getByName("net0"); - int mtu = nif.getMTU(); - assertEquals(1500, mtu); - } -} 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"); diff --git a/core-java/src/test/java/com/baeldung/java/nio2/PathTest.java b/core-java/src/test/java/com/baeldung/java/nio2/PathTest.java deleted file mode 100644 index 004aeb3deb..0000000000 --- a/core-java/src/test/java/com/baeldung/java/nio2/PathTest.java +++ /dev/null @@ -1,195 +0,0 @@ -package com.baeldung.java.nio2; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.net.URI; -import java.nio.file.NoSuchFileException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Date; - -import org.junit.Test; - -public class PathTest { - - private static final String HOME = System.getProperty("user.home"); - - // creating a path - @Test - public void givenPathString_whenCreatesPathObject_thenCorrect() { - Path p = Paths.get("/articles/baeldung"); - assertEquals("\\articles\\baeldung", p.toString()); - - } - - @Test - public void givenPathParts_whenCreatesPathObject_thenCorrect() { - Path p = Paths.get("/articles", "baeldung"); - assertEquals("\\articles\\baeldung", p.toString()); - - } - - // retrieving path info - @Test - public void givenPath_whenRetrievesFileName_thenCorrect() { - Path p = Paths.get("/articles/baeldung/logs"); - assertEquals("logs", p.getFileName().toString()); - } - - @Test - public void givenPath_whenRetrievesNameByIndex_thenCorrect() { - Path p = Paths.get("/articles/baeldung/logs"); - assertEquals("articles", p.getName(0).toString()); - assertEquals("baeldung", p.getName(1).toString()); - assertEquals("logs", p.getName(2).toString()); - } - - @Test - public void givenPath_whenCountsParts_thenCorrect() { - Path p = Paths.get("/articles/baeldung/logs"); - assertEquals(3, p.getNameCount()); - } - - @Test - public void givenPath_whenCanRetrieveSubsequenceByIndex_thenCorrect() { - Path p = Paths.get("/articles/baeldung/logs"); - assertEquals("articles", p.subpath(0, 1).toString()); - assertEquals("articles\\baeldung", p.subpath(0, 2).toString()); - assertEquals("articles\\baeldung\\logs", p.subpath(0, 3).toString()); - assertEquals("baeldung", p.subpath(1, 2).toString()); - assertEquals("baeldung\\logs", p.subpath(1, 3).toString()); - assertEquals("logs", p.subpath(2, 3).toString()); - } - - @Test - public void givenPath_whenRetrievesParent_thenCorrect() { - Path p1 = Paths.get("/articles/baeldung/logs"); - Path p2 = Paths.get("/articles/baeldung"); - Path p3 = Paths.get("/articles"); - Path p4 = Paths.get("/"); - - assertEquals("\\articles\\baeldung", p1.getParent().toString()); - assertEquals("\\articles", p2.getParent().toString()); - assertEquals("\\", p3.getParent().toString()); - assertEquals(null, p4.getParent()); - } - - @Test - public void givenPath_whenRetrievesRoot_thenCorrect() { - Path p1 = Paths.get("/articles/baeldung/logs"); - Path p2 = Paths.get("c:/articles/baeldung/logs"); - - assertEquals("\\", p1.getRoot().toString()); - assertEquals("c:\\", p2.getRoot().toString()); - } - - // removing redundancies from path - @Test - public void givenPath_whenRemovesRedundancies_thenCorrect1() { - Path p = Paths.get("/home/./baeldung/articles"); - p = p.normalize(); - assertEquals("\\home\\baeldung\\articles", p.toString()); - } - - @Test - public void givenPath_whenRemovesRedundancies_thenCorrect2() { - Path p = Paths.get("/home/baeldung/../articles"); - p = p.normalize(); - assertEquals("\\home\\articles", p.toString()); - } - - // converting a path - @Test - public void givenPath_whenConvertsToBrowseablePath_thenCorrect() { - Path p = Paths.get("/home/baeldung/articles.html"); - URI uri = p.toUri(); - assertEquals("file:///E:/home/baeldung/articles.html", uri.toString()); - } - - @Test - public void givenPath_whenConvertsToAbsolutePath_thenCorrect() { - Path p = Paths.get("/home/baeldung/articles.html"); - assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString()); - } - - @Test - public void givenAbsolutePath_whenRetainsAsAbsolute_thenCorrect() { - Path p = Paths.get("E:\\home\\baeldung\\articles.html"); - assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString()); - } - - @Test - public void givenExistingPath_whenGetsRealPathToFile_thenCorrect() throws IOException { - Path p = Paths.get(HOME); - assertEquals(HOME, p.toRealPath().toString()); - } - - @Test(expected = NoSuchFileException.class) - public void givenInExistentPath_whenFailsToConvert_thenCorrect() throws IOException { - Path p = Paths.get("E:\\home\\baeldung\\articles.html"); - - p.toRealPath(); - } - - // joining paths - @Test - public void givenTwoPaths_whenJoinsAndResolves_thenCorrect() throws IOException { - Path p = Paths.get("/baeldung/articles"); - assertEquals("\\baeldung\\articles\\java", p.resolve("java").toString()); - } - - @Test - public void givenAbsolutePath_whenResolutionRetainsIt_thenCorrect() throws IOException { - Path p = Paths.get("/baeldung/articles"); - assertEquals("C:\\baeldung\\articles\\java", p.resolve("C:\\baeldung\\articles\\java").toString()); - } - - @Test - public void givenPathWithRoot_whenResolutionRetainsIt_thenCorrect2() throws IOException { - Path p = Paths.get("/baeldung/articles"); - assertEquals("\\java", p.resolve("/java").toString()); - } - - // creating a path between 2 paths - @Test - public void givenSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException { - Path p1 = Paths.get("articles"); - Path p2 = Paths.get("authors"); - assertEquals("..\\authors", p1.relativize(p2).toString()); - assertEquals("..\\articles", p2.relativize(p1).toString()); - } - - @Test - public void givenNonSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException { - Path p1 = Paths.get("/baeldung"); - Path p2 = Paths.get("/baeldung/authors/articles"); - assertEquals("authors\\articles", p1.relativize(p2).toString()); - assertEquals("..\\..", p2.relativize(p1).toString()); - } - - // comparing 2 paths - @Test - public void givenTwoPaths_whenTestsEquality_thenCorrect() throws IOException { - Path p1 = Paths.get("/baeldung/articles"); - Path p2 = Paths.get("/baeldung/articles"); - Path p3 = Paths.get("/baeldung/authors"); - - assertTrue(p1.equals(p2)); - assertFalse(p1.equals(p3)); - } - - @Test - public void givenPath_whenInspectsStart_thenCorrect() { - Path p1 = Paths.get("/baeldung/articles"); - assertTrue(p1.startsWith("/baeldung")); - } - - @Test - public void givenPath_whenInspectsEnd_thenCorrect() { - Path p1 = Paths.get("/baeldung/articles"); - assertTrue(p1.endsWith("articles")); - } -} diff --git a/ejb/ejb-client/pom.xml b/ejb/ejb-client/pom.xml new file mode 100755 index 0000000000..772e4056d3 --- /dev/null +++ b/ejb/ejb-client/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + com.baeldung.ejb + ejb + 1.0-SNAPSHOT + + ejb-client + EJB3 Client Maven + EJB3 Client Maven + + 4.12 + 2.19.1 + + + + + org.wildfly + wildfly-ejb-client-bom + pom + import + + + com.baeldung.ejb + ejb-remote + ejb + + + + junit + junit + ${junit.version} + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*EJBSetupTest.java + + + + + + + + \ 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..08286d580e --- /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, "testUser"); + prop.put(Context.SECURITY_CREDENTIALS, "admin1234!"); + 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..077cd7583f --- /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=testUser +remote.connection.default.password=admin1234! \ 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..65bfc6dbec --- /dev/null +++ b/ejb/ejb-remote/pom.xml @@ -0,0 +1,39 @@ + + + 4.0.0 + + com.baeldung.ejb + ejb + 1.0-SNAPSHOT + + ejb-remote + ejb + + + + + org.jboss.spec.javax.ejb + jboss-ejb-api_3.2_spec + provided + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + 1.1.0.Alpha5 + + 127.0.0.1 + 9990 + testUser + admin1234! + ${build.finalName}.jar + + + + + + \ 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..4b88747e6a --- /dev/null +++ b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java @@ -0,0 +1,13 @@ +package com.baeldung.ejb.tutorial; + +import javax.ejb.Stateless; + +@Stateless(name = "HelloWorld") +public class HelloWorldBean implements HelloWorld { + + @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..5c54cdcf72 --- /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.8 + 1.8 + + + + + maven-ejb-plugin + 2.4 + + 3.2 + + + + + + + + ejb-remote + ejb-client + + \ No newline at end of file diff --git a/javaxval/README.md b/javaxval/README.md new file mode 100644 index 0000000000..b5001789f1 --- /dev/null +++ b/javaxval/README.md @@ -0,0 +1,9 @@ +========= + +## Java Bean Validation Examples + +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: +- [Java Bean Validation Basics](http://www.baeldung.com/javax-validation) diff --git a/pdf/pom.xml b/pdf/pom.xml index 311265880d..c6404c6b30 100644 --- a/pdf/pom.xml +++ b/pdf/pom.xml @@ -40,9 +40,9 @@ 5.5.10 - org.apache.poi - poi - 3.15 + com.itextpdf.tool + xmlworker + 5.5.10 org.apache.poi diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java index 0d38208bab..1fdf07a05f 100644 --- a/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java @@ -1,6 +1,8 @@ package com.baeldung.pdf; import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; @@ -10,14 +12,21 @@ import javax.xml.parsers.ParserConfigurationException; import org.apache.pdfbox.pdmodel.PDDocument; import org.fit.pdfdom.PDFDomTree; +import com.itextpdf.text.Document; +import com.itextpdf.text.DocumentException; +import com.itextpdf.text.pdf.PdfWriter; +import com.itextpdf.tool.xml.XMLWorkerHelper; + public class PDF2HTMLExample { - private static final String FILENAME = "src/main/resources/pdf.pdf"; + private static final String PDF = "src/main/resources/pdf.pdf"; + private static final String HTML = "src/main/resources/html.html"; public static void main(String[] args) { try { - generateHTMLFromPDF(FILENAME); - } catch (IOException | ParserConfigurationException e) { + generateHTMLFromPDF(PDF); + generatePDFFromHTML(HTML); + } catch (IOException | ParserConfigurationException | DocumentException e) { e.printStackTrace(); } } @@ -32,4 +41,12 @@ public class PDF2HTMLExample { pdf.close(); } } + + private static void generatePDFFromHTML(String filename) throws ParserConfigurationException, IOException, DocumentException { + Document document = new Document(); + PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("src/output/html.pdf")); + document.open(); + XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(filename)); + document.close(); + } } diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java index 00778d16c1..69f5d9731f 100644 --- a/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java @@ -1,24 +1,36 @@ package com.baeldung.pdf; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; + import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.pdfbox.tools.imageio.ImageIOUtil; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; +import com.itextpdf.text.BadElementException; +import com.itextpdf.text.Document; +import com.itextpdf.text.DocumentException; +import com.itextpdf.text.Image; +import com.itextpdf.text.pdf.PdfWriter; public class PDF2ImageExample { - private static final String FILENAME = "src/main/resources/pdf.pdf"; - + private static final String PDF = "src/main/resources/pdf.pdf"; + private static final String JPG = "http://cdn2.baeldung.netdna-cdn.com/wp-content/uploads/2016/05/baeldung-rest-widget-main-1.2.0"; + private static final String GIF = "https://media.giphy.com/media/l3V0x6kdXUW9M4ONq/giphy"; + public static void main(String[] args) { try { - generateImageFromPDF(FILENAME, "png"); - generateImageFromPDF(FILENAME, "jpeg"); - generateImageFromPDF(FILENAME, "gif"); - } catch (IOException e) { + generateImageFromPDF(PDF, "png"); + generateImageFromPDF(PDF, "jpeg"); + generateImageFromPDF(PDF, "gif"); + generatePDFFromImage(JPG, "jpg"); + generatePDFFromImage(GIF, "gif"); + } catch (IOException | DocumentException e) { e.printStackTrace(); } } @@ -32,4 +44,19 @@ public class PDF2ImageExample { } document.close(); } + + private static void generatePDFFromImage(String filename, String extension) + throws IOException, BadElementException, DocumentException { + Document document = new Document(); + String input = filename + "." + extension; + String output = "src/output/" + extension + ".pdf"; + FileOutputStream fos = new FileOutputStream(output); + PdfWriter writer = PdfWriter.getInstance(document, fos); + writer.open(); + document.open(); + document.add(Image.getInstance((new URL(input)))); + document.close(); + writer.close(); + } + } diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java index c5880a4e91..7965152234 100644 --- a/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java @@ -1,6 +1,9 @@ package com.baeldung.pdf; +import java.io.BufferedReader; import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; @@ -10,14 +13,24 @@ import org.apache.pdfbox.pdfparser.PDFParser; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; +import com.itextpdf.text.Document; +import com.itextpdf.text.DocumentException; +import com.itextpdf.text.Element; +import com.itextpdf.text.Font; +import com.itextpdf.text.PageSize; +import com.itextpdf.text.Paragraph; +import com.itextpdf.text.pdf.PdfWriter; + public class PDF2TextExample { - private static final String FILENAME = "src/main/resources/pdf.pdf"; + private static final String PDF = "src/main/resources/pdf.pdf"; + private static final String TXT = "src/main/resources/txt.txt"; public static void main(String[] args) { try { - generateTxtFromPDF(FILENAME); - } catch (IOException e) { + generateTxtFromPDF(PDF); + generatePDFFromTxt(TXT); + } catch (IOException | DocumentException e) { e.printStackTrace(); } } @@ -45,4 +58,27 @@ public class PDF2TextExample { pw.close(); } + private static void generatePDFFromTxt(String filename) throws IOException, DocumentException { + Document pdfDoc = new Document(PageSize.A4); + PdfWriter.getInstance(pdfDoc, new FileOutputStream("src/output/txt.pdf")) + .setPdfVersion(PdfWriter.PDF_VERSION_1_7); + pdfDoc.open(); + + Font myfont = new Font(); + myfont.setStyle(Font.NORMAL); + myfont.setSize(11); + pdfDoc.add(new Paragraph("\n")); + + BufferedReader br = new BufferedReader(new FileReader(filename)); + String strLine; + while ((strLine = br.readLine()) != null) { + Paragraph para = new Paragraph(strLine + "\n", myfont); + para.setAlignment(Element.ALIGN_JUSTIFIED); + pdfDoc.add(para); + } + + pdfDoc.close(); + br.close(); + } + } diff --git a/pdf/src/main/resources/html.html b/pdf/src/main/resources/html.html new file mode 100644 index 0000000000..d3072c056c --- /dev/null +++ b/pdf/src/main/resources/html.html @@ -0,0 +1,53 @@ + + + + +A very simple webpage + + + +

A very simple webpage. This is an "h1" level header.

+ +

This is a level h2 header.

+ +
This is a level h6 header. Pretty small!
+ +

This is a standard paragraph.

+ +

Now I've aligned it in the center of the screen.

+ +

Now aligned to the right

+ +

Bold text

+ +

Strongly emphasized text Can you tell the difference vs. bold?

+ +

Italics

+ +

Emphasized text Just like Italics!

+ +

How about a nice ordered list!

+
    +
  1. This little piggy went to market
  2. +
  3. This little piggy went to SB228 class
  4. +
  5. This little piggy went to an expensive restaurant in Downtown Palo Alto
  6. +
  7. This little piggy ate too much at Indian Buffet.
  8. +
  9. This little piggy got lost
  10. +
+ +

Unordered list

+
    +
  • First element
  • +
  • Second element
  • +
  • Third element
  • +
+ + +

And finally, how about some

Links? + +

Remember, you can view the HTMl code from this or any other page by using the "View Page Source" command of your browser.

+ + + + + diff --git a/pdf/src/main/resources/txt.txt b/pdf/src/main/resources/txt.txt new file mode 100644 index 0000000000..de0c36ae75 --- /dev/null +++ b/pdf/src/main/resources/txt.txt @@ -0,0 +1,3 @@ +Test +Text + Test TEST \ No newline at end of file diff --git a/pom.xml b/pom.xml index 9dfb0fdaaf..b8d0303160 100644 --- a/pom.xml +++ b/pom.xml @@ -52,11 +52,11 @@ jee7 jjwt jpa-storedprocedure - jsf + jsf json-path json junit5 - + log4j log-mdc lombok @@ -72,19 +72,19 @@ querydsl - redis + redis rest-assured rest-testing resteasy selenium-junit-testng - spring-akka + spring-akka spring-all spring-apache-camel spring-autowire spring-batch spring-boot - spring-cloud-data-flow + spring-cloud-data-flow spring-cloud spring-core spring-cucumber @@ -132,7 +132,7 @@ spring-security-rest-custom spring-security-rest-digest-auth spring-security-rest-full - spring-security-rest + spring-security-rest spring-security-x509 spring-session spring-spel diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java index dd309cec79..b97f66e9dd 100644 --- a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java +++ b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java @@ -1,14 +1,13 @@ package main.java.com.baeldung.selenium; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.concurrent.TimeUnit; - import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; +import java.util.List; +import java.util.concurrent.TimeUnit; + public class SeleniumExample { private WebDriver webDriver; @@ -38,12 +37,12 @@ public class SeleniumExample { private void closeOverlay() { List webElementList = webDriver.findElements(By.tagName("a")); - try { - if (webElementList != null && !webElementList.isEmpty()) { - webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().orElseThrow(NoSuchElementException::new).click(); - } - } catch (NoSuchElementException exception) { - exception.printStackTrace(); + if (webElementList != null) { + webElementList.stream() + .filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))) + .filter(WebElement::isDisplayed) + .findAny() + .ifPresent(WebElement::click); } } diff --git a/spring-apache-camel/pom.xml b/spring-apache-camel/pom.xml index fbea9b779d..6cd4f136e0 100644 --- a/spring-apache-camel/pom.xml +++ b/spring-apache-camel/pom.xml @@ -11,25 +11,26 @@ 2.16.1 4.2.4.RELEASE + 2.19.1 1.7 - 4.1 + 4.12 - + junit junit ${junit.version} test - + org.apache.camel camel-core ${env.camel.version} - + org.apache.camel camel-spring @@ -49,7 +50,7 @@ - + @@ -62,6 +63,22 @@ ${java.version} + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + + + + + + diff --git a/spring-apache-camel/src/test/java/org/apache/camel/file/processor/FileProcessorIntegrationTest.java b/spring-apache-camel/src/test/java/org/apache/camel/file/processor/FileProcessorIntegrationTest.java new file mode 100644 index 0000000000..e73ad1e4a4 --- /dev/null +++ b/spring-apache-camel/src/test/java/org/apache/camel/file/processor/FileProcessorIntegrationTest.java @@ -0,0 +1,68 @@ +package org.apache.camel.file.processor; + +import java.io.File; + +import org.apache.camel.CamelContext; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.impl.DefaultCamelContext; +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.camel.file.FileProcessor; + + +public class FileProcessorIntegrationTest { + + private static final long DURATION_MILIS = 10000; + private static final String SOURCE_FOLDER = "src/test/source-folder"; + private static final String DESTINATION_FOLDER = "src/test/destination-folder"; + + @Before + public void setUp() throws Exception { + File sourceFolder = new File(SOURCE_FOLDER); + File destinationFolder = new File(DESTINATION_FOLDER); + + cleanFolder(sourceFolder); + cleanFolder(destinationFolder); + + sourceFolder.mkdirs(); + File file1 = new File(SOURCE_FOLDER + "/File1.txt"); + File file2 = new File(SOURCE_FOLDER + "/File2.txt"); + file1.createNewFile(); + file2.createNewFile(); + } + + private void cleanFolder(File folder) { + File[] files = folder.listFiles(); + if (files != null) { + for (File file : files) { + if (file.isFile()) { + file.delete(); + } + } + } + } + + @Test + public void moveFolderContentJavaDSLTest() throws Exception { + final CamelContext camelContext = new DefaultCamelContext(); + camelContext.addRoutes(new RouteBuilder() { + @Override + public void configure() throws Exception { + from("file://" + SOURCE_FOLDER + "?delete=true").process(new FileProcessor()).to("file://" + DESTINATION_FOLDER); + } + }); + camelContext.start(); + Thread.sleep(DURATION_MILIS); + camelContext.stop(); + } + + @Test + public void moveFolderContentSpringDSLTest() throws InterruptedException { + ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context-test.xml"); + Thread.sleep(DURATION_MILIS); + applicationContext.close(); + + } +} \ No newline at end of file diff --git a/spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java b/spring-apache-camel/src/test/java/org/apache/camel/main/AppIntegrationTest.java similarity index 95% rename from spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java rename to spring-apache-camel/src/test/java/org/apache/camel/main/AppIntegrationTest.java index 87b20369f3..fc7fa9653b 100644 --- a/spring-apache-camel/src/test/java/org/apache/camel/main/AppTest.java +++ b/spring-apache-camel/src/test/java/org/apache/camel/main/AppIntegrationTest.java @@ -15,7 +15,7 @@ import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Paths; -public class AppTest extends TestCase { +public class AppIntegrationTest extends TestCase { private static final String FILE_NAME = "file.txt"; private static final String SAMPLE_INPUT_DIR = "src/test/data/sampleInputFile/"; diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java index 847c86f881..c51819dfe5 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/ConfigApplication.java @@ -9,7 +9,7 @@ import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @EnableConfigServer @EnableEurekaClient public class ConfigApplication { - public static void main(String[] args) { - SpringApplication.run(ConfigApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(ConfigApplication.class, args); + } } diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/DiscoveryApplication.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/DiscoveryApplication.java index 32bcdc90b6..4ac445b083 100644 --- a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/DiscoveryApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/DiscoveryApplication.java @@ -7,7 +7,7 @@ import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class DiscoveryApplication { - public static void main(String[] args) { - SpringApplication.run(DiscoveryApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(DiscoveryApplication.class, args); + } } diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java index a3d2df5357..b5ae1e4e7b 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java @@ -18,23 +18,23 @@ import java.util.List; @EnableZuulProxy @EnableEurekaClient public class GatewayApplication { - public static void main(String[] args) { - SpringApplication.run(GatewayApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(GatewayApplication.class, args); + } - @Autowired(required = false) - private List configurations = new ArrayList<>(); + @Autowired(required = false) + private List configurations = new ArrayList<>(); - @Bean - @LoadBalanced RestTemplate restTemplate(){ - return new RestTemplate(); - } + @Bean + @LoadBalanced + RestTemplate restTemplate() { + return new RestTemplate(); + } - - @Bean - public SpringClientFactory springClientFactory() { - SpringClientFactory factory = new SpringClientFactory(); - factory.setConfigurations(this.configurations); - return factory; - } + @Bean + public SpringClientFactory springClientFactory() { + SpringClientFactory factory = new SpringClientFactory(); + factory.setConfigurations(this.configurations); + return factory; + } } diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingZuulPreFilter.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingZuulPreFilter.java index 9a2b5bab74..1c90ba2e12 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingZuulPreFilter.java +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/filter/SessionSavingZuulPreFilter.java @@ -14,34 +14,34 @@ import javax.servlet.http.HttpSession; @Component public class SessionSavingZuulPreFilter extends ZuulFilter { - private Logger log = LoggerFactory.getLogger(this.getClass()); + private Logger log = LoggerFactory.getLogger(this.getClass()); - @Autowired - private SessionRepository repository; + @Autowired + private SessionRepository repository; - @Override public boolean shouldFilter() { - return true; - } + @Override + public boolean shouldFilter() { + return true; + } - @Override - public Object run() { - RequestContext context = RequestContext.getCurrentContext(); + @Override + public Object run() { + RequestContext context = RequestContext.getCurrentContext(); + HttpSession httpSession = context.getRequest().getSession(); + Session session = repository.getSession(httpSession.getId()); - HttpSession httpSession = context.getRequest().getSession(); - Session session = repository.getSession(httpSession.getId()); + context.addZuulRequestHeader("Cookie", "SESSION=" + httpSession.getId()); + log.info("ZuulPreFilter session proxy: {}", session.getId()); + return null; + } - context.addZuulRequestHeader("Cookie", "SESSION=" + httpSession.getId()); + @Override + public String filterType() { + return "pre"; + } - log.info("ZuulPreFilter session proxy: {}", session.getId()); - - return null; - } - - @Override public String filterType() { - return "pre"; - } - - @Override public int filterOrder() { - return 0; - } + @Override + public int filterOrder() { + return 0; + } } diff --git a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/ResourceApplication.java b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/ResourceApplication.java index e12d43f46b..accef18a14 100644 --- a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/ResourceApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/ResourceApplication.java @@ -11,31 +11,31 @@ import org.springframework.web.bind.annotation.RestController; @EnableEurekaClient @RestController public class ResourceApplication { - public static void main(String[] args) { - SpringApplication.run(ResourceApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(ResourceApplication.class, args); + } - @Value("${resource.returnString}") - private String returnString; + @Value("${resource.returnString}") + private String returnString; - @Value("${resource.user.returnString}") - private String userReturnString; + @Value("${resource.user.returnString}") + private String userReturnString; - @Value("${resource.admin.returnString}") - private String adminReturnString; + @Value("${resource.admin.returnString}") + private String adminReturnString; - @RequestMapping("/hello/cloud") - public String getString() { - return returnString; - } + @RequestMapping("/hello/cloud") + public String getString() { + return returnString; + } - @RequestMapping("/hello/user") - public String getUserString() { - return userReturnString; - } + @RequestMapping("/hello/user") + public String getUserString() { + return userReturnString; + } - @RequestMapping("/hello/admin") - public String getAdminString() { - return adminReturnString; - } + @RequestMapping("/hello/admin") + public String getAdminString() { + return adminReturnString; + } } diff --git a/spring-core/.gitignore b/spring-core/.gitignore index 6531dfc93f..08259abdaf 100644 --- a/spring-core/.gitignore +++ b/spring-core/.gitignore @@ -5,8 +5,8 @@ RemoteSystemsTempFiles/ bin/ .metadata/ docs/*.autosave -docs/*.autosave .recommenders/ build/ .gradle/ .DS_Store +.idea/ \ No newline at end of file diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 9b94ba7b35..84a492bbe4 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -4,22 +4,13 @@ 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 - - junit - junit - 4.11 - test - org.mockito mockito-all @@ -50,6 +41,12 @@ javax.inject 1 + + junit + junit + 4.12 + test + diff --git a/spring-core/src/main/java/com/baeldung/beanfactory/Employee.java b/spring-core/src/main/java/com/baeldung/beanfactory/Employee.java new file mode 100644 index 0000000000..bd7c7a5dc7 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beanfactory/Employee.java @@ -0,0 +1,28 @@ +package com.baeldung.beanfactory; + +public class Employee { + + private String name; + private int age; + + public Employee(String name, int age) { + this.name = name; + this.age = age; + } + + 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; + } +} diff --git a/spring-core/src/test/java/com/baeldung/beanfactory/BeanFactoryWithClassPathResourceTest.java b/spring-core/src/test/java/com/baeldung/beanfactory/BeanFactoryWithClassPathResourceTest.java new file mode 100644 index 0000000000..80123a1bee --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/beanfactory/BeanFactoryWithClassPathResourceTest.java @@ -0,0 +1,25 @@ +package com.baeldung.beanfactory; + +import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.xml.XmlBeanFactory; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class BeanFactoryWithClassPathResourceTest { + + @Test + public void createBeanFactoryAndCheckEmployeeBean() { + Resource res = new ClassPathResource("beanfactory-example.xml"); + BeanFactory factory = new XmlBeanFactory(res); + Employee emp = (Employee) factory.getBean("employee"); + + assertTrue(factory.isSingleton("employee")); + assertTrue(factory.getBean("employee") instanceof Employee); + assertTrue(factory.isTypeMatch("employee", Employee.class)); + assertTrue(factory.getAliases("employee").length > 0); + } +} diff --git a/spring-core/src/test/resources/beanfactory-example.xml b/spring-core/src/test/resources/beanfactory-example.xml new file mode 100644 index 0000000000..7b3d4f29ed --- /dev/null +++ b/spring-core/src/test/resources/beanfactory-example.xml @@ -0,0 +1,13 @@ + + + + + + + + + + \ No newline at end of file diff --git a/spring-data-solr/pom.xml b/spring-data-solr/pom.xml index bd48a53d06..ec6eb7bf46 100644 --- a/spring-data-solr/pom.xml +++ b/spring-data-solr/pom.xml @@ -1,21 +1,21 @@ - + 4.0.0 com.baeldung spring-data-solr 0.0.1-SNAPSHOT jar spring-data-solr - - + + UTF-8 4.2.5.RELEASE 2.19.1 2.0.4.RELEASE - + org.springframework @@ -50,20 +50,58 @@ test - + + + maven-compiler-plugin + org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} - - **/*IntegrationTest.java - + + **/*IntegrationTest.java + **/*LiveTest.java + - - + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + \ No newline at end of file diff --git a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java index 7cd0890718..5286f53309 100644 --- a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java +++ b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/model/Product.java @@ -6,50 +6,28 @@ import org.springframework.data.solr.core.mapping.SolrDocument; @SolrDocument(solrCoreName = "product") public class Product { - + @Id @Indexed(name = "id", type = "string") private String id; - + @Indexed(name = "name", type = "string") private String name; - - @Indexed(name = "category", type = "string") - private String category; - - @Indexed(name = "description", type = "string") - private String description; - + public String getId() { return id; } - + public void setId(String id) { this.id = id; } - + public String getName() { return name; } - + public void setName(String name) { this.name = name; } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - + } diff --git a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java index 01ec1fb909..5649cd7888 100644 --- a/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java +++ b/spring-data-solr/src/main/java/com/baeldung/spring/data/solr/repository/ProductRepository.java @@ -13,7 +13,7 @@ public interface ProductRepository extends SolrCrudRepository { public List findByName(String name); - @Query("name:*?0* OR category:*?0* OR description:*?0*") + @Query("id:*?0* OR name:*?0*") public Page findByCustomQuery(String searchTerm, Pageable pageable); @Query(name = "Product.findByNamedQuery") diff --git a/spring-data-solr/src/main/resources/solr-named-queries.properties b/spring-data-solr/src/main/resources/solr-named-queries.properties index cec59cbebd..c00b5bace9 100644 --- a/spring-data-solr/src/main/resources/solr-named-queries.properties +++ b/spring-data-solr/src/main/resources/solr-named-queries.properties @@ -1 +1 @@ -Product.findByNamedQuery=name:*?0* OR category:*?0* OR description:*?0* \ No newline at end of file +Product.findByNamedQuery=id:*?0* OR name:*?0* \ No newline at end of file diff --git a/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java b/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java index 74d94ef91c..a3765a74ec 100644 --- a/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java +++ b/spring-data-solr/src/test/java/com/baeldung/spring/data/solr/repo/ProductRepositoryIntegrationTest.java @@ -21,124 +21,105 @@ import com.baeldung.spring.data.solr.repository.ProductRepository; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SolrConfig.class) public class ProductRepositoryIntegrationTest { - + @Autowired private ProductRepository productRepository; - + @Before public void clearSolrData() { productRepository.deleteAll(); } - + @Test public void whenSavingProduct_thenAvailableOnRetrieval() throws Exception { final Product product = new Product(); product.setId("P000089998"); product.setName("Desk"); - product.setCategory("Furniture"); - product.setDescription("New Desk"); productRepository.save(product); final Product retrievedProduct = productRepository.findOne(product.getId()); assertEquals(product.getId(), retrievedProduct.getId()); } - + @Test public void whenUpdatingProduct_thenChangeAvailableOnRetrieval() throws Exception { final Product product = new Product(); product.setId("P0001"); product.setName("T-Shirt"); - product.setCategory("Kitchen"); - product.setDescription("New T-Shirt"); + productRepository.save(product); - - product.setCategory("Clothes"); + + product.setName("Shirt"); productRepository.save(product); - + final Product retrievedProduct = productRepository.findOne(product.getId()); - assertEquals(product.getCategory(), retrievedProduct.getCategory()); + assertEquals(product.getName(), retrievedProduct.getName()); } - + @Test public void whenDeletingProduct_thenNotAvailableOnRetrieval() throws Exception { final Product product = new Product(); product.setId("P0001"); product.setName("Desk"); - product.setCategory("Furniture"); - product.setDescription("New Desk"); productRepository.save(product); - + productRepository.delete(product); - + Product retrievedProduct = productRepository.findOne(product.getId()); assertNull(retrievedProduct); - + } - + @Test public void whenFindByName_thenAvailableOnRetrieval() throws Exception { Product phone = new Product(); phone.setId("P0001"); phone.setName("Phone"); - phone.setCategory("Electronics"); - phone.setDescription("New Phone"); productRepository.save(phone); - + List retrievedProducts = productRepository.findByName("Phone"); assertEquals(phone.getId(), retrievedProducts.get(0).getId()); } - + @Test public void whenSearchingProductsByQuery_thenAllMatchingProductsShouldAvialble() throws Exception { final Product phone = new Product(); phone.setId("P0001"); phone.setName("Smart Phone"); - phone.setCategory("Electronics"); - phone.setDescription("New Item"); productRepository.save(phone); - + final Product phoneCover = new Product(); phoneCover.setId("P0002"); - phoneCover.setName("Cover"); - phoneCover.setCategory("Phone"); - phoneCover.setDescription("New Product"); + phoneCover.setName("Phone Cover"); productRepository.save(phoneCover); - + final Product wirelessCharger = new Product(); wirelessCharger.setId("P0003"); - wirelessCharger.setName("Charging Cable"); - wirelessCharger.setCategory("Cable"); - wirelessCharger.setDescription("Wireless Charger for Phone"); + wirelessCharger.setName("Phone Charging Cable"); productRepository.save(wirelessCharger); - + Page result = productRepository.findByCustomQuery("Phone", new PageRequest(0, 10)); assertEquals(3, result.getNumberOfElements()); } - + @Test public void whenSearchingProductsByNamedQuery_thenAllMatchingProductsShouldAvialble() throws Exception { final Product phone = new Product(); phone.setId("P0001"); phone.setName("Smart Phone"); - phone.setCategory("Electronics"); - phone.setDescription("New Item"); productRepository.save(phone); - + final Product phoneCover = new Product(); phoneCover.setId("P0002"); - phoneCover.setName("Cover"); - phoneCover.setCategory("Phone"); - phoneCover.setDescription("New Product"); + phoneCover.setName("Phone Cover"); productRepository.save(phoneCover); - + final Product wirelessCharger = new Product(); wirelessCharger.setId("P0003"); - wirelessCharger.setName("Charging Cable"); - wirelessCharger.setCategory("Cable"); - wirelessCharger.setDescription("Wireless Charger for Phone"); + wirelessCharger.setName("Phone Charging Cable"); productRepository.save(wirelessCharger); - + Page result = productRepository.findByNamedQuery("one", new PageRequest(0, 10)); assertEquals(3, result.getNumberOfElements()); } - + } diff --git a/spring-integration/src/main/java/com/baeldung/samples/FileCopyConfig.java b/spring-integration/src/main/java/com/baeldung/samples/FileCopyConfig.java index e7cf43e902..aec2ae8858 100644 --- a/spring-integration/src/main/java/com/baeldung/samples/FileCopyConfig.java +++ b/spring-integration/src/main/java/com/baeldung/samples/FileCopyConfig.java @@ -26,7 +26,7 @@ public class FileCopyConfig { public final String INPUT_DIR = "source"; public final String OUTPUT_DIR = "target"; - public final String FILE_PATTERN = ".jpg"; + public final String FILE_PATTERN = "*.jpg"; @Bean public MessageChannel fileChannel() { @@ -47,11 +47,12 @@ public class FileCopyConfig { public MessageHandler fileWritingMessageHandler() { FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(OUTPUT_DIR)); handler.setFileExistsMode(FileExistsMode.REPLACE); + handler.setExpectReply(false); return handler; } public static void main(final String... args) { - final AbstractApplicationContext context = new AnnotationConfigApplicationContext(FileCopyConfig.class.getCanonicalName()); + final AbstractApplicationContext context = new AnnotationConfigApplicationContext(FileCopyConfig.class); context.registerShutdownHook(); final Scanner scanner = new Scanner(System.in); System.out.print("Please enter a string and press : "); diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java b/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java index 768a0f8e7b..ff828ca9ec 100644 --- a/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/controllers/MailController.java @@ -20,12 +20,10 @@ import java.util.Iterator; import java.util.Map; import java.util.Set; -/** - * Created by Olga on 7/20/2016. - */ @Controller @RequestMapping("/mail") public class MailController { + @Autowired public EmailServiceImpl emailService; @@ -33,7 +31,6 @@ public class MailController { private String attachmentPath; @Autowired - @Qualifier("templateSimpleMessage") public SimpleMailMessage template; private static final Map> labels; diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 011de70ad2..8e2db044a6 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -248,8 +248,8 @@ - 4.2.5.RELEASE - 4.0.4.RELEASE + 4.3.4.RELEASE + 4.2.0.RELEASE 2.1.4.RELEASE 2.7.8 diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 849699cfae..ca51a56633 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -112,6 +112,11 @@ commons-io 2.2
+ + com.maxmind.geoip2 + geoip2 + 2.8.0 + @@ -146,7 +151,7 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java new file mode 100644 index 0000000000..16de4e56f5 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GeoIPTestController.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.controller; + +import java.io.IOException; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.spring.form.GeoIP; +import com.baeldung.spring.service.RawDBDemoGeoIPLocationService; + +@Controller +public class GeoIPTestController { + private RawDBDemoGeoIPLocationService locationService; + public GeoIPTestController() throws IOException { + locationService + = new RawDBDemoGeoIPLocationService(); + } + @RequestMapping(value="/GeoIPTest", method = RequestMethod.POST) + @ResponseBody + public GeoIP getLocation( + @RequestParam(value="ipAddress", required=true) String ipAddress) throws Exception { + + return locationService.getLocation(ipAddress); + } +} diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java new file mode 100644 index 0000000000..19f56867a1 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/GeoIP.java @@ -0,0 +1,56 @@ +package com.baeldung.spring.form; + +public class GeoIP { + private String ipAddress; + private String city; + private String latitude; + private String longitude; + + public GeoIP() { + + } + + public GeoIP(String ipAddress) { + this.ipAddress = ipAddress; + } + + public GeoIP(String ipAddress, String city, String latitude, String longitude) { + this.ipAddress = ipAddress; + this.city = city; + this.latitude = latitude; + this.longitude = longitude; + } + + public String getIpAddress() { + return ipAddress; + } + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getLatitude() { + return latitude; + } + + public void setLatitude(String latitude) { + this.latitude = latitude; + } + + public String getLongitude() { + return longitude; + } + + public void setLongitude(String longitude) { + this.longitude = longitude; + } + +} diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java new file mode 100644 index 0000000000..0a292ab1e9 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/service/RawDBDemoGeoIPLocationService.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.service; + +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; + +import com.baeldung.spring.form.GeoIP; +import com.maxmind.geoip2.DatabaseReader; +import com.maxmind.geoip2.exception.GeoIp2Exception; +import com.maxmind.geoip2.model.CityResponse; + +public class RawDBDemoGeoIPLocationService{ + private DatabaseReader dbReader; + + public RawDBDemoGeoIPLocationService() throws IOException { + File database = new File("C:\\Users\\Parth Joshi\\Desktop\\GeoLite2-City.mmdb\\GeoLite2-City.mmdb"); + dbReader = new DatabaseReader.Builder(database).build(); + } + + public GeoIP getLocation(String ip) throws IOException, GeoIp2Exception { + InetAddress ipAddress = InetAddress.getByName(ip); + CityResponse response = dbReader.city(ipAddress); + + String cityName = response.getCity().getName(); + String latitude = response.getLocation().getLatitude().toString(); + String longitude = response.getLocation().getLongitude().toString(); + return new GeoIP(ip, cityName, latitude, longitude); + } +} diff --git a/spring-mvc-xml/src/main/webapp/GeoIpTest.jsp b/spring-mvc-xml/src/main/webapp/GeoIpTest.jsp new file mode 100644 index 0000000000..431f6162bc --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/GeoIpTest.jsp @@ -0,0 +1,84 @@ + + + + +Geo IP Test + + + + + + + + +
+ + + +
+ +
+ +
+ + + + \ No newline at end of file diff --git a/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java b/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java new file mode 100644 index 0000000000..72d528095e --- /dev/null +++ b/spring-mvc-xml/src/test/java/com/baeldung/geoip/GeoIpIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.geoip; + +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; + +import org.junit.Test; + +import com.maxmind.geoip2.DatabaseReader; +import com.maxmind.geoip2.exception.GeoIp2Exception; +import com.maxmind.geoip2.model.CityResponse; + + +public class GeoIpIntegrationTest { + + @Test + public void givenIP_whenFetchingCity_thenReturnsCityData() throws IOException, GeoIp2Exception { + File database = new File("C:\\Users\\Parth Joshi\\Desktop\\GeoLite2-City.mmdb\\GeoLite2-City.mmdb"); + DatabaseReader dbReader = new DatabaseReader.Builder(database).build(); + + InetAddress ipAddress = InetAddress.getByName("202.47.112.9"); + CityResponse response = dbReader.city(ipAddress); + + String countryName = response.getCountry().getName(); + String cityName = response.getCity().getName(); + String postal = response.getPostal().getCode(); + String state = response.getLeastSpecificSubdivision().getName(); + + } + +} diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 6580f5ecc7..3c23f1bca7 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung spring-rest @@ -9,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.5.RELEASE + 1.4.2.RELEASE @@ -24,6 +25,10 @@ org.springframework.boot spring-boot-starter-actuator + + org.springframework.boot + spring-boot-devtools + @@ -49,7 +54,7 @@ commons-fileupload commons-fileupload - 1.3.1 + 1.3.2 @@ -73,9 +78,9 @@ - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + com.thoughtworks.xstream @@ -94,7 +99,7 @@ org.apache.commons commons-lang3 - 3.2.1 + 3.5 @@ -157,16 +162,21 @@ - com.jayway.restassured - rest-assured - ${rest-assured.version} - + com.jayway.restassured + rest-assured + ${rest-assured.version} + - + com.google.protobuf protobuf-java - 2.6.1 + 3.1.0 + + + com.googlecode.protobuf-java-format + protobuf-java-format + 1.4 @@ -206,7 +216,8 @@ maven-surefire-plugin - **/*LiveTest.java + **/*IntegrationTest.java + **/*LiveTest.java @@ -240,6 +251,36 @@
+ + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*IntegrationTest.java + + + + + + + + + + live @@ -292,6 +333,7 @@ + @@ -299,13 +341,13 @@ 4.3.11.Final - 5.1.39 + 5.1.40 5.2.2.Final - 19.0 + 20.0 3.4 @@ -323,7 +365,7 @@ 1.1.3 - 3.5.1 + 3.6.0 2.6 2.19.1 1.6.0 @@ -332,7 +374,8 @@ 3.4.1 - + + org.codehaus.mojo @@ -345,4 +388,5 @@ + diff --git a/spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java b/spring-rest/src/main/java/org/baeldung/config/Application.java similarity index 61% rename from spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java rename to spring-rest/src/main/java/org/baeldung/config/Application.java index 445a70f29c..077213b04d 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java +++ b/spring-rest/src/main/java/org/baeldung/config/Application.java @@ -1,17 +1,16 @@ -package org.baeldung.example.spring; +package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; -import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -@EnableScheduling @EnableAutoConfiguration @ComponentScan("org.baeldung") -public class AnotherBootApp extends WebMvcConfigurerAdapter { +public class Application extends WebMvcConfigurerAdapter { public static void main(final String[] args) { - SpringApplication.run(AnotherBootApp.class, args); + SpringApplication.run(Application.class, args); } + } \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java index d116148f09..39c1252c4f 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java @@ -17,9 +17,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter /* * Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml - * */ - @Configuration @EnableWebMvc @ComponentScan({ "org.baeldung.web" }) @@ -33,13 +31,14 @@ public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(final List> messageConverters) { - messageConverters.add(createXmlHttpMessageConverter()); - // messageConverters.add(new MappingJackson2HttpMessageConverter()); - final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.indentOutput(true).dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm")); messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); // messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); + + // messageConverters.add(createXmlHttpMessageConverter()); + // messageConverters.add(new MappingJackson2HttpMessageConverter()); + messageConverters.add(new ProtobufHttpMessageConverter()); messageConverters.add(new KryoHttpMessageConverter()); super.configureMessageConverters(messageConverters); diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java index dd1e3ca222..21ba3c6d13 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java @@ -1,7 +1,6 @@ package org.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import org.baeldung.web.dto.Foo; import org.baeldung.web.dto.FooProtos; @@ -26,7 +25,7 @@ public class FooController { @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { - return new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); + return new Foo(id, randomAlphabetic(4)); } // API - write diff --git a/spring-rest/src/main/resources/application.properties b/spring-rest/src/main/resources/application.properties new file mode 100644 index 0000000000..300589f561 --- /dev/null +++ b/spring-rest/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port= 8082 +server.context-path=/spring-rest \ No newline at end of file diff --git a/spring-rest/src/test/java/org/baeldung/client/Consts.java b/spring-rest/src/test/java/org/baeldung/client/Consts.java new file mode 100644 index 0000000000..b40561d9c3 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/client/Consts.java @@ -0,0 +1,5 @@ +package org.baeldung.client; + +public interface Consts { + int APPLICATION_PORT = 8082; +} diff --git a/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java new file mode 100644 index 0000000000..e4321e163f --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -0,0 +1,59 @@ +package org.baeldung.client; + +import static org.baeldung.client.Consts.APPLICATION_PORT; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Matchers.notNull; + +import java.io.IOException; + +import org.baeldung.web.dto.Foo; +import org.junit.Before; +import org.junit.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class RestTemplateBasicLiveTest { + + private RestTemplate restTemplate; + private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos"; + + @Before + public void beforeTest() { + restTemplate = new RestTemplate(); + } + + // GET + + @Test + public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { + ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); + + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException { + ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode root = mapper.readTree(response.getBody()); + JsonNode name = root.path("name"); + assertThat(name.asText(), is(notNull())); + } + + @Test + public void givenResourceUrl_whenRetrievingResource_thenCorrect() throws IOException { + final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); + + assertThat(foo.getName(), notNullValue()); + assertThat(foo.getId(), is(1L)); + } + +} diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java similarity index 78% rename from spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerTest.java rename to spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java index cafaff7b07..b31bfcf5ec 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java @@ -1,6 +1,6 @@ package org.baeldung.web.controller.redirect; -import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash; @@ -24,7 +24,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("file:src/main/webapp/WEB-INF/api-servlet.xml") @WebAppConfiguration -public class RedirectControllerTest { +public class RedirectControllerIntegrationTest { private MockMvc mockMvc; @@ -38,30 +38,30 @@ public class RedirectControllerTest { @Test public void whenRedirectOnUrlWithUsingXMLConfig_thenStatusRedirectionAndRedirectedOnUrl() throws Exception { - mockMvc.perform(get("/redirectWithXMLConfig")).andExpect(status().is3xxRedirection()).andExpect(view().name("RedirectedUrl")).andExpect(model().attribute("attribute", is("redirectWithXMLConfig"))) + mockMvc.perform(get("/redirectWithXMLConfig")).andExpect(status().is3xxRedirection()).andExpect(view().name("RedirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithXMLConfig"))) .andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithXMLConfig")); } @Test public void whenRedirectOnUrlWithUsingRedirectPrefix_thenStatusRedirectionAndRedirectedOnUrl() throws Exception { - mockMvc.perform(get("/redirectWithRedirectPrefix")).andExpect(status().is3xxRedirection()).andExpect(view().name("redirect:/redirectedUrl")).andExpect(model().attribute("attribute", is("redirectWithRedirectPrefix"))) + mockMvc.perform(get("/redirectWithRedirectPrefix")).andExpect(status().is3xxRedirection()).andExpect(view().name("redirect:/redirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithRedirectPrefix"))) .andExpect(redirectedUrl("/redirectedUrl?attribute=redirectWithRedirectPrefix")); } @Test public void whenRedirectOnUrlWithUsingRedirectAttributes_thenStatusRedirectionAndRedirectedOnUrlAndAddedAttributeToFlashScope() throws Exception { - mockMvc.perform(get("/redirectWithRedirectAttributes")).andExpect(status().is3xxRedirection()).andExpect(flash().attribute("flashAttribute", is("redirectWithRedirectAttributes"))) - .andExpect(model().attribute("attribute", is("redirectWithRedirectAttributes"))).andExpect(model().attribute("flashAttribute", is(nullValue()))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectAttributes")); + mockMvc.perform(get("/redirectWithRedirectAttributes")).andExpect(status().is3xxRedirection()).andExpect(flash().attribute("flashAttribute", equalTo("redirectWithRedirectAttributes"))) + .andExpect(model().attribute("attribute", equalTo("redirectWithRedirectAttributes"))).andExpect(model().attribute("flashAttribute", equalTo(nullValue()))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectAttributes")); } @Test public void whenRedirectOnUrlWithUsingRedirectView_thenStatusRedirectionAndRedirectedOnUrlAndAddedAttributeToFlashScope() throws Exception { - mockMvc.perform(get("/redirectWithRedirectView")).andExpect(status().is3xxRedirection()).andExpect(model().attribute("attribute", is("redirectWithRedirectView"))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectView")); + mockMvc.perform(get("/redirectWithRedirectView")).andExpect(status().is3xxRedirection()).andExpect(model().attribute("attribute", equalTo("redirectWithRedirectView"))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectView")); } @Test public void whenRedirectOnUrlWithUsingForwardPrefix_thenStatusOkAndForwardedOnUrl() throws Exception { - mockMvc.perform(get("/forwardWithForwardPrefix")).andExpect(status().isOk()).andExpect(view().name("forward:/redirectedUrl")).andExpect(model().attribute("attribute", is("redirectWithForwardPrefix"))).andExpect(forwardedUrl("/redirectedUrl")); + mockMvc.perform(get("/forwardWithForwardPrefix")).andExpect(status().isOk()).andExpect(view().name("forward:/redirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithForwardPrefix"))).andExpect(forwardedUrl("/redirectedUrl")); } } diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java similarity index 96% rename from spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java rename to spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java index c50e1b4f43..e29bef501e 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java @@ -18,7 +18,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) @WebAppConfiguration -public class ExampleControllerTest { +public class ExampleControllerIntegrationTest { private MockMvc mockMvc; diff --git a/spring-security-rest-full/.springBeans b/spring-security-rest-full/.springBeans new file mode 100644 index 0000000000..f100c6afbe --- /dev/null +++ b/spring-security-rest-full/.springBeans @@ -0,0 +1,19 @@ + + + 1 + + + + + + + java:org.baeldung.security.spring.SecurityWithoutCsrfConfig + + + src/main/webapp/WEB-INF/api-servlet.xml + java:org.baeldung.spring.Application + java:org.baeldung.security.spring.SecurityWithCsrfConfig + + + + diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index 957a349d3c..ab354d51a7 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.8.RELEASE + 1.4.2.RELEASE @@ -109,14 +109,12 @@ - com.mysema.querydsl + com.querydsl querydsl-apt - ${querydsl.version} - com.mysema.querydsl + com.querydsl querydsl-jpa - ${querydsl.version} @@ -161,7 +159,6 @@ xml-apis xml-apis - ${xml-apis.version} org.javassist @@ -358,7 +355,7 @@ target/generated-sources/java - com.mysema.query.apt.jpa.JPAAnnotationProcessor + com.querydsl.apt.jpa.JPAAnnotationProcessor @@ -467,16 +464,13 @@ - 4.2.5.RELEASE - 4.0.4.RELEASE 4.3.11.Final - 5.1.38 - 1.8.2.RELEASE + 5.1.40 2.0.0 - 3.6.2 + 4.1.4 2.7.8 @@ -505,7 +499,7 @@ 2.9.0 - 3.5.1 + 3.6.0 2.6 2.19.1 1.4.18 diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java index 7a00e7490c..63ae35ec1f 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicate.java @@ -3,10 +3,10 @@ package org.baeldung.persistence.dao; import org.baeldung.persistence.model.MyUser; import org.baeldung.web.util.SearchCriteria; -import com.mysema.query.types.expr.BooleanExpression; -import com.mysema.query.types.path.NumberPath; -import com.mysema.query.types.path.PathBuilder; -import com.mysema.query.types.path.StringPath; +import com.querydsl.core.types.dsl.BooleanExpression; +import com.querydsl.core.types.dsl.NumberPath; +import com.querydsl.core.types.dsl.PathBuilder; +import com.querydsl.core.types.dsl.StringPath; public class MyUserPredicate { diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java index 5e08bde273..caee59c1ec 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java @@ -5,7 +5,7 @@ import java.util.List; import org.baeldung.web.util.SearchCriteria; -import com.mysema.query.types.expr.BooleanExpression; +import com.querydsl.core.types.dsl.BooleanExpression; public final class MyUserPredicatesBuilder { private final List params; diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java index db3627817a..029b57016b 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/MyUserRepository.java @@ -7,7 +7,7 @@ import org.springframework.data.querydsl.QueryDslPredicateExecutor; import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; import org.springframework.data.querydsl.binding.QuerydslBindings; -import com.mysema.query.types.path.StringPath; +import com.querydsl.core.types.dsl.StringPath; public interface MyUserRepository extends JpaRepository, QueryDslPredicateExecutor, QuerydslBinderCustomizer { @Override diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java similarity index 98% rename from spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java rename to spring-security-rest-full/src/main/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java index aeb2428326..f1a78d1472 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/SecurityWithoutCsrfConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/security/spring/SecurityWithoutCsrfConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package org.baeldung.security.spring; import org.baeldung.web.error.CustomAccessDeniedHandler; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java index cf46e35e57..d20423ddc0 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/UserController.java @@ -29,8 +29,8 @@ import org.springframework.web.bind.annotation.ResponseStatus; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; -import com.mysema.query.types.Predicate; -import com.mysema.query.types.expr.BooleanExpression; +import com.querydsl.core.types.Predicate; +import com.querydsl.core.types.dsl.BooleanExpression; import cz.jirutka.rsql.parser.RSQLParser; import cz.jirutka.rsql.parser.ast.Node; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java index 63efd870cd..e06461fc2c 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfDisabledIntegrationTest.java @@ -4,8 +4,8 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.baeldung.security.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.WebConfig; import org.junit.Test; import org.springframework.http.MediaType; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java index b04644f847..939b745de8 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -4,6 +4,7 @@ import static org.springframework.security.test.web.servlet.request.SecurityMock import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.baeldung.security.spring.SecurityWithCsrfConfig; import org.baeldung.spring.PersistenceConfig; import org.baeldung.spring.WebConfig; import org.junit.Test; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java b/spring-security-rest-full/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java similarity index 98% rename from spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java rename to spring-security-rest-full/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java index ae4a655265..97ae1f1dd2 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/spring/SecurityWithCsrfConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.security.csrf; +package org.baeldung.security.spring; import org.baeldung.web.error.CustomAccessDeniedHandler; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java index 99b391eda1..7dcaec5a12 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java @@ -3,8 +3,8 @@ package org.baeldung.web.interceptor; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.baeldung.security.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.WebConfig; import org.junit.Before; import org.junit.Test; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java index 662fc997f9..d62fab0670 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java @@ -5,8 +5,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import javax.servlet.http.HttpSession; +import org.baeldung.security.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.WebConfig; import org.junit.Before; import org.junit.Test; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java index 0e8f7c98ed..f995f86145 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java @@ -1,7 +1,7 @@ package org.baeldung.web.interceptor; +import org.baeldung.security.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.PersistenceConfig; -import org.baeldung.spring.SecurityWithoutCsrfConfig; import org.baeldung.spring.WebConfig; import org.junit.Before; import org.junit.Test; diff --git a/spring-session/jetty-session-demo/pom.xml b/spring-session/jetty-session-demo/pom.xml index 86a8596862..19f0577d2e 100644 --- a/spring-session/jetty-session-demo/pom.xml +++ b/spring-session/jetty-session-demo/pom.xml @@ -37,6 +37,11 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-test + test + diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/TestController.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyController.java similarity index 90% rename from spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/TestController.java rename to spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyController.java index f5c82f2260..308b0a8d51 100644 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/TestController.java +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyController.java @@ -4,7 +4,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController -public class TestController { +public class JettyController { @RequestMapping public String helloJetty() { return "hello Jetty"; diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java index f692d0ff23..ebb2a8e188 100644 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java @@ -2,7 +2,6 @@ package com.baeldung.spring.session.jettyex; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.web.bind.annotation.RestController; @SpringBootApplication public class JettyWebApplication { diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java index 28cdb3cc08..09f752b261 100644 --- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java +++ b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java @@ -13,9 +13,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http - .sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.NEVER) - .and() - .authorizeRequests().anyRequest().hasRole("ADMIN"); + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and() + .authorizeRequests().anyRequest().hasRole("ADMIN"); } } diff --git a/spring-session/pom.xml b/spring-session/pom.xml index fec6a46af2..3a5965c193 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -19,4 +19,5 @@ jetty-session-demo tomcat-session-demo + \ No newline at end of file diff --git a/spring-session/tomcat-session-demo/pom.xml b/spring-session/tomcat-session-demo/pom.xml index 805d7bec25..7d52082651 100644 --- a/spring-session/tomcat-session-demo/pom.xml +++ b/spring-session/tomcat-session-demo/pom.xml @@ -32,6 +32,11 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-test + test + @@ -61,6 +66,20 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*ControllerTest.java + + + + + + 2.19.1 + \ No newline at end of file diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java index 3e419b27a2..691aad3ee5 100644 --- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java @@ -13,8 +13,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication() - .withUser("user").password("password").roles("USER").and() + auth + .inMemoryAuthentication() .withUser("admin").password("password").roles("ADMIN"); } @@ -23,8 +23,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { http .httpBasic().and() .authorizeRequests() - .antMatchers("/").permitAll() - .antMatchers("/tomcat").hasRole("USER") .antMatchers("/tomcat/admin").hasRole("ADMIN") .anyRequest().authenticated(); } diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatController.java similarity index 57% rename from spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java rename to spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatController.java index 877f29e1d3..a241158294 100644 --- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TestController.java +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatController.java @@ -4,18 +4,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController -public class TestController { - - @RequestMapping - public String helloDefault() { - return "hello default"; - } - - @RequestMapping("/tomcat") - public String helloTomcat() { - return "hello tomcat"; - } - +public class TomcatController { @RequestMapping("/tomcat/admin") public String helloTomcatAdmin() { return "hello tomcat admin"; diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java index b7e26027d8..fb4e059dd1 100644 --- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java +++ b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java @@ -2,8 +2,6 @@ package com.baeldung.spring.session.tomcatex; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; @SpringBootApplication public class TomcatWebApplication { diff --git a/spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java b/spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java new file mode 100644 index 0000000000..5bfb7e9411 --- /dev/null +++ b/spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java @@ -0,0 +1,103 @@ +package com.baeldung.spring.session.tomcatex; + +import org.apache.tomcat.util.codec.binary.Base64; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; +import org.springframework.http.*; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class TomcatControllerTest { + + @Autowired + private TestRestTemplate restTemplate; + @LocalServerPort + private int port; + @Autowired + private JedisConnectionFactory jedisConnectionFactory; + private RedisConnection connection; + + @Before + public void clearRedisData() { + connection = jedisConnectionFactory.getConnection(); + connection.flushAll(); + } + + @Test + public void testRedisIsEmpty() { + Set result = connection.keys("*".getBytes()); + assertEquals(0, result.size()); + } + + @Test + public void testForbiddenToProtectedEndpoint() { + ResponseEntity result = restTemplate.getForEntity("/tomcat/admin", String.class); + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); + } + + @Test + public void testLoginAddsRedisKey() { + ResponseEntity result = makeRequest(); + assertEquals("hello tomcat admin", result.getBody()); //login worked + + Set redisResult = connection.keys("*".getBytes()); + assertTrue(redisResult.size() > 0); //redis was populated with data + } + + @Test //requires that the jetty service is running on port 8081 + public void testFailureAccessingJettyResourceWithTomcatSessionToken() { + //call the jetty server with the token + ResponseEntity jettyResult = restTemplate.getForEntity("http://localhost:8081", String.class); + assertEquals(HttpStatus.UNAUTHORIZED, jettyResult.getStatusCode()); //login worked + } + + @Test //requires that the jetty service is running on port 8081 + public void testAccessingJettyResourceWithTomcatSessionToken() { + //login to get a session token + ResponseEntity result = makeRequest(); + assertEquals("hello tomcat admin", result.getBody()); //login worked + + assertTrue(result.getHeaders().containsKey("Set-Cookie")); + + String setCookieValue = result.getHeaders().get("Set-Cookie").get(0); + String sessionCookie = setCookieValue.split(";")[0]; + String sessionValue = sessionCookie.split("=")[1]; + + //Add session token to headers + HttpHeaders headers = new HttpHeaders(); + headers.add("x-auth-token", sessionValue); + + //call the jetty server with the token + HttpEntity request = new HttpEntity<>(headers); + ResponseEntity jettyResult = restTemplate.exchange("http://localhost:8081", HttpMethod.GET, request, String.class); + assertEquals("hello Jetty", jettyResult.getBody()); //login worked + + } + + private ResponseEntity makeRequest() { + String plainCreds = "admin:password"; + byte[] plainCredsBytes = plainCreds.getBytes(); + byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); + String base64Creds = new String(base64CredsBytes); + + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic " + base64Creds); + + HttpEntity request = new HttpEntity<>(headers); + return restTemplate.exchange("http://localhost:" + port + "/tomcat/admin", HttpMethod.GET, request, String.class); + } + +} \ No newline at end of file