merge upstream
This commit is contained in:
commit
750aad44df
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,60 @@
|
||||||
|
package com.baeldung.java.nio2.visitor;
|
||||||
|
|
||||||
|
import static java.nio.file.FileVisitResult.CONTINUE;
|
||||||
|
import static java.nio.file.FileVisitResult.TERMINATE;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.FileVisitResult;
|
||||||
|
import java.nio.file.FileVisitor;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
|
|
||||||
|
public class FileSearchExample implements FileVisitor<Path> {
|
||||||
|
private static String FILE_NAME;
|
||||||
|
private static Path START_DIR;
|
||||||
|
|
||||||
|
public FileSearchExample(String fileName, Path startingDir) {
|
||||||
|
FILE_NAME = fileName;
|
||||||
|
START_DIR = startingDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
|
||||||
|
return CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
|
||||||
|
String fileName = file.getFileName().toString();
|
||||||
|
if (FILE_NAME.equals(fileName)) {
|
||||||
|
System.out.println("File found: " + file.toString());
|
||||||
|
return TERMINATE;
|
||||||
|
}
|
||||||
|
return CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
|
||||||
|
System.out.println("Failed to access file: " + file.toString());
|
||||||
|
return CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
|
||||||
|
boolean finishedSearch = Files.isSameFile(dir, START_DIR);
|
||||||
|
if (finishedSearch) {
|
||||||
|
System.out.println("File:" + FILE_NAME + " not found");
|
||||||
|
return TERMINATE;
|
||||||
|
}
|
||||||
|
return CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
Path startingDir = Paths.get("C:/Users/new/Desktop");
|
||||||
|
FileSearchExample crawler = new FileSearchExample("hibernate.txt", startingDir);
|
||||||
|
Files.walkFileTree(startingDir, crawler);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.java.nio2.visitor;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.FileVisitResult;
|
||||||
|
import java.nio.file.FileVisitor;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
|
|
||||||
|
public class FileVisitorImpl implements FileVisitor<Path> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFileFailed(Path file, IOException exc) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.java.nio2.watcher;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.FileSystems;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.StandardWatchEventKinds;
|
||||||
|
import java.nio.file.WatchEvent;
|
||||||
|
import java.nio.file.WatchKey;
|
||||||
|
import java.nio.file.WatchService;
|
||||||
|
|
||||||
|
public class DirectoryWatcherExample {
|
||||||
|
public static void main(String[] args) throws IOException, InterruptedException {
|
||||||
|
WatchService watchService = FileSystems.getDefault().newWatchService();
|
||||||
|
Path path = Paths.get(System.getProperty("user.home"));
|
||||||
|
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
|
||||||
|
WatchKey key;
|
||||||
|
while ((key = watchService.take()) != null) {
|
||||||
|
for (WatchEvent<?> event : key.pollEvents()) {
|
||||||
|
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
|
||||||
|
}
|
||||||
|
key.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,64 +1,72 @@
|
||||||
package com.baeldung.java.nio2;
|
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.assertFalse;
|
||||||
import static org.junit.Assert.assertTrue;
|
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 {
|
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
|
// checking file or dir
|
||||||
@Test
|
@Test
|
||||||
public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
|
public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
|
||||||
Path p = Paths.get(HOME);
|
Path p = Paths.get(TEMP_DIR);
|
||||||
assertTrue(Files.exists(p));
|
assertTrue(Files.exists(p));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() {
|
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));
|
assertTrue(Files.notExists(p));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||||
Path p = Paths.get(HOME);
|
Path p = Paths.get(TEMP_DIR);
|
||||||
assertFalse(Files.isRegularFile(p));
|
assertFalse(Files.isRegularFile(p));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
|
public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
|
||||||
Path p = Paths.get(HOME);
|
Path p = Paths.get(TEMP_DIR);
|
||||||
assertTrue(Files.isReadable(p));
|
assertTrue(Files.isReadable(p));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
|
public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
|
||||||
Path p = Paths.get(HOME);
|
Path p = Paths.get(System.getProperty("user.home"));
|
||||||
assertTrue(Files.isWritable(p));
|
assertTrue(Files.isWritable(p));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
|
public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
|
||||||
Path p = Paths.get(HOME);
|
Path p = Paths.get(System.getProperty("user.home"));
|
||||||
assertTrue(Files.isExecutable(p));
|
assertTrue(Files.isExecutable(p));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
|
public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
|
||||||
Path p1 = Paths.get(HOME);
|
Path p1 = Paths.get(TEMP_DIR);
|
||||||
Path p2 = Paths.get(HOME);
|
Path p2 = Paths.get(TEMP_DIR);
|
||||||
assertTrue(Files.isSameFile(p1, p2));
|
assertTrue(Files.isSameFile(p1, p2));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -67,7 +75,7 @@ public class FileTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
|
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
|
||||||
String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
|
String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
|
||||||
Path p = Paths.get(HOME + "/" + fileName);
|
Path p = Paths.get(TEMP_DIR + "/" + fileName);
|
||||||
assertFalse(Files.exists(p));
|
assertFalse(Files.exists(p));
|
||||||
Files.createFile(p);
|
Files.createFile(p);
|
||||||
assertTrue(Files.exists(p));
|
assertTrue(Files.exists(p));
|
||||||
|
@ -77,7 +85,7 @@ public class FileTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
|
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
|
||||||
String dirName = "myDir_" + UUID.randomUUID().toString();
|
String dirName = "myDir_" + UUID.randomUUID().toString();
|
||||||
Path p = Paths.get(HOME + "/" + dirName);
|
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||||
assertFalse(Files.exists(p));
|
assertFalse(Files.exists(p));
|
||||||
Files.createDirectory(p);
|
Files.createDirectory(p);
|
||||||
assertTrue(Files.exists(p));
|
assertTrue(Files.exists(p));
|
||||||
|
@ -89,7 +97,7 @@ public class FileTest {
|
||||||
@Test(expected = NoSuchFileException.class)
|
@Test(expected = NoSuchFileException.class)
|
||||||
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
|
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
|
||||||
String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
|
String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
|
||||||
Path p = Paths.get(HOME + "/" + dirName);
|
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||||
assertFalse(Files.exists(p));
|
assertFalse(Files.exists(p));
|
||||||
Files.createDirectory(p);
|
Files.createDirectory(p);
|
||||||
|
|
||||||
|
@ -97,7 +105,7 @@ public class FileTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
|
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");
|
Path subdir = dir.resolve("subdir");
|
||||||
assertFalse(Files.exists(dir));
|
assertFalse(Files.exists(dir));
|
||||||
assertFalse(Files.exists(subdir));
|
assertFalse(Files.exists(subdir));
|
||||||
|
@ -110,7 +118,7 @@ public class FileTest {
|
||||||
public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException {
|
public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException {
|
||||||
String prefix = "log_";
|
String prefix = "log_";
|
||||||
String suffix = ".txt";
|
String suffix = ".txt";
|
||||||
Path p = Paths.get(HOME + "/");
|
Path p = Paths.get(TEMP_DIR + "/");
|
||||||
p = Files.createTempFile(p, prefix, suffix);
|
p = Files.createTempFile(p, prefix, suffix);
|
||||||
// like log_8821081429012075286.txt
|
// like log_8821081429012075286.txt
|
||||||
assertTrue(Files.exists(p));
|
assertTrue(Files.exists(p));
|
||||||
|
@ -119,7 +127,7 @@ public class FileTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
|
public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
|
||||||
Path p = Paths.get(HOME + "/");
|
Path p = Paths.get(TEMP_DIR + "/");
|
||||||
p = Files.createTempFile(p, null, null);
|
p = Files.createTempFile(p, null, null);
|
||||||
// like 8600179353689423985.tmp
|
// like 8600179353689423985.tmp
|
||||||
assertTrue(Files.exists(p));
|
assertTrue(Files.exists(p));
|
||||||
|
@ -136,7 +144,7 @@ public class FileTest {
|
||||||
// delete file
|
// delete file
|
||||||
@Test
|
@Test
|
||||||
public void givenPath_whenDeletes_thenCorrect() throws IOException {
|
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));
|
assertFalse(Files.exists(p));
|
||||||
Files.createFile(p);
|
Files.createFile(p);
|
||||||
assertTrue(Files.exists(p));
|
assertTrue(Files.exists(p));
|
||||||
|
@ -147,7 +155,7 @@ public class FileTest {
|
||||||
|
|
||||||
@Test(expected = DirectoryNotEmptyException.class)
|
@Test(expected = DirectoryNotEmptyException.class)
|
||||||
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
|
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);
|
Files.createDirectory(dir);
|
||||||
assertTrue(Files.exists(dir));
|
assertTrue(Files.exists(dir));
|
||||||
Path file = dir.resolve("file.txt");
|
Path file = dir.resolve("file.txt");
|
||||||
|
@ -160,7 +168,7 @@ public class FileTest {
|
||||||
|
|
||||||
@Test(expected = NoSuchFileException.class)
|
@Test(expected = NoSuchFileException.class)
|
||||||
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
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));
|
assertFalse(Files.exists(p));
|
||||||
Files.delete(p);
|
Files.delete(p);
|
||||||
|
|
||||||
|
@ -168,7 +176,7 @@ public class FileTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException {
|
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));
|
assertFalse(Files.exists(p));
|
||||||
Files.deleteIfExists(p);
|
Files.deleteIfExists(p);
|
||||||
|
|
||||||
|
@ -177,8 +185,8 @@ public class FileTest {
|
||||||
// copy file
|
// copy file
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
||||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir1);
|
Files.createDirectory(dir1);
|
||||||
Files.createDirectory(dir2);
|
Files.createDirectory(dir2);
|
||||||
Path file1 = dir1.resolve("filetocopy.txt");
|
Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
|
@ -193,8 +201,8 @@ public class FileTest {
|
||||||
|
|
||||||
@Test(expected = FileAlreadyExistsException.class)
|
@Test(expected = FileAlreadyExistsException.class)
|
||||||
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir1);
|
Files.createDirectory(dir1);
|
||||||
Files.createDirectory(dir2);
|
Files.createDirectory(dir2);
|
||||||
Path file1 = dir1.resolve("filetocopy.txt");
|
Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
|
@ -210,8 +218,8 @@ public class FileTest {
|
||||||
// moving files
|
// moving files
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
||||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir1);
|
Files.createDirectory(dir1);
|
||||||
Files.createDirectory(dir2);
|
Files.createDirectory(dir2);
|
||||||
Path file1 = dir1.resolve("filetocopy.txt");
|
Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
|
@ -227,8 +235,8 @@ public class FileTest {
|
||||||
|
|
||||||
@Test(expected = FileAlreadyExistsException.class)
|
@Test(expected = FileAlreadyExistsException.class)
|
||||||
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||||
Files.createDirectory(dir1);
|
Files.createDirectory(dir1);
|
||||||
Files.createDirectory(dir2);
|
Files.createDirectory(dir2);
|
||||||
Path file1 = dir1.resolve("filetocopy.txt");
|
Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
|
|
|
@ -0,0 +1,82 @@
|
||||||
|
package com.baeldung.java.nio2.async;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.channels.AsynchronousSocketChannel;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
|
public class AsyncEchoClient {
|
||||||
|
private AsynchronousSocketChannel client;
|
||||||
|
private Future<Void> future;
|
||||||
|
private static AsyncEchoClient instance;
|
||||||
|
|
||||||
|
private AsyncEchoClient() {
|
||||||
|
try {
|
||||||
|
client = AsynchronousSocketChannel.open();
|
||||||
|
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
|
||||||
|
future = client.connect(hostAddress);
|
||||||
|
start();
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AsyncEchoClient getInstance() {
|
||||||
|
if (instance == null)
|
||||||
|
instance = new AsyncEchoClient();
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void start() {
|
||||||
|
try {
|
||||||
|
future.get();
|
||||||
|
} catch (InterruptedException | ExecutionException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String sendMessage(String message) {
|
||||||
|
byte[] byteMsg = new String(message).getBytes();
|
||||||
|
ByteBuffer buffer = ByteBuffer.wrap(byteMsg);
|
||||||
|
Future<Integer> writeResult = client.write(buffer);
|
||||||
|
|
||||||
|
while (!writeResult.isDone()) {
|
||||||
|
// do nothing
|
||||||
|
}
|
||||||
|
buffer.flip();
|
||||||
|
Future<Integer> readResult = client.read(buffer);
|
||||||
|
while (!readResult.isDone()) {
|
||||||
|
|
||||||
|
}
|
||||||
|
String echo = new String(buffer.array()).trim();
|
||||||
|
buffer.clear();
|
||||||
|
return echo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void stop() {
|
||||||
|
try {
|
||||||
|
client.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
AsyncEchoClient client = AsyncEchoClient.getInstance();
|
||||||
|
client.start();
|
||||||
|
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||||
|
String line = null;
|
||||||
|
System.out.println("Message to server:");
|
||||||
|
while ((line = br.readLine()) != null) {
|
||||||
|
String response = client.sendMessage(line);
|
||||||
|
System.out.println("response from server: " + response);
|
||||||
|
System.out.println("Message to server:");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,79 @@
|
||||||
|
package com.baeldung.java.nio2.async;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.channels.AsynchronousServerSocketChannel;
|
||||||
|
import java.nio.channels.AsynchronousSocketChannel;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
|
public class AsyncEchoServer {
|
||||||
|
private AsynchronousServerSocketChannel serverChannel;
|
||||||
|
private Future<AsynchronousSocketChannel> acceptResult;
|
||||||
|
private AsynchronousSocketChannel clientChannel;
|
||||||
|
|
||||||
|
public AsyncEchoServer() {
|
||||||
|
try {
|
||||||
|
serverChannel = AsynchronousServerSocketChannel.open();
|
||||||
|
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
|
||||||
|
serverChannel.bind(hostAddress);
|
||||||
|
acceptResult = serverChannel.accept();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void runServer() {
|
||||||
|
try {
|
||||||
|
clientChannel = acceptResult.get();
|
||||||
|
if ((clientChannel != null) && (clientChannel.isOpen())) {
|
||||||
|
while (true) {
|
||||||
|
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||||
|
Future<Integer> readResult = clientChannel.read(buffer);
|
||||||
|
|
||||||
|
while (!readResult.isDone()) {
|
||||||
|
// do nothing
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer.flip();
|
||||||
|
String message = new String(buffer.array()).trim();
|
||||||
|
if (message.equals("bye")) {
|
||||||
|
break; // while loop
|
||||||
|
}
|
||||||
|
buffer = ByteBuffer.wrap(new String(message).getBytes());
|
||||||
|
Future<Integer> writeResult = clientChannel.write(buffer);
|
||||||
|
while (!writeResult.isDone()) {
|
||||||
|
// do nothing
|
||||||
|
}
|
||||||
|
buffer.clear();
|
||||||
|
|
||||||
|
} // while()
|
||||||
|
|
||||||
|
clientChannel.close();
|
||||||
|
serverChannel.close();
|
||||||
|
|
||||||
|
}
|
||||||
|
} catch (InterruptedException | ExecutionException | IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
AsyncEchoServer server = new AsyncEchoServer();
|
||||||
|
server.runServer();
|
||||||
|
}
|
||||||
|
public static Process start() throws IOException, InterruptedException {
|
||||||
|
String javaHome = System.getProperty("java.home");
|
||||||
|
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
||||||
|
String classpath = System.getProperty("java.class.path");
|
||||||
|
String className = AsyncEchoServer.class.getCanonicalName();
|
||||||
|
|
||||||
|
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
|
||||||
|
|
||||||
|
return builder.start();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,100 @@
|
||||||
|
package com.baeldung.java.nio2.async;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.channels.AsynchronousServerSocketChannel;
|
||||||
|
import java.nio.channels.AsynchronousSocketChannel;
|
||||||
|
import java.nio.channels.CompletionHandler;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class AsyncEchoServer2 {
|
||||||
|
private AsynchronousServerSocketChannel serverChannel;
|
||||||
|
private AsynchronousSocketChannel clientChannel;
|
||||||
|
|
||||||
|
public AsyncEchoServer2() {
|
||||||
|
try {
|
||||||
|
serverChannel = AsynchronousServerSocketChannel.open();
|
||||||
|
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
|
||||||
|
serverChannel.bind(hostAddress);
|
||||||
|
while (true) {
|
||||||
|
|
||||||
|
serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void completed(AsynchronousSocketChannel result, Object attachment) {
|
||||||
|
if (serverChannel.isOpen())
|
||||||
|
serverChannel.accept(null, this);
|
||||||
|
clientChannel = result;
|
||||||
|
if ((clientChannel != null) && (clientChannel.isOpen())) {
|
||||||
|
ReadWriteHandler handler = new ReadWriteHandler();
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||||
|
Map<String, Object> readInfo = new HashMap<>();
|
||||||
|
readInfo.put("action", "read");
|
||||||
|
readInfo.put("buffer", buffer);
|
||||||
|
clientChannel.read(buffer, readInfo, handler);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void failed(Throwable exc, Object attachment) {
|
||||||
|
// process error
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
System.in.read();
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ReadWriteHandler implements CompletionHandler<Integer, Map<String, Object>> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void completed(Integer result, Map<String, Object> attachment) {
|
||||||
|
Map<String, Object> actionInfo = attachment;
|
||||||
|
String action = (String) actionInfo.get("action");
|
||||||
|
if ("read".equals(action)) {
|
||||||
|
ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer");
|
||||||
|
buffer.flip();
|
||||||
|
actionInfo.put("action", "write");
|
||||||
|
clientChannel.write(buffer, actionInfo, this);
|
||||||
|
buffer.clear();
|
||||||
|
} else if ("write".equals(action)) {
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||||
|
actionInfo.put("action", "read");
|
||||||
|
actionInfo.put("buffer", buffer);
|
||||||
|
clientChannel.read(buffer, actionInfo, this);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void failed(Throwable exc, Map<String, Object> attachment) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
new AsyncEchoServer2();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Process start() throws IOException, InterruptedException {
|
||||||
|
String javaHome = System.getProperty("java.home");
|
||||||
|
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
||||||
|
String classpath = System.getProperty("java.class.path");
|
||||||
|
String className = AsyncEchoServer2.class.getCanonicalName();
|
||||||
|
|
||||||
|
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
|
||||||
|
|
||||||
|
return builder.start();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,36 @@
|
||||||
|
package com.baeldung.java.nio2.async;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class AsyncEchoTest {
|
||||||
|
|
||||||
|
Process server;
|
||||||
|
AsyncEchoClient client;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() throws IOException, InterruptedException {
|
||||||
|
server = AsyncEchoServer2.start();
|
||||||
|
client = AsyncEchoClient.getInstance();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenServerClient_whenServerEchosMessage_thenCorrect() {
|
||||||
|
String resp1 = client.sendMessage("hello");
|
||||||
|
String resp2 = client.sendMessage("world");
|
||||||
|
assertEquals("hello", resp1);
|
||||||
|
assertEquals("world", resp2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void teardown() throws IOException {
|
||||||
|
server.destroy();
|
||||||
|
client.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,130 @@
|
||||||
|
package com.baeldung.java.nio2.async;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.channels.AsynchronousFileChannel;
|
||||||
|
import java.nio.channels.CompletionHandler;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.StandardOpenOption;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class AsyncFileTest {
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException {
|
||||||
|
Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString()));
|
||||||
|
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||||
|
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||||
|
|
||||||
|
Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||||
|
|
||||||
|
while (!operation.isDone())
|
||||||
|
;
|
||||||
|
|
||||||
|
String fileContent = new String(buffer.array()).trim();
|
||||||
|
buffer.clear();
|
||||||
|
|
||||||
|
assertEquals(fileContent, "baeldung.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException {
|
||||||
|
Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString()));
|
||||||
|
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||||
|
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||||
|
|
||||||
|
fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void completed(Integer result, ByteBuffer attachment) {
|
||||||
|
// result is number of bytes read
|
||||||
|
// attachment is the buffer
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void failed(Throwable exc, ByteBuffer attachment) {
|
||||||
|
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException {
|
||||||
|
String fileName = UUID.randomUUID().toString();
|
||||||
|
Path path = Paths.get(fileName);
|
||||||
|
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,StandardOpenOption.DELETE_ON_CLOSE);
|
||||||
|
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||||
|
long position = 0;
|
||||||
|
|
||||||
|
buffer.put("hello world".getBytes());
|
||||||
|
buffer.flip();
|
||||||
|
|
||||||
|
Future<Integer> operation = fileChannel.write(buffer, position);
|
||||||
|
buffer.clear();
|
||||||
|
|
||||||
|
while (!operation.isDone()) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
String content = readContent(path);
|
||||||
|
assertEquals("hello world", content);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException {
|
||||||
|
String fileName = UUID.randomUUID().toString();
|
||||||
|
Path path = Paths.get(fileName);
|
||||||
|
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,StandardOpenOption.DELETE_ON_CLOSE);
|
||||||
|
|
||||||
|
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||||
|
buffer.put("hello world".getBytes());
|
||||||
|
buffer.flip();
|
||||||
|
|
||||||
|
fileChannel.write(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void completed(Integer result, ByteBuffer attachment) {
|
||||||
|
// result is number of bytes written
|
||||||
|
// attachment is the buffer
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void failed(Throwable exc, ByteBuffer attachment) {
|
||||||
|
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String readContent(Path file) {
|
||||||
|
AsynchronousFileChannel fileChannel = null;
|
||||||
|
try {
|
||||||
|
fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
|
||||||
|
} catch (IOException e) {
|
||||||
|
// TODO Auto-generated catch block
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||||
|
|
||||||
|
Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||||
|
|
||||||
|
while (!operation.isDone())
|
||||||
|
;
|
||||||
|
|
||||||
|
String fileContent = new String(buffer.array()).trim();
|
||||||
|
buffer.clear();
|
||||||
|
return fileContent;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,68 @@
|
||||||
|
package com.baeldung.java.nio2.attributes;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributeView;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
|
import java.nio.file.attribute.FileTime;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class BasicAttribsTest {
|
||||||
|
private static final String HOME = System.getProperty("user.home");
|
||||||
|
BasicFileAttributes basicAttribs;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() throws IOException {
|
||||||
|
Path home = Paths.get(HOME);
|
||||||
|
BasicFileAttributeView basicView = Files.getFileAttributeView(home, BasicFileAttributeView.class);
|
||||||
|
basicAttribs = basicView.readAttributes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFileTimes_whenComparesThem_ThenCorrect() {
|
||||||
|
FileTime created = basicAttribs.creationTime();
|
||||||
|
FileTime modified = basicAttribs.lastModifiedTime();
|
||||||
|
FileTime accessed = basicAttribs.lastAccessTime();
|
||||||
|
|
||||||
|
assertTrue(0 > created.compareTo(accessed));
|
||||||
|
assertTrue(0 < modified.compareTo(created));
|
||||||
|
assertTrue(0 == created.compareTo(created));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenGetsFileSize_thenCorrect() {
|
||||||
|
long size = basicAttribs.size();
|
||||||
|
assertTrue(size > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenChecksIfDirectory_thenCorrect() {
|
||||||
|
boolean isDir = basicAttribs.isDirectory();
|
||||||
|
assertTrue(isDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenChecksIfFile_thenCorrect() {
|
||||||
|
boolean isFile = basicAttribs.isRegularFile();
|
||||||
|
assertFalse(isFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenChecksIfSymLink_thenCorrect() {
|
||||||
|
boolean isSymLink = basicAttribs.isSymbolicLink();
|
||||||
|
assertFalse(isSymLink);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenChecksIfOther_thenCorrect() {
|
||||||
|
boolean isOther = basicAttribs.isOther();
|
||||||
|
assertFalse(isOther);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,7 +1,9 @@
|
||||||
package org.baeldung.java.io;
|
package org.baeldung.java.io;
|
||||||
|
|
||||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
import org.apache.commons.io.FileUtils;
|
||||||
import static org.junit.Assert.assertTrue;
|
import org.junit.AfterClass;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
@ -9,17 +11,29 @@ import java.nio.file.FileSystemException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.apache.commons.io.FileUtils;
|
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||||
import org.junit.Test;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class JavaFileUnitTest {
|
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
|
@Test
|
||||||
public final void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException {
|
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();
|
final boolean success = newFile.createNewFile();
|
||||||
|
|
||||||
assertTrue(success);
|
assertTrue(success);
|
||||||
|
@ -27,48 +41,48 @@ public class JavaFileUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingJDK7nio2_whenCreatingFile_thenCorrect() throws IOException {
|
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);
|
Files.createFile(newFilePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
|
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
|
@Test
|
||||||
public final void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
|
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
|
// move a file
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
|
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();
|
fileToMove.createNewFile();// .exists();
|
||||||
final File destDir = new File("src/test/resources/");
|
final File destDir = new File(TEMP_DIR + "/");
|
||||||
destDir.mkdir();
|
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) {
|
if (!isMoved) {
|
||||||
throw new FileSystemException("src/test/resources/movedFile_jdk6.txt");
|
throw new FileSystemException(TEMP_DIR + "/movedFile_jdk6.txt");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
|
public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
|
||||||
final Path fileToMovePath = Files.createFile(Paths.get("src/test/resources/" + randomAlphabetic(5) + ".txt"));
|
final Path fileToMovePath = Files.createFile(Paths.get(TEMP_DIR + "/" + randomAlphabetic(5) + ".txt"));
|
||||||
final Path targetPath = Paths.get("src/main/resources/");
|
final Path targetPath = Paths.get(TEMP_DIR + "/");
|
||||||
|
|
||||||
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
|
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException {
|
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();
|
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());
|
final File targetFile = new File(destDir, fileToMove.getName());
|
||||||
com.google.common.io.Files.createParentDirs(targetFile);
|
com.google.common.io.Files.createParentDirs(targetFile);
|
||||||
com.google.common.io.Files.move(fileToMove, targetFile);
|
com.google.common.io.Files.move(fileToMove, targetFile);
|
||||||
|
@ -76,23 +90,24 @@ public class JavaFileUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
|
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
|
||||||
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
|
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
|
||||||
FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/test/resources/fileMoved_apache2.txt"));
|
FileUtils.moveFile(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/fileMoved_apache2.txt"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
|
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
|
||||||
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
|
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
|
||||||
FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/main/resources/"), true);
|
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
|
// delete a file
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException {
|
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();
|
final boolean success = fileToDelete.delete();
|
||||||
|
|
||||||
assertTrue(success);
|
assertTrue(success);
|
||||||
|
@ -100,17 +115,17 @@ public class JavaFileUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException {
|
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);
|
Files.delete(fileToDeletePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException {
|
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);
|
final boolean success = FileUtils.deleteQuietly(fileToDelete);
|
||||||
|
|
||||||
assertTrue(success);
|
assertTrue(success);
|
||||||
|
@ -118,9 +133,9 @@ public class JavaFileUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException {
|
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"));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,11 +10,6 @@
|
||||||
<artifactId>ejb-client</artifactId>
|
<artifactId>ejb-client</artifactId>
|
||||||
<name>EJB3 Client Maven</name>
|
<name>EJB3 Client Maven</name>
|
||||||
<description>EJB3 Client Maven</description>
|
<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>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.wildfly</groupId>
|
<groupId>org.wildfly</groupId>
|
||||||
|
@ -49,6 +44,4 @@
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -13,8 +13,9 @@
|
||||||
<!-- <name>ejb-remote</name> -->
|
<!-- <name>ejb-remote</name> -->
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jboss.spec.javax.ejb</groupId>
|
<groupId>javax</groupId>
|
||||||
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
|
<artifactId>javaee-api</artifactId>
|
||||||
|
<version>7.0</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
|
@ -1,13 +1,19 @@
|
||||||
package com.baeldung.ejb.tutorial;
|
package com.baeldung.ejb.tutorial;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
import javax.ejb.SessionContext;
|
||||||
import javax.ejb.Stateless;
|
import javax.ejb.Stateless;
|
||||||
|
|
||||||
@Stateless(name = "HelloWorld")
|
@Stateless(name = "HelloWorld")
|
||||||
public class HelloWorldBean implements HelloWorld {
|
public class HelloWorldBean implements HelloWorld {
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private SessionContext context;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getHelloWorld() {
|
public String getHelloWorld() {
|
||||||
return "Welcome to EJB Tutorial!";
|
return "Welcome to EJB Tutorial!";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -36,11 +36,10 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jboss.spec</groupId>
|
<groupId>javax</groupId>
|
||||||
<artifactId>jboss-javaee-7.0</artifactId>
|
<artifactId>javaee-api</artifactId>
|
||||||
<version>1.0.1.Final</version>
|
<version>7.0</version>
|
||||||
<type>pom</type>
|
<scope>provided</scope>
|
||||||
<scope>import</scope>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|
1
pom.xml
1
pom.xml
|
@ -109,6 +109,7 @@
|
||||||
<module>spring-katharsis</module>
|
<module>spring-katharsis</module>
|
||||||
<module>spring-mockito</module>
|
<module>spring-mockito</module>
|
||||||
<module>spring-mvc-java</module>
|
<module>spring-mvc-java</module>
|
||||||
|
<module>spring-mvc-forms</module>
|
||||||
<module>spring-mvc-no-xml</module>
|
<module>spring-mvc-no-xml</module>
|
||||||
<module>spring-mvc-tiles</module>
|
<module>spring-mvc-tiles</module>
|
||||||
<module>spring-mvc-velocity</module>
|
<module>spring-mvc-velocity</module>
|
||||||
|
|
|
@ -26,11 +26,11 @@ public class GatewayApplication {
|
||||||
private List<RibbonClientSpecification> configurations = new ArrayList<>();
|
private List<RibbonClientSpecification> configurations = new ArrayList<>();
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@LoadBalanced RestTemplate restTemplate(){
|
@LoadBalanced
|
||||||
|
RestTemplate restTemplate() {
|
||||||
return new RestTemplate();
|
return new RestTemplate();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public SpringClientFactory springClientFactory() {
|
public SpringClientFactory springClientFactory() {
|
||||||
SpringClientFactory factory = new SpringClientFactory();
|
SpringClientFactory factory = new SpringClientFactory();
|
||||||
|
|
|
@ -19,29 +19,29 @@ public class SessionSavingZuulPreFilter extends ZuulFilter {
|
||||||
@Autowired
|
@Autowired
|
||||||
private SessionRepository repository;
|
private SessionRepository repository;
|
||||||
|
|
||||||
@Override public boolean shouldFilter() {
|
@Override
|
||||||
|
public boolean shouldFilter() {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object run() {
|
public Object run() {
|
||||||
RequestContext context = RequestContext.getCurrentContext();
|
RequestContext context = RequestContext.getCurrentContext();
|
||||||
|
|
||||||
HttpSession httpSession = context.getRequest().getSession();
|
HttpSession httpSession = context.getRequest().getSession();
|
||||||
Session session = repository.getSession(httpSession.getId());
|
Session session = repository.getSession(httpSession.getId());
|
||||||
|
|
||||||
context.addZuulRequestHeader("Cookie", "SESSION=" + httpSession.getId());
|
context.addZuulRequestHeader("Cookie", "SESSION=" + httpSession.getId());
|
||||||
|
|
||||||
log.info("ZuulPreFilter session proxy: {}", session.getId());
|
log.info("ZuulPreFilter session proxy: {}", session.getId());
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override public String filterType() {
|
@Override
|
||||||
|
public String filterType() {
|
||||||
return "pre";
|
return "pre";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override public int filterOrder() {
|
@Override
|
||||||
|
public int filterOrder() {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,2 +1,3 @@
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Wiring in Spring: @Autowired, @Resource and @Inject](http://www.baeldung.com/spring-annotations-resource-inject-autowire)
|
- [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)
|
||||||
|
|
|
@ -4,14 +4,11 @@
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>dependency-injection</artifactId>
|
<artifactId>spring-core</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<packaging>war</packaging>
|
<packaging>war</packaging>
|
||||||
|
|
||||||
<name>dependency-injection</name>
|
<name>spring-core</name>
|
||||||
<description>Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely
|
|
||||||
Resource, Inject, and Autowired
|
|
||||||
</description>
|
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -5,6 +5,7 @@ import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
public class FactoryBeanAppConfig {
|
public class FactoryBeanAppConfig {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public ToolFactory toolFactory() {
|
public ToolFactory toolFactory() {
|
||||||
ToolFactory factory = new ToolFactory();
|
ToolFactory factory = new ToolFactory();
|
||||||
|
|
|
@ -3,6 +3,7 @@ package com.baeldung.factorybean;
|
||||||
import org.springframework.beans.factory.config.AbstractFactoryBean;
|
import org.springframework.beans.factory.config.AbstractFactoryBean;
|
||||||
|
|
||||||
public class NonSingleToolFactory extends AbstractFactoryBean<Tool> {
|
public class NonSingleToolFactory extends AbstractFactoryBean<Tool> {
|
||||||
|
|
||||||
private int factoryId;
|
private int factoryId;
|
||||||
private int toolId;
|
private int toolId;
|
||||||
|
|
||||||
|
|
|
@ -4,6 +4,7 @@ import org.springframework.beans.factory.config.AbstractFactoryBean;
|
||||||
|
|
||||||
//no need to set singleton property because default value is true
|
//no need to set singleton property because default value is true
|
||||||
public class SingleToolFactory extends AbstractFactoryBean<Tool> {
|
public class SingleToolFactory extends AbstractFactoryBean<Tool> {
|
||||||
|
|
||||||
private int factoryId;
|
private int factoryId;
|
||||||
private int toolId;
|
private int toolId;
|
||||||
|
|
||||||
|
|
|
@ -3,6 +3,7 @@ package com.baeldung.factorybean;
|
||||||
import org.springframework.beans.factory.FactoryBean;
|
import org.springframework.beans.factory.FactoryBean;
|
||||||
|
|
||||||
public class ToolFactory implements FactoryBean<Tool> {
|
public class ToolFactory implements FactoryBean<Tool> {
|
||||||
|
|
||||||
private int factoryId;
|
private int factoryId;
|
||||||
private int toolId;
|
private int toolId;
|
||||||
|
|
||||||
|
|
|
@ -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>
|
|
@ -0,0 +1,99 @@
|
||||||
|
<?xml version="1.0"?>
|
||||||
|
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||||
|
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||||
|
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>0.1-SNAPSHOT</version>
|
||||||
|
<artifactId>spring-mvc-forms</artifactId>
|
||||||
|
|
||||||
|
<name>spring-mvc-forms</name>
|
||||||
|
<packaging>war</packaging>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-webmvc</artifactId>
|
||||||
|
<version>${springframework.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.servlet</groupId>
|
||||||
|
<artifactId>javax.servlet-api</artifactId>
|
||||||
|
<version>${javax.servlet-api.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.servlet.jsp</groupId>
|
||||||
|
<artifactId>javax.servlet.jsp-api</artifactId>
|
||||||
|
<version>${javax.servlet.jsp-api.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.servlet</groupId>
|
||||||
|
<artifactId>jstl</artifactId>
|
||||||
|
<version>${jstl.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hibernate</groupId>
|
||||||
|
<artifactId>hibernate-validator</artifactId>
|
||||||
|
<version>${hibernate-validator.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
<profiles>
|
||||||
|
<!-- Local -->
|
||||||
|
<profile>
|
||||||
|
<id>spring-mvc-forms</id>
|
||||||
|
<activation>
|
||||||
|
<activeByDefault>true</activeByDefault>
|
||||||
|
</activation>
|
||||||
|
<build>
|
||||||
|
<pluginManagement>
|
||||||
|
<plugins>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>${maven-compiler-plugin.source}</source>
|
||||||
|
<target>${maven-compiler-plugin.source}</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-war-plugin</artifactId>
|
||||||
|
<version>${maven-war-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<warSourceDirectory>src/main/webapp</warSourceDirectory>
|
||||||
|
<warName>spring-mvc-forms</warName>
|
||||||
|
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||||
|
<outputDirectory>${deploy-path}</outputDirectory>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
</plugins>
|
||||||
|
</pluginManagement>
|
||||||
|
<finalName>spring-mvc-forms</finalName>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
</profiles>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<springframework.version>4.0.6.RELEASE</springframework.version>
|
||||||
|
<maven-war-plugin.version>2.4</maven-war-plugin.version>
|
||||||
|
<jstl.version>1.2</jstl.version>
|
||||||
|
<javax.servlet.jsp-api.version>2.3.1</javax.servlet.jsp-api.version>
|
||||||
|
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
|
||||||
|
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||||
|
<maven-compiler-plugin.source>1.8</maven-compiler-plugin.source>
|
||||||
|
<hibernate-validator.version>5.1.1.Final</hibernate-validator.version>
|
||||||
|
<deploy-path>enter-location-of-server</deploy-path>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
||||||
|
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.springmvcforms.configuration;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
|
||||||
|
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||||
|
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebMvc
|
||||||
|
@ComponentScan(basePackages = "com.baeldung.springmvcforms")
|
||||||
|
class ApplicationConfiguration extends WebMvcConfigurerAdapter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
|
||||||
|
configurer.enable();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public InternalResourceViewResolver jspViewResolver() {
|
||||||
|
InternalResourceViewResolver bean = new InternalResourceViewResolver();
|
||||||
|
bean.setPrefix("/WEB-INF/views/");
|
||||||
|
bean.setSuffix(".jsp");
|
||||||
|
return bean;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,47 @@
|
||||||
|
package com.baeldung.springmvcforms.configuration;
|
||||||
|
|
||||||
|
import org.springframework.web.WebApplicationInitializer;
|
||||||
|
import org.springframework.web.context.ContextLoaderListener;
|
||||||
|
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||||
|
import org.springframework.web.servlet.DispatcherServlet;
|
||||||
|
|
||||||
|
import javax.servlet.ServletContext;
|
||||||
|
import javax.servlet.ServletException;
|
||||||
|
import javax.servlet.ServletRegistration;
|
||||||
|
|
||||||
|
public class WebInitializer implements WebApplicationInitializer {
|
||||||
|
|
||||||
|
public void onStartup(ServletContext container) throws ServletException {
|
||||||
|
|
||||||
|
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
|
||||||
|
ctx.register(ApplicationConfiguration.class);
|
||||||
|
ctx.setServletContext(container);
|
||||||
|
|
||||||
|
// Manage the lifecycle of the root application context
|
||||||
|
container.addListener(new ContextLoaderListener(ctx));
|
||||||
|
|
||||||
|
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
|
||||||
|
|
||||||
|
servlet.setLoadOnStartup(1);
|
||||||
|
servlet.addMapping("/");
|
||||||
|
}
|
||||||
|
// @Override
|
||||||
|
// public void onStartup(ServletContext container) {
|
||||||
|
// // Create the 'root' Spring application context
|
||||||
|
// AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
|
||||||
|
// rootContext.register(ServiceConfig.class, JPAConfig.class, SecurityConfig.class);
|
||||||
|
//
|
||||||
|
// // Manage the lifecycle of the root application context
|
||||||
|
// container.addListener(new ContextLoaderListener(rootContext));
|
||||||
|
//
|
||||||
|
// // Create the dispatcher servlet's Spring application context
|
||||||
|
// AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
|
||||||
|
// dispatcherServlet.register(MvcConfig.class);
|
||||||
|
//
|
||||||
|
// // Register and map the dispatcher servlet
|
||||||
|
// ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
|
||||||
|
// dispatcher.setLoadOnStartup(1);
|
||||||
|
// dispatcher.addMapping("/");
|
||||||
|
//
|
||||||
|
// }
|
||||||
|
}
|
|
@ -0,0 +1,41 @@
|
||||||
|
package com.baeldung.springmvcforms.controller;
|
||||||
|
|
||||||
|
import com.baeldung.springmvcforms.domain.Employee;
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
import org.springframework.ui.ModelMap;
|
||||||
|
import org.springframework.validation.BindingResult;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.servlet.ModelAndView;
|
||||||
|
|
||||||
|
import javax.validation.Valid;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
public class EmployeeController {
|
||||||
|
|
||||||
|
Map<Long, Employee> employeeMap = new HashMap<>();
|
||||||
|
|
||||||
|
@RequestMapping(value = "/employee", method = RequestMethod.GET)
|
||||||
|
public ModelAndView showForm() {
|
||||||
|
return new ModelAndView("employeeHome", "employee", new Employee());
|
||||||
|
}
|
||||||
|
|
||||||
|
@RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
|
||||||
|
public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) {
|
||||||
|
return employeeMap.get(Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
|
||||||
|
public String submit(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
|
||||||
|
if (result.hasErrors()) {
|
||||||
|
return "error";
|
||||||
|
}
|
||||||
|
model.addAttribute("name", employee.getName());
|
||||||
|
model.addAttribute("contactNumber", employee.getContactNumber());
|
||||||
|
model.addAttribute("id", employee.getId());
|
||||||
|
employeeMap.put(employee.getId(), employee);
|
||||||
|
return "employeeView";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.springmvcforms.domain;
|
||||||
|
|
||||||
|
import javax.validation.constraints.NotNull;
|
||||||
|
import javax.validation.constraints.Size;
|
||||||
|
|
||||||
|
public class Employee {
|
||||||
|
|
||||||
|
private long id;
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@Size(min = 5)
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@Size(min = 7)
|
||||||
|
private String contactNumber;
|
||||||
|
|
||||||
|
public Employee() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(final String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(final long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getContactNumber() {
|
||||||
|
return contactNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setContactNumber(final String contactNumber) {
|
||||||
|
this.contactNumber = contactNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,33 @@
|
||||||
|
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
|
||||||
|
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||||
|
<title>Form Example - Register an Employee</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h3>Welcome, Enter The Employee Details</h3>
|
||||||
|
|
||||||
|
<form:form method="POST" action="${pageContext.request.contextPath}/addEmployee" modelAttribute="employee">
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td><form:label path="name">Name</form:label></td>
|
||||||
|
<td><form:input path="name" /></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td><form:label path="id">Id</form:label></td>
|
||||||
|
<td><form:input path="id" /></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td><form:label path="contactNumber">Contact Number</form:label></td>
|
||||||
|
<td><form:input path="contactNumber" /></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td><input type="submit" value="Submit" /></td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</form:form>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
|
@ -0,0 +1,24 @@
|
||||||
|
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Spring MVC Form Handling</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<h2>Submitted Employee Information</h2>
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td>Name :</td>
|
||||||
|
<td>${name}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>ID :</td>
|
||||||
|
<td>${id}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Contact Number :</td>
|
||||||
|
<td>${contactNumber}</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -0,0 +1,20 @@
|
||||||
|
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||||
|
pageEncoding="ISO-8859-1"%>
|
||||||
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||||
|
<title>SpringMVCExample</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<h3>Pleas enter the correct details</h3>
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td><a href="employee">Retry</a></td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
|
@ -12,3 +12,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||||
- [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout)
|
- [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout)
|
||||||
- [Basic Forms with Spring MVC](http://www.baeldung.com/spring-mvc-form-tutorial)
|
- [Basic Forms with Spring MVC](http://www.baeldung.com/spring-mvc-form-tutorial)
|
||||||
- [Returning Image/Media Data with Spring MVC](http://www.baeldung.com/spring-mvc-image-media-data)
|
- [Returning Image/Media Data with Spring MVC](http://www.baeldung.com/spring-mvc-image-media-data)
|
||||||
|
- [Geolocation by IP in Java](http://www.baeldung.com/geolocation-by-ip-with-maxmind)
|
||||||
|
|
|
@ -13,7 +13,7 @@ public class RawDBDemoGeoIPLocationService{
|
||||||
private DatabaseReader dbReader;
|
private DatabaseReader dbReader;
|
||||||
|
|
||||||
public RawDBDemoGeoIPLocationService() throws IOException {
|
public RawDBDemoGeoIPLocationService() throws IOException {
|
||||||
File database = new File("C:\\Users\\Parth Joshi\\Desktop\\GeoLite2-City.mmdb\\GeoLite2-City.mmdb");
|
File database = new File("your-path-to-db-file");
|
||||||
dbReader = new DatabaseReader.Builder(database).build();
|
dbReader = new DatabaseReader.Builder(database).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -77,8 +77,8 @@
|
||||||
<div id="status"></div>
|
<div id="status"></div>
|
||||||
|
|
||||||
<div id="map" style="height: 500px; width:100%; position:absolute"></div>
|
<div id="map" style="height: 500px; width:100%; position:absolute"></div>
|
||||||
<!--AIzaSyDDr65sVtJtlbliOTAeXyZSDPvG9NROjJA -->
|
|
||||||
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA4vsDQWHeOrDnzS98XMXl5hgwA9raaQZ8"
|
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-MAPS-API-KEY"
|
||||||
async defer></script>
|
async defer></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
|
@ -15,10 +15,10 @@ public class GeoIpIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenIP_whenFetchingCity_thenReturnsCityData() throws IOException, GeoIp2Exception {
|
public void givenIP_whenFetchingCity_thenReturnsCityData() throws IOException, GeoIp2Exception {
|
||||||
File database = new File("C:\\Users\\Parth Joshi\\Desktop\\GeoLite2-City.mmdb\\GeoLite2-City.mmdb");
|
File database = new File("your-path-to-db-file");
|
||||||
DatabaseReader dbReader = new DatabaseReader.Builder(database).build();
|
DatabaseReader dbReader = new DatabaseReader.Builder(database).build();
|
||||||
|
|
||||||
InetAddress ipAddress = InetAddress.getByName("202.47.112.9");
|
InetAddress ipAddress = InetAddress.getByName("your-public-ip");
|
||||||
CityResponse response = dbReader.city(ipAddress);
|
CityResponse response = dbReader.city(ipAddress);
|
||||||
|
|
||||||
String countryName = response.getCountry().getName();
|
String countryName = response.getCountry().getName();
|
||||||
|
|
|
@ -8,6 +8,7 @@ import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import org.baeldung.okhttp.ProgressRequestWrapper;
|
import org.baeldung.okhttp.ProgressRequestWrapper;
|
||||||
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import okhttp3.Call;
|
import okhttp3.Call;
|
||||||
|
@ -22,11 +23,16 @@ public class OkHttpFileUploadingLiveTest {
|
||||||
|
|
||||||
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
||||||
|
|
||||||
|
OkHttpClient client;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
client = new OkHttpClient();
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUploadFile_thenCorrect() throws IOException {
|
public void whenUploadFile_thenCorrect() throws IOException {
|
||||||
|
|
||||||
OkHttpClient client = new OkHttpClient();
|
|
||||||
|
|
||||||
RequestBody requestBody = new MultipartBody.Builder()
|
RequestBody requestBody = new MultipartBody.Builder()
|
||||||
.setType(MultipartBody.FORM)
|
.setType(MultipartBody.FORM)
|
||||||
.addFormDataPart("file", "file.txt",
|
.addFormDataPart("file", "file.txt",
|
||||||
|
@ -47,22 +53,17 @@ public class OkHttpFileUploadingLiveTest {
|
||||||
@Test
|
@Test
|
||||||
public void whenGetUploadFileProgress_thenCorrect() throws IOException {
|
public void whenGetUploadFileProgress_thenCorrect() throws IOException {
|
||||||
|
|
||||||
OkHttpClient client = new OkHttpClient();
|
|
||||||
|
|
||||||
RequestBody requestBody = new MultipartBody.Builder()
|
RequestBody requestBody = new MultipartBody.Builder()
|
||||||
.setType(MultipartBody.FORM)
|
.setType(MultipartBody.FORM)
|
||||||
.addFormDataPart("file", "file.txt",
|
.addFormDataPart("file", "file.txt",
|
||||||
RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
|
RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
|
||||||
.build();
|
.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);
|
assertFalse(Float.compare(percentage, 100) > 0);
|
||||||
};
|
});
|
||||||
|
|
||||||
ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, listener);
|
|
||||||
|
|
||||||
Request request = new Request.Builder()
|
Request request = new Request.Builder()
|
||||||
.url(BASE_URL + "/users/upload")
|
.url(BASE_URL + "/users/upload")
|
||||||
|
|
|
@ -1,26 +1,36 @@
|
||||||
package org.baeldung.okhttp;
|
package org.baeldung.okhttp;
|
||||||
|
|
||||||
import okhttp3.*;
|
import static org.hamcrest.CoreMatchers.equalTo;
|
||||||
import org.junit.Test;
|
import static org.junit.Assert.assertThat;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import org.junit.Before;
|
||||||
import static org.junit.Assert.assertThat;
|
import org.junit.Test;
|
||||||
import static org.junit.Assert.fail;
|
|
||||||
|
import okhttp3.Call;
|
||||||
|
import okhttp3.Callback;
|
||||||
|
import okhttp3.HttpUrl;
|
||||||
|
import okhttp3.OkHttpClient;
|
||||||
|
import okhttp3.Request;
|
||||||
|
import okhttp3.Response;
|
||||||
|
|
||||||
public class OkHttpGetLiveTest {
|
public class OkHttpGetLiveTest {
|
||||||
|
|
||||||
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
||||||
|
|
||||||
|
OkHttpClient client;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
|
||||||
|
client = new OkHttpClient();
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGetRequest_thenCorrect() throws IOException {
|
public void whenGetRequest_thenCorrect() throws IOException {
|
||||||
|
Request request = new Request.Builder().url(BASE_URL + "/date").build();
|
||||||
OkHttpClient client = new OkHttpClient();
|
|
||||||
|
|
||||||
Request request = new Request.Builder()
|
|
||||||
.url(BASE_URL + "/date")
|
|
||||||
.build();
|
|
||||||
|
|
||||||
Call call = client.newCall(request);
|
Call call = client.newCall(request);
|
||||||
Response response = call.execute();
|
Response response = call.execute();
|
||||||
|
@ -30,17 +40,12 @@ public class OkHttpGetLiveTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException {
|
public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException {
|
||||||
|
|
||||||
OkHttpClient client = new OkHttpClient();
|
|
||||||
|
|
||||||
HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder();
|
HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder();
|
||||||
urlBuilder.addQueryParameter("id", "1");
|
urlBuilder.addQueryParameter("id", "1");
|
||||||
|
|
||||||
String url = urlBuilder.build().toString();
|
String url = urlBuilder.build().toString();
|
||||||
|
|
||||||
Request request = new Request.Builder()
|
Request request = new Request.Builder().url(url).build();
|
||||||
.url(url)
|
|
||||||
.build();
|
|
||||||
|
|
||||||
Call call = client.newCall(request);
|
Call call = client.newCall(request);
|
||||||
Response response = call.execute();
|
Response response = call.execute();
|
||||||
|
@ -50,12 +55,7 @@ public class OkHttpGetLiveTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException {
|
public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException {
|
||||||
|
Request request = new Request.Builder().url(BASE_URL + "/date").build();
|
||||||
OkHttpClient client = new OkHttpClient();
|
|
||||||
|
|
||||||
Request request = new Request.Builder()
|
|
||||||
.url(BASE_URL + "/date")
|
|
||||||
.build();
|
|
||||||
|
|
||||||
Call call = client.newCall(request);
|
Call call = client.newCall(request);
|
||||||
|
|
||||||
|
|
|
@ -2,6 +2,7 @@ package org.baeldung.okhttp;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import okhttp3.Call;
|
import okhttp3.Call;
|
||||||
|
@ -13,11 +14,16 @@ public class OkHttpHeaderLiveTest {
|
||||||
|
|
||||||
private static final String SAMPLE_URL = "http://www.github.com";
|
private static final String SAMPLE_URL = "http://www.github.com";
|
||||||
|
|
||||||
|
OkHttpClient client;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
|
||||||
|
client = new OkHttpClient();
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSetHeader_thenCorrect() throws IOException {
|
public void whenSetHeader_thenCorrect() throws IOException {
|
||||||
|
|
||||||
OkHttpClient client = new OkHttpClient();
|
|
||||||
|
|
||||||
Request request = new Request.Builder()
|
Request request = new Request.Builder()
|
||||||
.url(SAMPLE_URL)
|
.url(SAMPLE_URL)
|
||||||
.addHeader("Content-Type", "application/json")
|
.addHeader("Content-Type", "application/json")
|
||||||
|
@ -31,7 +37,7 @@ public class OkHttpHeaderLiveTest {
|
||||||
@Test
|
@Test
|
||||||
public void whenSetDefaultHeader_thenCorrect() throws IOException {
|
public void whenSetDefaultHeader_thenCorrect() throws IOException {
|
||||||
|
|
||||||
OkHttpClient client = new OkHttpClient.Builder()
|
OkHttpClient clientWithInterceptor = new OkHttpClient.Builder()
|
||||||
.addInterceptor(new DefaultContentTypeInterceptor("application/json"))
|
.addInterceptor(new DefaultContentTypeInterceptor("application/json"))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
|
@ -39,10 +45,8 @@ public class OkHttpHeaderLiveTest {
|
||||||
.url(SAMPLE_URL)
|
.url(SAMPLE_URL)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
Call call = client.newCall(request);
|
Call call = clientWithInterceptor.newCall(request);
|
||||||
Response response = call.execute();
|
Response response = call.execute();
|
||||||
response.close();
|
response.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,22 +4,37 @@ import okhttp3.*;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
import java.util.concurrent.TimeUnit;
|
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 {
|
public class OkHttpMiscLiveTest {
|
||||||
|
|
||||||
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
||||||
private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class);
|
private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class);
|
||||||
|
|
||||||
|
OkHttpClient client;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
|
||||||
|
client = new OkHttpClient();
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSetRequestTimeout_thenFail() throws IOException {
|
public void whenSetRequestTimeout_thenFail() throws IOException {
|
||||||
|
OkHttpClient clientWithTimeout = new OkHttpClient.Builder()
|
||||||
OkHttpClient client = new OkHttpClient.Builder()
|
|
||||||
.readTimeout(1, TimeUnit.SECONDS)
|
.readTimeout(1, TimeUnit.SECONDS)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
|
@ -27,18 +42,15 @@ public class OkHttpMiscLiveTest {
|
||||||
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
Call call = client.newCall(request);
|
Call call = clientWithTimeout.newCall(request);
|
||||||
Response response = call.execute();
|
Response response = call.execute();
|
||||||
response.close();
|
response.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected = IOException.class)
|
@Test(expected = IOException.class)
|
||||||
public void whenCancelRequest_thenCorrect() throws IOException {
|
public void whenCancelRequest_thenCorrect() throws IOException {
|
||||||
|
|
||||||
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
|
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
|
||||||
|
|
||||||
OkHttpClient client = new OkHttpClient();
|
|
||||||
|
|
||||||
Request request = new Request.Builder()
|
Request request = new Request.Builder()
|
||||||
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
||||||
.build();
|
.build();
|
||||||
|
@ -69,7 +81,7 @@ public class OkHttpMiscLiveTest {
|
||||||
File cacheDirectory = new File("src/test/resources/cache");
|
File cacheDirectory = new File("src/test/resources/cache");
|
||||||
Cache cache = new Cache(cacheDirectory, cacheSize);
|
Cache cache = new Cache(cacheDirectory, cacheSize);
|
||||||
|
|
||||||
OkHttpClient client = new OkHttpClient.Builder()
|
OkHttpClient clientCached = new OkHttpClient.Builder()
|
||||||
.cache(cache)
|
.cache(cache)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
|
@ -77,10 +89,10 @@ public class OkHttpMiscLiveTest {
|
||||||
.url("http://publicobject.com/helloworld.txt")
|
.url("http://publicobject.com/helloworld.txt")
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
Response response1 = client.newCall(request).execute();
|
Response response1 = clientCached.newCall(request).execute();
|
||||||
logResponse(response1);
|
logResponse(response1);
|
||||||
|
|
||||||
Response response2 = client.newCall(request).execute();
|
Response response2 = clientCached.newCall(request).execute();
|
||||||
logResponse(response2);
|
logResponse(response2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -6,6 +6,7 @@ import static org.junit.Assert.assertThat;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import okhttp3.Call;
|
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 BASE_URL = "http://localhost:8080/spring-rest";
|
||||||
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
|
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
|
@Test
|
||||||
public void whenSendPostRequest_thenCorrect() throws IOException {
|
public void whenSendPostRequest_thenCorrect() throws IOException {
|
||||||
|
|
||||||
OkHttpClient client = new OkHttpClient();
|
|
||||||
|
|
||||||
RequestBody formBody = new FormBody.Builder()
|
RequestBody formBody = new FormBody.Builder()
|
||||||
.add("username", "test")
|
.add("username", "test")
|
||||||
.add("password", "test")
|
.add("password", "test")
|
||||||
|
@ -46,11 +52,8 @@ public class OkHttpPostingLiveTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException {
|
public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException {
|
||||||
|
|
||||||
String postBody = "test post";
|
String postBody = "test post";
|
||||||
|
|
||||||
OkHttpClient client = new OkHttpClient();
|
|
||||||
|
|
||||||
Request request = new Request.Builder()
|
Request request = new Request.Builder()
|
||||||
.url(URL_SECURED_BY_BASIC_AUTHENTICATION)
|
.url(URL_SECURED_BY_BASIC_AUTHENTICATION)
|
||||||
.addHeader("Authorization", Credentials.basic("test", "test"))
|
.addHeader("Authorization", Credentials.basic("test", "test"))
|
||||||
|
@ -65,9 +68,6 @@ public class OkHttpPostingLiveTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPostJson_thenCorrect() throws IOException {
|
public void whenPostJson_thenCorrect() throws IOException {
|
||||||
|
|
||||||
OkHttpClient client = new OkHttpClient();
|
|
||||||
|
|
||||||
String json = "{\"id\":1,\"name\":\"John\"}";
|
String json = "{\"id\":1,\"name\":\"John\"}";
|
||||||
|
|
||||||
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
|
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
|
||||||
|
@ -85,9 +85,6 @@ public class OkHttpPostingLiveTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSendMultipartRequest_thenCorrect() throws IOException {
|
public void whenSendMultipartRequest_thenCorrect() throws IOException {
|
||||||
|
|
||||||
OkHttpClient client = new OkHttpClient();
|
|
||||||
|
|
||||||
RequestBody requestBody = new MultipartBody.Builder()
|
RequestBody requestBody = new MultipartBody.Builder()
|
||||||
.setType(MultipartBody.FORM)
|
.setType(MultipartBody.FORM)
|
||||||
.addFormDataPart("username", "test")
|
.addFormDataPart("username", "test")
|
||||||
|
|
|
@ -0,0 +1,53 @@
|
||||||
|
package org.baeldung.uribuilder;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.springframework.web.util.UriComponents;
|
||||||
|
import org.springframework.web.util.UriComponentsBuilder;
|
||||||
|
|
||||||
|
public class SpringUriBuilderTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void constructUri() {
|
||||||
|
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com")
|
||||||
|
.path("/junit-5").build();
|
||||||
|
|
||||||
|
assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void constructUriEncoded() {
|
||||||
|
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com")
|
||||||
|
.path("/junit 5").build().encode();
|
||||||
|
|
||||||
|
assertEquals("http://www.baeldung.com/junit%205", uriComponents.toUriString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void constructUriFromTemplate() {
|
||||||
|
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com")
|
||||||
|
.path("/{article-name}").buildAndExpand("junit-5");
|
||||||
|
|
||||||
|
assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void constructUriWithQueryParameter() {
|
||||||
|
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.google.com")
|
||||||
|
.path("/").query("q={keyword}").buildAndExpand("baeldung");
|
||||||
|
|
||||||
|
assertEquals("http://www.google.com/?q=baeldung", uriComponents.toUriString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void expandWithRegexVar() {
|
||||||
|
String template = "/myurl/{name:[a-z]{1,5}}/show";
|
||||||
|
UriComponents uriComponents = UriComponentsBuilder.fromUriString(template).build();
|
||||||
|
uriComponents = uriComponents.expand(Collections.singletonMap("name", "test"));
|
||||||
|
|
||||||
|
assertEquals("/myurl/test/show", uriComponents.getPath());
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,17 +1,40 @@
|
||||||
package org.baeldung.security.filter.configuration;
|
package org.baeldung.security.filter.configuration;
|
||||||
|
|
||||||
|
import org.baeldung.security.basic.MyBasicAuthenticationEntryPoint;
|
||||||
import org.baeldung.security.filter.CustomFilter;
|
import org.baeldung.security.filter.CustomFilter;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.context.annotation.Configuration;
|
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.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
|
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
|
@EnableWebSecurity
|
||||||
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
|
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
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,11 +2,10 @@ package org.baeldung.spring;
|
||||||
|
|
||||||
import org.springframework.context.annotation.ComponentScan;
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.context.annotation.ImportResource;
|
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@ImportResource({ "classpath:webSecurityConfig.xml" })
|
|
||||||
@ComponentScan("org.baeldung.security")
|
@ComponentScan("org.baeldung.security")
|
||||||
|
//@ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||||
public class SecSecurityConfig {
|
public class SecSecurityConfig {
|
||||||
|
|
||||||
public SecSecurityConfig() {
|
public SecSecurityConfig() {
|
||||||
|
|
|
@ -1,2 +1,11 @@
|
||||||
###The Course
|
=========
|
||||||
|
## Spring Security Authentication/Authorization Example Project
|
||||||
|
|
||||||
|
##The Course
|
||||||
The "REST With Spring" Classes: http://github.learnspringsecurity.com
|
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
|
||||||
|
|
|
@ -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.ResourceHandlerRegistry;
|
||||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableWebMvc
|
@EnableWebMvc
|
||||||
|
@Profile("!manual")
|
||||||
public class MvcConfig extends WebMvcConfigurerAdapter {
|
public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||||
|
|
||||||
public MvcConfig() {
|
public MvcConfig() {
|
||||||
|
|
|
@ -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");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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.");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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.builders.WebSecurity;
|
||||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableWebSecurity
|
@EnableWebSecurity
|
||||||
|
@Profile("!manual")
|
||||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -0,0 +1 @@
|
||||||
|
Registration could not be completed at this time. Please try again later or contact support!
|
|
@ -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>
|
|
@ -37,6 +37,11 @@
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
|
|
|
@ -4,7 +4,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
public class TestController {
|
public class JettyController {
|
||||||
@RequestMapping
|
@RequestMapping
|
||||||
public String helloJetty() {
|
public String helloJetty() {
|
||||||
return "hello Jetty";
|
return "hello Jetty";
|
|
@ -2,7 +2,6 @@ package com.baeldung.spring.session.jettyex;
|
||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
public class JettyWebApplication {
|
public class JettyWebApplication {
|
||||||
|
|
|
@ -13,9 +13,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
http
|
http
|
||||||
.sessionManagement()
|
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and()
|
||||||
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
|
|
||||||
.and()
|
|
||||||
.authorizeRequests().anyRequest().hasRole("ADMIN");
|
.authorizeRequests().anyRequest().hasRole("ADMIN");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,4 +19,5 @@
|
||||||
<module>jetty-session-demo</module>
|
<module>jetty-session-demo</module>
|
||||||
<module>tomcat-session-demo</module>
|
<module>tomcat-session-demo</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -32,6 +32,11 @@
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
|
@ -61,6 +66,20 @@
|
||||||
<target>1.8</target>
|
<target>1.8</target>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</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>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
|
</properties>
|
||||||
</project>
|
</project>
|
|
@ -13,8 +13,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||||
auth.inMemoryAuthentication()
|
auth
|
||||||
.withUser("user").password("password").roles("USER").and()
|
.inMemoryAuthentication()
|
||||||
.withUser("admin").password("password").roles("ADMIN");
|
.withUser("admin").password("password").roles("ADMIN");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -23,8 +23,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||||
http
|
http
|
||||||
.httpBasic().and()
|
.httpBasic().and()
|
||||||
.authorizeRequests()
|
.authorizeRequests()
|
||||||
.antMatchers("/").permitAll()
|
|
||||||
.antMatchers("/tomcat").hasRole("USER")
|
|
||||||
.antMatchers("/tomcat/admin").hasRole("ADMIN")
|
.antMatchers("/tomcat/admin").hasRole("ADMIN")
|
||||||
.anyRequest().authenticated();
|
.anyRequest().authenticated();
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,18 +4,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
public class TestController {
|
public class TomcatController {
|
||||||
|
|
||||||
@RequestMapping
|
|
||||||
public String helloDefault() {
|
|
||||||
return "hello default";
|
|
||||||
}
|
|
||||||
|
|
||||||
@RequestMapping("/tomcat")
|
|
||||||
public String helloTomcat() {
|
|
||||||
return "hello tomcat";
|
|
||||||
}
|
|
||||||
|
|
||||||
@RequestMapping("/tomcat/admin")
|
@RequestMapping("/tomcat/admin")
|
||||||
public String helloTomcatAdmin() {
|
public String helloTomcatAdmin() {
|
||||||
return "hello tomcat admin";
|
return "hello tomcat admin";
|
|
@ -2,8 +2,6 @@ package com.baeldung.spring.session.tomcatex;
|
||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
public class TomcatWebApplication {
|
public class TomcatWebApplication {
|
||||||
|
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue