Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Kevin Gilmore 2016-11-20 08:16:45 -06:00
commit ebf3387f95
81 changed files with 1407 additions and 664 deletions

View File

@ -49,7 +49,7 @@
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.55</version>
<version>${bouncycastle.version}</version>
</dependency>
<!-- web -->
@ -134,7 +134,7 @@
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
<version>${commons-codec.version}</version>
</dependency>
</dependencies>
@ -338,6 +338,8 @@
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>

View File

@ -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<InetAddress> 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<InterfaceAddress> 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);
}
}

View File

@ -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");

View File

@ -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"));
}
}

54
ejb/ejb-client/pom.xml Executable file
View File

@ -0,0 +1,54 @@
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>ejb-client</artifactId>
<name>EJB3 Client Maven</name>
<description>EJB3 Client Maven</description>
<properties>
<junit.version>4.12</junit.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-ejb-client-bom</artifactId>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb-remote</artifactId>
<type>ejb</type>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*EJBSetupTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -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();
}
}
}

View File

@ -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!

View File

@ -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());
}
}

39
ejb/ejb-remote/pom.xml Executable file
View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>ejb-remote</artifactId>
<packaging>ejb</packaging>
<!-- <name>ejb-remote</name> -->
<dependencies>
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.wildfly.plugins</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>1.1.0.Alpha5</version>
<configuration>
<hostname>127.0.0.1</hostname>
<port>9990</port>
<username>testUser</username>
<password>admin1234!</password>
<filename>${build.finalName}.jar</filename>
</configuration>
</plugin>
</plugins>
<!-- <finalName>ejb-remote</finalName> -->
</build>
</project>

View File

@ -0,0 +1,8 @@
package com.baeldung.ejb.tutorial;
import javax.ejb.Remote;
@Remote
public interface HelloWorld {
String getHelloWorld();
}

View File

@ -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!";
}
}

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd"
version="3.2">
<module-name>remote</module-name>
</ejb-jar>

83
ejb/pom.xml Executable file
View File

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>ejb</name>
<description>EJB Tutorial</description>
<repositories>
<repository>
<id>jboss-public-repository-group</id>
<name>JBoss Public Maven Repository Group</name>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb-remote</artifactId>
<version>1.0-SNAPSHOT</version>
<type>ejb</type>
</dependency>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-7.0</artifactId>
<version>1.0.1.Final</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-ejb-client-bom</artifactId>
<version>10.1.0.Final</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-ejb-plugin</artifactId>
<version>2.4</version>
<configuration>
<ejbVersion>3.2</ejbVersion>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<modules>
<module>ejb-remote</module>
<module>ejb-client</module>
</modules>
</project>

9
javaxval/README.md Normal file
View File

@ -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)

View File

@ -40,9 +40,9 @@
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,53 @@
<!DOCTYPE html>
<html>
<head>
<title>A very simple webpage</title>
</head>
<body>
<h1>A very simple webpage. This is an "h1" level header.</h1>
<h2>This is a level h2 header.</h2>
<h6>This is a level h6 header. Pretty small!</h6>
<p>This is a standard paragraph.</p>
<p align=center>Now I've aligned it in the center of the screen.</p>
<p align=right>Now aligned to the right</p>
<p><b>Bold text</b></p>
<p><strong>Strongly emphasized text</strong> Can you tell the difference vs. bold?</p>
<p><i>Italics</i></p>
<p><em>Emphasized text</em> Just like Italics!</p>
<h2>How about a nice ordered list!</h2>
<ol>
<li>This little piggy went to market</li>
<li>This little piggy went to SB228 class</li>
<li>This little piggy went to an expensive restaurant in Downtown Palo Alto</li>
<li>This little piggy ate too much at Indian Buffet.</li>
<li>This little piggy got lost</li>
</ol>
<h2>Unordered list</h2>
<ul>
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
</ul>
<p>And finally, how about some</p><a href="http://www.google.com/">Links?</a>
<p>Remember, you can view the HTMl code from this or any other page by using the "View Page Source" command of your browser.</p>
</body>
</html>

View File

