Merge branch 'master' into pr/873-yassser
Conflicts: core-java/src/main/java/com/baeldung/generics/Generics.java core-java/src/test/java/com/baeldung/generics/GenericsTest.java
This commit is contained in:
commit
287fbc3b10
|
@ -98,13 +98,14 @@
|
|||
<execution>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
<goal>test-compile</goal>
|
||||
<goal>test-compile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<!-- <plugin>
|
||||
<!--
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.10</version>
|
||||
|
@ -113,7 +114,8 @@
|
|||
<useSystemClassLoader>true</useSystemClassLoader>
|
||||
<forkMode>always</forkMode>
|
||||
</configuration>
|
||||
</plugin> -->
|
||||
</plugin>
|
||||
-->
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
|
|
@ -4,10 +4,10 @@ public class Account {
|
|||
int balance = 20;
|
||||
|
||||
public boolean withdraw(int amount) {
|
||||
if (balance - amount > 0) {
|
||||
balance = balance - amount;
|
||||
return true;
|
||||
} else
|
||||
if (balance < amount) {
|
||||
return false;
|
||||
}
|
||||
balance = balance - amount;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,12 +16,11 @@ public aspect AccountAspect {
|
|||
}
|
||||
|
||||
boolean around(int amount, Account account) : callWithDraw(amount, account) {
|
||||
if (account.balance - amount >= MIN_BALANCE)
|
||||
return proceed(amount, account);
|
||||
else {
|
||||
if (account.balance < amount) {
|
||||
logger.info("Withdrawal Rejected!");
|
||||
return false;
|
||||
}
|
||||
return proceed(amount, account);
|
||||
}
|
||||
|
||||
after(int amount, Account balance) : callWithDraw(amount, balance) {
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.hashing;
|
||||
|
||||
|
||||
import com.google.common.hash.Hashing;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
|
@ -11,17 +10,14 @@ import java.security.NoSuchAlgorithmException;
|
|||
|
||||
public class SHA256Hashing {
|
||||
|
||||
public static String HashWithJavaMessageDigest(final String originalString)
|
||||
throws NoSuchAlgorithmException {
|
||||
public static String HashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException {
|
||||
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
final byte[] encodedhash = digest.digest(
|
||||
originalString.getBytes(StandardCharsets.UTF_8));
|
||||
final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return bytesToHex(encodedhash);
|
||||
}
|
||||
|
||||
public static String HashWithGuava(final String originalString) {
|
||||
final String sha256hex = Hashing.sha256().hashString(
|
||||
originalString, StandardCharsets.UTF_8).toString();
|
||||
final String sha256hex = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
|
||||
return sha256hex;
|
||||
}
|
||||
|
||||
|
@ -30,11 +26,9 @@ public class SHA256Hashing {
|
|||
return sha256hex;
|
||||
}
|
||||
|
||||
public static String HashWithBouncyCastle(final String originalString)
|
||||
throws NoSuchAlgorithmException {
|
||||
public static String HashWithBouncyCastle(final String originalString) throws NoSuchAlgorithmException {
|
||||
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
final byte[] hash = digest.digest(
|
||||
originalString.getBytes(StandardCharsets.UTF_8));
|
||||
final byte[] hash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
final String sha256hex = new String(Hex.encode(hash));
|
||||
return sha256hex;
|
||||
}
|
||||
|
@ -43,7 +37,8 @@ public class SHA256Hashing {
|
|||
StringBuffer hexString = new StringBuffer();
|
||||
for (int i = 0; i < hash.length; i++) {
|
||||
String hex = Integer.toHexString(0xff & hash[i]);
|
||||
if(hex.length() == 1) hexString.append('0');
|
||||
if (hex.length() == 1)
|
||||
hexString.append('0');
|
||||
hexString.append(hex);
|
||||
}
|
||||
return hexString.toString();
|
||||
|
|
|
@ -0,0 +1,56 @@
|
|||
package com.baeldung.java.nio2.visitor;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
|
||||
import static java.nio.file.FileVisitResult.CONTINUE;
|
||||
import static java.nio.file.FileVisitResult.TERMINATE;
|
||||
|
||||
public class FileSearchExample implements FileVisitor<Path> {
|
||||
private final String fileName;
|
||||
private final Path startDir;
|
||||
|
||||
public FileSearchExample(String fileName, Path startingDir) {
|
||||
this.fileName = fileName;
|
||||
startDir = 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 (this.fileName.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, startDir);
|
||||
if (finishedSearch) {
|
||||
System.out.println("File:" + fileName + " 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,39 @@
|
|||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class Person {
|
||||
private String name;
|
||||
private int age;
|
||||
private String password;
|
||||
|
||||
public Person(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public Optional<String> getName() {
|
||||
return Optional.ofNullable(name);
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Optional<Integer> getAge() {
|
||||
return Optional.ofNullable(age);
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public Optional<String> getPassword() {
|
||||
return Optional.ofNullable(password);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,11 +1,12 @@
|
|||
package com.baeldung.file;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
@ -14,12 +15,6 @@ import java.nio.file.Path;
|
|||
import java.nio.file.Paths;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileOperationsUnitTest {
|
||||
|
||||
@Test
|
||||
|
@ -58,9 +53,9 @@ public class FileOperationsUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
|
||||
String expectedData = "Baeldung";
|
||||
String expectedData = "Example Domain";
|
||||
|
||||
URL urlObject = new URL("http://www.baeldung.com/");
|
||||
URL urlObject = new URL("http://www.example.com/");
|
||||
|
||||
URLConnection urlConnection = urlObject.openConnection();
|
||||
|
||||
|
|
|
@ -4,12 +4,10 @@ import org.junit.Test;
|
|||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class SHA256HashingTest {
|
||||
|
||||
private static String originalValue = "abc123";
|
||||
private static String hashedValue =
|
||||
"6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090";
|
||||
private static String hashedValue = "6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090";
|
||||
|
||||
@Test
|
||||
public void testHashWithJavaMessageDigest() throws Exception {
|
||||
|
|
|
@ -119,8 +119,7 @@ public class StringConversionTest {
|
|||
int afterConvCalendarDay = 03;
|
||||
Month afterConvCalendarMonth = Month.DECEMBER;
|
||||
int afterConvCalendarYear = 2007;
|
||||
LocalDateTime afterConvDate
|
||||
= new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
|
||||
LocalDateTime afterConvDate = new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
|
||||
|
||||
assertEquals(afterConvDate.getDayOfMonth(), afterConvCalendarDay);
|
||||
assertEquals(afterConvDate.getMonth(), afterConvCalendarMonth);
|
||||
|
|
|
@ -1,64 +1,72 @@
|
|||
package com.baeldung.java.nio2;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.DirectoryNotEmptyException;
|
||||
import java.nio.file.FileAlreadyExistsException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileTest {
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
private static final String TEMP_DIR = String.format("%s/temp%s", System.getProperty("user.home"), UUID.randomUUID().toString());
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws IOException {
|
||||
Files.createDirectory(Paths.get(TEMP_DIR));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanup() throws IOException {
|
||||
FileUtils.deleteDirectory(new File(TEMP_DIR));
|
||||
}
|
||||
|
||||
// checking file or dir
|
||||
@Test
|
||||
public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.exists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() {
|
||||
Path p = Paths.get(HOME + "/inexistent_file.txt");
|
||||
Path p = Paths.get(TEMP_DIR + "/inexistent_file.txt");
|
||||
assertTrue(Files.notExists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertFalse(Files.isRegularFile(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.isReadable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(System.getProperty("user.home"));
|
||||
assertTrue(Files.isWritable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
|
||||
Path p = Paths.get(HOME);
|
||||
Path p = Paths.get(System.getProperty("user.home"));
|
||||
assertTrue(Files.isExecutable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get(HOME);
|
||||
Path p2 = Paths.get(HOME);
|
||||
Path p1 = Paths.get(TEMP_DIR);
|
||||
Path p2 = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.isSameFile(p1, p2));
|
||||
}
|
||||
|
||||
|
@ -67,7 +75,7 @@ public class FileTest {
|
|||
@Test
|
||||
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
|
||||
String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
|
||||
Path p = Paths.get(HOME + "/" + fileName);
|
||||
Path p = Paths.get(TEMP_DIR + "/" + fileName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createFile(p);
|
||||
assertTrue(Files.exists(p));
|
||||
|
@ -77,7 +85,7 @@ public class FileTest {
|
|||
@Test
|
||||
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString();
|
||||
Path p = Paths.get(HOME + "/" + dirName);
|
||||
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createDirectory(p);
|
||||
assertTrue(Files.exists(p));
|
||||
|
@ -89,7 +97,7 @@ public class FileTest {
|
|||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
|
||||
Path p = Paths.get(HOME + "/" + dirName);
|
||||
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createDirectory(p);
|
||||
|
||||
|
@ -97,7 +105,7 @@ public class FileTest {
|
|||
|
||||
@Test
|
||||
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
|
||||
Path dir = Paths.get(HOME + "/myDir_" + UUID.randomUUID().toString());
|
||||
Path dir = Paths.get(TEMP_DIR + "/myDir_" + UUID.randomUUID().toString());
|
||||
Path subdir = dir.resolve("subdir");
|
||||
assertFalse(Files.exists(dir));
|
||||
assertFalse(Files.exists(subdir));
|
||||
|
@ -110,7 +118,7 @@ public class FileTest {
|
|||
public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException {
|
||||
String prefix = "log_";
|
||||
String suffix = ".txt";
|
||||
Path p = Paths.get(HOME + "/");
|
||||
Path p = Paths.get(TEMP_DIR + "/");
|
||||
p = Files.createTempFile(p, prefix, suffix);
|
||||
// like log_8821081429012075286.txt
|
||||
assertTrue(Files.exists(p));
|
||||
|
@ -119,7 +127,7 @@ public class FileTest {
|
|||
|
||||
@Test
|
||||
public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME + "/");
|
||||
Path p = Paths.get(TEMP_DIR + "/");
|
||||
p = Files.createTempFile(p, null, null);
|
||||
// like 8600179353689423985.tmp
|
||||
assertTrue(Files.exists(p));
|
||||
|
@ -136,7 +144,7 @@ public class FileTest {
|
|||
// delete file
|
||||
@Test
|
||||
public void givenPath_whenDeletes_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME + "/fileToDelete.txt");
|
||||
Path p = Paths.get(TEMP_DIR + "/fileToDelete.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createFile(p);
|
||||
assertTrue(Files.exists(p));
|
||||
|
@ -147,7 +155,7 @@ public class FileTest {
|
|||
|
||||
@Test(expected = DirectoryNotEmptyException.class)
|
||||
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
|
||||
Path dir = Paths.get(HOME + "/emptyDir" + UUID.randomUUID().toString());
|
||||
Path dir = Paths.get(TEMP_DIR + "/emptyDir" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir);
|
||||
assertTrue(Files.exists(dir));
|
||||
Path file = dir.resolve("file.txt");
|
||||
|
@ -160,7 +168,7 @@ public class FileTest {
|
|||
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME + "/inexistentFile.txt");
|
||||
Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.delete(p);
|
||||
|
||||
|
@ -168,7 +176,7 @@ public class FileTest {
|
|||
|
||||
@Test
|
||||
public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME + "/inexistentFile.txt");
|
||||
Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.deleteIfExists(p);
|
||||
|
||||
|
@ -177,8 +185,8 @@ public class FileTest {
|
|||
// copy file
|
||||
@Test
|
||||
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
|
@ -193,8 +201,8 @@ public class FileTest {
|
|||
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
|
@ -210,8 +218,8 @@ public class FileTest {
|
|||
// moving files
|
||||
@Test
|
||||
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
|
@ -227,8 +235,8 @@ public class FileTest {
|
|||
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
|
|
|
@ -0,0 +1,81 @@
|
|||
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);
|
||||
|
||||
//run some code
|
||||
writeResult.get();
|
||||
buffer.flip();
|
||||
Future<Integer> readResult = client.read(buffer);
|
||||
|
||||
//run some code
|
||||
readResult.get();
|
||||
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,80 @@
|
|||
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);
|
||||
|
||||
//do some computation
|
||||
|
||||
readResult.get();
|
||||
|
||||
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);
|
||||
|
||||
//do some computation
|
||||
writeResult.get();
|
||||
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,98 @@
|
|||
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) {
|
||||
String action = (String) attachment.get("action");
|
||||
if ("read".equals(action)) {
|
||||
ByteBuffer buffer = (ByteBuffer) attachment.get("buffer");
|
||||
buffer.flip();
|
||||
attachment.put("action", "write");
|
||||
clientChannel.write(buffer, attachment, this);
|
||||
buffer.clear();
|
||||
} else if ("write".equals(action)) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||
attachment.put("action", "read");
|
||||
attachment.put("buffer", buffer);
|
||||
clientChannel.read(buffer, attachment, 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,126 @@
|
|||
package com.baeldung.java.nio2.async;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
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.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class AsyncFileTest {
|
||||
@Test
|
||||
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
|
||||
Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
|
||||
operation.get();
|
||||
|
||||
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(AsyncFileTest.class.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, ExecutionException, InterruptedException {
|
||||
String fileName = "temp";
|
||||
Path path = Paths.get(fileName);
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
long position = 0;
|
||||
|
||||
buffer.put("hello world".getBytes());
|
||||
buffer.flip();
|
||||
|
||||
Future<Integer> operation = fileChannel.write(buffer, position);
|
||||
buffer.clear();
|
||||
|
||||
operation.get();
|
||||
|
||||
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) throws ExecutionException, InterruptedException {
|
||||
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);
|
||||
|
||||
operation.get();
|
||||
|
||||
String fileContent = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
return fileContent;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package com.baeldung.java.nio2.attributes;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
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 static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class BasicAttribsTest {
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
private static BasicFileAttributes basicAttribs;
|
||||
|
||||
@BeforeClass
|
||||
public static 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();
|
||||
|
||||
System.out.println("Created: " + created);
|
||||
System.out.println("Modified: " + modified);
|
||||
System.out.println("Accessed: " + accessed);
|
||||
|
||||
}
|
||||
|
||||
@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,211 @@
|
|||
package com.baeldung.java8.optional;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Optional;
|
||||
import com.baeldung.java_8_features.Person;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class OptionalTest {
|
||||
// creating Optional
|
||||
@Test
|
||||
public void whenCreatesEmptyOptional_thenCorrect() {
|
||||
Optional<String> empty = Optional.empty();
|
||||
assertFalse(empty.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonNull_whenCreatesNonNullable_thenCorrect() {
|
||||
String name = "baeldung";
|
||||
Optional.of(name);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenNull_whenThrowsErrorOnCreate_thenCorrect() {
|
||||
String name = null;
|
||||
Optional<String> opt = Optional.of(name);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonNull_whenCreatesOptional_thenCorrect() {
|
||||
String name = "baeldung";
|
||||
Optional<String> opt = Optional.of(name);
|
||||
assertEquals("Optional[baeldung]", opt.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonNull_whenCreatesNullable_thenCorrect() {
|
||||
String name = "baeldung";
|
||||
Optional<String> opt = Optional.ofNullable(name);
|
||||
assertEquals("Optional[baeldung]", opt.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNull_whenCreatesNullable_thenCorrect() {
|
||||
String name = null;
|
||||
Optional<String> opt = Optional.ofNullable(name);
|
||||
assertEquals("Optional.empty", opt.toString());
|
||||
}
|
||||
// Checking Value With isPresent()
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenIsPresentWorks_thenCorrect() {
|
||||
Optional<String> opt = Optional.of("Baeldung");
|
||||
assertTrue(opt.isPresent());
|
||||
|
||||
opt = Optional.ofNullable(null);
|
||||
assertFalse(opt.isPresent());
|
||||
}
|
||||
|
||||
// Condition Action With ifPresent()
|
||||
@Test
|
||||
public void givenOptional_whenIfPresentWorks_thenCorrect() {
|
||||
Optional<String> opt = Optional.of("baeldung");
|
||||
opt.ifPresent(name -> System.out.println(name.length()));
|
||||
opt.ifPresent(String::length);
|
||||
}
|
||||
|
||||
// returning Value With get()
|
||||
@Test
|
||||
public void givenOptional_whenGetsValue_thenCorrect() {
|
||||
Optional<String> opt = Optional.of("baeldung");
|
||||
String name = opt.get();
|
||||
assertEquals("baeldung", name);
|
||||
}
|
||||
|
||||
@Test(expected = NoSuchElementException.class)
|
||||
public void givenOptionalWithNull_whenGetThrowsException_thenCorrect() {
|
||||
Optional<String> opt = Optional.ofNullable(null);
|
||||
String name = opt.get();
|
||||
}
|
||||
|
||||
// Conditional Return With filter()
|
||||
@Test
|
||||
public void whenOptionalFilterWorks_thenCorrect() {
|
||||
Integer year = 2016;
|
||||
Optional<Integer> yearOptional = Optional.of(year);
|
||||
boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent();
|
||||
assertTrue(is2016);
|
||||
boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent();
|
||||
assertFalse(is2017);
|
||||
}
|
||||
|
||||
// Transforming Value With map()
|
||||
@Test
|
||||
public void givenOptional_whenMapWorks_thenCorrect() {
|
||||
List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
|
||||
Optional<List<String>> listOptional = Optional.of(companyNames);
|
||||
|
||||
int size = listOptional.map(list -> list.size()).get();
|
||||
assertEquals(6, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenMapWorks_thenCorrect2() {
|
||||
String name = "baeldung";
|
||||
Optional<String> nameOptional = Optional.of(name);
|
||||
|
||||
int len = nameOptional.map(s -> s.length()).get();
|
||||
assertEquals(8, len);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenMapWorksWithFilter_thenCorrect() {
|
||||
String password = " password ";
|
||||
Optional<String> passOpt = Optional.of(password);
|
||||
boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent();
|
||||
assertFalse(correctPassword);
|
||||
|
||||
correctPassword = passOpt.map(pass -> pass.trim()).filter(pass -> pass.equals("password")).isPresent();
|
||||
assertTrue(correctPassword);
|
||||
}
|
||||
|
||||
// Transforming Value With flatMap()
|
||||
@Test
|
||||
public void givenOptional_whenFlatMapWorks_thenCorrect2() {
|
||||
Person person = new Person("john", 26);
|
||||
Optional<Person> personOptional = Optional.of(person);
|
||||
|
||||
Optional<Optional<String>> nameOptionalWrapper = personOptional.map(p -> p.getName());
|
||||
Optional<String> nameOptional = nameOptionalWrapper.get();
|
||||
String name1 = nameOptional.get();
|
||||
assertEquals("john", name1);
|
||||
|
||||
String name = personOptional.flatMap(p -> p.getName()).get();
|
||||
assertEquals("john", name);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenFlatMapWorksWithFilter_thenCorrect() {
|
||||
Person person = new Person("john", 26);
|
||||
person.setPassword("password");
|
||||
Optional<Person> personOptional = Optional.of(person);
|
||||
|
||||
String password = personOptional.flatMap(p -> p.getPassword()).filter(cleanPass -> cleanPass.equals("password")).get();
|
||||
assertEquals("password", password);
|
||||
}
|
||||
|
||||
// Default Value With orElse
|
||||
@Test
|
||||
public void whenOrElseWorks_thenCorrect() {
|
||||
String nullName = null;
|
||||
String name = Optional.ofNullable(nullName).orElse("john");
|
||||
assertEquals("john", name);
|
||||
}
|
||||
|
||||
// Default Value With orElseGet
|
||||
@Test
|
||||
public void whenOrElseGetWorks_thenCorrect() {
|
||||
String nullName = null;
|
||||
String name = Optional.ofNullable(nullName).orElseGet(() -> "john");
|
||||
assertEquals("john", name);
|
||||
|
||||
name = Optional.ofNullable(nullName).orElseGet(() -> {
|
||||
return "doe";
|
||||
});
|
||||
assertEquals("doe", name);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOrElseGetAndOrElseOverlap_thenCorrect() {
|
||||
String text = null;
|
||||
System.out.println("Using orElseGet:");
|
||||
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
|
||||
assertEquals("Default Value", defaultText);
|
||||
|
||||
System.out.println("Using orElse:");
|
||||
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
|
||||
assertEquals("Default Value", defaultText);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOrElseGetAndOrElseDiffer_thenCorrect() {
|
||||
String text = "Text present";
|
||||
System.out.println("Using orElseGet:");
|
||||
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
|
||||
assertEquals("Text present", defaultText);
|
||||
|
||||
System.out.println("Using orElse:");
|
||||
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
|
||||
assertEquals("Text present", defaultText);
|
||||
}
|
||||
|
||||
// Exceptions With orElseThrow
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenOrElseThrowWorks_thenCorrect() {
|
||||
String nullName = null;
|
||||
String name = Optional.ofNullable(nullName).orElseThrow(IllegalArgumentException::new);
|
||||
}
|
||||
|
||||
public String getMyDefault() {
|
||||
System.out.println("Getting default value...");
|
||||
return "Default Value";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,110 @@
|
|||
package org.baeldung.java.collections;
|
||||
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Lists;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
|
||||
public class CollectionsConcatenateUnitTest {
|
||||
|
||||
@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> i1, Iterable<? extends E> i2) {
|
||||
return new Iterable<E>() {
|
||||
public Iterator<E> iterator() {
|
||||
return new Iterator<E>() {
|
||||
Iterator<? extends E> listIterator = i1.iterator();
|
||||
Boolean checkedHasNext;
|
||||
E nextValue;
|
||||
private boolean startTheSecond;
|
||||
|
||||
void theNext() {
|
||||
if (listIterator.hasNext()) {
|
||||
checkedHasNext = true;
|
||||
nextValue = listIterator.next();
|
||||
} else if (startTheSecond)
|
||||
checkedHasNext = false;
|
||||
else {
|
||||
startTheSecond = true;
|
||||
listIterator = i2.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<>();
|
||||
for (E item : iter) {
|
||||
list.add(item);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,179 @@
|
|||
package org.baeldung.java.collections;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class JoinSplitCollectionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenJoiningTwoArrays_thenJoined() {
|
||||
String[] animals1 = new String[] { "Dog", "Cat" };
|
||||
String[] animals2 = new String[] { "Bird", "Cow" };
|
||||
String[] result = Stream.concat(Arrays.stream(animals1), Arrays.stream(animals2))
|
||||
.toArray(String[]::new);
|
||||
|
||||
assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningTwoCollections_thenJoined() {
|
||||
Collection<Integer> collection1 = Arrays.asList(7, 8, 9);
|
||||
Collection<Integer> collection2 = Arrays.asList(10, 11, 12);
|
||||
Collection<Integer> result = Stream.concat(collection1.stream(), collection2.stream())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(result.equals(Arrays.asList(7, 8, 9, 10, 11, 12)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningTwoCollectionsWithFilter_thenJoined() {
|
||||
Collection<Integer> collection1 = Arrays.asList(7, 8, 11);
|
||||
Collection<Integer> collection2 = Arrays.asList(9, 12, 10);
|
||||
Collection<Integer> result = Stream.concat(collection1.stream(), collection2.stream())
|
||||
.filter(next -> next <= 10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(result.equals(Arrays.asList(7, 8, 9, 10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertArrayToString_thenConverted() {
|
||||
String[] colors = new String[] { "Red", "Blue", "Green", "Yellow" };
|
||||
String result = Arrays.stream(colors)
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
assertEquals(result, "Red, Blue, Green, Yellow");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertCollectionToString_thenConverted() {
|
||||
Collection<String> directions = Arrays.asList("Left", "Right", "Top", "Bottom");
|
||||
String result = directions.stream()
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
assertEquals(result, "Left, Right, Top, Bottom");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertMapToString_thenConverted() {
|
||||
Map<Integer, String> users = new HashMap<>();
|
||||
users.put(1, "John Doe");
|
||||
users.put(2, "Paul Smith");
|
||||
users.put(3, "Susan Anderson");
|
||||
|
||||
String result = users.entrySet().stream().map(entry -> entry.getKey() + " = " + entry.getValue())
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
assertEquals(result, "1 = John Doe, 2 = Paul Smith, 3 = Susan Anderson");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertNestedCollectionToString_thenConverted() {
|
||||
Collection<List<String>> nested = new ArrayList<>();
|
||||
nested.add(Arrays.asList("Left", "Right", "Top", "Bottom"));
|
||||
nested.add(Arrays.asList("Red", "Blue", "Green", "Yellow"));
|
||||
|
||||
String result = nested.stream()
|
||||
.map(nextList -> nextList.stream()
|
||||
.collect(Collectors.joining("-")))
|
||||
.collect(Collectors.joining("; "));
|
||||
|
||||
assertEquals(result, "Left-Right-Top-Bottom; Red-Blue-Green-Yellow");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertCollectionToStringAndSkipNull_thenConverted() {
|
||||
Collection<String> fruits = Arrays.asList("Apple", "Orange", null, "Grape");
|
||||
String result = fruits.stream()
|
||||
.filter(next -> next != null)
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
assertEquals(result, "Apple, Orange, Grape");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSplitCollectionHalf_thenConverted() {
|
||||
Collection<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
Collection<Integer> result1 = new ArrayList<>();
|
||||
Collection<Integer> result2 = new ArrayList<>();
|
||||
AtomicInteger count = new AtomicInteger();
|
||||
int midpoint = Math.round(numbers.size() / 2);
|
||||
|
||||
numbers.forEach(next -> {
|
||||
int index = count.getAndIncrement();
|
||||
if(index < midpoint){
|
||||
result1.add(next);
|
||||
}else{
|
||||
result2.add(next);
|
||||
}
|
||||
});
|
||||
|
||||
assertTrue(result1.equals(Arrays.asList(1, 2, 3, 4, 5)));
|
||||
assertTrue(result2.equals(Arrays.asList(6, 7, 8, 9, 10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSplitArrayByWordLength_thenConverted() {
|
||||
String[] words = new String[]{"bye", "cold", "it", "and", "my", "word"};
|
||||
Map<Integer, List<String>> result = Arrays.stream(words)
|
||||
.collect(Collectors.groupingBy(word -> word.length()));
|
||||
|
||||
assertTrue(result.get(2).equals(Arrays.asList("it", "my")));
|
||||
assertTrue(result.get(3).equals(Arrays.asList("bye", "and")));
|
||||
assertTrue(result.get(4).equals(Arrays.asList("cold", "word")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToArray_thenConverted() {
|
||||
String colors = "Red, Blue, Green, Yellow";
|
||||
String[] result = colors.split(", ");
|
||||
|
||||
assertArrayEquals(result, new String[] { "Red", "Blue", "Green", "Yellow" });
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToCollection_thenConverted() {
|
||||
String colors = "Left, Right, Top, Bottom";
|
||||
Collection<String> result = Arrays.asList(colors.split(", "));
|
||||
|
||||
assertTrue(result.equals(Arrays.asList("Left", "Right", "Top", "Bottom")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToMap_thenConverted() {
|
||||
String users = "1 = John Doe, 2 = Paul Smith, 3 = Susan Anderson";
|
||||
|
||||
Map<Integer, String> result = Arrays.stream(users.split(", "))
|
||||
.map(next -> next.split(" = "))
|
||||
.collect(Collectors.toMap(entry -> Integer.parseInt(entry[0]), entry -> entry[1]));
|
||||
|
||||
assertEquals(result.get(1), "John Doe");
|
||||
assertEquals(result.get(2), "Paul Smith");
|
||||
assertEquals(result.get(3), "Susan Anderson");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertCollectionToStringMultipleSeparators_thenConverted() {
|
||||
String fruits = "Apple. , Orange, Grape. Lemon";
|
||||
|
||||
Collection<String> result = Arrays.stream(fruits.split("[,|.]"))
|
||||
.map(String::trim)
|
||||
.filter(next -> !next.isEmpty())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(result.equals(Arrays.asList("Apple", "Orange", "Grape", "Lemon")));
|
||||
}
|
||||
}
|
|
@ -1,7 +1,9 @@
|
|||
package org.baeldung.java.io;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
@ -9,17 +11,28 @@ import java.nio.file.FileSystemException;
|
|||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Test;
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class JavaFileUnitTest {
|
||||
|
||||
// create a file
|
||||
private static final String TEMP_DIR = "src/test/resources/temp" + UUID.randomUUID().toString();
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws IOException {
|
||||
Files.createDirectory(Paths.get(TEMP_DIR));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanup() throws IOException {
|
||||
FileUtils.deleteDirectory(new File(TEMP_DIR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException {
|
||||
final File newFile = new File("src/test/resources/newFile_jdk6.txt");
|
||||
final File newFile = new File(TEMP_DIR + "/newFile_jdk6.txt");
|
||||
final boolean success = newFile.createNewFile();
|
||||
|
||||
assertTrue(success);
|
||||
|
@ -27,48 +40,48 @@ public class JavaFileUnitTest {
|
|||
|
||||
@Test
|
||||
public final void givenUsingJDK7nio2_whenCreatingFile_thenCorrect() throws IOException {
|
||||
final Path newFilePath = Paths.get("src/test/resources/newFile_jdk7.txt");
|
||||
final Path newFilePath = Paths.get(TEMP_DIR + "/newFile_jdk7.txt");
|
||||
Files.createFile(newFilePath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt"));
|
||||
FileUtils.touch(new File(TEMP_DIR + "/newFile_commonsio.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
|
||||
com.google.common.io.Files.touch(new File("src/test/resources/newFile_guava.txt"));
|
||||
com.google.common.io.Files.touch(new File(TEMP_DIR + "/newFile_guava.txt"));
|
||||
}
|
||||
|
||||
// move a file
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
|
||||
final File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt");
|
||||
final File fileToMove = new File(TEMP_DIR + "/toMoveFile_jdk6.txt");
|
||||
fileToMove.createNewFile();// .exists();
|
||||
final File destDir = new File("src/test/resources/");
|
||||
final File destDir = new File(TEMP_DIR + "/");
|
||||
destDir.mkdir();
|
||||
|
||||
final boolean isMoved = fileToMove.renameTo(new File("src/test/resources/movedFile_jdk6.txt"));
|
||||
final boolean isMoved = fileToMove.renameTo(new File(TEMP_DIR + "/movedFile_jdk6.txt"));
|
||||
if (!isMoved) {
|
||||
throw new FileSystemException("src/test/resources/movedFile_jdk6.txt");
|
||||
throw new FileSystemException(TEMP_DIR + "/movedFile_jdk6.txt");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
|
||||
final Path fileToMovePath = Files.createFile(Paths.get("src/test/resources/" + randomAlphabetic(5) + ".txt"));
|
||||
final Path targetPath = Paths.get("src/main/resources/");
|
||||
final Path fileToMovePath = Files.createFile(Paths.get(TEMP_DIR + "/" + randomAlphabetic(5) + ".txt"));
|
||||
final Path targetPath = Paths.get(TEMP_DIR + "/");
|
||||
|
||||
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException {
|
||||
final File fileToMove = new File("src/test/resources/fileToMove.txt");
|
||||
final File fileToMove = new File(TEMP_DIR + "/fileToMove.txt");
|
||||
fileToMove.createNewFile();
|
||||
final File destDir = new File("src/main/resources/");
|
||||
final File destDir = new File(TEMP_DIR + "/temp");
|
||||
final File targetFile = new File(destDir, fileToMove.getName());
|
||||
com.google.common.io.Files.createParentDirs(targetFile);
|
||||
com.google.common.io.Files.move(fileToMove, targetFile);
|
||||
|
@ -76,23 +89,24 @@ public class JavaFileUnitTest {
|
|||
|
||||
@Test
|
||||
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
|
||||
FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/test/resources/fileMoved_apache2.txt"));
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
|
||||
FileUtils.moveFile(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/fileMoved_apache2.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
|
||||
FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/main/resources/"), true);
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
|
||||
Files.createDirectory(Paths.get(TEMP_DIR + "/temp"));
|
||||
FileUtils.moveFileToDirectory(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/temp"), true);
|
||||
}
|
||||
|
||||
// delete a file
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException {
|
||||
new File("src/test/resources/fileToDelete_jdk6.txt").createNewFile();
|
||||
new File(TEMP_DIR + "/fileToDelete_jdk6.txt").createNewFile();
|
||||
|
||||
final File fileToDelete = new File("src/test/resources/fileToDelete_jdk6.txt");
|
||||
final File fileToDelete = new File(TEMP_DIR + "/fileToDelete_jdk6.txt");
|
||||
final boolean success = fileToDelete.delete();
|
||||
|
||||
assertTrue(success);
|
||||
|
@ -100,17 +114,17 @@ public class JavaFileUnitTest {
|
|||
|
||||
@Test
|
||||
public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException {
|
||||
Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt"));
|
||||
Files.createFile(Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt"));
|
||||
|
||||
final Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt");
|
||||
final Path fileToDeletePath = Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt");
|
||||
Files.delete(fileToDeletePath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File("src/test/resources/fileToDelete_commonsIo.txt"));
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete_commonsIo.txt"));
|
||||
|
||||
final File fileToDelete = FileUtils.getFile("src/test/resources/fileToDelete_commonsIo.txt");
|
||||
final File fileToDelete = FileUtils.getFile(TEMP_DIR + "/fileToDelete_commonsIo.txt");
|
||||
final boolean success = FileUtils.deleteQuietly(fileToDelete);
|
||||
|
||||
assertTrue(success);
|
||||
|
@ -118,9 +132,9 @@ public class JavaFileUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File("src/test/resources/fileToDelete.txt"));
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete.txt"));
|
||||
|
||||
FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt"));
|
||||
FileUtils.forceDelete(FileUtils.getFile(TEMP_DIR + "/fileToDelete.txt"));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,55 @@
|
|||
package org.baeldung.java.sorting;
|
||||
|
||||
public class Employee implements Comparable {
|
||||
|
||||
private String name;
|
||||
private int age;
|
||||
private double salary;
|
||||
|
||||
public Employee(String name, int age, double salary) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public double getSalary() {
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void setSalary(double salary) {
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return ((Employee) obj).getName().equals(getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Object o) {
|
||||
Employee e = (Employee) o;
|
||||
return getName().compareTo(e.getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringBuffer().append("(").append(getName()).append(getAge()).append(",").append(getSalary()).append(")").toString();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,186 @@
|
|||
package org.baeldung.java.sorting;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.primitives.Ints;
|
||||
|
||||
public class JavaSorting {
|
||||
|
||||
private int[] toSort;
|
||||
private int[] sortedInts;
|
||||
private int[] sortedRangeInts;
|
||||
// private Integer [] integers;
|
||||
// private Integer [] sortedIntegers;
|
||||
// private List<Integer> integersList;
|
||||
// private List<Integer> sortedIntegersList;
|
||||
private Employee[] employees;
|
||||
private Employee[] employeesSorted;
|
||||
private Employee[] employeesSortedByAge;
|
||||
private HashMap<Integer, String> map;
|
||||
|
||||
@Before
|
||||
public void initVariables() {
|
||||
|
||||
toSort = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 };
|
||||
sortedInts = new int[] { 1, 5, 7, 66, 88, 89, 123, 200, 255 };
|
||||
sortedRangeInts = new int[] { 5, 1, 89, 7, 88, 200, 255, 123, 66 };
|
||||
|
||||
// integers = new Integer[]
|
||||
// { 5, 1, 89, 255, 7, 88, 200, 123, 66 };
|
||||
// sortedIntegers = new Integer[]
|
||||
// {1, 5, 7, 66, 88, 89, 123, 200, 255};
|
||||
//
|
||||
// integersList = Arrays.asList(new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 });
|
||||
// sortedIntegersList = Arrays.asList(new Integer[] {1, 5, 7, 66, 88, 89, 123, 200, 255});
|
||||
|
||||
employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) };
|
||||
employeesSorted = new Employee[] { new Employee("Earl", 43, 10000), new Employee("Frank", 33, 70000), new Employee("Jessica", 23, 4000), new Employee("John", 23, 5000), new Employee("Pearl", 33, 4000), new Employee("Steve", 26, 6000) };
|
||||
employeesSortedByAge = new Employee[] { new Employee("John", 23, 5000), new Employee("Jessica", 23, 4000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 70000), new Employee("Pearl", 33, 4000), new Employee("Earl", 43, 10000) };
|
||||
|
||||
HashMap<Integer, String> map = new HashMap<>();
|
||||
map.put(55, "John");
|
||||
map.put(22, "Apple");
|
||||
map.put(66, "Earl");
|
||||
map.put(77, "Pearl");
|
||||
map.put(12, "George");
|
||||
map.put(6, "Rocky");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenUsingSort_thenSortedArray() {
|
||||
Arrays.sort(toSort);
|
||||
|
||||
assertTrue(Arrays.equals(toSort, sortedInts));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerArray_whenUsingSort_thenSortedArray() {
|
||||
Integer[] integers = ArrayUtils.toObject(toSort);
|
||||
Arrays.sort(integers, new Comparator<Integer>() {
|
||||
@Override
|
||||
public int compare(Integer a, Integer b) {
|
||||
return a - b;
|
||||
}
|
||||
});
|
||||
|
||||
assertTrue(Arrays.equals(integers, ArrayUtils.toObject(sortedInts)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenUsingSortWithLambdas_thenSortedArray() {
|
||||
Integer[] integersToSort = ArrayUtils.toObject(toSort);
|
||||
Arrays.sort(integersToSort, (a, b) -> {
|
||||
return a - b;
|
||||
});
|
||||
|
||||
assertTrue(Arrays.equals(integersToSort, ArrayUtils.toObject(sortedInts)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpArray_SortEmpArray_thenSortedArrayinNaturalOrder() {
|
||||
Arrays.sort(employees);
|
||||
|
||||
assertTrue(Arrays.equals(employees, employeesSorted));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenUsingRangeSort_thenRangeSortedArray() {
|
||||
Arrays.sort(toSort, 3, 7);
|
||||
|
||||
assertTrue(Arrays.equals(toSort, sortedRangeInts));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenUsingParallelSort_thenArraySorted() {
|
||||
Arrays.parallelSort(toSort);
|
||||
|
||||
assertTrue(Arrays.equals(toSort, sortedInts));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayObjects_whenUsingComparing_thenSortedArrayObjects() {
|
||||
List<Employee> employeesList = Arrays.asList(employees);
|
||||
|
||||
employeesList.sort(Comparator.comparing(Employee::getAge));// .thenComparing(Employee::getName));
|
||||
|
||||
assertTrue(Arrays.equals(employeesList.toArray(), employeesSortedByAge));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenUsingSort_thenSortedList() {
|
||||
List<Integer> toSortList = Ints.asList(toSort);
|
||||
Collections.sort(toSortList);
|
||||
|
||||
assertTrue(Arrays.equals(toSortList.toArray(), ArrayUtils.toObject(sortedInts)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMap_whenSortingByKeys_thenSortedMap() {
|
||||
Integer[] sortedKeys = new Integer[] { 6, 12, 22, 55, 66, 77 };
|
||||
|
||||
List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
|
||||
Collections.sort(entries, new Comparator<Entry<Integer, String>>() {
|
||||
@Override
|
||||
public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
|
||||
return o1.getKey().compareTo(o2.getKey());
|
||||
}
|
||||
});
|
||||
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
|
||||
for (Map.Entry<Integer, String> entry : entries) {
|
||||
sortedMap.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMap_whenSortingByValues_thenSortedMap() {
|
||||
String[] sortedValues = new String[] { "Apple", "Earl", "George", "John", "Pearl", "Rocky" };
|
||||
|
||||
List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
|
||||
Collections.sort(entries, new Comparator<Entry<Integer, String>>() {
|
||||
@Override
|
||||
public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
|
||||
return o1.getValue().compareTo(o2.getValue());
|
||||
}
|
||||
});
|
||||
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
|
||||
for (Map.Entry<Integer, String> entry : entries) {
|
||||
sortedMap.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_whenUsingSort_thenSortedSet() {
|
||||
HashSet<Integer> integersSet = new LinkedHashSet<>(Ints.asList(toSort));
|
||||
HashSet<Integer> descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(new Integer[] { 255, 200, 123, 89, 88, 66, 7, 5, 1 }));
|
||||
|
||||
ArrayList<Integer> list = new ArrayList<Integer>(integersSet);
|
||||
Collections.sort(list, (i1, i2) -> {
|
||||
return i2 - i1;
|
||||
});
|
||||
integersSet = new LinkedHashSet<>(list);
|
||||
|
||||
assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray()));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
baeldung.com
|
|
@ -1,20 +1,15 @@
|
|||
<?xml version="1.0"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>ejb-client</artifactId>
|
||||
<name>EJB3 Client Maven</name>
|
||||
<description>EJB3 Client Maven</description>
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
<artifactId>ejb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>ejb-client</artifactId>
|
||||
<name>EJB3 Client Maven</name>
|
||||
<description>EJB3 Client Maven</description>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.wildfly</groupId>
|
||||
|
@ -49,6 +44,4 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
|
@ -5,4 +5,4 @@ remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMO
|
|||
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
|
||||
remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER}
|
||||
remote.connection.default.username=testUser
|
||||
remote.connection.default.password=admin1234!
|
||||
remote.connection.default.password=admin1234!
|
||||
|
|
|
@ -12,11 +12,12 @@
|
|||
|
||||
<!-- <name>ejb-remote</name> -->
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jboss.spec.javax.ejb</groupId>
|
||||
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>7.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -1,13 +1,19 @@
|
|||
package com.baeldung.ejb.tutorial;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.ejb.SessionContext;
|
||||
import javax.ejb.Stateless;
|
||||
|
||||
@Stateless(name = "HelloWorld")
|
||||
public class HelloWorldBean implements HelloWorld {
|
||||
|
||||
@Resource
|
||||
private SessionContext context;
|
||||
|
||||
@Override
|
||||
public String getHelloWorld() {
|
||||
return "Welcome to EJB Tutorial!";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -36,11 +36,10 @@
|
|||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jboss.spec</groupId>
|
||||
<artifactId>jboss-javaee-7.0</artifactId>
|
||||
<version>1.0.1.Final</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>7.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
|
1
pom.xml
1
pom.xml
|
@ -109,6 +109,7 @@
|
|||
<module>spring-katharsis</module>
|
||||
<module>spring-mockito</module>
|
||||
<module>spring-mvc-java</module>
|
||||
<module>spring-mvc-forms</module>
|
||||
<module>spring-mvc-no-xml</module>
|
||||
<module>spring-mvc-tiles</module>
|
||||
<module>spring-mvc-velocity</module>
|
||||
|
|
|
@ -1,2 +1,5 @@
|
|||
### Relevant Articles:
|
||||
- [Wiring in Spring: @Autowired, @Resource and @Inject](http://www.baeldung.com/spring-annotations-resource-inject-autowire)
|
||||
- [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory)
|
||||
- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean)
|
||||
|
||||
|
|
|
@ -4,14 +4,11 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>dependency-injection</artifactId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<name>dependency-injection</name>
|
||||
<description>Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely
|
||||
Resource, Inject, and Autowired
|
||||
</description>
|
||||
<name>spring-core</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
@ -50,6 +47,11 @@
|
|||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>20.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.factorybean;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class FactoryBeanAppConfig {
|
||||
|
||||
@Bean(name = "tool")
|
||||
public ToolFactory toolFactory() {
|
||||
ToolFactory factory = new ToolFactory();
|
||||
factory.setFactoryId(7070);
|
||||
factory.setToolId(2);
|
||||
return factory;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.factorybean;
|
||||
|
||||
import org.springframework.beans.factory.config.AbstractFactoryBean;
|
||||
|
||||
public class NonSingleToolFactory extends AbstractFactoryBean<Tool> {
|
||||
|
||||
private int factoryId;
|
||||
private int toolId;
|
||||
|
||||
public NonSingleToolFactory() {
|
||||
setSingleton(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getObjectType() {
|
||||
return Tool.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Tool createInstance() throws Exception {
|
||||
return new Tool(toolId);
|
||||
}
|
||||
|
||||
public int getFactoryId() {
|
||||
return factoryId;
|
||||
}
|
||||
|
||||
public void setFactoryId(int factoryId) {
|
||||
this.factoryId = factoryId;
|
||||
}
|
||||
|
||||
public int getToolId() {
|
||||
return toolId;
|
||||
}
|
||||
|
||||
public void setToolId(int toolId) {
|
||||
this.toolId = toolId;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.factorybean;
|
||||
|
||||
import org.springframework.beans.factory.config.AbstractFactoryBean;
|
||||
|
||||
//no need to set singleton property because default value is true
|
||||
public class SingleToolFactory extends AbstractFactoryBean<Tool> {
|
||||
|
||||
private int factoryId;
|
||||
private int toolId;
|
||||
|
||||
@Override
|
||||
public Class<?> getObjectType() {
|
||||
return Tool.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Tool createInstance() throws Exception {
|
||||
return new Tool(toolId);
|
||||
}
|
||||
|
||||
public int getFactoryId() {
|
||||
return factoryId;
|
||||
}
|
||||
|
||||
public void setFactoryId(int factoryId) {
|
||||
this.factoryId = factoryId;
|
||||
}
|
||||
|
||||
public int getToolId() {
|
||||
return toolId;
|
||||
}
|
||||
|
||||
public void setToolId(int toolId) {
|
||||
this.toolId = toolId;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.factorybean;
|
||||
|
||||
public class Tool {
|
||||
private int id;
|
||||
|
||||
public Tool() {
|
||||
}
|
||||
|
||||
public Tool(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.factorybean;
|
||||
|
||||
import org.springframework.beans.factory.FactoryBean;
|
||||
|
||||
public class ToolFactory implements FactoryBean<Tool> {
|
||||
|
||||
private int factoryId;
|
||||
private int toolId;
|
||||
|
||||
@Override
|
||||
public Tool getObject() throws Exception {
|
||||
return new Tool(toolId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getObjectType() {
|
||||
return Tool.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSingleton() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getFactoryId() {
|
||||
return factoryId;
|
||||
}
|
||||
|
||||
public void setFactoryId(int factoryId) {
|
||||
this.factoryId = factoryId;
|
||||
}
|
||||
|
||||
public int getToolId() {
|
||||
return toolId;
|
||||
}
|
||||
|
||||
public void setToolId(int toolId) {
|
||||
this.toolId = toolId;
|
||||
}
|
||||
}
|
|
@ -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,15 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://www.springframework.org/schema/beans"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<bean id="singleTool" class="com.baeldung.factorybean.SingleToolFactory">
|
||||
<property name="factoryId" value="3001"/>
|
||||
<property name="toolId" value="1"/>
|
||||
</bean>
|
||||
|
||||
<bean id="nonSingleTool" class="com.baeldung.factorybean.NonSingleToolFactory">
|
||||
<property name="factoryId" value="3002"/>
|
||||
<property name="toolId" value="2"/>
|
||||
</bean>
|
||||
</beans>
|
|
@ -0,0 +1,10 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://www.springframework.org/schema/beans"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<bean id="tool" class="com.baeldung.factorybean.ToolFactory">
|
||||
<property name="factoryId" value="9090"/>
|
||||
<property name="toolId" value="1"/>
|
||||
</bean>
|
||||
</beans>
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.factorybean;
|
||||
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(locations = { "classpath:factorybean-abstract-spring-ctx.xml" })
|
||||
public class AbstractFactoryBeanTest {
|
||||
|
||||
@Resource(name = "singleTool")
|
||||
private Tool tool1;
|
||||
@Resource(name = "singleTool")
|
||||
private Tool tool2;
|
||||
@Resource(name = "nonSingleTool")
|
||||
private Tool tool3;
|
||||
@Resource(name = "nonSingleTool")
|
||||
private Tool tool4;
|
||||
|
||||
@Test
|
||||
public void testSingleToolFactory() {
|
||||
assertThat(tool1.getId(), equalTo(1));
|
||||
assertTrue(tool1 == tool2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonSingleToolFactory() {
|
||||
assertThat(tool3.getId(), equalTo(2));
|
||||
assertThat(tool4.getId(), equalTo(2));
|
||||
assertTrue(tool3 != tool4);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.factorybean;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = FactoryBeanAppConfig.class)
|
||||
public class FactoryBeanJavaConfigTest {
|
||||
|
||||
@Autowired
|
||||
private Tool tool;
|
||||
|
||||
@Resource(name = "&tool")
|
||||
private ToolFactory toolFactory;
|
||||
|
||||
@Test
|
||||
public void testConstructWorkerByJava() {
|
||||
assertThat(tool.getId(), equalTo(2));
|
||||
assertThat(toolFactory.getFactoryId(), equalTo(7070));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.factorybean;
|
||||
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(locations = { "classpath:factorybean-spring-ctx.xml" })
|
||||
public class FactoryBeanXmlConfigTest {
|
||||
|
||||
@Autowired
|
||||
private Tool tool;
|
||||
@Resource(name = "&tool")
|
||||
private ToolFactory toolFactory;
|
||||
|
||||
@Test
|
||||
public void testConstructWorkerByXml() {
|
||||
assertThat(tool.getId(), equalTo(1));
|
||||
assertThat(toolFactory.getFactoryId(), equalTo(9090));
|
||||
}
|
||||
}
|
|
@ -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>
|
|
@ -0,0 +1,15 @@
|
|||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
<form action="#" th:action="@{/message/processForm}" method="post">
|
||||
Message: <input type="text" value="message" id="message" name="message"/>
|
||||
<input type="submit" />
|
||||
</form>
|
||||
|
||||
<span th:text="${message}" id="received"></span>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.htmlunit;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.gargoylesoftware.htmlunit.WebClient;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
|
||||
public class HtmlUnitAndJUnitTest {
|
||||
|
||||
@Before
|
||||
public void init() throws Exception {
|
||||
webClient = new WebClient();
|
||||
}
|
||||
|
||||
@After
|
||||
public void close() throws Exception {
|
||||
webClient.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAClient_whenEnteringBaeldung_thenPageTitleIsOk()
|
||||
throws Exception {
|
||||
webClient.getOptions().setThrowExceptionOnScriptError(false);
|
||||
HtmlPage page = webClient.getPage("http://www.baeldung.com/");
|
||||
Assert.assertEquals(
|
||||
"Baeldung | Java, Spring and Web Development tutorials",
|
||||
page.getTitleText());
|
||||
}
|
||||
|
||||
}
|
|
@ -1,72 +0,0 @@
|
|||
package com.baeldung.htmlunit;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
|
||||
import com.gargoylesoftware.htmlunit.WebClient;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlForm;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = { TestConfig.class })
|
||||
public class HtmlUnitAndSpringIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
|
||||
private WebClient webClient;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
@Ignore("Related view message.html does not exist check MessageController")
|
||||
public void givenAMessage_whenSent_thenItShows() throws FailingHttpStatusCodeException, MalformedURLException, IOException {
|
||||
final String text = "Hello world!";
|
||||
final HtmlPage page = webClient.getPage("http://localhost/message/showForm");
|
||||
System.out.println(page.asXml());
|
||||
|
||||
final HtmlTextInput messageText = page.getHtmlElementById("message");
|
||||
messageText.setValueAttribute(text);
|
||||
|
||||
final HtmlForm form = page.getForms().get(0);
|
||||
final HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit");
|
||||
final HtmlPage newPage = submit.click();
|
||||
|
||||
final String receivedText = newPage.getHtmlElementById("received").getTextContent();
|
||||
|
||||
Assert.assertEquals(receivedText, text);
|
||||
System.out.println(newPage.asXml());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception {
|
||||
try (final WebClient client = new WebClient()) {
|
||||
webClient.getOptions().setThrowExceptionOnScriptError(false);
|
||||
|
||||
final HtmlPage page = webClient.getPage("http://www.baeldung.com/");
|
||||
Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.htmlunit;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
|
||||
import com.gargoylesoftware.htmlunit.WebClient;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlForm;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = { TestConfig.class })
|
||||
public class HtmlUnitAndSpringTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
|
||||
private WebClient webClient;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
webClient = MockMvcWebClientBuilder
|
||||
.webAppContextSetup(wac).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAMessage_whenSent_thenItShows() throws Exception {
|
||||
String text = "Hello world!";
|
||||
HtmlPage page;
|
||||
|
||||
String url = "http://localhost/message/showForm";
|
||||
page = webClient.getPage(url);
|
||||
|
||||
HtmlTextInput messageText = page.getHtmlElementById("message");
|
||||
messageText.setValueAttribute(text);
|
||||
|
||||
HtmlForm form = page.getForms().get(0);
|
||||
HtmlSubmitInput submit = form.getOneHtmlElementByAttribute(
|
||||
"input", "type", "submit");
|
||||
HtmlPage newPage = submit.click();
|
||||
|
||||
String receivedText = newPage.getHtmlElementById("received")
|
||||
.getTextContent();
|
||||
|
||||
Assert.assertEquals(receivedText, text);
|
||||
}
|
||||
}
|
|
@ -1,21 +0,0 @@
|
|||
package com.baeldung.htmlunit;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.gargoylesoftware.htmlunit.WebClient;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
|
||||
public class HtmlUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception {
|
||||
try (final WebClient webClient = new WebClient()) {
|
||||
webClient.getOptions().setThrowExceptionOnScriptError(false);
|
||||
|
||||
final HtmlPage page = webClient.getPage("http://www.baeldung.com/");
|
||||
Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -5,36 +5,38 @@ import java.util.List;
|
|||
import com.gargoylesoftware.htmlunit.WebClient;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlHeading1;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlHeading2;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
|
||||
public class HtmlUnitWebScraping {
|
||||
|
||||
public static void main(final String[] args) throws Exception {
|
||||
try (final WebClient webClient = new WebClient()) {
|
||||
private WebClient webClient;
|
||||
|
||||
webClient.getOptions().setCssEnabled(false);
|
||||
webClient.getOptions().setJavaScriptEnabled(false);
|
||||
@Before
|
||||
public void init() throws Exception {
|
||||
webClient = new WebClient();
|
||||
}
|
||||
|
||||
final HtmlPage page = webClient.getPage("http://www.baeldung.com/full_archive");
|
||||
final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath("(//ul[@class='car-monthlisting']/li)[1]/a").get(0);
|
||||
@After
|
||||
public void close() throws Exception {
|
||||
webClient.close();
|
||||
}
|
||||
|
||||
System.out.println("Entering: " + latestPostLink.getHrefAttribute());
|
||||
@Test
|
||||
public void givenBaeldungArchive_whenRetrievingArticle_thenHasH1()
|
||||
throws Exception {
|
||||
webClient.getOptions().setCssEnabled(false);
|
||||
webClient.getOptions().setJavaScriptEnabled(false);
|
||||
|
||||
final HtmlPage postPage = latestPostLink.click();
|
||||
String url = "http://www.baeldung.com/full_archive";
|
||||
HtmlPage page = webClient.getPage(url);
|
||||
String xpath = "(//ul[@class='car-monthlisting']/li)[1]/a";
|
||||
HtmlAnchor latestPostLink
|
||||
= (HtmlAnchor) page.getByXPath(xpath).get(0);
|
||||
HtmlPage postPage = latestPostLink.click();
|
||||
|
||||
final HtmlHeading1 heading1 = (HtmlHeading1) postPage.getByXPath("//h1").get(0);
|
||||
System.out.println("Title: " + heading1.getTextContent());
|
||||
|
||||
final List<HtmlHeading2> headings2 = (List<HtmlHeading2>) postPage.getByXPath("//h2");
|
||||
|
||||
final StringBuilder sb = new StringBuilder(heading1.getTextContent());
|
||||
for (final HtmlHeading2 h2 : headings2) {
|
||||
sb.append("\n").append(h2.getTextContent());
|
||||
}
|
||||
|
||||
System.out.println(sb.toString());
|
||||
}
|
||||
}
|
||||
List<HtmlHeading1> h1
|
||||
= (List<HtmlHeading1>) postPage.getByXPath("//h1");
|
||||
|
||||
Assert.assertTrue(h1.size() > 0);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -12,3 +12,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||
- [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout)
|
||||
- [Basic Forms with Spring MVC](http://www.baeldung.com/spring-mvc-form-tutorial)
|
||||
- [Returning Image/Media Data with Spring MVC](http://www.baeldung.com/spring-mvc-image-media-data)
|
||||
- [Geolocation by IP in Java](http://www.baeldung.com/geolocation-by-ip-with-maxmind)
|
||||
|
|
|
@ -13,7 +13,7 @@ public class RawDBDemoGeoIPLocationService{
|
|||
private DatabaseReader dbReader;
|
||||
|
||||
public RawDBDemoGeoIPLocationService() throws IOException {
|
||||
File database = new File("C:\\Users\\Parth Joshi\\Desktop\\GeoLite2-City.mmdb\\GeoLite2-City.mmdb");
|
||||
File database = new File("your-path-to-db-file");
|
||||
dbReader = new DatabaseReader.Builder(database).build();
|
||||
}
|
||||
|
||||
|
|
|
@ -77,8 +77,8 @@
|
|||
<div id="status"></div>
|
||||
|
||||
<div id="map" style="height: 500px; width:100%; position:absolute"></div>
|
||||
<!--AIzaSyDDr65sVtJtlbliOTAeXyZSDPvG9NROjJA -->
|
||||
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA4vsDQWHeOrDnzS98XMXl5hgwA9raaQZ8"
|
||||
|
||||
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-MAPS-API-KEY"
|
||||
async defer></script>
|
||||
</body>
|
||||
</html>
|
|
@ -15,10 +15,10 @@ public class GeoIpIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void givenIP_whenFetchingCity_thenReturnsCityData() throws IOException, GeoIp2Exception {
|
||||
File database = new File("C:\\Users\\Parth Joshi\\Desktop\\GeoLite2-City.mmdb\\GeoLite2-City.mmdb");
|
||||
File database = new File("your-path-to-db-file");
|
||||
DatabaseReader dbReader = new DatabaseReader.Builder(database).build();
|
||||
|
||||
InetAddress ipAddress = InetAddress.getByName("202.47.112.9");
|
||||
InetAddress ipAddress = InetAddress.getByName("your-public-ip");
|
||||
CityResponse response = dbReader.city(ipAddress);
|
||||
|
||||
String countryName = response.getCountry().getName();
|
||||
|
|
|
@ -0,0 +1,76 @@
|
|||
package org.baeldung.web.controller;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.baeldung.web.dto.Foo;
|
||||
import org.baeldung.web.exception.ResourceNotFoundException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/myfoos")
|
||||
public class MyFooController {
|
||||
|
||||
private final Map<Long, Foo> myfoos;
|
||||
|
||||
public MyFooController() {
|
||||
super();
|
||||
myfoos = new HashMap<Long, Foo>();
|
||||
myfoos.put(1L, new Foo(1L, "sample foo"));
|
||||
}
|
||||
|
||||
// API - read
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public Collection<Foo> findAll() {
|
||||
return myfoos.values();
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = { "application/json" })
|
||||
@ResponseBody
|
||||
public Foo findById(@PathVariable final long id) {
|
||||
final Foo foo = myfoos.get(id);
|
||||
if (foo == null) {
|
||||
throw new ResourceNotFoundException();
|
||||
}
|
||||
return foo;
|
||||
}
|
||||
|
||||
// API - write
|
||||
|
||||
@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) {
|
||||
myfoos.put(id, foo);
|
||||
return foo;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST)
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
@ResponseBody
|
||||
public Foo createFoo(@RequestBody final Foo foo, HttpServletResponse response) {
|
||||
myfoos.put(foo.getId(), foo);
|
||||
response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentRequest().path("/" + foo.getId()).toUriString());
|
||||
return foo;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void deleteById(@PathVariable final long id) {
|
||||
myfoos.remove(id);
|
||||
}
|
||||
|
||||
}
|
|
@ -11,6 +11,12 @@ public class Foo {
|
|||
super();
|
||||
}
|
||||
|
||||
public Foo(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Foo(final long id, final String name) {
|
||||
super();
|
||||
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
package org.baeldung.web.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(value = HttpStatus.NOT_FOUND)
|
||||
public class ResourceNotFoundException extends RuntimeException {
|
||||
}
|
|
@ -8,7 +8,7 @@
|
|||
|
||||
<context:component-scan base-package="org.baeldung.web" />
|
||||
|
||||
<mvc:annotation-driven>
|
||||
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" >
|
||||
<mvc:message-converters register-defaults="true">
|
||||
<!--
|
||||
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
|
||||
|
@ -18,6 +18,7 @@
|
|||
<property name="unmarshaller" ref="xstreamMarshaller" />
|
||||
</bean>
|
||||
-->
|
||||
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
|
||||
<bean class="org.baeldung.config.converter.KryoHttpMessageConverter"/>
|
||||
<bean class="org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter"/>
|
||||
</mvc:message-converters>
|
||||
|
@ -43,6 +44,11 @@
|
|||
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
|
||||
|
||||
</bean>
|
||||
|
||||
<bean id="contentNegotiationManager"
|
||||
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
|
||||
<property name="defaultContentType" value="application/json" />
|
||||
</bean>
|
||||
|
||||
|
||||
</beans>
|
||||
|
|
|
@ -1,28 +1,42 @@
|
|||
package org.baeldung.client;
|
||||
|
||||
import static org.apache.commons.codec.binary.Base64.encodeBase64;
|
||||
import static org.baeldung.client.Consts.APPLICATION_PORT;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.CoreMatchers.notNullValue;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.mockito.Matchers.notNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
import java.util.Set;
|
||||
|
||||
import org.baeldung.web.dto.Foo;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.ClientHttpRequestFactory;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.RequestCallback;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.common.base.Charsets;
|
||||
|
||||
public class RestTemplateBasicLiveTest {
|
||||
|
||||
private RestTemplate restTemplate;
|
||||
private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos";
|
||||
private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/myfoos";
|
||||
|
||||
@Before
|
||||
public void beforeTest() {
|
||||
|
@ -33,19 +47,19 @@ public class RestTemplateBasicLiveTest {
|
|||
|
||||
@Test
|
||||
public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException {
|
||||
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
|
||||
final ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
|
||||
|
||||
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException {
|
||||
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
|
||||
final ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
JsonNode root = mapper.readTree(response.getBody());
|
||||
JsonNode name = root.path("name");
|
||||
assertThat(name.asText(), is(notNull()));
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final JsonNode root = mapper.readTree(response.getBody());
|
||||
final JsonNode name = root.path("name");
|
||||
assertThat(name.asText(), notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -56,4 +70,147 @@ public class RestTemplateBasicLiveTest {
|
|||
assertThat(foo.getId(), is(1L));
|
||||
}
|
||||
|
||||
// HEAD, OPTIONS
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() {
|
||||
final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl);
|
||||
|
||||
assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
|
||||
}
|
||||
|
||||
// POST
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() {
|
||||
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
|
||||
final Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
|
||||
assertThat(foo, notNullValue());
|
||||
assertThat(foo.getName(), is("bar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenPostForLocation_thenCreatedLocationIsReturned() {
|
||||
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
|
||||
final URI location = restTemplate.postForLocation(fooResourceUrl, request);
|
||||
assertThat(location, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenPostResource_thenResourceIsCreated() {
|
||||
final RestTemplate template = new RestTemplate();
|
||||
|
||||
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
|
||||
|
||||
final ResponseEntity<Foo> response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
|
||||
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
|
||||
final Foo foo = response.getBody();
|
||||
assertThat(foo, notNullValue());
|
||||
assertThat(foo.getName(), is("bar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() {
|
||||
final Set<HttpMethod> optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl);
|
||||
final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD };
|
||||
|
||||
assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
|
||||
}
|
||||
|
||||
// PUT
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenPutExistingEntity_thenItIsUpdated() {
|
||||
final RestTemplate template = new RestTemplate();
|
||||
final HttpHeaders headers = prepareBasicAuthHeaders();
|
||||
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
|
||||
|
||||
// Create Resource
|
||||
final ResponseEntity<Foo> createResponse = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
|
||||
|
||||
// Update Resource
|
||||
final Foo updatedInstance = new Foo("newName");
|
||||
updatedInstance.setId(createResponse.getBody().getId());
|
||||
final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody().getId();
|
||||
final HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedInstance, headers);
|
||||
template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);
|
||||
|
||||
// Check that Resource was updated
|
||||
final ResponseEntity<Foo> updateResponse = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
|
||||
final Foo foo = updateResponse.getBody();
|
||||
assertThat(foo.getName(), is(updatedInstance.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenPutExistingEntityWithCallback_thenItIsUpdated() {
|
||||
final RestTemplate template = new RestTemplate();
|
||||
final HttpHeaders headers = prepareBasicAuthHeaders();
|
||||
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
|
||||
|
||||
// Create entity
|
||||
ResponseEntity<Foo> response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
|
||||
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
|
||||
|
||||
// Update entity
|
||||
final Foo updatedInstance = new Foo("newName");
|
||||
updatedInstance.setId(response.getBody().getId());
|
||||
final String resourceUrl = fooResourceUrl + '/' + response.getBody().getId();
|
||||
template.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null);
|
||||
|
||||
// Check that entity was updated
|
||||
response = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
|
||||
final Foo foo = response.getBody();
|
||||
assertThat(foo.getName(), is(updatedInstance.getName()));
|
||||
}
|
||||
|
||||
// DELETE
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenCallDelete_thenEntityIsRemoved() {
|
||||
final Foo foo = new Foo("remove me");
|
||||
final ResponseEntity<Foo> response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class);
|
||||
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
|
||||
|
||||
final String entityUrl = fooResourceUrl + "/" + response.getBody().getId();
|
||||
restTemplate.delete(entityUrl);
|
||||
try {
|
||||
restTemplate.getForEntity(entityUrl, Foo.class);
|
||||
fail();
|
||||
} catch (final HttpClientErrorException ex) {
|
||||
assertThat(ex.getStatusCode(), is(HttpStatus.NOT_FOUND));
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private HttpHeaders prepareBasicAuthHeaders() {
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
final String encodedLogPass = getBase64EncodedLogPass();
|
||||
headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass);
|
||||
return headers;
|
||||
}
|
||||
|
||||
private String getBase64EncodedLogPass() {
|
||||
final String logPass = "user1:user1Pass";
|
||||
final byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII));
|
||||
return new String(authHeaderBytes, Charsets.US_ASCII);
|
||||
}
|
||||
|
||||
private RequestCallback requestCallback(final Foo updatedInstance) {
|
||||
return clientHttpRequest -> {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.writeValue(clientHttpRequest.getBody(), updatedInstance);
|
||||
clientHttpRequest.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
|
||||
clientHttpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass());
|
||||
};
|
||||
}
|
||||
|
||||
// Simply setting restTemplate timeout using ClientHttpRequestFactory
|
||||
|
||||
ClientHttpRequestFactory getSimpleClientHttpRequestFactory() {
|
||||
final int timeout = 5;
|
||||
final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||
clientHttpRequestFactory.setConnectTimeout(timeout * 1000);
|
||||
return clientHttpRequestFactory;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
package org.baeldung.okhttp;
|
||||
|
||||
import static org.baeldung.client.Consts.APPLICATION_PORT;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
@ -7,9 +8,6 @@ import static org.junit.Assert.assertThat;
|
|||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.baeldung.okhttp.ProgressRequestWrapper;
|
||||
import org.junit.Test;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.MultipartBody;
|
||||
|
@ -18,28 +16,29 @@ import okhttp3.Request;
|
|||
import okhttp3.RequestBody;
|
||||
import okhttp3.Response;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class OkHttpFileUploadingLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
||||
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
|
||||
|
||||
OkHttpClient client;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUploadFile_thenCorrect() throws IOException {
|
||||
|
||||
OkHttpClient client = new OkHttpClient();
|
||||
final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
|
||||
|
||||
RequestBody requestBody = new MultipartBody.Builder()
|
||||
.setType(MultipartBody.FORM)
|
||||
.addFormDataPart("file", "file.txt",
|
||||
RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
|
||||
.build();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(requestBody).build();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/users/upload")
|
||||
.post(requestBody)
|
||||
.build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
@ -47,30 +46,18 @@ public class OkHttpFileUploadingLiveTest {
|
|||
@Test
|
||||
public void whenGetUploadFileProgress_thenCorrect() throws IOException {
|
||||
|
||||
OkHttpClient client = new OkHttpClient();
|
||||
final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
|
||||
|
||||
RequestBody requestBody = new MultipartBody.Builder()
|
||||
.setType(MultipartBody.FORM)
|
||||
.addFormDataPart("file", "file.txt",
|
||||
RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
|
||||
.build();
|
||||
final ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> {
|
||||
|
||||
|
||||
ProgressRequestWrapper.ProgressListener listener = (bytesWritten, contentLength) -> {
|
||||
|
||||
float percentage = 100f * bytesWritten / contentLength;
|
||||
final float percentage = (100f * bytesWritten) / contentLength;
|
||||
assertFalse(Float.compare(percentage, 100) > 0);
|
||||
};
|
||||
});
|
||||
|
||||
ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, listener);
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(countingBody).build();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/users/upload")
|
||||
.post(countingBody)
|
||||
.build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
|
||||
|
|
|
@ -1,71 +1,74 @@
|
|||
package org.baeldung.okhttp;
|
||||
|
||||
import okhttp3.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.baeldung.client.Consts.APPLICATION_PORT;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.Callback;
|
||||
import okhttp3.HttpUrl;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class OkHttpGetLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
||||
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
|
||||
|
||||
OkHttpClient client;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequest_thenCorrect() throws IOException {
|
||||
final 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);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException {
|
||||
|
||||
OkHttpClient client = new OkHttpClient();
|
||||
|
||||
HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder();
|
||||
final HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder();
|
||||
urlBuilder.addQueryParameter("id", "1");
|
||||
|
||||
String url = urlBuilder.build().toString();
|
||||
final String url = urlBuilder.build().toString();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(url)
|
||||
.build();
|
||||
final Request request = new Request.Builder().url(url).build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException {
|
||||
final 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);
|
||||
final Call call = client.newCall(request);
|
||||
|
||||
call.enqueue(new Callback() {
|
||||
@Override
|
||||
public void onResponse(Call call, Response response) throws IOException {
|
||||
System.out.println("OK");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call call, IOException e) {
|
||||
fail();
|
||||
fail();
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
@ -2,6 +2,7 @@ package org.baeldung.okhttp;
|
|||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import okhttp3.Call;
|
||||
|
@ -13,11 +14,16 @@ public class OkHttpHeaderLiveTest {
|
|||
|
||||
private static final String SAMPLE_URL = "http://www.github.com";
|
||||
|
||||
OkHttpClient client;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSetHeader_thenCorrect() throws IOException {
|
||||
|
||||
OkHttpClient client = new OkHttpClient();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(SAMPLE_URL)
|
||||
.addHeader("Content-Type", "application/json")
|
||||
|
@ -31,7 +37,7 @@ public class OkHttpHeaderLiveTest {
|
|||
@Test
|
||||
public void whenSetDefaultHeader_thenCorrect() throws IOException {
|
||||
|
||||
OkHttpClient client = new OkHttpClient.Builder()
|
||||
OkHttpClient clientWithInterceptor = new OkHttpClient.Builder()
|
||||
.addInterceptor(new DefaultContentTypeInterceptor("application/json"))
|
||||
.build();
|
||||
|
||||
|
@ -39,10 +45,8 @@ public class OkHttpHeaderLiveTest {
|
|||
.url(SAMPLE_URL)
|
||||
.build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Call call = clientWithInterceptor.newCall(request);
|
||||
Response response = call.execute();
|
||||
response.close();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
package org.baeldung.okhttp;
|
||||
|
||||
import okhttp3.*;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import static org.baeldung.client.Consts.APPLICATION_PORT;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
@ -11,37 +8,48 @@ import java.util.concurrent.Executors;
|
|||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import okhttp3.Cache;
|
||||
import okhttp3.Call;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class OkHttpMiscLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
||||
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
|
||||
private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class);
|
||||
|
||||
OkHttpClient client;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSetRequestTimeout_thenFail() throws IOException {
|
||||
final OkHttpClient clientWithTimeout = new OkHttpClient.Builder().readTimeout(1, TimeUnit.SECONDS).build();
|
||||
|
||||
OkHttpClient client = new OkHttpClient.Builder()
|
||||
.readTimeout(1, TimeUnit.SECONDS)
|
||||
.build();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
||||
.build();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
||||
.build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = clientWithTimeout.newCall(request);
|
||||
final Response response = call.execute();
|
||||
response.close();
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void whenCancelRequest_thenCorrect() throws IOException {
|
||||
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
|
||||
|
||||
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
|
||||
|
||||
OkHttpClient client = new OkHttpClient();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
||||
.build();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay.
|
||||
.build();
|
||||
|
||||
final int seconds = 1;
|
||||
final long startNanos = System.nanoTime();
|
||||
|
@ -51,42 +59,38 @@ public class OkHttpMiscLiveTest {
|
|||
// Schedule a job to cancel the call in 1 second.
|
||||
executor.schedule(() -> {
|
||||
|
||||
logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f);
|
||||
logger.debug("Canceling call: " + ((System.nanoTime() - startNanos) / 1e9f));
|
||||
call.cancel();
|
||||
logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f);
|
||||
logger.debug("Canceled call: " + ((System.nanoTime() - startNanos) / 1e9f));
|
||||
|
||||
}, seconds, TimeUnit.SECONDS);
|
||||
|
||||
logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f);
|
||||
Response response = call.execute();
|
||||
logger.debug("Call completed: " + (System.nanoTime() - startNanos) / 1e9f, response);
|
||||
logger.debug("Executing call: " + ((System.nanoTime() - startNanos) / 1e9f));
|
||||
final Response response = call.execute();
|
||||
logger.debug("Call completed: " + ((System.nanoTime() - startNanos) / 1e9f), response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSetResponseCache_thenCorrect() throws IOException {
|
||||
public void whenSetResponseCache_thenCorrect() throws IOException {
|
||||
|
||||
int cacheSize = 10 * 1024 * 1024; // 10 MiB
|
||||
File cacheDirectory = new File("src/test/resources/cache");
|
||||
Cache cache = new Cache(cacheDirectory, cacheSize);
|
||||
final int cacheSize = 10 * 1024 * 1024; // 10 MiB
|
||||
final File cacheDirectory = new File("src/test/resources/cache");
|
||||
final Cache cache = new Cache(cacheDirectory, cacheSize);
|
||||
|
||||
OkHttpClient client = new OkHttpClient.Builder()
|
||||
.cache(cache)
|
||||
.build();
|
||||
final OkHttpClient clientCached = new OkHttpClient.Builder().cache(cache).build();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url("http://publicobject.com/helloworld.txt")
|
||||
.build();
|
||||
final Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();
|
||||
|
||||
Response response1 = client.newCall(request).execute();
|
||||
final Response response1 = clientCached.newCall(request).execute();
|
||||
logResponse(response1);
|
||||
|
||||
Response response2 = client.newCall(request).execute();
|
||||
final Response response2 = clientCached.newCall(request).execute();
|
||||
logResponse(response2);
|
||||
}
|
||||
|
||||
private void logResponse(Response response) throws IOException {
|
||||
|
||||
logger.debug("Response response: " + response);
|
||||
logger.debug("Response response: " + response);
|
||||
logger.debug("Response cache response: " + response.cacheResponse());
|
||||
logger.debug("Response network response: " + response.networkResponse());
|
||||
logger.debug("Response responseBody: " + response.body().string());
|
||||
|
|
|
@ -1,13 +1,12 @@
|
|||
package org.baeldung.okhttp;
|
||||
|
||||
import static org.baeldung.client.Consts.APPLICATION_PORT;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.Credentials;
|
||||
import okhttp3.FormBody;
|
||||
|
@ -18,91 +17,69 @@ import okhttp3.Request;
|
|||
import okhttp3.RequestBody;
|
||||
import okhttp3.Response;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class OkHttpPostingLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:8080/spring-rest";
|
||||
private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest";
|
||||
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
|
||||
|
||||
OkHttpClient client;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
|
||||
client = new OkHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendPostRequest_thenCorrect() throws IOException {
|
||||
final RequestBody formBody = new FormBody.Builder().add("username", "test").add("password", "test").build();
|
||||
|
||||
OkHttpClient client = new OkHttpClient();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users").post(formBody).build();
|
||||
|
||||
RequestBody formBody = new FormBody.Builder()
|
||||
.add("username", "test")
|
||||
.add("password", "test")
|
||||
.build();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/users")
|
||||
.post(formBody)
|
||||
.build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException {
|
||||
final String postBody = "test post";
|
||||
|
||||
String postBody = "test post";
|
||||
final Request request = new Request.Builder().url(URL_SECURED_BY_BASIC_AUTHENTICATION).addHeader("Authorization", Credentials.basic("test", "test")).post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody)).build();
|
||||
|
||||
OkHttpClient client = new OkHttpClient();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(URL_SECURED_BY_BASIC_AUTHENTICATION)
|
||||
.addHeader("Authorization", Credentials.basic("test", "test"))
|
||||
.post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody))
|
||||
.build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostJson_thenCorrect() throws IOException {
|
||||
final String json = "{\"id\":1,\"name\":\"John\"}";
|
||||
|
||||
OkHttpClient client = new OkHttpClient();
|
||||
final RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
|
||||
|
||||
String json = "{\"id\":1,\"name\":\"John\"}";
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
|
||||
|
||||
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/users/detail")
|
||||
.post(body)
|
||||
.build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendMultipartRequest_thenCorrect() throws IOException {
|
||||
final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("username", "test").addFormDataPart("password", "test")
|
||||
.addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
|
||||
|
||||
OkHttpClient client = new OkHttpClient();
|
||||
final Request request = new Request.Builder().url(BASE_URL + "/users/multipart").post(requestBody).build();
|
||||
|
||||
RequestBody requestBody = new MultipartBody.Builder()
|
||||
.setType(MultipartBody.FORM)
|
||||
.addFormDataPart("username", "test")
|
||||
.addFormDataPart("password", "test")
|
||||
.addFormDataPart("file", "file.txt",
|
||||
RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt")))
|
||||
.build();
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(BASE_URL + "/users/multipart")
|
||||
.post(requestBody)
|
||||
.build();
|
||||
|
||||
Call call = client.newCall(request);
|
||||
Response response = call.execute();
|
||||
final Call call = client.newCall(request);
|
||||
final Response response = call.execute();
|
||||
|
||||
assertThat(response.code(), equalTo(200));
|
||||
}
|
||||
|
|
|
@ -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,5 +1,6 @@
|
|||
package org.baeldung.web.test;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
import org.junit.Test;
|
||||
|
@ -31,7 +32,7 @@ public class RequestMappingLiveTest {
|
|||
|
||||
@Test
|
||||
public void givenAcceptHeader_whenGetFoos_thenOk() {
|
||||
RestAssured.given().accept("application/json").get(BASE_URI + "foos").then().assertThat().body(equalTo("Get some Foos with Header New"));
|
||||
RestAssured.given().accept("application/json").get(BASE_URI + "foos").then().assertThat().body(containsString("Get some Foos with Header New"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -1,17 +1,39 @@
|
|||
package org.baeldung.security.filter.configuration;
|
||||
|
||||
import org.baeldung.security.basic.MyBasicAuthenticationEntryPoint;
|
||||
import org.baeldung.security.filter.CustomFilter;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
private MyBasicAuthenticationEntryPoint authenticationEntryPoint;
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.inMemoryAuthentication()
|
||||
.withUser("user1").password("user1Pass")
|
||||
.authorities("ROLE_USER");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
|
||||
}
|
||||
http.authorizeRequests()
|
||||
.antMatchers("/securityNone").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.httpBasic()
|
||||
.authenticationEntryPoint(authenticationEntryPoint);
|
||||
|
||||
http.addFilterAfter(new CustomFilter(),
|
||||
BasicAuthenticationFilter.class);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,11 +2,10 @@ package org.baeldung.spring;
|
|||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.ImportResource;
|
||||
|
||||
@Configuration
|
||||
@ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||
@ComponentScan("org.baeldung.security")
|
||||
//@ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||
public class SecSecurityConfig {
|
||||
|
||||
public SecSecurityConfig() {
|
||||
|
|
|
@ -1,2 +1,11 @@
|
|||
###The Course
|
||||
=========
|
||||
## Spring Security Authentication/Authorization Example Project
|
||||
|
||||
##The Course
|
||||
The "REST With Spring" Classes: http://github.learnspringsecurity.com
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring Security Manual Authentication](http://www.baeldung.com/spring-security-authentication)
|
||||
|
||||
### Build the Project
|
||||
mvn clean install
|
||||
|
|
|
@ -13,7 +13,7 @@
|
|||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.3.3.RELEASE</version>
|
||||
<version>1.4.2.RELEASE</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
|
|
@ -8,9 +8,11 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
|||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@Profile("!manual")
|
||||
public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
public MvcConfig() {
|
||||
|
|
|
@ -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.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@Profile("!manual")
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
|
|
|
@ -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>
|
|
@ -1,393 +1,400 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-security-rest</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-security-rest</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
<name>spring-security-rest</name>
|
||||
<packaging>war</packaging>
|
||||
<name>spring-security-rest</name>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<dependencies>
|
||||
<dependencies>
|
||||
|
||||
<!-- Spring Security -->
|
||||
<!-- Spring Security -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring -->
|
||||
<!-- Spring -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-jdbc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-beans</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-aop</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-tx</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-expression</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-jdbc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-beans</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-aop</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-tx</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-expression</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring HATEOAS -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.hateoas</groupId>
|
||||
<artifactId>spring-hateoas</artifactId>
|
||||
<version>${org.springframework.hateoas.version}</version>
|
||||
</dependency>
|
||||
<!-- Spring HATEOAS -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.hateoas</groupId>
|
||||
<artifactId>spring-hateoas</artifactId>
|
||||
<version>${org.springframework.hateoas.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- web -->
|
||||
<!-- web -->
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>${javax.servlet-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>${javax.servlet-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>${jstl.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>${jstl.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>${javax.validation.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>${javax.validation.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- marshalling -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!-- marshalling -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- util -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<!-- util -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.jayway.restassured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.restassured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- swagger -->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger2</artifactId>
|
||||
<version>${springfox-swagger.version}</version>
|
||||
</dependency>
|
||||
<!-- swagger -->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger2</artifactId>
|
||||
<version>${springfox-swagger.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${springfox-swagger.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${springfox-swagger.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
|
||||
<dependency>
|
||||
<groupId>commons-fileupload</groupId>
|
||||
<artifactId>commons-fileupload</artifactId>
|
||||
<version>1.3.2</version>
|
||||
</dependency>
|
||||
|
||||
<build>
|
||||
<finalName>spring-security-rest</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</dependencies>
|
||||
|
||||
<plugins>
|
||||
<build>
|
||||
<finalName>spring-security-rest</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<systemPropertyVariables>
|
||||
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<version>${cargo-maven2-plugin.version}</version>
|
||||
<configuration>
|
||||
<container>
|
||||
<containerId>jetty8x</containerId>
|
||||
<type>embedded</type>
|
||||
<systemProperties>
|
||||
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
|
||||
</systemProperties>
|
||||
</container>
|
||||
<configuration>
|
||||
<properties>
|
||||
<cargo.servlet.port>8082</cargo.servlet.port>
|
||||
</properties>
|
||||
</configuration>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<systemPropertyVariables>
|
||||
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<version>${cargo-maven2-plugin.version}</version>
|
||||
<configuration>
|
||||
<container>
|
||||
<containerId>jetty8x</containerId>
|
||||
<type>embedded</type>
|
||||
<systemProperties>
|
||||
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
|
||||
</systemProperties>
|
||||
</container>
|
||||
<configuration>
|
||||
<properties>
|
||||
<cargo.servlet.port>8082</cargo.servlet.port>
|
||||
</properties>
|
||||
</configuration>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</build>
|
||||
</plugins>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>live</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>start-server</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>start</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>stop-server</id>
|
||||
<phase>post-integration-test</phase>
|
||||
<goals>
|
||||
<goal>stop</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</build>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>none</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*LiveTest.java</include>
|
||||
</includes>
|
||||
<systemPropertyVariables>
|
||||
<webTarget>cargo</webTarget>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>live</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.cargo</groupId>
|
||||
<artifactId>cargo-maven2-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>start-server</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>start</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>stop-server</id>
|
||||
<phase>post-integration-test</phase>
|
||||
<goals>
|
||||
<goal>stop</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
|
||||
<properties>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
|
||||
<org.springframework.security.version>4.0.4.RELEASE</org.springframework.security.version>
|
||||
<org.springframework.hateoas.version>0.19.0.RELEASE</org.springframework.hateoas.version>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>none</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*LiveTest.java</include>
|
||||
</includes>
|
||||
<systemPropertyVariables>
|
||||
<webTarget>cargo</webTarget>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<!-- persistence -->
|
||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.2.2.Final</hibernate-validator.version>
|
||||
<javax.servlet-api.version>3.0.1</javax.servlet-api.version>
|
||||
<javax.validation.version>1.1.0.Final</javax.validation.version>
|
||||
<jstl.version>1.2</jstl.version>
|
||||
<jackson.version>2.7.8</jackson.version>
|
||||
<properties>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
|
||||
<org.springframework.security.version>4.0.4.RELEASE</org.springframework.security.version>
|
||||
<org.springframework.hateoas.version>0.19.0.RELEASE</org.springframework.hateoas.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
<!-- persistence -->
|
||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!-- swagger -->
|
||||
<springfox-swagger.version>2.4.0</springfox-swagger.version>
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.2.2.Final</hibernate-validator.version>
|
||||
<javax.servlet-api.version>3.0.1</javax.servlet-api.version>
|
||||
<javax.validation.version>1.1.0.Final</javax.validation.version>
|
||||
<jstl.version>1.2</jstl.version>
|
||||
<jackson.version>2.7.8</jackson.version>
|
||||
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
<httpclient.version>4.5</httpclient.version>
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
|
||||
<!-- Maven plugins -->
|
||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
|
||||
<!-- swagger -->
|
||||
<springfox-swagger.version>2.4.0</springfox-swagger.version>
|
||||
|
||||
</properties>
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
<httpclient.version>4.5</httpclient.version>
|
||||
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
|
||||
<!-- Maven plugins -->
|
||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
|
||||
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
package org.baeldung.web.controller;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Controller
|
||||
public class AsyncController {
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, value = "/upload")
|
||||
public Callable<Boolean> processUpload(final MultipartFile file) {
|
||||
|
||||
return new Callable<Boolean>() {
|
||||
public Boolean call() throws Exception {
|
||||
// ...
|
||||
return true;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
|
@ -1,6 +1,10 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd" >
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
|
||||
|
||||
<bean id="multipartResolver"
|
||||
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
|
||||
<property name="maxUploadSize" value="1000000" />
|
||||
</bean>
|
||||
</beans>
|
|
@ -1,54 +1,57 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
|
||||
xsi:schemaLocation="
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
|
||||
xsi:schemaLocation="
|
||||
http://java.sun.com/xml/ns/javaee
|
||||
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
|
||||
>
|
||||
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
|
||||
id="WebApp_ID" version="3.0">
|
||||
|
||||
<display-name>Spring MVC Application</display-name>
|
||||
<display-name>Spring MVC Application</display-name>
|
||||
|
||||
<!-- Spring root -->
|
||||
<context-param>
|
||||
<param-name>contextClass</param-name>
|
||||
<param-value>
|
||||
<!-- Spring root -->
|
||||
<context-param>
|
||||
<param-name>contextClass</param-name>
|
||||
<param-value>
|
||||
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
|
||||
</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>org.baeldung.spring</param-value>
|
||||
</context-param>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>org.baeldung.spring</param-value>
|
||||
</context-param>
|
||||
|
||||
<listener>
|
||||
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
|
||||
</listener>
|
||||
<listener>
|
||||
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
|
||||
</listener>
|
||||
|
||||
<!-- Spring child -->
|
||||
<servlet>
|
||||
<servlet-name>api</servlet-name>
|
||||
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
|
||||
<init-param>
|
||||
<param-name>throwExceptionIfNoHandlerFound</param-name>
|
||||
<param-value>true</param-value>
|
||||
</init-param>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>api</servlet-name>
|
||||
<url-pattern>/api/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
<!-- Spring child -->
|
||||
<servlet>
|
||||
<servlet-name>api</servlet-name>
|
||||
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
|
||||
<init-param>
|
||||
<param-name>throwExceptionIfNoHandlerFound</param-name>
|
||||
<param-value>true</param-value>
|
||||
</init-param>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>api</servlet-name>
|
||||
<url-pattern>/api/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<!-- Spring Security -->
|
||||
<filter>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
|
||||
</filter>
|
||||
<filter-mapping>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
<!-- Spring Security -->
|
||||
<filter>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
|
||||
</filter>
|
||||
<filter-mapping>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
<dispatcher>REQUEST</dispatcher>
|
||||
<dispatcher>ASYNC</dispatcher>
|
||||
</filter-mapping>
|
||||
|
||||
<!-- <welcome-file-list> -->
|
||||
<!-- <welcome-file>index.html</welcome-file> -->
|
||||
<!-- </welcome-file-list> -->
|
||||
<!-- <welcome-file-list> -->
|
||||
<!-- <welcome-file>index.html</welcome-file> -->
|
||||
<!-- </welcome-file-list> -->
|
||||
|
||||
</web-app>
|
|
@ -0,0 +1,51 @@
|
|||
package org.baeldung.web;
|
||||
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.baeldung.spring.ClientWebConfig;
|
||||
import org.baeldung.spring.SecurityJavaConfig;
|
||||
import org.baeldung.spring.WebConfig;
|
||||
import org.baeldung.web.controller.AsyncController;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.mock.web.MockHttpSession;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class})
|
||||
public class AsyncControllerTest {
|
||||
|
||||
@Autowired
|
||||
WebApplicationContext wac;
|
||||
@Autowired
|
||||
MockHttpSession session;
|
||||
|
||||
@Mock
|
||||
AsyncController controller;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessUpload() throws Exception {
|
||||
MockMultipartFile jsonFile = new MockMultipartFile("json", "", "application/json",
|
||||
"{\"json\": \"someValue\"}".getBytes());
|
||||
mockMvc.perform(MockMvcRequestBuilders.fileUpload("/upload").file(jsonFile)).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
}
|
|
@ -1,10 +1,19 @@
|
|||
package org.baeldung.web;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.multipart.MultipartResolver;
|
||||
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan({ "org.baeldung.web" })
|
||||
public class TestConfig {
|
||||
|
||||
@Bean
|
||||
public MultipartResolver multipartResolver() {
|
||||
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
|
||||
return multipartResolver;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,76 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>jetty-session-demo</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.4.0.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jetty</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.session</groupId>
|
||||
<artifactId>spring-session</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>Brixton.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue