Merge remote-tracking branch 'upstream/master'

# Conflicts:
#	spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java
#	spring-session/pom.xml
#	spring-session/src/main/java/com/baeldung/spring/session/SecurityConfig.java
#	spring-session/tomcat-session-demo/pom.xml
This commit is contained in:
tschiman 2016-11-23 16:10:19 -07:00
commit 510dbeac24
81 changed files with 1775 additions and 242 deletions

View File

@ -0,0 +1,23 @@
package com.baeldung.generics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Generics {
// definition of a generic method
public static <T> List<T> fromArrayToList(T[] a) {
List<T> list = new ArrayList<>();
Arrays.stream(a).forEach(list::add);
return list;
}
// example of a generic method that has Number as an upper bound for T
public static <T extends Number> List<T> fromArrayToListWithUpperBound(T[] a) {
List<T> list = new ArrayList<>();
Arrays.stream(a).forEach(list::add);
return list;
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.generics;
import org.junit.Test;
import java.util.List;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
public class GenericsTest {
// testing the generic method with Integer
@Test
public void givenArrayOfIntegers_thanListOfIntegersReturnedOK() {
Integer[] intArray = {1, 2, 3, 4, 5};
List<Integer> list = Generics.fromArrayToList(intArray);
assertThat(list, hasItems(intArray));
}
// testing the generic method with String
@Test
public void givenArrayOfStrings_thanListOfStringsReturnedOK() {
String[] stringArray = {"hello1", "hello2", "hello3", "hello4", "hello5"};
List<String> list = Generics.fromArrayToList(stringArray);
assertThat(list, hasItems(stringArray));
}
// testing the generic method with Number as upper bound with Integer
// if we test fromArrayToListWithUpperBound with any type that doesn't
// extend Number it will fail to compile
@Test
public void givenArrayOfIntegersAndNumberUpperBound_thanListOfIntegersReturnedOK() {
Integer[] intArray = {1, 2, 3, 4, 5};
List<Integer> list = Generics.fromArrayToListWithUpperBound(intArray);
assertThat(list, hasItems(intArray));
}
}

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

@ -0,0 +1,116 @@
package org.baeldung.java.collections;
import static java.util.Arrays.asList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
public class CollectionsConcatenateUnitTest {
@Test
public void givenUsingJava8_whenConcatenatingUsingConcat_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Collection<String> collectionC = asList("W", "X");
Stream<String> combinedStream = Stream.concat(Stream.concat(collectionA.stream(), collectionB.stream()), collectionC.stream());
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
Assert.assertEquals(asList("S", "T", "U", "V", "W", "X"), collectionCombined);
}
@Test
public void givenUsingJava8_whenConcatenatingUsingflatMap_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Stream<String> combinedStream = Stream.of(collectionA, collectionB).flatMap(Collection::stream);
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
@Test
public void givenUsingGuava_whenConcatenatingUsingIterables_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = Iterables.unmodifiableIterable(Iterables.concat(collectionA, collectionB));
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
@Test
public void givenUsingJava7_whenConcatenatingUsingIterables_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = concat(collectionA, collectionB);
Collection<String> collectionCombined = makeListFromIterable(combinedIterables);
Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined);
}
public static <E> Iterable<E> concat(Iterable<? extends E> list1, Iterable<? extends E> list2) {
return new Iterable<E>() {
public Iterator<E> iterator() {
return new Iterator<E>() {
protected Iterator<? extends E> listIterator = list1.iterator();
protected Boolean checkedHasNext;
protected E nextValue;
private boolean startTheSecond;
public void theNext() {
if (listIterator.hasNext()) {
checkedHasNext = true;
nextValue = listIterator.next();
} else if (startTheSecond)
checkedHasNext = false;
else {
startTheSecond = true;
listIterator = list2.iterator();
theNext();
}
}
public boolean hasNext() {
if (checkedHasNext == null)
theNext();
return checkedHasNext;
}
public E next() {
if (!hasNext())
throw new NoSuchElementException();
checkedHasNext = null;
return nextValue;
}
public void remove() {
listIterator.remove();
}
};
}
};
}
public static <E> List<E> makeListFromIterable(Iterable<E> iter) {
List<E> list = new ArrayList<E>();
for (E item : iter) {
list.add(item);
}
return list;
}
}

View File

@ -1,7 +1,9 @@
package org.baeldung.java.io;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertTrue;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
@ -9,17 +11,29 @@ import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertTrue;
public class JavaFileUnitTest {
// create a file
private static final String TEMP_DIR = "src/test/resources/temp" + UUID.randomUUID().toString();
@BeforeClass
public static void setup() throws IOException {
Files.createDirectory(Paths.get(TEMP_DIR));
}
@AfterClass
public static void cleanup() throws IOException {
FileUtils.deleteDirectory(new File(TEMP_DIR));
}
@Test
public final void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException {
final File newFile = new File("src/test/resources/newFile_jdk6.txt");
final File newFile = new File(TEMP_DIR + "/newFile_jdk6.txt");
final boolean success = newFile.createNewFile();
assertTrue(success);
@ -27,48 +41,48 @@ public class JavaFileUnitTest {
@Test
public final void givenUsingJDK7nio2_whenCreatingFile_thenCorrect() throws IOException {
final Path newFilePath = Paths.get("src/test/resources/newFile_jdk7.txt");
final Path newFilePath = Paths.get(TEMP_DIR + "/newFile_jdk7.txt");
Files.createFile(newFilePath);
}
@Test
public final void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt"));
FileUtils.touch(new File(TEMP_DIR + "/newFile_commonsio.txt"));
}
@Test
public final void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
com.google.common.io.Files.touch(new File("src/test/resources/newFile_guava.txt"));
com.google.common.io.Files.touch(new File(TEMP_DIR + "/newFile_guava.txt"));
}
// move a file
@Test
public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
final File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt");
final File fileToMove = new File(TEMP_DIR + "/toMoveFile_jdk6.txt");
fileToMove.createNewFile();// .exists();
final File destDir = new File("src/test/resources/");
final File destDir = new File(TEMP_DIR + "/");
destDir.mkdir();
final boolean isMoved = fileToMove.renameTo(new File("src/test/resources/movedFile_jdk6.txt"));
final boolean isMoved = fileToMove.renameTo(new File(TEMP_DIR + "/movedFile_jdk6.txt"));
if (!isMoved) {
throw new FileSystemException("src/test/resources/movedFile_jdk6.txt");
throw new FileSystemException(TEMP_DIR + "/movedFile_jdk6.txt");
}
}
@Test
public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
final Path fileToMovePath = Files.createFile(Paths.get("src/test/resources/" + randomAlphabetic(5) + ".txt"));
final Path targetPath = Paths.get("src/main/resources/");
final Path fileToMovePath = Files.createFile(Paths.get(TEMP_DIR + "/" + randomAlphabetic(5) + ".txt"));
final Path targetPath = Paths.get(TEMP_DIR + "/");
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
}
@Test
public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException {
final File fileToMove = new File("src/test/resources/fileToMove.txt");
final File fileToMove = new File(TEMP_DIR + "/fileToMove.txt");
fileToMove.createNewFile();
final File destDir = new File("src/main/resources/");
final File destDir = new File(TEMP_DIR + "/temp");
final File targetFile = new File(destDir, fileToMove.getName());
com.google.common.io.Files.createParentDirs(targetFile);
com.google.common.io.Files.move(fileToMove, targetFile);
@ -76,23 +90,24 @@ public class JavaFileUnitTest {
@Test
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/test/resources/fileMoved_apache2.txt"));
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
FileUtils.moveFile(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/fileMoved_apache2.txt"));
}
@Test
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/main/resources/"), true);
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
Files.createDirectory(Paths.get(TEMP_DIR + "/temp"));
FileUtils.moveFileToDirectory(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/temp"), true);
}
// delete a file
@Test
public final void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException {
new File("src/test/resources/fileToDelete_jdk6.txt").createNewFile();
new File(TEMP_DIR + "/fileToDelete_jdk6.txt").createNewFile();
final File fileToDelete = new File("src/test/resources/fileToDelete_jdk6.txt");
final File fileToDelete = new File(TEMP_DIR + "/fileToDelete_jdk6.txt");
final boolean success = fileToDelete.delete();
assertTrue(success);
@ -100,17 +115,17 @@ public class JavaFileUnitTest {
@Test
public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException {
Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt"));
Files.createFile(Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt"));
final Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt");
final Path fileToDeletePath = Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt");
Files.delete(fileToDeletePath);
}
@Test
public final void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/fileToDelete_commonsIo.txt"));
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete_commonsIo.txt"));
final File fileToDelete = FileUtils.getFile("src/test/resources/fileToDelete_commonsIo.txt");
final File fileToDelete = FileUtils.getFile(TEMP_DIR + "/fileToDelete_commonsIo.txt");
final boolean success = FileUtils.deleteQuietly(fileToDelete);
assertTrue(success);
@ -118,9 +133,9 @@ public class JavaFileUnitTest {
@Test
public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/fileToDelete.txt"));
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete.txt"));
FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt"));
FileUtils.forceDelete(FileUtils.getFile(TEMP_DIR + "/fileToDelete.txt"));
}
}

View File

@ -1,20 +1,15 @@
<?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>
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>
<dependencies>
<dependency>
<groupId>org.wildfly</groupId>
@ -49,6 +44,4 @@
</plugin>
</plugins>
</build>
</project>

View File

@ -5,4 +5,4 @@ remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMO
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!
remote.connection.default.password=admin1234!

View File

@ -12,11 +12,12 @@
<!-- <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>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>

View File

@ -1,13 +1,19 @@
package com.baeldung.ejb.tutorial;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
@Stateless(name = "HelloWorld")
public class HelloWorldBean implements HelloWorld {
@Resource
private SessionContext context;
@Override
public String getHelloWorld() {
return "Welcome to EJB Tutorial!";
}
}

View File

@ -36,11 +36,10 @@
</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>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>

View File

@ -1,2 +1,3 @@
### Relevant Articles:
- [Wiring in Spring: @Autowired, @Resource and @Inject](http://www.baeldung.com/spring-annotations-resource-inject-autowire)
- [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory)

View File

@ -4,14 +4,11 @@
<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>
@ -50,6 +47,11 @@
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,23 @@
package com.baeldung.constructordi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.baeldung.constructordi.domain.Engine;
import com.baeldung.constructordi.domain.Transmission;
@Configuration
@ComponentScan("com.baeldung.constructordi")
public class Config {
@Bean
public Engine engine() {
return new Engine("v8", 5);
}
@Bean
public Transmission transmission() {
return new Transmission("sliding");
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.constructordi;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baeldung.constructordi.domain.Car;
public class SpringRunner {
public static void main(String[] args) {
Car toyota = getCarFromXml();
System.out.println(toyota);
toyota = getCarFromJavaConfig();
System.out.println(toyota);
}
private static Car getCarFromJavaConfig() {
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
return context.getBean(Car.class);
}
private static Car getCarFromXml() {
ApplicationContext context = new ClassPathXmlApplicationContext("baeldung.xml");
return context.getBean(Car.class);
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.constructordi.domain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Car {
private Engine engine;
private Transmission transmission;
@Autowired
public Car(Engine engine, Transmission transmission) {
this.engine = engine;
this.transmission = transmission;
}
@Override
public String toString() {
return String.format("Engine: %s Transmission: %s", engine, transmission);
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.constructordi.domain;
public class Engine {
private String type;
private int volume;
public Engine(String type, int volume) {
this.type = type;
this.volume = volume;
}
@Override
public String toString() {
return String.format("%s %d", type, volume);
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.constructordi.domain;
public class Transmission {
private String type;
public Transmission(String type) {
this.type = type;
}
@Override
public String toString() {
return String.format("%s", type);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.factorybean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FactoryBeanAppConfig {
@Bean
public ToolFactory tool() {
ToolFactory factory = new ToolFactory();
factory.setFactoryId(7070);
factory.setToolId(2);
factory.setToolName("wrench");
factory.setToolPrice(3.7);
return factory;
}
@Bean
public Worker worker() throws Exception {
Worker worker = new Worker();
worker.setNumber("1002");
worker.setTool(tool().getObject());
return worker;
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.factorybean;
import static com.google.common.base.Preconditions.checkArgument;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.StringUtils;
public class InitializationToolFactory implements FactoryBean<Tool>, InitializingBean {
private int factoryId;
private int toolId;
private String toolName;
private double toolPrice;
@Override
public void afterPropertiesSet() throws Exception {
checkArgument(!StringUtils.isEmpty(toolName), "tool name cannot be empty");
checkArgument(toolPrice >= 0, "tool price should not be less than 0");
}
@Override
public Tool getObject() throws Exception {
return new Tool(toolId, toolName, toolPrice);
}
@Override
public Class<?> getObjectType() {
return Tool.class;
}
@Override
public boolean isSingleton() {
return false;
}
public int getFactoryId() {
return factoryId;
}
public void setFactoryId(int factoryId) {
this.factoryId = factoryId;
}
public int getToolId() {
return toolId;
}
public void setToolId(int toolId) {
this.toolId = toolId;
}
public String getToolName() {
return toolName;
}
public void setToolName(String toolName) {
this.toolName = toolName;
}
public double getToolPrice() {
return toolPrice;
}
public void setToolPrice(double toolPrice) {
this.toolPrice = toolPrice;
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.factorybean;
import org.springframework.beans.factory.config.AbstractFactoryBean;
public class NonSingleToolFactory extends AbstractFactoryBean<Tool> {
private int factoryId;
private int toolId;
private String toolName;
private double toolPrice;
public NonSingleToolFactory() {
setSingleton(false);
}
@Override
public Class<?> getObjectType() {
return Tool.class;
}
@Override
protected Tool createInstance() throws Exception {
return new Tool(toolId, toolName, toolPrice);
}
public int getFactoryId() {
return factoryId;
}
public void setFactoryId(int factoryId) {
this.factoryId = factoryId;
}
public int getToolId() {
return toolId;
}
public void setToolId(int toolId) {
this.toolId = toolId;
}
public String getToolName() {
return toolName;
}
public void setToolName(String toolName) {
this.toolName = toolName;
}
public double getToolPrice() {
return toolPrice;
}
public void setToolPrice(double toolPrice) {
this.toolPrice = toolPrice;
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.factorybean;
import static com.google.common.base.Preconditions.checkArgument;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.util.StringUtils;
public class PostConstructToolFactory implements FactoryBean<Tool> {
private int factoryId;
private int toolId;
private String toolName;
private double toolPrice;
@Override
public Tool getObject() throws Exception {
return new Tool(toolId, toolName, toolPrice);
}
@Override
public Class<?> getObjectType() {
return Tool.class;
}
@Override
public boolean isSingleton() {
return false;
}
@PostConstruct
public void checkParams() {
checkArgument(!StringUtils.isEmpty(toolName), "tool name cannot be empty");
checkArgument(toolPrice >= 0, "tool price should not be less than 0");
}
public int getFactoryId() {
return factoryId;
}
public void setFactoryId(int factoryId) {
this.factoryId = factoryId;
}
public int getToolId() {
return toolId;
}
public void setToolId(int toolId) {
this.toolId = toolId;
}
public String getToolName() {
return toolName;
}
public void setToolName(String toolName) {
this.toolName = toolName;
}
public double getToolPrice() {
return toolPrice;
}
public void setToolPrice(double toolPrice) {
this.toolPrice = toolPrice;
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.factorybean;
import org.springframework.beans.factory.config.AbstractFactoryBean;
//no need to set singleton property because default value is true
public class SingleToolFactory extends AbstractFactoryBean<Tool> {
private int factoryId;
private int toolId;
private String toolName;
private double toolPrice;
@Override
public Class<?> getObjectType() {
return Tool.class;
}
@Override
protected Tool createInstance() throws Exception {
return new Tool(toolId, toolName, toolPrice);
}
public int getFactoryId() {
return factoryId;
}
public void setFactoryId(int factoryId) {
this.factoryId = factoryId;
}
public int getToolId() {
return toolId;
}
public void setToolId(int toolId) {
this.toolId = toolId;
}
public String getToolName() {
return toolName;
}
public void setToolName(String toolName) {
this.toolName = toolName;
}
public double getToolPrice() {
return toolPrice;
}
public void setToolPrice(double toolPrice) {
this.toolPrice = toolPrice;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.factorybean;
public class Tool {
private int id;
private String name;
private double price;
public Tool(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.factorybean;
import org.springframework.beans.factory.FactoryBean;
public class ToolFactory implements FactoryBean<Tool> {
private int factoryId;
private int toolId;
private String toolName;
private double toolPrice;
@Override
public Tool getObject() throws Exception {
return new Tool(toolId, toolName, toolPrice);
}
@Override
public Class<?> getObjectType() {
return Tool.class;
}
@Override
public boolean isSingleton() {
return false;
}
public int getFactoryId() {
return factoryId;
}
public void setFactoryId(int factoryId) {
this.factoryId = factoryId;
}
public int getToolId() {
return toolId;
}
public void setToolId(int toolId) {
this.toolId = toolId;
}
public String getToolName() {
return toolName;
}
public void setToolName(String toolName) {
this.toolName = toolName;
}
public double getToolPrice() {
return toolPrice;
}
public void setToolPrice(double toolPrice) {
this.toolPrice = toolPrice;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.factorybean;
public class Worker {
private String number;
private Tool tool;
public Worker() {}
public Worker(String number, Tool tool) {
this.number = number;
this.tool = tool;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Tool getTool() {
return tool;
}
public void setTool(Tool tool) {
this.tool = tool;
}
}

View File

@ -0,0 +1,20 @@
<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="toyota" class="com.baeldung.constructordi.domain.Car">
<constructor-arg index="0" ref="engine"/>
<constructor-arg index="1" ref="transmission"/>
</bean>
<bean id="engine" class="com.baeldung.constructordi.domain.Engine">
<constructor-arg index="0" value="v4"/>
<constructor-arg index="1" value="2"/>
</bean>
<bean id="transmission" class="com.baeldung.constructordi.domain.Transmission">
<constructor-arg value="sliding"/>
</bean>
</beans>

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="singleTool" class="com.baeldung.factorybean.SingleToolFactory">
<property name="factoryId" value="3001"/>
<property name="toolId" value="1"/>
<property name="toolName" value="screwdriver"/>
<property name="toolPrice" value="1.5"/>
</bean>
<bean id="nonSingleTool" class="com.baeldung.factorybean.NonSingleToolFactory">
<property name="factoryId" value="3002"/>
<property name="toolId" value="2"/>
<property name="toolName" value="screwdriver"/>
<property name="toolPrice" value="1.5"/>
</bean>
<bean id="worker1" class="com.baeldung.factorybean.Worker">
<property name="number" value="50001"/>
<property name="tool" ref="singleTool"/>
</bean>
<bean id="worker2" class="com.baeldung.factorybean.Worker">
<property name="number" value="50002"/>
<property name="tool" ref="singleTool"/>
</bean>
<bean id="worker3" class="com.baeldung.factorybean.Worker">
<property name="number" value="50003"/>
<property name="tool" ref="nonSingleTool"/>
</bean>
<bean id="worker4" class="com.baeldung.factorybean.Worker">
<property name="number" value="50004"/>
<property name="tool" ref="nonSingleTool"/>
</bean>
</beans>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="initializationTool" class="com.baeldung.factorybean.InitializationToolFactory">
<property name="factoryId" value="1010"/>
<property name="toolId" value="1"/>
<property name="toolName" value="screwdriver"/>
<property name="toolPrice" value="-1"/>
</bean>
<bean id="worker" class="com.baeldung.factorybean.Worker">
<property name="number" value="36"/>
<property name="tool" ref="initializationTool"/>
</bean>
</beans>

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="postConstructTool" class="com.baeldung.factorybean.PostConstructToolFactory">
<property name="factoryId" value="2020"/>
<property name="toolId" value="1"/>
<property name="toolName" value=""/>
<property name="toolPrice" value="2.2"/>
</bean>
<bean id="worker" class="com.baeldung.factorybean.Worker">
<property name="number" value="37"/>
<property name="tool" ref="postConstructTool"/>
</bean>
</beans>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="tool" class="com.baeldung.factorybean.ToolFactory">
<property name="factoryId" value="9090"/>
<property name="toolId" value="1"/>
<property name="toolName" value="screwdriver"/>
<property name="toolPrice" value="1.5"/>
</bean>
<bean id="worker" class="com.baeldung.factorybean.Worker">
<property name="number" value="1001"/>
<property name="tool" ref="tool"/>
</bean>
</beans>

View File

@ -0,0 +1,36 @@
package com.baeldung.factorybean;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AbstractFactoryBeanTest {
@Test
public void testSingleToolFactory() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-abstract-spring-ctx.xml");
Worker worker1 = (Worker) context.getBean("worker1");
Worker worker2 = (Worker) context.getBean("worker2");
assertThat(worker1.getNumber(), equalTo("50001"));
assertThat(worker2.getNumber(), equalTo("50002"));
assertTrue(worker1.getTool() == worker2.getTool());
}
@Test
public void testNonSingleToolFactory() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-abstract-spring-ctx.xml");
Worker worker3 = (Worker) context.getBean("worker3");
Worker worker4 = (Worker) context.getBean("worker4");
assertThat(worker3.getNumber(), equalTo("50003"));
assertThat(worker4.getNumber(), equalTo("50004"));
assertTrue(worker3.getTool() != worker4.getTool());
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.factorybean;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class FactoryBeanInitializeTest {
@Test(expected = BeanCreationException.class)
public void testInitializationToolFactory() {
new ClassPathXmlApplicationContext("classpath:factorybean-init-spring-ctx.xml");
}
@Test(expected = BeanCreationException.class)
public void testPostConstructToolFactory() {
new ClassPathXmlApplicationContext("classpath:factorybean-postconstruct-spring-ctx.xml");
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.factorybean;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class FactoryBeanTest {
@Test
public void testConstructWorkerByXml() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-spring-ctx.xml");
Worker worker = (Worker) context.getBean("worker");
assertThat(worker.getNumber(), equalTo("1001"));
assertThat(worker.getTool().getId(), equalTo(1));
assertThat(worker.getTool().getName(), equalTo("screwdriver"));
assertThat(worker.getTool().getPrice(), equalTo(1.5));
ToolFactory toolFactory = (ToolFactory) context.getBean("&tool");
assertThat(toolFactory.getFactoryId(), equalTo(9090));
}
@Test
public void testConstructWorkerByJava() {
ApplicationContext context = new AnnotationConfigApplicationContext(FactoryBeanAppConfig.class);
Worker worker = (Worker) context.getBean("worker");
assertThat(worker.getNumber(), equalTo("1002"));
assertThat(worker.getTool().getId(), equalTo(2));
assertThat(worker.getTool().getName(), equalTo("wrench"));
assertThat(worker.getTool().getPrice(), equalTo(3.7));
ToolFactory toolFactory = (ToolFactory) context.getBean("&tool");
assertThat(toolFactory.getFactoryId(), equalTo(7070));
}
}

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("your-path-to-db-file");
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>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-MAPS-API-KEY"
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("your-path-to-db-file");
DatabaseReader dbReader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName("your-public-ip");
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

@ -8,6 +8,7 @@ import java.io.File;
import java.io.IOException;
import org.baeldung.okhttp.ProgressRequestWrapper;
import org.junit.Before;
import org.junit.Test;
import okhttp3.Call;
@ -22,11 +23,16 @@ public class OkHttpFileUploadingLiveTest {
private static final String BASE_URL = "http://localhost:8080/spring-rest";
OkHttpClient client;
@Before
public void init() {
client = new OkHttpClient();
}
@Test
public void whenUploadFile_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "file.txt",
@ -47,22 +53,17 @@ public class OkHttpFileUploadingLiveTest {
@Test
public void whenGetUploadFileProgress_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "file.txt",
RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
.build();
ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> {
ProgressRequestWrapper.ProgressListener listener = (bytesWritten, contentLength) -> {
float percentage = 100f * bytesWritten / contentLength;
float percentage = 100f * bytesWritten / contentLength;
assertFalse(Float.compare(percentage, 100) > 0);
};
ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, listener);
});
Request request = new Request.Builder()
.url(BASE_URL + "/users/upload")

View File

@ -1,26 +1,36 @@
package org.baeldung.okhttp;
import okhttp3.*;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpGetLiveTest {
private static final String BASE_URL = "http://localhost:8080/spring-rest";
OkHttpClient client;
@Before
public void init() {
client = new OkHttpClient();
}
@Test
public void whenGetRequest_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(BASE_URL + "/date")
.build();
Request request = new Request.Builder().url(BASE_URL + "/date").build();
Call call = client.newCall(request);
Response response = call.execute();
@ -30,17 +40,12 @@ public class OkHttpGetLiveTest {
@Test
public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder();
urlBuilder.addQueryParameter("id", "1");
String url = urlBuilder.build().toString();
Request request = new Request.Builder()
.url(url)
.build();
Request request = new Request.Builder().url(url).build();
Call call = client.newCall(request);
Response response = call.execute();
@ -50,12 +55,7 @@ public class OkHttpGetLiveTest {
@Test
public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(BASE_URL + "/date")
.build();
Request request = new Request.Builder().url(BASE_URL + "/date").build();
Call call = client.newCall(request);
@ -65,7 +65,7 @@ public class OkHttpGetLiveTest {
}
public void onFailure(Call call, IOException e) {
fail();
fail();
}
});

View File

@ -2,6 +2,7 @@ package org.baeldung.okhttp;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import okhttp3.Call;
@ -13,11 +14,16 @@ public class OkHttpHeaderLiveTest {
private static final String SAMPLE_URL = "http://www.github.com";
OkHttpClient client;
@Before
public void init() {
client = new OkHttpClient();
}
@Test
public void whenSetHeader_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(SAMPLE_URL)
.addHeader("Content-Type", "application/json")
@ -31,7 +37,7 @@ public class OkHttpHeaderLiveTest {
@Test
public void whenSetDefaultHeader_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
OkHttpClient clientWithInterceptor = new OkHttpClient.Builder()
.addInterceptor(new DefaultContentTypeInterceptor("application/json"))
.build();
@ -39,10 +45,8 @@ public class OkHttpHeaderLiveTest {
.url(SAMPLE_URL)
.build();
Call call = client.newCall(request);
Call call = clientWithInterceptor.newCall(request);
Response response = call.execute();
response.close();
}
}

View File

@ -4,22 +4,37 @@ import okhttp3.*;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpMiscLiveTest {
private static final String BASE_URL = "http://localhost:8080/spring-rest";
private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class);
OkHttpClient client;
@Before
public void init() {
client = new OkHttpClient();
}
@Test
public void whenSetRequestTimeout_thenFail() throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
OkHttpClient clientWithTimeout = new OkHttpClient.Builder()
.readTimeout(1, TimeUnit.SECONDS)
.build();
@ -27,18 +42,15 @@ public class OkHttpMiscLiveTest {
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
.build();
Call call = client.newCall(request);
Call call = clientWithTimeout.newCall(request);
Response response = call.execute();
response.close();
}
@Test(expected = IOException.class)
public void whenCancelRequest_thenCorrect() throws IOException {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
.build();
@ -69,7 +81,7 @@ public class OkHttpMiscLiveTest {
File cacheDirectory = new File("src/test/resources/cache");
Cache cache = new Cache(cacheDirectory, cacheSize);
OkHttpClient client = new OkHttpClient.Builder()
OkHttpClient clientCached = new OkHttpClient.Builder()
.cache(cache)
.build();
@ -77,10 +89,10 @@ public class OkHttpMiscLiveTest {
.url("http://publicobject.com/helloworld.txt")
.build();
Response response1 = client.newCall(request).execute();
Response response1 = clientCached.newCall(request).execute();
logResponse(response1);
Response response2 = client.newCall(request).execute();
Response response2 = clientCached.newCall(request).execute();
logResponse(response2);
}

View File

@ -6,6 +6,7 @@ import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import okhttp3.Call;
@ -23,11 +24,16 @@ public class OkHttpPostingLiveTest {
private static final String BASE_URL = "http://localhost:8080/spring-rest";
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
OkHttpClient client;
@Before
public void init() {
client = new OkHttpClient();
}
@Test
public void whenSendPostRequest_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("username", "test")
.add("password", "test")
@ -46,11 +52,8 @@ public class OkHttpPostingLiveTest {
@Test
public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException {
String postBody = "test post";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(URL_SECURED_BY_BASIC_AUTHENTICATION)
.addHeader("Authorization", Credentials.basic("test", "test"))
@ -65,9 +68,6 @@ public class OkHttpPostingLiveTest {
@Test
public void whenPostJson_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient();
String json = "{\"id\":1,\"name\":\"John\"}";
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
@ -85,9 +85,6 @@ public class OkHttpPostingLiveTest {
@Test
public void whenSendMultipartRequest_thenCorrect() throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("username", "test")

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

@ -1,17 +1,40 @@
package org.baeldung.security.filter.configuration;
import org.baeldung.security.basic.MyBasicAuthenticationEntryPoint;
import org.baeldung.security.filter.CustomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private MyBasicAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user1").password("user1Pass")
.authorities("ROLE_USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
}
http.authorizeRequests()
.antMatchers("/securityNone").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new CustomFilter(),
BasicAuthenticationFilter.class);
}
}

View File

@ -2,11 +2,10 @@ package org.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource({ "classpath:webSecurityConfig.xml" })
@ComponentScan("org.baeldung.security")
//@ImportResource({ "classpath:webSecurityConfig.xml" })
public class SecSecurityConfig {
public SecSecurityConfig() {

View File

@ -1,2 +1,11 @@
###The Course
=========
## Spring Security Authentication/Authorization Example Project
##The Course
The "REST With Spring" Classes: http://github.learnspringsecurity.com
### Relevant Articles:
- [Spring Security Manual Authentication](http://www.baeldung.com/spring-security-authentication)
### Build the Project
mvn clean install

View File

@ -8,9 +8,11 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.context.annotation.Profile;
@Configuration
@EnableWebMvc
@Profile("!manual")
public class MvcConfig extends WebMvcConfigurerAdapter {
public MvcConfig() {

View File

@ -0,0 +1,22 @@
package org.baeldung.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
@Profile("manual")
public class MvcConfigManual extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}

View File

@ -0,0 +1,92 @@
package org.baeldung.config;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.context.annotation.Profile;
/**
* Manually authenticate a user using Spring Security / Spring Web MVC' (upon successful account registration)
* (http://stackoverflow.com/questions/4664893/how-to-manually-set-an-authenticated-user-in-spring-security-springmvc)
*
* @author jim clayson
*/
@Controller
@Profile("manual")
public class RegistrationController {
private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);
@Autowired
AuthenticationManager authenticationManager;
/**
* For demo purposes this need only be a GET request method
*
* @param request
* @param response
* @return The view. Page confirming either successful registration (and/or
* successful authentication) or failed registration.
*/
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String registerAndAuthenticate(HttpServletRequest request, HttpServletResponse response) {
logger.debug("registerAndAuthenticate: attempt to register, application should manually authenticate.");
// Mocked values. Potentially could come from an HTML registration form,
// in which case this mapping would match on an HTTP POST, rather than a GET
String username = "user";
String password = "password";
String view = "registrationSuccess";
if (requestQualifiesForManualAuthentication()) {
try {
authenticate(username, password, request, response);
logger.debug("registerAndAuthenticate: authentication completed.");
} catch (BadCredentialsException bce) {
logger.debug("Authentication failure: bad credentials");
bce.printStackTrace();
view = "systemError"; // assume a low-level error, since the registration
// form would have been successfully validated
}
}
return view;
}
private boolean requestQualifiesForManualAuthentication() {
// Some processing to determine that the user requires a Spring Security-recognized,
// application-directed login e.g. successful account registration.
return true;
}
private void authenticate(String username, String password, HttpServletRequest request, HttpServletResponse response) throws BadCredentialsException {
logger.debug("attempting to authenticated, manually ... ");
// create and populate the token
AbstractAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password);
authToken.setDetails(new WebAuthenticationDetails(request));
// This call returns an authentication object, which holds principle and user credentials
Authentication authentication = this.authenticationManager.authenticate(authToken);
// The security context holds the authentication object, and is stored
// in thread local scope.
SecurityContextHolder.getContext().setAuthentication(authentication);
logger.debug("User should now be authenticated.");
}
}

View File

@ -6,9 +6,11 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.context.annotation.Profile;
@Configuration
@EnableWebSecurity
@Profile("!manual")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override

View File

@ -0,0 +1,35 @@
package org.baeldung.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@Profile("manual")
public class WebSecurityConfigManual extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/", "/home", "/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout().permitAll();
// @formatter:on
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
<p>Click <a th:href="@{/home}">here</a> to go to the home page.</p>
</body>
</html>

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
<p sec:authorize="isAnonymous()">Click <a th:href="@{/register}">here</a> to send a dummy registration request, where the application logs you in.</p>
</body>
</html>

View File

@ -0,0 +1,21 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
<p>Click <a th:href="@{/home}">here</a> to go to the home page.</p>
</body>
</html>

View File

@ -0,0 +1 @@
Registration could not be completed at this time. Please try again later or contact support!

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Registration Success!</title>
</head>
<body>
<h2 th:inline="text">Registration succeeded. You have been logged in by the system. Welcome [[${#httpServletRequest.remoteUser}]]!</h2>
<form th:action="@{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
<p>Click <a th:href="@{/home}">here</a> to go to the home page.</p>
</body>
</html>

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;