@ -0,0 +1,3 @@
Test
Text
Test TEST

12
pom.xml
View File

@ -52,11 +52,11 @@
<module>jee7</module>
<module>jjwt</module>
<module>jpa-storedprocedure</module>
<module>jsf</module>
<module>jsf</module>
<module>json-path</module>
<module>json</module>
<module>junit5</module>
<module>log4j</module>
<module>log-mdc</module>
<module>lombok</module>
@ -72,19 +72,19 @@
<module>querydsl</module>
<!-- <module>raml</module> -->
<module>redis</module>
<module>redis</module>
<module>rest-assured</module>
<module>rest-testing</module>
<module>resteasy</module>
<module>selenium-junit-testng</module>
<module>spring-akka</module>
<module>spring-akka</module>
<module>spring-all</module>
<module>spring-apache-camel</module>
<module>spring-autowire</module>
<module>spring-batch</module>
<module>spring-boot</module>
<module>spring-cloud-data-flow</module>
<module>spring-cloud-data-flow</module>
<module>spring-cloud</module>
<module>spring-core</module>
<module>spring-cucumber</module>
@ -132,7 +132,7 @@
<module>spring-security-rest-custom</module>
<module>spring-security-rest-digest-auth</module>
<module>spring-security-rest-full</module>
<module>spring-security-rest</module>
<module>spring-security-rest</module>
<module>spring-security-x509</module>
<module>spring-session</module>
<module>spring-spel</module>

View File

@ -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<WebElement> 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);
}
}

View File

@ -11,25 +11,26 @@
<properties>
<env.camel.version>2.16.1</env.camel.version>
<env.spring.version>4.2.4.RELEASE</env.spring.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<java.version>1.7</java.version>
<junit.version>4.1</junit.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>${env.camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring</artifactId>
@ -49,7 +50,7 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
@ -62,6 +63,22 @@
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
<systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -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();
}
}

View File

@ -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/";

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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<RibbonClientSpecification> configurations = new ArrayList<>();
@Autowired(required = false)
private List<RibbonClientSpecification> 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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -5,8 +5,8 @@ RemoteSystemsTempFiles/
bin/
.metadata/
docs/*.autosave
docs/*.autosave
.recommenders/
build/
.gradle/
.DS_Store
.idea/

View File

@ -4,22 +4,13 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>dependency-injection</artifactId>
<artifactId>spring-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>dependency-injection</name>
<description>Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely
Resource, Inject, and Autowired
</description>
<name>spring-core</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
@ -50,6 +41,12 @@
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="employee" class="com.baeldung.beanfactory.Employee">
<constructor-arg name="name" value="Hello! My name is Java"/>
<constructor-arg name="age" value="18"/>
</bean>
<alias name="employee" alias="empalias" />
</beans>

View File

@ -1,21 +1,21 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-data-solr</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-data-solr</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.2.5.RELEASE</spring.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<spring-data-solr>2.0.4.RELEASE</spring-data-solr>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
@ -50,20 +50,58 @@
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -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;
}
}

View File

@ -13,7 +13,7 @@ public interface ProductRepository extends SolrCrudRepository<Product, String> {
public List<Product> findByName(String name);
@Query("name:*?0* OR category:*?0* OR description:*?0*")
@Query("id:*?0* OR name:*?0*")
public Page<Product> findByCustomQuery(String searchTerm, Pageable pageable);
@Query(name = "Product.findByNamedQuery")

View File

@ -1 +1 @@
Product.findByNamedQuery=name:*?0* OR category:*?0* OR description:*?0*
Product.findByNamedQuery=id:*?0* OR name:*?0*

View File

@ -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<Product> 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<Product> 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<Product> result = productRepository.findByNamedQuery("one", new PageRequest(0, 10));
assertEquals(3, result.getNumberOfElements());
}
}

View File

@ -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 <enter>: ");

View File

@ -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<String, Map<String, String>> labels;

View File

@ -248,8 +248,8 @@
<properties>
<!-- Spring -->
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
<org.springframework.security.version>4.0.4.RELEASE</org.springframework.security.version>
<org.springframework.version>4.3.4.RELEASE</org.springframework.version>
<org.springframework.security.version>4.2.0.RELEASE</org.springframework.security.version>
<thymeleaf.version>2.1.4.RELEASE</thymeleaf.version>
<jackson.version>2.7.8</jackson.version>

View File

@ -112,6 +112,11 @@
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.8.0</version>
</dependency>
</dependencies>
<build>
@ -146,7 +151,7 @@
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<!-- <exclude>**/*ProductionTest.java</exclude> -->
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
<systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -0,0 +1,84 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Geo IP Test</title>
<!--jquery dep -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready (function () {
// getting the public ip address from api and setting on text box
// ip api : https://www.ipify.org/
$.get( "https://api.ipify.org?format=json", function( data ) {
console.log(data);
$("#ip").val(data.ip) ;
});
function showLocationOnMap (location) {
var map;
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: Number(location.latitude), lng: Number(location.longitude)},
zoom: 15
});
var marker = new google.maps.Marker({
position: {lat: Number(location.latitude), lng: Number(location.longitude)},
map: map,
title: "Public IP:"+location.ipAddress+" @ "+location.city
});
}
$( "#ipForm" ).submit(function( event ) {
event.preventDefault();
$.ajax({
url: "GeoIPTest",
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8", // send as JSON
data: $.param( {ipAddress : $("#ip").val()} ),
complete: function(data) {
console.log ("Request complete");
},
success: function(data) {
$("#status").html(JSON.stringify(data));
if (data.ipAddress !=null) {
console.log ("Success:"+data.ipAddress);
showLocationOnMap(data);
}
},
error: function(err) {
console.log(err);
$("#status").html("Error:"+JSON.stringify(data));
},
});
});
});
</script>
</head>
<body>
<form id="ipForm" action="GeoIPTest" method="POST">
<input type="text" name = "ipAddress" id = "ip"/>
<input type="submit" name="submit" value="submit" />
</form>
<div id="status"></div>
<div id="map" style="height: 500px; width:100%; position:absolute"></div>
<!--AIzaSyDDr65sVtJtlbliOTAeXyZSDPvG9NROjJA -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA4vsDQWHeOrDnzS98XMXl5hgwA9raaQZ8"
async defer></script>
</body>
</html>

View File

@ -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();
}
}

View File

@ -1,4 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-rest</artifactId>
@ -9,7 +10,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
<version>1.4.2.RELEASE</version>
</parent>
<dependencies>
@ -24,6 +25,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!-- Spring -->
@ -49,7 +54,7 @@
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
<version>1.3.2</version>
</dependency>
<!-- web -->
@ -73,9 +78,9 @@
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
@ -94,7 +99,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.2.1</version>
<version>3.5</version>
</dependency>
<!-- logging -->
@ -157,16 +162,21 @@
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version>
</dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version>
</dependency>
<!-- -->
<!-- -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.6.1</version>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.googlecode.protobuf-java-format</groupId>
<artifactId>protobuf-java-format</artifactId>
<version>1.4</version>
</dependency>
<dependency>
@ -206,7 +216,8 @@
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
@ -240,6 +251,36 @@
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>live</id>
<build>
@ -292,6 +333,7 @@
</plugins>
</build>
</profile>
</profiles>
<properties>
@ -299,13 +341,13 @@
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.39</mysql-connector-java.version>
<mysql-connector-java.version>5.1.40</mysql-connector-java.version>
<!-- various -->
<hibernate-validator.version>5.2.2.Final</hibernate-validator.version>
<!-- util -->
<guava.version>19.0</guava.version>
<guava.version>20.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<!-- testing -->
@ -323,7 +365,7 @@
<logback.version>1.1.3</logback.version>
<!-- Maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<cargo-maven2-plugin.version>1.6.0</cargo-maven2-plugin.version>
@ -332,7 +374,8 @@
<com.squareup.okhttp3.version>3.4.1</com.squareup.okhttp3.version>
</properties>
<reporting>
<reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
@ -345,4 +388,5 @@
</plugin>
</plugins>
</reporting>
</project>

View File

@ -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);
}
}

View File

@ -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<HttpMessageConverter<?>> 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);

View File

@ -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

View File

@ -0,0 +1,2 @@
server.port= 8082
server.context-path=/spring-rest

View File

@ -0,0 +1,5 @@
package org.baeldung.client;
public interface Consts {
int APPLICATION_PORT = 8082;
}

View File

@ -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<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException {
ResponseEntity<String> 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));
}
}

View File

@ -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"));
}
}

View File

@ -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;

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<beansProjectDescription>
<version>1</version>
<pluginVersion><![CDATA[3.8.2.201610040608-RELEASE]]></pluginVersion>
<configSuffixes>
<configSuffix><![CDATA[xml]]></configSuffix>
</configSuffixes>
<enableImports><![CDATA[false]]></enableImports>
<configs>
<config>java:org.baeldung.security.spring.SecurityWithoutCsrfConfig</config>
</configs>
<autoconfigs>
<config>src/main/webapp/WEB-INF/api-servlet.xml</config>
<config>java:org.baeldung.spring.Application</config>
<config>java:org.baeldung.security.spring.SecurityWithCsrfConfig</config>
</autoconfigs>
<configSets>
</configSets>
</beansProjectDescription>

View File

@ -10,7 +10,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.8.RELEASE</version>
<version>1.4.2.RELEASE</version>
</parent>
<dependencies>
@ -109,14 +109,12 @@
<!-- Querydsl -->
<dependency>
<groupId>com.mysema.querydsl</groupId>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
</dependency>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>${querydsl.version}</version>
</dependency>
<!-- Rsql -->
@ -161,7 +159,6 @@
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>${xml-apis.version}</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
@ -358,7 +355,7 @@
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
@ -467,16 +464,13 @@
<properties>
<!-- Spring -->
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
<org.springframework.security.version>4.0.4.RELEASE</org.springframework.security.version>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<spring-data-jpa.version>1.8.2.RELEASE</spring-data-jpa.version>
<mysql-connector-java.version>5.1.40</mysql-connector-java.version>
<rsql.version>2.0.0</rsql.version>
<querydsl.version>3.6.2</querydsl.version>
<querydsl.version>4.1.4</querydsl.version>
<!-- marshalling -->
<jackson.version>2.7.8</jackson.version>
@ -505,7 +499,7 @@
<rest-assured.version>2.9.0</rest-assured.version>
<!-- Maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>

View File

@ -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 {

View File

@ -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<SearchCriteria> params;

View File

@ -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<MyUser, Long>, QueryDslPredicateExecutor<MyUser>, QuerydslBinderCustomizer<QMyUser> {
@Override

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -37,6 +37,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>

View File

@ -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";

View File

@ -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 {

View File

@ -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");
}
}

View File

@ -19,4 +19,5 @@
<module>jetty-session-demo</module>
<module>tomcat-session-demo</module>
</modules>
</project>

View File

@ -32,6 +32,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
@ -61,6 +66,20 @@
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*ControllerTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</project>

View File

@ -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();
}

View File

@ -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";

View File

@ -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 {

View File

@ -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<byte[]> result = connection.keys("*".getBytes());
assertEquals(0, result.size());
}
@Test
public void testForbiddenToProtectedEndpoint() {
ResponseEntity<String> result = restTemplate.getForEntity("/tomcat/admin", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
}
@Test
public void testLoginAddsRedisKey() {
ResponseEntity<String> result = makeRequest();
assertEquals("hello tomcat admin", result.getBody()); //login worked
Set<byte[]> 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<String> 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<String> 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<String> request = new HttpEntity<>(headers);
ResponseEntity<String> jettyResult = restTemplate.exchange("http://localhost:8081", HttpMethod.GET, request, String.class);
assertEquals("hello Jetty", jettyResult.getBody()); //login worked
}
private ResponseEntity<String> 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<String> request = new HttpEntity<>(headers);
return restTemplate.exchange("http://localhost:" + port + "/tomcat/admin", HttpMethod.GET, request, String.class);
}
}