diff --git a/aspectj/pom.xml b/aspectj/pom.xml
index 2a1cff11c8..1c409483ec 100644
--- a/aspectj/pom.xml
+++ b/aspectj/pom.xml
@@ -98,13 +98,14 @@
compile
- test-compile
+ test-compile
-
+
+ -->
diff --git a/aspectj/src/main/java/com/baeldung/aspectj/Account.java b/aspectj/src/main/java/com/baeldung/aspectj/Account.java
index 59cab72ebf..bc9ca375aa 100644
--- a/aspectj/src/main/java/com/baeldung/aspectj/Account.java
+++ b/aspectj/src/main/java/com/baeldung/aspectj/Account.java
@@ -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;
}
}
diff --git a/aspectj/src/main/java/com/baeldung/aspectj/AccountAspect.aj b/aspectj/src/main/java/com/baeldung/aspectj/AccountAspect.aj
index 2ddf03192b..8423c1da97 100644
--- a/aspectj/src/main/java/com/baeldung/aspectj/AccountAspect.aj
+++ b/aspectj/src/main/java/com/baeldung/aspectj/AccountAspect.aj
@@ -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) {
diff --git a/core-java/src/main/java/com/baeldung/generics/Building.java b/core-java/src/main/java/com/baeldung/generics/Building.java
new file mode 100644
index 0000000000..a34dcd3c7e
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/generics/Building.java
@@ -0,0 +1,12 @@
+package com.baeldung.generics;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class Building {
+ private static final Logger LOGGER = LoggerFactory.getLogger(Building.class);
+
+ public void paint() {
+ LOGGER.info("Painting Building");
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/generics/Generics.java b/core-java/src/main/java/com/baeldung/generics/Generics.java
index 69c7baddd3..e0536ca02e 100644
--- a/core-java/src/main/java/com/baeldung/generics/Generics.java
+++ b/core-java/src/main/java/com/baeldung/generics/Generics.java
@@ -1,23 +1,31 @@
package com.baeldung.generics;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import java.util.function.Function;
+import java.util.stream.Collectors;
public class Generics {
// definition of a generic method
public static List fromArrayToList(T[] a) {
- List list = new ArrayList<>();
- Arrays.stream(a).forEach(list::add);
- return list;
+ return Arrays.stream(a).collect(Collectors.toList());
+ }
+
+ // definition of a generic method
+ public static List fromArrayToList(T[] a, Function mapperFunction) {
+ return Arrays.stream(a).map(mapperFunction).collect(Collectors.toList());
}
// example of a generic method that has Number as an upper bound for T
public static List fromArrayToListWithUpperBound(T[] a) {
- List list = new ArrayList<>();
- Arrays.stream(a).forEach(list::add);
- return list;
+ return Arrays.stream(a).collect(Collectors.toList());
}
-}
+ // example of a generic method with a wild card, this method can be used
+ // with a list of any subtype of Building
+ public static void paintAllBuildings(List extends Building> buildings) {
+ buildings.forEach(Building::paint);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/generics/House.java b/core-java/src/main/java/com/baeldung/generics/House.java
new file mode 100644
index 0000000000..88e7d2710a
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/generics/House.java
@@ -0,0 +1,12 @@
+package com.baeldung.generics;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class House extends Building {
+ private static final Logger LOGGER = LoggerFactory.getLogger(House.class);
+
+ public void paint() {
+ LOGGER.info("Painting House");
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/hashing/SHA256Hashing.java b/core-java/src/main/java/com/baeldung/hashing/SHA256Hashing.java
index 9c8fc86e7a..4fa164cadc 100644
--- a/core-java/src/main/java/com/baeldung/hashing/SHA256Hashing.java
+++ b/core-java/src/main/java/com/baeldung/hashing/SHA256Hashing.java
@@ -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();
diff --git a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java
index 15910abf9b..b1b790f541 100644
--- a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java
+++ b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java
@@ -1,23 +1,19 @@
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;
-import java.io.IOException;
-import java.nio.file.FileVisitResult;
-import java.nio.file.FileVisitor;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.attribute.BasicFileAttributes;
-
public class FileSearchExample implements FileVisitor {
- private static String FILE_NAME;
- private static Path START_DIR;
+ private final String fileName;
+ private final Path startDir;
public FileSearchExample(String fileName, Path startingDir) {
- FILE_NAME = fileName;
- START_DIR = startingDir;
+ this.fileName = fileName;
+ startDir = startingDir;
}
@Override
@@ -28,7 +24,7 @@ public class FileSearchExample implements FileVisitor {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String fileName = file.getFileName().toString();
- if (FILE_NAME.equals(fileName)) {
+ if (this.fileName.equals(fileName)) {
System.out.println("File found: " + file.toString());
return TERMINATE;
}
@@ -43,9 +39,9 @@ public class FileSearchExample implements FileVisitor {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
- boolean finishedSearch = Files.isSameFile(dir, START_DIR);
+ boolean finishedSearch = Files.isSameFile(dir, startDir);
if (finishedSearch) {
- System.out.println("File:" + FILE_NAME + " not found");
+ System.out.println("File:" + fileName + " not found");
return TERMINATE;
}
return CONTINUE;
@@ -57,4 +53,4 @@ public class FileSearchExample implements FileVisitor {
Files.walkFileTree(startingDir, crawler);
}
-}
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java
index 360d6d0689..aa769b5091 100644
--- a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java
+++ b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java
@@ -19,12 +19,12 @@ public class FileVisitorImpl implements FileVisitor {
}
@Override
- public FileVisitResult visitFileFailed(Path file, IOException exc) {
+ public FileVisitResult visitFileFailed(Path file, IOException exc) {
return null;
}
@Override
- public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
+ public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return null;
}
-}
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/java_8_features/Person.java b/core-java/src/main/java/com/baeldung/java_8_features/Person.java
new file mode 100644
index 0000000000..82b6819699
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java_8_features/Person.java
@@ -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 getName() {
+ return Optional.ofNullable(name);
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Optional getAge() {
+ return Optional.ofNullable(age);
+ }
+
+ public void setAge(int age) {
+ this.age = age;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ public Optional getPassword() {
+ return Optional.ofNullable(password);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java b/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java
index 3319716dc6..16d0cb570b 100644
--- a/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java
@@ -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();
diff --git a/core-java/src/test/java/com/baeldung/generics/GenericsTest.java b/core-java/src/test/java/com/baeldung/generics/GenericsTest.java
index 9eb459ccb5..6cbc0eba05 100644
--- a/core-java/src/test/java/com/baeldung/generics/GenericsTest.java
+++ b/core-java/src/test/java/com/baeldung/generics/GenericsTest.java
@@ -2,26 +2,36 @@ package com.baeldung.generics;
import org.junit.Test;
+import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
public class GenericsTest {
// testing the generic method with Integer
@Test
public void givenArrayOfIntegers_thanListOfIntegersReturnedOK() {
- Integer[] intArray = {1, 2, 3, 4, 5};
+ Integer[] intArray = { 1, 2, 3, 4, 5 };
List list = Generics.fromArrayToList(intArray);
assertThat(list, hasItems(intArray));
}
+ // testing the generic method with Integer and String type
+ @Test
+ public void givenArrayOfIntegers_thanListOfStringReturnedOK() {
+ Integer[] intArray = { 1, 2, 3, 4, 5 };
+ List stringList = Generics.fromArrayToList(intArray, Object::toString);
+ assertThat(stringList, hasItems("1", "2", "3", "4", "5"));
+ }
+
// testing the generic method with String
@Test
public void givenArrayOfStrings_thanListOfStringsReturnedOK() {
- String[] stringArray = {"hello1", "hello2", "hello3", "hello4", "hello5"};
+ String[] stringArray = { "hello1", "hello2", "hello3", "hello4", "hello5" };
List list = Generics.fromArrayToList(stringArray);
assertThat(list, hasItems(stringArray));
@@ -32,10 +42,28 @@ public class GenericsTest {
// extend Number it will fail to compile
@Test
public void givenArrayOfIntegersAndNumberUpperBound_thanListOfIntegersReturnedOK() {
- Integer[] intArray = {1, 2, 3, 4, 5};
+ Integer[] intArray = { 1, 2, 3, 4, 5 };
List list = Generics.fromArrayToListWithUpperBound(intArray);
assertThat(list, hasItems(intArray));
}
-}
+ // testing paintAllBuildings method with a subtype of Building, the method
+ // will work with all subtypes of Building
+ @Test
+ public void givenSubTypeOfWildCardBoundedGenericType_thanPaintingOK() {
+ try {
+ List subBuildingsList = new ArrayList<>();
+ subBuildingsList.add(new Building());
+ subBuildingsList.add(new House());
+
+ // prints
+ // Painting Building
+ // Painting House
+ Generics.paintAllBuildings(subBuildingsList);
+ } catch (Exception e) {
+ fail();
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/hashing/SHA256HashingTest.java b/core-java/src/test/java/com/baeldung/hashing/SHA256HashingTest.java
index dc496d589b..ce77b824d8 100644
--- a/core-java/src/test/java/com/baeldung/hashing/SHA256HashingTest.java
+++ b/core-java/src/test/java/com/baeldung/hashing/SHA256HashingTest.java
@@ -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 {
diff --git a/core-java/src/test/java/com/baeldung/java/conversion/StringConversionTest.java b/core-java/src/test/java/com/baeldung/java/conversion/StringConversionTest.java
index 09cacd0a29..9a4ac053af 100644
--- a/core-java/src/test/java/com/baeldung/java/conversion/StringConversionTest.java
+++ b/core-java/src/test/java/com/baeldung/java/conversion/StringConversionTest.java
@@ -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);
diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java
index ea35130f49..da586706a2 100644
--- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java
+++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java
@@ -41,17 +41,21 @@ public class AsyncEchoClient {
}
public String sendMessage(String message) {
- byte[] byteMsg = new String(message).getBytes();
+ byte[] byteMsg = message.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(byteMsg);
Future writeResult = client.write(buffer);
- while (!writeResult.isDone()) {
- // do nothing
+ try {
+ writeResult.get();
+ } catch (Exception e) {
+ e.printStackTrace();
}
buffer.flip();
Future readResult = client.read(buffer);
- while (!readResult.isDone()) {
-
+ try {
+ readResult.get();
+ } catch (Exception e) {
+ e.printStackTrace();
}
String echo = new String(buffer.array()).trim();
buffer.clear();
@@ -66,11 +70,11 @@ public class AsyncEchoClient {
}
}
- public static void main(String[] args) throws IOException {
+ public static void main(String[] args) throws Exception {
AsyncEchoClient client = AsyncEchoClient.getInstance();
client.start();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String line = null;
+ String line;
System.out.println("Message to server:");
while ((line = br.readLine()) != null) {
String response = client.sendMessage(line);
@@ -79,4 +83,4 @@ public class AsyncEchoClient {
}
}
-}
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java
index 0e58cb5f10..01873b344a 100644
--- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java
+++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java
@@ -34,9 +34,9 @@ public class AsyncEchoServer {
ByteBuffer buffer = ByteBuffer.allocate(32);
Future readResult = clientChannel.read(buffer);
- while (!readResult.isDone()) {
- // do nothing
- }
+ // do some computation
+
+ readResult.get();
buffer.flip();
String message = new String(buffer.array()).trim();
@@ -45,9 +45,9 @@ public class AsyncEchoServer {
}
buffer = ByteBuffer.wrap(new String(message).getBytes());
Future writeResult = clientChannel.write(buffer);
- while (!writeResult.isDone()) {
- // do nothing
- }
+
+ // do some computation
+ writeResult.get();
buffer.clear();
} // while()
@@ -66,6 +66,7 @@ public class AsyncEchoServer {
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";
@@ -76,4 +77,4 @@ public class AsyncEchoServer {
return builder.start();
}
-}
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java
index 03ce233ce9..663fc4f2ed 100644
--- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java
+++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java
@@ -82,7 +82,6 @@ public class AsyncEchoServer2 {
}
-
public static void main(String[] args) {
new AsyncEchoServer2();
}
@@ -97,4 +96,4 @@ public class AsyncEchoServer2 {
return builder.start();
}
-}
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java
index 7ac388fb09..93cb3e1eb6 100644
--- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java
+++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java
@@ -1,13 +1,13 @@
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;
+import java.io.IOException;
+
+import static org.junit.Assert.assertEquals;
+
public class AsyncEchoTest {
Process server;
@@ -20,7 +20,7 @@ public class AsyncEchoTest {
}
@Test
- public void givenServerClient_whenServerEchosMessage_thenCorrect() {
+ public void givenServerClient_whenServerEchosMessage_thenCorrect() throws Exception {
String resp1 = client.sendMessage("hello");
String resp2 = client.sendMessage("world");
assertEquals("hello", resp1);
diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java
index db30d32210..4395017e63 100644
--- a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java
+++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java
@@ -1,6 +1,6 @@
package com.baeldung.java.nio2.async;
-import static org.junit.Assert.assertEquals;
+import org.junit.Test;
import java.io.IOException;
import java.net.URI;
@@ -11,22 +11,22 @@ 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 org.junit.Test;
+import static org.junit.Assert.assertEquals;
public class AsyncFileTest {
@Test
- public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException {
- Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString()));
+ 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 operation = fileChannel.read(buffer, 0);
- while (!operation.isDone())
- ;
+ operation.get();
String fileContent = new String(buffer.array()).trim();
buffer.clear();
@@ -36,7 +36,7 @@ public class AsyncFileTest {
@Test
public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException {
- Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString()));
+ Path path = Paths.get(URI.create(AsyncFileTest.class.getResource("/file.txt").toString()));
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
@@ -58,10 +58,10 @@ public class AsyncFileTest {
}
@Test
- public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException {
- String fileName = UUID.randomUUID().toString();
+ 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,StandardOpenOption.DELETE_ON_CLOSE);
+ AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;
@@ -72,9 +72,7 @@ public class AsyncFileTest {
Future operation = fileChannel.write(buffer, position);
buffer.clear();
- while (!operation.isDone()) {
-
- }
+ operation.get();
String content = readContent(path);
assertEquals("hello world", content);
@@ -84,8 +82,7 @@ public class AsyncFileTest {
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);
-
+ AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("hello world".getBytes());
@@ -107,7 +104,7 @@ public class AsyncFileTest {
});
}
- public static String readContent(Path file) {
+ public static String readContent(Path file) throws ExecutionException, InterruptedException {
AsynchronousFileChannel fileChannel = null;
try {
fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
@@ -120,11 +117,10 @@ public class AsyncFileTest {
Future operation = fileChannel.read(buffer, 0);
- while (!operation.isDone())
- ;
+ operation.get();
String fileContent = new String(buffer.array()).trim();
buffer.clear();
return fileContent;
}
-}
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java
index dcc24c6415..24097542d0 100644
--- a/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java
+++ b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java
@@ -1,7 +1,7 @@
package com.baeldung.java.nio2.attributes;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import org.junit.BeforeClass;
+import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
@@ -11,15 +11,15 @@ import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
public class BasicAttribsTest {
private static final String HOME = System.getProperty("user.home");
- BasicFileAttributes basicAttribs;
+ private static BasicFileAttributes basicAttribs;
- @Before
- public void setup() throws IOException {
+ @BeforeClass
+ public static void setup() throws IOException {
Path home = Paths.get(HOME);
BasicFileAttributeView basicView = Files.getFileAttributeView(home, BasicFileAttributeView.class);
basicAttribs = basicView.readAttributes();
@@ -31,9 +31,10 @@ public class BasicAttribsTest {
FileTime modified = basicAttribs.lastModifiedTime();
FileTime accessed = basicAttribs.lastAccessTime();
- assertTrue(0 > created.compareTo(accessed));
- assertTrue(0 < modified.compareTo(created));
- assertTrue(0 == created.compareTo(created));
+ System.out.println("Created: " + created);
+ System.out.println("Modified: " + modified);
+ System.out.println("Accessed: " + accessed);
+
}
@Test
@@ -65,4 +66,4 @@ public class BasicAttribsTest {
boolean isOther = basicAttribs.isOther();
assertFalse(isOther);
}
-}
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/java8/optional/OptionalTest.java b/core-java/src/test/java/com/baeldung/java8/optional/OptionalTest.java
new file mode 100644
index 0000000000..1038043d49
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java8/optional/OptionalTest.java
@@ -0,0 +1,206 @@
+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 org.junit.Test;
+
+import com.baeldung.java_8_features.Person;
+
+public class OptionalTest {
+ // creating Optional
+ @Test
+ public void whenCreatesEmptyOptional_thenCorrect() {
+ Optional 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 opt = Optional.of(name);
+ }
+
+ @Test
+ public void givenNonNull_whenCreatesOptional_thenCorrect() {
+ String name = "baeldung";
+ Optional opt = Optional.of(name);
+ assertEquals("Optional[baeldung]", opt.toString());
+ }
+
+ @Test
+ public void givenNonNull_whenCreatesNullable_thenCorrect() {
+ String name = "baeldung";
+ Optional opt = Optional.ofNullable(name);
+ assertEquals("Optional[baeldung]", opt.toString());
+ }
+
+ @Test
+ public void givenNull_whenCreatesNullable_thenCorrect() {
+ String name = null;
+ Optional opt = Optional.ofNullable(name);
+ assertEquals("Optional.empty", opt.toString());
+ }
+ // Checking Value With isPresent()
+
+ @Test
+ public void givenOptional_whenIsPresentWorks_thenCorrect() {
+ Optional 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 opt = Optional.of("baeldung");
+ opt.ifPresent(name -> System.out.println(name.length()));
+ }
+
+ // returning Value With get()
+ @Test
+ public void givenOptional_whenGetsValue_thenCorrect() {
+ Optional opt = Optional.of("baeldung");
+ String name = opt.get();
+ assertEquals("baeldung", name);
+ }
+
+ @Test(expected = NoSuchElementException.class)
+ public void givenOptionalWithNull_whenGetThrowsException_thenCorrect() {
+ Optional opt = Optional.ofNullable(null);
+ String name = opt.get();
+ }
+
+ // Conditional Return With filter()
+ @Test
+ public void whenOptionalFilterWorks_thenCorrect() {
+ Integer year = 2016;
+ Optional 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 companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
+ Optional> listOptional = Optional.of(companyNames);
+
+ int size = listOptional.map(List::size).orElse(0);
+ assertEquals(6, size);
+ }
+
+ @Test
+ public void givenOptional_whenMapWorks_thenCorrect2() {
+ String name = "baeldung";
+ Optional nameOptional = Optional.of(name);
+
+ int len = nameOptional.map(String::length).orElse(0);
+ assertEquals(8, len);
+ }
+
+ @Test
+ public void givenOptional_whenMapWorksWithFilter_thenCorrect() {
+ String password = " password ";
+ Optional passOpt = Optional.of(password);
+ boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent();
+ assertFalse(correctPassword);
+
+ correctPassword = passOpt.map(String::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 personOptional = Optional.of(person);
+
+ Optional> nameOptionalWrapper = personOptional.map(Person::getName);
+ Optional nameOptional = nameOptionalWrapper.orElseThrow(IllegalArgumentException::new);
+ String name1 = nameOptional.orElseThrow(IllegalArgumentException::new);
+ assertEquals("john", name1);
+
+ String name = personOptional.flatMap(Person::getName).orElseThrow(IllegalArgumentException::new);
+ assertEquals("john", name);
+ }
+
+ @Test
+ public void givenOptional_whenFlatMapWorksWithFilter_thenCorrect() {
+ Person person = new Person("john", 26);
+ person.setPassword("password");
+ Optional personOptional = Optional.of(person);
+
+ String password = personOptional.flatMap(Person::getPassword).filter(cleanPass -> cleanPass.equals("password")).orElseThrow(IllegalArgumentException::new);
+ 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);
+
+ }
+
+ @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";
+ }
+}
diff --git a/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java
index 3ee08767bd..0d913db1bd 100644
--- a/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java
+++ b/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java
@@ -1,21 +1,15 @@
package org.baeldung.java.collections;
-import static java.util.Arrays.asList;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import org.junit.Assert;
-import org.junit.Test;
-
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
+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 {
@@ -63,16 +57,16 @@ public class CollectionsConcatenateUnitTest {
Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined);
}
- public static Iterable concat(Iterable extends E> list1, Iterable extends E> list2) {
+ public static Iterable concat(Iterable extends E> i1, Iterable extends E> i2) {
return new Iterable() {
public Iterator iterator() {
return new Iterator() {
- protected Iterator extends E> listIterator = list1.iterator();
- protected Boolean checkedHasNext;
- protected E nextValue;
+ Iterator extends E> listIterator = i1.iterator();
+ Boolean checkedHasNext;
+ E nextValue;
private boolean startTheSecond;
- public void theNext() {
+ void theNext() {
if (listIterator.hasNext()) {
checkedHasNext = true;
nextValue = listIterator.next();
@@ -80,7 +74,7 @@ public class CollectionsConcatenateUnitTest {
checkedHasNext = false;
else {
startTheSecond = true;
- listIterator = list2.iterator();
+ listIterator = i2.iterator();
theNext();
}
}
@@ -107,7 +101,7 @@ public class CollectionsConcatenateUnitTest {
}
public static List makeListFromIterable(Iterable iter) {
- List list = new ArrayList();
+ List list = new ArrayList<>();
for (E item : iter) {
list.add(item);
}
diff --git a/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java
new file mode 100644
index 0000000000..78f79f646b
--- /dev/null
+++ b/core-java/src/test/java/org/baeldung/java/collections/JoinSplitCollectionsUnitTest.java
@@ -0,0 +1,154 @@
+package org.baeldung.java.collections;
+
+import org.junit.Test;
+
+import java.util.*;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.*;
+
+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 collection1 = Arrays.asList(7, 8, 9);
+ Collection collection2 = Arrays.asList(10, 11, 12);
+ Collection 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 collection1 = Arrays.asList(7, 8, 11);
+ Collection collection2 = Arrays.asList(9, 12, 10);
+ Collection 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 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 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> 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 fruits = Arrays.asList("Apple", "Orange", null, "Grape");
+ String result = fruits.stream().filter(Objects::nonNull).collect(Collectors.joining(", "));
+
+ assertEquals(result, "Apple, Orange, Grape");
+ }
+
+ @Test
+ public void whenSplitCollectionHalf_thenConverted() {
+ Collection numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ Collection result1 = new ArrayList<>();
+ Collection 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> result = Arrays.stream(words).collect(Collectors.groupingBy(String::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 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 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 result = Arrays.stream(fruits.split("[,|.]")).map(String::trim).filter(next -> !next.isEmpty()).collect(Collectors.toList());
+
+ assertTrue(result.equals(Arrays.asList("Apple", "Orange", "Grape", "Lemon")));
+ }
+}
diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java
index d4b63beaa4..6d972611f1 100644
--- a/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java
+++ b/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java
@@ -20,7 +20,6 @@ public class JavaFileUnitTest {
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));
diff --git a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java
new file mode 100644
index 0000000000..477092bfcb
--- /dev/null
+++ b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java
@@ -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();
+ }
+
+}
diff --git a/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java b/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java
new file mode 100644
index 0000000000..72730aeb8b
--- /dev/null
+++ b/core-java/src/test/java/org/baeldung/java/sorting/JavaSorting.java
@@ -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 integersList;
+ // private List sortedIntegersList;
+ private Employee[] employees;
+ private Employee[] employeesSorted;
+ private Employee[] employeesSortedByAge;
+ private HashMap 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 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() {
+ @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 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 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> entries = new ArrayList<>(map.entrySet());
+ Collections.sort(entries, new Comparator>() {
+ @Override
+ public int compare(Entry o1, Entry o2) {
+ return o1.getKey().compareTo(o2.getKey());
+ }
+ });
+ HashMap sortedMap = new LinkedHashMap<>();
+ for (Map.Entry 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> entries = new ArrayList<>(map.entrySet());
+ Collections.sort(entries, new Comparator>() {
+ @Override
+ public int compare(Entry o1, Entry o2) {
+ return o1.getValue().compareTo(o2.getValue());
+ }
+ });
+ HashMap sortedMap = new LinkedHashMap<>();
+ for (Map.Entry entry : entries) {
+ sortedMap.put(entry.getKey(), entry.getValue());
+ }
+
+ assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues));
+ }
+
+ @Test
+ public void givenSet_whenUsingSort_thenSortedSet() {
+ HashSet integersSet = new LinkedHashSet<>(Ints.asList(toSort));
+ HashSet descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(new Integer[] { 255, 200, 123, 89, 88, 66, 7, 5, 1 }));
+
+ ArrayList list = new ArrayList(integersSet);
+ Collections.sort(list, (i1, i2) -> {
+ return i2 - i1;
+ });
+ integersSet = new LinkedHashSet<>(list);
+
+ assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray()));
+ }
+
+}
diff --git a/core-java/src/test/resources/file.txt b/core-java/src/test/resources/file.txt
new file mode 100644
index 0000000000..558d8bbf35
--- /dev/null
+++ b/core-java/src/test/resources/file.txt
@@ -0,0 +1 @@
+baeldung.com
\ No newline at end of file
diff --git a/javax-servlets/.gitignore b/javax-servlets/.gitignore
new file mode 100644
index 0000000000..a51a433798
--- /dev/null
+++ b/javax-servlets/.gitignore
@@ -0,0 +1,5 @@
+# Created by .ignore support plugin (hsz.mobi)
+.idea
+classes
+target
+*.iml
\ No newline at end of file
diff --git a/javax-servlets/pom.xml b/javax-servlets/pom.xml
new file mode 100644
index 0000000000..4fe4575e48
--- /dev/null
+++ b/javax-servlets/pom.xml
@@ -0,0 +1,39 @@
+
+
+ 4.0.0
+
+ com.root
+ ServletmavenExample
+ 1.0-SNAPSHOT
+
+
+
+
+ javax.servlet
+ javax.servlet-api
+ ${javax.servlet.version}
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+ org.apache.httpcomponents
+ httpclient
+ ${org.apache.httpcomponents.version}
+ test
+
+
+
+
+
+ 3.1.0
+ 4.12
+ 4.5
+
+
+
\ No newline at end of file
diff --git a/javax-servlets/src/main/java/com/root/FormServlet.java b/javax-servlets/src/main/java/com/root/FormServlet.java
new file mode 100644
index 0000000000..4f55a02745
--- /dev/null
+++ b/javax-servlets/src/main/java/com/root/FormServlet.java
@@ -0,0 +1,47 @@
+package com.root;
+
+import javax.servlet.RequestDispatcher;
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@WebServlet(name = "FormServlet", urlPatterns = "/calculateServlet")
+public class FormServlet extends HttpServlet {
+
+ @Override
+ protected void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+
+ String height = request.getParameter("height");
+ String weight = request.getParameter("weight");
+
+ try {
+ double bmi = calculateBMI(Double.parseDouble(weight), Double.parseDouble(height));
+
+ request.setAttribute("bmi", bmi);
+ response.setHeader("Test", "Success");
+ response.setHeader("BMI", String.valueOf(bmi));
+
+ RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
+ dispatcher.forward(request, response);
+ } catch (Exception e) {
+
+ response.sendRedirect("index.jsp");
+ }
+ }
+
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+
+ // do something else here
+ }
+
+ private Double calculateBMI(Double weight, Double height) {
+
+ return weight / (height * height);
+ }
+}
\ No newline at end of file
diff --git a/javax-servlets/src/test/java/com/root/FormServletTest.java b/javax-servlets/src/test/java/com/root/FormServletTest.java
new file mode 100644
index 0000000000..437741e12d
--- /dev/null
+++ b/javax-servlets/src/test/java/com/root/FormServletTest.java
@@ -0,0 +1,34 @@
+package com.root;
+
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.message.BasicNameValuePair;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+
+public class FormServletTest {
+
+ @Test
+ public void whenPostRequestUsingHttpClient_thenCorrect() throws Exception {
+
+ HttpClient client = new DefaultHttpClient();
+ HttpPost method = new HttpPost("http://localhost:8080/calculateServlet");
+
+ List nvps = new ArrayList();
+ nvps.add(new BasicNameValuePair("height", String.valueOf(2)));
+ nvps.add(new BasicNameValuePair("weight", String.valueOf(80)));
+
+ method.setEntity(new UrlEncodedFormEntity(nvps));
+ HttpResponse httpResponse = client.execute(method);
+
+ assertEquals("Success", httpResponse.getHeaders("Test")[0].getValue());
+ assertEquals("20.0", httpResponse.getHeaders("BMI")[0].getValue());
+ }
+}
diff --git a/javax-servlets/web/WEB-INF/web.xml b/javax-servlets/web/WEB-INF/web.xml
new file mode 100644
index 0000000000..66934d8fd3
--- /dev/null
+++ b/javax-servlets/web/WEB-INF/web.xml
@@ -0,0 +1,7 @@
+
+
+
+
\ No newline at end of file
diff --git a/javax-servlets/web/index.jsp b/javax-servlets/web/index.jsp
new file mode 100644
index 0000000000..5a2e018a41
--- /dev/null
+++ b/javax-servlets/web/index.jsp
@@ -0,0 +1,26 @@
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+
+
+ Calculate BMI
+
+
+
+
+
+
+
diff --git a/pom.xml b/pom.xml
index db62629081..1dde581d13 100644
--- a/pom.xml
+++ b/pom.xml
@@ -49,6 +49,7 @@
jackson
jackson-annotations
java-cassandra
+ javax-servlets
javaxval
jee7
jjwt
diff --git a/spring-core/README.md b/spring-core/README.md
index 53842ecb1a..f05ba9384f 100644
--- a/spring-core/README.md
+++ b/spring-core/README.md
@@ -1,3 +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)
+
diff --git a/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java b/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java
index 40e181b7a7..e5e6d2ec05 100644
--- a/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java
+++ b/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java
@@ -6,21 +6,11 @@ import org.springframework.context.annotation.Configuration;
@Configuration
public class FactoryBeanAppConfig {
- @Bean
- public ToolFactory tool() {
+ @Bean(name = "tool")
+ public ToolFactory toolFactory() {
ToolFactory factory = new ToolFactory();
factory.setFactoryId(7070);
factory.setToolId(2);
- factory.setToolName("wrench");
- factory.setToolPrice(3.7);
return factory;
}
-
- @Bean
- public Worker worker() throws Exception {
- Worker worker = new Worker();
- worker.setNumber("1002");
- worker.setTool(tool().getObject());
- return worker;
- }
-}
+}
\ No newline at end of file
diff --git a/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java
deleted file mode 100644
index 15e2b01f49..0000000000
--- a/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package com.baeldung.factorybean;
-
-import static com.google.common.base.Preconditions.checkArgument;
-
-import org.springframework.beans.factory.FactoryBean;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.util.StringUtils;
-
-public class InitializationToolFactory implements FactoryBean, InitializingBean {
-
- private int factoryId;
- private int toolId;
- private String toolName;
- private double toolPrice;
-
- @Override
- public void afterPropertiesSet() throws Exception {
- checkArgument(!StringUtils.isEmpty(toolName), "tool name cannot be empty");
- checkArgument(toolPrice >= 0, "tool price should not be less than 0");
- }
-
- @Override
- public Tool getObject() throws Exception {
- return new Tool(toolId, toolName, toolPrice);
- }
-
- @Override
- public Class> getObjectType() {
- return Tool.class;
- }
-
- @Override
- public boolean isSingleton() {
- return false;
- }
-
- public int getFactoryId() {
- return factoryId;
- }
-
- public void setFactoryId(int factoryId) {
- this.factoryId = factoryId;
- }
-
- public int getToolId() {
- return toolId;
- }
-
- public void setToolId(int toolId) {
- this.toolId = toolId;
- }
-
- public String getToolName() {
- return toolName;
- }
-
- public void setToolName(String toolName) {
- this.toolName = toolName;
- }
-
- public double getToolPrice() {
- return toolPrice;
- }
-
- public void setToolPrice(double toolPrice) {
- this.toolPrice = toolPrice;
- }
-}
diff --git a/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java
index 158318649c..981df2206f 100644
--- a/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java
+++ b/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java
@@ -6,8 +6,6 @@ public class NonSingleToolFactory extends AbstractFactoryBean {
private int factoryId;
private int toolId;
- private String toolName;
- private double toolPrice;
public NonSingleToolFactory() {
setSingleton(false);
@@ -20,7 +18,7 @@ public class NonSingleToolFactory extends AbstractFactoryBean {
@Override
protected Tool createInstance() throws Exception {
- return new Tool(toolId, toolName, toolPrice);
+ return new Tool(toolId);
}
public int getFactoryId() {
@@ -38,20 +36,4 @@ public class NonSingleToolFactory extends AbstractFactoryBean {
public void setToolId(int toolId) {
this.toolId = toolId;
}
-
- public String getToolName() {
- return toolName;
- }
-
- public void setToolName(String toolName) {
- this.toolName = toolName;
- }
-
- public double getToolPrice() {
- return toolPrice;
- }
-
- public void setToolPrice(double toolPrice) {
- this.toolPrice = toolPrice;
- }
}
diff --git a/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java
deleted file mode 100644
index 696545a70a..0000000000
--- a/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package com.baeldung.factorybean;
-
-import static com.google.common.base.Preconditions.checkArgument;
-
-import javax.annotation.PostConstruct;
-
-import org.springframework.beans.factory.FactoryBean;
-import org.springframework.util.StringUtils;
-
-public class PostConstructToolFactory implements FactoryBean {
-
- private int factoryId;
- private int toolId;
- private String toolName;
- private double toolPrice;
-
- @Override
- public Tool getObject() throws Exception {
- return new Tool(toolId, toolName, toolPrice);
- }
-
- @Override
- public Class> getObjectType() {
- return Tool.class;
- }
-
- @Override
- public boolean isSingleton() {
- return false;
- }
-
- @PostConstruct
- public void checkParams() {
- checkArgument(!StringUtils.isEmpty(toolName), "tool name cannot be empty");
- checkArgument(toolPrice >= 0, "tool price should not be less than 0");
- }
-
- public int getFactoryId() {
- return factoryId;
- }
-
- public void setFactoryId(int factoryId) {
- this.factoryId = factoryId;
- }
-
- public int getToolId() {
- return toolId;
- }
-
- public void setToolId(int toolId) {
- this.toolId = toolId;
- }
-
- public String getToolName() {
- return toolName;
- }
-
- public void setToolName(String toolName) {
- this.toolName = toolName;
- }
-
- public double getToolPrice() {
- return toolPrice;
- }
-
- public void setToolPrice(double toolPrice) {
- this.toolPrice = toolPrice;
- }
-}
diff --git a/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java
index 37fd978a3c..76b87bbbbf 100644
--- a/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java
+++ b/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java
@@ -7,8 +7,6 @@ public class SingleToolFactory extends AbstractFactoryBean {
private int factoryId;
private int toolId;
- private String toolName;
- private double toolPrice;
@Override
public Class> getObjectType() {
@@ -17,7 +15,7 @@ public class SingleToolFactory extends AbstractFactoryBean {
@Override
protected Tool createInstance() throws Exception {
- return new Tool(toolId, toolName, toolPrice);
+ return new Tool(toolId);
}
public int getFactoryId() {
@@ -35,20 +33,4 @@ public class SingleToolFactory extends AbstractFactoryBean {
public void setToolId(int toolId) {
this.toolId = toolId;
}
-
- public String getToolName() {
- return toolName;
- }
-
- public void setToolName(String toolName) {
- this.toolName = toolName;
- }
-
- public double getToolPrice() {
- return toolPrice;
- }
-
- public void setToolPrice(double toolPrice) {
- this.toolPrice = toolPrice;
- }
}
diff --git a/spring-core/src/main/java/com/baeldung/factorybean/Tool.java b/spring-core/src/main/java/com/baeldung/factorybean/Tool.java
index 2a69cbaf2a..be56745b3d 100644
--- a/spring-core/src/main/java/com/baeldung/factorybean/Tool.java
+++ b/spring-core/src/main/java/com/baeldung/factorybean/Tool.java
@@ -1,15 +1,13 @@
package com.baeldung.factorybean;
public class Tool {
-
private int id;
- private String name;
- private double price;
- public Tool(int id, String name, double price) {
+ public Tool() {
+ }
+
+ public Tool(int id) {
this.id = id;
- this.name = name;
- this.price = price;
}
public int getId() {
@@ -19,20 +17,4 @@ public class Tool {
public void setId(int id) {
this.id = id;
}
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public double getPrice() {
- return price;
- }
-
- public void setPrice(double price) {
- this.price = price;
- }
}
diff --git a/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java
index 5e6385c679..2a17574f8e 100644
--- a/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java
+++ b/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java
@@ -6,12 +6,10 @@ public class ToolFactory implements FactoryBean {
private int factoryId;
private int toolId;
- private String toolName;
- private double toolPrice;
@Override
public Tool getObject() throws Exception {
- return new Tool(toolId, toolName, toolPrice);
+ return new Tool(toolId);
}
@Override
@@ -39,20 +37,4 @@ public class ToolFactory implements FactoryBean {
public void setToolId(int toolId) {
this.toolId = toolId;
}
-
- public String getToolName() {
- return toolName;
- }
-
- public void setToolName(String toolName) {
- this.toolName = toolName;
- }
-
- public double getToolPrice() {
- return toolPrice;
- }
-
- public void setToolPrice(double toolPrice) {
- this.toolPrice = toolPrice;
- }
}
diff --git a/spring-core/src/main/java/com/baeldung/factorybean/Worker.java b/spring-core/src/main/java/com/baeldung/factorybean/Worker.java
deleted file mode 100644
index 0d1dc5d7d6..0000000000
--- a/spring-core/src/main/java/com/baeldung/factorybean/Worker.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.baeldung.factorybean;
-
-public class Worker {
-
- private String number;
- private Tool tool;
-
- public Worker() {}
-
- public Worker(String number, Tool tool) {
- this.number = number;
- this.tool = tool;
- }
-
- public String getNumber() {
- return number;
- }
-
- public void setNumber(String number) {
- this.number = number;
- }
-
- public Tool getTool() {
- return tool;
- }
-
- public void setTool(Tool tool) {
- this.tool = tool;
- }
-}
diff --git a/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml b/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml
index 33b3051cae..a82b884ee5 100644
--- a/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml
+++ b/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml
@@ -6,34 +6,10 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/spring-core/src/main/resources/factorybean-init-spring-ctx.xml b/spring-core/src/main/resources/factorybean-init-spring-ctx.xml
deleted file mode 100644
index 1ff492e5df..0000000000
--- a/spring-core/src/main/resources/factorybean-init-spring-ctx.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml b/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml
deleted file mode 100644
index f34325160f..0000000000
--- a/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/spring-core/src/main/resources/factorybean-spring-ctx.xml b/spring-core/src/main/resources/factorybean-spring-ctx.xml
index 2987b67d94..3231fda676 100644
--- a/spring-core/src/main/resources/factorybean-spring-ctx.xml
+++ b/spring-core/src/main/resources/factorybean-spring-ctx.xml
@@ -6,12 +6,5 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java b/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java
index a7ba6d9a68..aa6d7c2cd2 100644
--- a/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java
+++ b/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java
@@ -4,33 +4,36 @@ import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
-import org.junit.Test;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
+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() {
- ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-abstract-spring-ctx.xml");
-
- Worker worker1 = (Worker) context.getBean("worker1");
- Worker worker2 = (Worker) context.getBean("worker2");
-
- assertThat(worker1.getNumber(), equalTo("50001"));
- assertThat(worker2.getNumber(), equalTo("50002"));
- assertTrue(worker1.getTool() == worker2.getTool());
+ assertThat(tool1.getId(), equalTo(1));
+ assertTrue(tool1 == tool2);
}
@Test
public void testNonSingleToolFactory() {
- ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-abstract-spring-ctx.xml");
-
- Worker worker3 = (Worker) context.getBean("worker3");
- Worker worker4 = (Worker) context.getBean("worker4");
-
- assertThat(worker3.getNumber(), equalTo("50003"));
- assertThat(worker4.getNumber(), equalTo("50004"));
- assertTrue(worker3.getTool() != worker4.getTool());
+ assertThat(tool3.getId(), equalTo(2));
+ assertThat(tool4.getId(), equalTo(2));
+ assertTrue(tool3 != tool4);
}
}
diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java
deleted file mode 100644
index 87947b148a..0000000000
--- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.baeldung.factorybean;
-
-import org.junit.Test;
-import org.springframework.beans.factory.BeanCreationException;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
-
-public class FactoryBeanInitializeTest {
-
- @Test(expected = BeanCreationException.class)
- public void testInitializationToolFactory() {
- new ClassPathXmlApplicationContext("classpath:factorybean-init-spring-ctx.xml");
- }
-
- @Test(expected = BeanCreationException.class)
- public void testPostConstructToolFactory() {
- new ClassPathXmlApplicationContext("classpath:factorybean-postconstruct-spring-ctx.xml");
- }
-}
diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java
new file mode 100644
index 0000000000..c725f786dc
--- /dev/null
+++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java
@@ -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));
+ }
+}
\ No newline at end of file
diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java
deleted file mode 100644
index f35503794a..0000000000
--- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package com.baeldung.factorybean;
-
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Test;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
-
-public class FactoryBeanTest {
-
- @Test
- public void testConstructWorkerByXml() {
- ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-spring-ctx.xml");
-
- Worker worker = (Worker) context.getBean("worker");
- assertThat(worker.getNumber(), equalTo("1001"));
- assertThat(worker.getTool().getId(), equalTo(1));
- assertThat(worker.getTool().getName(), equalTo("screwdriver"));
- assertThat(worker.getTool().getPrice(), equalTo(1.5));
-
- ToolFactory toolFactory = (ToolFactory) context.getBean("&tool");
- assertThat(toolFactory.getFactoryId(), equalTo(9090));
- }
-
- @Test
- public void testConstructWorkerByJava() {
- ApplicationContext context = new AnnotationConfigApplicationContext(FactoryBeanAppConfig.class);
-
- Worker worker = (Worker) context.getBean("worker");
- assertThat(worker.getNumber(), equalTo("1002"));
- assertThat(worker.getTool().getId(), equalTo(2));
- assertThat(worker.getTool().getName(), equalTo("wrench"));
- assertThat(worker.getTool().getPrice(), equalTo(3.7));
-
- ToolFactory toolFactory = (ToolFactory) context.getBean("&tool");
- assertThat(toolFactory.getFactoryId(), equalTo(7070));
- }
-}
diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java
new file mode 100644
index 0000000000..443515f872
--- /dev/null
+++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java
@@ -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));
+ }
+}
\ No newline at end of file
diff --git a/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java b/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java
index 3ca0dbf5e4..8768bac58c 100644
--- a/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java
+++ b/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java
@@ -40,7 +40,7 @@ public class PersistenceJPAConfigL2Cache {
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
- em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
+ em.setPackagesToScan(getPackagesToScan());
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
@@ -49,6 +49,10 @@ public class PersistenceJPAConfigL2Cache {
return em;
}
+ protected String[] getPackagesToScan() {
+ return new String[] { "org.baeldung.persistence.model" };
+ }
+
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
@@ -78,6 +82,7 @@ public class PersistenceJPAConfigL2Cache {
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
hibernateProperties.setProperty("hibernate.cache.region.factory_class", env.getProperty("hibernate.cache.region.factory_class"));
+ hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
return hibernateProperties;
}
diff --git a/spring-jpa/src/main/resources/persistence-h2.properties b/spring-jpa/src/main/resources/persistence-h2.properties
index d195af5ec9..2c3e18b58d 100644
--- a/spring-jpa/src/main/resources/persistence-h2.properties
+++ b/spring-jpa/src/main/resources/persistence-h2.properties
@@ -6,7 +6,7 @@ jdbc.user=sa
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
-hibernate.show_sql=false
+hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java b/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java
new file mode 100644
index 0000000000..37388d1c51
--- /dev/null
+++ b/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java
@@ -0,0 +1,17 @@
+package org.baeldung.persistence.deletion.config;
+
+import org.baeldung.config.PersistenceJPAConfigL2Cache;
+
+import java.util.Properties;
+
+public class PersistenceJPAConfigDeletion extends PersistenceJPAConfigL2Cache {
+
+ public PersistenceJPAConfigDeletion() {
+ super();
+ }
+
+ @Override
+ protected String[] getPackagesToScan() {
+ return new String[] { "org.baeldung.persistence.deletion.model" };
+ }
+}
\ No newline at end of file
diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Bar.java b/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Bar.java
new file mode 100644
index 0000000000..26c4846fd2
--- /dev/null
+++ b/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Bar.java
@@ -0,0 +1,60 @@
+package org.baeldung.persistence.deletion.model;
+
+import javax.persistence.*;
+import java.util.ArrayList;
+import java.util.List;
+
+@Entity
+@Table(name = "BAR")
+public class Bar {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private long id;
+
+ @Column(nullable = false)
+ private String name;
+
+ @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
+ List bazList = new ArrayList<>();
+
+ public Bar() {
+ super();
+ }
+
+ public Bar(final String name) {
+ super();
+ this.name = name;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(final long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ public List getBazList() {
+ return bazList;
+ }
+
+ public void setBazList(final List bazList) {
+ this.bazList = bazList;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("Bar [name=").append(name).append("]");
+ return builder.toString();
+ }
+}
diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java b/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java
new file mode 100644
index 0000000000..2dad3e6654
--- /dev/null
+++ b/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java
@@ -0,0 +1,48 @@
+package org.baeldung.persistence.deletion.model;
+
+import javax.persistence.*;
+import java.util.List;
+
+@Entity
+@Table(name = "BAZ")
+public class Baz {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private long id;
+
+ @Column(nullable = false)
+ private String name;
+
+ public Baz() {
+ super();
+ }
+
+ public Baz(final String name) {
+ super();
+ this.name = name;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(final long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("Bar [name=").append(name).append("]");
+ return builder.toString();
+ }
+}
diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Foo.java b/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Foo.java
new file mode 100644
index 0000000000..00fc34c166
--- /dev/null
+++ b/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Foo.java
@@ -0,0 +1,63 @@
+package org.baeldung.persistence.deletion.model;
+
+import org.hibernate.annotations.Where;
+
+import javax.persistence.*;
+
+@Entity
+@Table(name = "FOO")
+@Where(clause = "DELETED = 0")
+public class Foo {
+
+ public Foo() {
+ super();
+ }
+
+ public Foo(final String name) {
+ super();
+ this.name = name;
+ }
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @Column(name = "ID")
+ private long id;
+
+ @Column(name = "NAME")
+ private String name;
+
+ @Column(name = "DELETED")
+ private Integer deleted = 0;
+
+ @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
+ @JoinColumn(name = "BAR_ID")
+ private Bar bar;
+
+ public Bar getBar() {
+ return bar;
+ }
+
+ public void setBar(final Bar bar) {
+ this.bar = bar;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(final int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ public void setDeleted() {
+ this.deleted = 1;
+ }
+}
diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java
new file mode 100644
index 0000000000..9e5c5fa07a
--- /dev/null
+++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java
@@ -0,0 +1,159 @@
+package org.baeldung.persistence.service;
+
+import org.baeldung.persistence.deletion.config.PersistenceJPAConfigDeletion;
+import org.baeldung.persistence.deletion.model.Bar;
+import org.baeldung.persistence.deletion.model.Baz;
+import org.baeldung.persistence.deletion.model.Foo;
+import org.junit.Before;
+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.support.AnnotationConfigContextLoader;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.Assert.assertThat;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = { PersistenceJPAConfigDeletion.class }, loader = AnnotationConfigContextLoader.class)
+public class DeletionIntegrationTest {
+
+ @PersistenceContext
+ private EntityManager entityManager;
+ @Autowired
+ private PlatformTransactionManager platformTransactionManager;
+
+ @Before
+ public final void before() {
+ entityManager.getEntityManagerFactory().getCache().evictAll();
+ }
+
+ @Test
+ @Transactional
+ public final void givenEntityIsRemoved_thenItIsNotInDB() {
+ Foo foo = new Foo("foo");
+ entityManager.persist(foo);
+ flushAndClear();
+
+ foo = entityManager.find(Foo.class, foo.getId());
+ assertThat(foo, notNullValue());
+
+ entityManager.remove(foo);
+ flushAndClear();
+
+ assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
+ }
+
+ @Test
+ @Transactional
+ public final void givenEntityIsRemovedAndReferencedByAnotherEntity_thenItIsNotRemoved() {
+ Bar bar = new Bar("bar");
+ Foo foo = new Foo("foo");
+ foo.setBar(bar);
+ entityManager.persist(foo);
+ flushAndClear();
+
+ foo = entityManager.find(Foo.class, foo.getId());
+ bar = entityManager.find(Bar.class, bar.getId());
+ entityManager.remove(bar);
+ flushAndClear();
+
+ bar = entityManager.find(Bar.class, bar.getId());
+ assertThat(bar, notNullValue());
+
+ foo = entityManager.find(Foo.class, foo.getId());
+ foo.setBar(null);
+ entityManager.remove(bar);
+ flushAndClear();
+
+ assertThat(entityManager.find(Bar.class, bar.getId()), nullValue());
+ }
+
+ @Test
+ @Transactional
+ public final void givenEntityIsRemoved_thenRemovalIsCascaded() {
+ Bar bar = new Bar("bar");
+ Foo foo = new Foo("foo");
+ foo.setBar(bar);
+ entityManager.persist(foo);
+ flushAndClear();
+
+ foo = entityManager.find(Foo.class, foo.getId());
+ entityManager.remove(foo);
+ flushAndClear();
+
+ assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
+ assertThat(entityManager.find(Bar.class, bar.getId()), nullValue());
+ }
+
+ @Test
+ @Transactional
+ public final void givenEntityIsDisassociated_thenOrphanRemovalIsApplied() {
+ Bar bar = new Bar("bar");
+ Baz baz = new Baz("baz");
+ bar.getBazList().add(baz);
+ entityManager.persist(bar);
+ flushAndClear();
+
+ bar = entityManager.find(Bar.class, bar.getId());
+ baz = bar.getBazList().get(0);
+ bar.getBazList().remove(baz);
+ flushAndClear();
+
+ assertThat(entityManager.find(Baz.class, baz.getId()), nullValue());
+ }
+
+ @Test
+ @Transactional
+ public final void givenEntityIsDeletedWithJpaBulkDeleteStatement_thenItIsNotInDB() {
+ Foo foo = new Foo("foo");
+ entityManager.persist(foo);
+ flushAndClear();
+
+ entityManager.createQuery("delete from Foo where id = :id")
+ .setParameter("id", foo.getId())
+ .executeUpdate();
+
+ assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
+ }
+
+ @Test
+ @Transactional
+ public final void givenEntityIsDeletedWithNativeQuery_thenItIsNotInDB() {
+ Foo foo = new Foo("foo");
+ entityManager.persist(foo);
+ flushAndClear();
+
+ entityManager.createNativeQuery("delete from FOO where ID = :id")
+ .setParameter("id", foo.getId())
+ .executeUpdate();
+
+ assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
+ }
+
+ @Test
+ @Transactional
+ public final void givenEntityIsSoftDeleted_thenItIsNotReturnedFromQueries() {
+ Foo foo = new Foo("foo");
+ entityManager.persist(foo);
+ flushAndClear();
+
+ foo = entityManager.find(Foo.class, foo.getId());
+ foo.setDeleted();
+ flushAndClear();
+
+ assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
+ }
+
+ private void flushAndClear() {
+ entityManager.flush();
+ entityManager.clear();
+ }
+}
diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/templates/message.html b/spring-mvc-java/src/main/webapp/WEB-INF/templates/message.html
new file mode 100644
index 0000000000..291e8312ae
--- /dev/null
+++ b/spring-mvc-java/src/main/webapp/WEB-INF/templates/message.html
@@ -0,0 +1,15 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java
new file mode 100644
index 0000000000..46a95ae694
--- /dev/null
+++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java
@@ -0,0 +1,34 @@
+package com.baeldung.htmlunit;
+
+import com.gargoylesoftware.htmlunit.WebClient;
+import com.gargoylesoftware.htmlunit.html.HtmlPage;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class HtmlUnitAndJUnitTest {
+
+ private WebClient webClient;
+
+ @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());
+ }
+
+}
diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java
deleted file mode 100644
index 406975b6cc..0000000000
--- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java
+++ /dev/null
@@ -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());
- }
- }
-
-}
diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java
new file mode 100644
index 0000000000..45e441f47f
--- /dev/null
+++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java
@@ -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);
+ }
+}
diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java
deleted file mode 100644
index 6a7e961eb1..0000000000
--- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java
+++ /dev/null
@@ -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());
- }
- }
-
-}
diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java
index 9919d7571d..f97bedddef 100644
--- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java
+++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java
@@ -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 headings2 = (List) 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 h1
+ = (List) postPage.getByXPath("//h1");
+ Assert.assertTrue(h1.size() > 0);
+ }
}
diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml
index ce496df742..e838e2d5e6 100644
--- a/spring-rest-angular/pom.xml
+++ b/spring-rest-angular/pom.xml
@@ -11,7 +11,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.3.3.RELEASE
+ 1.4.2.RELEASE
@@ -45,7 +45,7 @@
org.apache.commons
commons-lang3
- 3.3
+ ${commons-lang3.version}
com.google.guava
@@ -60,15 +60,20 @@
io.rest-assured
rest-assured
- 3.0.0
+ ${rest-assured.version}
test
io.rest-assured
spring-mock-mvc
- 3.0.0
+ ${rest-assured.version}
test
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
@@ -142,6 +147,8 @@
19.0
+ 3.5
+ 3.0.1
diff --git a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java
index 6ad80e5caf..48c985fb9d 100644
--- a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java
+++ b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java
@@ -1,26 +1,23 @@
package org.baeldung.web.service;
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsCollectionContaining.hasItems;
+import static org.hamcrest.core.IsEqual.equalTo;
+
import org.apache.commons.lang3.RandomStringUtils;
import org.baeldung.web.main.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.springframework.boot.test.IntegrationTest;
-import org.springframework.boot.test.SpringApplicationConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.web.WebAppConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
+import org.springframework.test.context.junit4.SpringRunner;
-import static io.restassured.RestAssured.*;
-import static org.hamcrest.core.IsCollectionContaining.*;
-import static org.hamcrest.core.Is.*;
-import static org.hamcrest.core.IsEqual.*;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@SpringApplicationConfiguration(classes = Application.class)
-@WebAppConfiguration
-@IntegrationTest("server.port:8888")
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT)
public class StudentServiceIntegrationTest {
- private static final String ENDPOINT = "http://localhost:8888/student/get";
+ private static final String ENDPOINT = "http://localhost:8080/student/get";
@Test
public void givenRequestForStudents_whenPageIsOne_expectContainsNames() {
diff --git a/spring-rest-docs/pom.xml b/spring-rest-docs/pom.xml
index 8e758eeb4a..2e8a70e96b 100644
--- a/spring-rest-docs/pom.xml
+++ b/spring-rest-docs/pom.xml
@@ -14,7 +14,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.3.3.RELEASE
+ 1.4.2.RELEASE
@@ -22,6 +22,9 @@
UTF-8
1.8
${project.build.directory}/generated-snippets
+ 1.1.2.RELEASE
+ 2.2.0
+ 1.5.3
@@ -42,23 +45,23 @@
org.springframework.restdocs
spring-restdocs-mockmvc
- 1.0.1.RELEASE
+ ${restdocs.version}
test
- com.jayway.jsonpath
- json-path
- 2.0.0
-
+ com.jayway.jsonpath
+ json-path
+ ${jsonpath.version}
+
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
org.apache.maven.plugins
maven-surefire-plugin
@@ -70,7 +73,7 @@
org.asciidoctor
asciidoctor-maven-plugin
- 1.5.2
+ ${asciidoctor-plugin.version}
generate-docs
diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java b/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java
new file mode 100644
index 0000000000..f19ddca435
--- /dev/null
+++ b/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java
@@ -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 myfoos;
+
+ public MyFooController() {
+ super();
+ myfoos = new HashMap();
+ myfoos.put(1L, new Foo(1L, "sample foo"));
+ }
+
+ // API - read
+
+ @RequestMapping(method = RequestMethod.GET)
+ @ResponseBody
+ public Collection 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);
+ }
+
+}
diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java b/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java
index 774d547464..240b368b50 100644
--- a/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java
+++ b/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java
@@ -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();
diff --git a/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java b/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java
new file mode 100644
index 0000000000..aab737b6ec
--- /dev/null
+++ b/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java
@@ -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 {
+}
diff --git a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml
index 21136b62c6..0f80990c16 100644
--- a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml
+++ b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml
@@ -8,7 +8,7 @@
-
+
+
@@ -43,6 +44,11 @@
+
+
+
+
diff --git a/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java
index e4321e163f..a47c60e9d8 100644
--- a/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java
+++ b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java
@@ -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 response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
+ final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException {
- ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
+ final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
- ObjectMapper mapper = new ObjectMapper();
- JsonNode root = mapper.readTree(response.getBody());
- JsonNode name = root.path("name");
- assertThat(name.asText(), is(notNull()));
+ 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 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 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 request = new HttpEntity<>(new Foo("bar"));
+
+ final ResponseEntity 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 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 request = new HttpEntity<>(new Foo("bar"), headers);
+
+ // Create Resource
+ final ResponseEntity 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 requestUpdate = new HttpEntity<>(updatedInstance, headers);
+ template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);
+
+ // Check that Resource was updated
+ final ResponseEntity 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 request = new HttpEntity<>(new Foo("bar"), headers);
+
+ // Create entity
+ ResponseEntity 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 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;
+ }
}
diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java
index d5765b9756..71fc755321 100644
--- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java
+++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java
@@ -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,10 +8,6 @@ import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.IOException;
-import org.baeldung.okhttp.ProgressRequestWrapper;
-import org.junit.Before;
-import org.junit.Test;
-
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
@@ -19,33 +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();
+ client = new OkHttpClient();
}
@Test
public void whenUploadFile_thenCorrect() throws IOException {
- 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 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();
- Request request = new Request.Builder()
- .url(BASE_URL + "/users/upload")
- .post(requestBody)
- .build();
+ final 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));
}
@@ -53,25 +46,18 @@ public class OkHttpFileUploadingLiveTest {
@Test
public void whenGetUploadFileProgress_thenCorrect() throws IOException {
- 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 RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();
- ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> {
+ final ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> {
- float percentage = 100f * bytesWritten / contentLength;
+ final float percentage = (100f * bytesWritten) / contentLength;
assertFalse(Float.compare(percentage, 100) > 0);
});
- Request request = new Request.Builder()
- .url(BASE_URL + "/users/upload")
- .post(countingBody)
- .build();
+ final 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));
diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java
index 034833da0d..fc78899da1 100644
--- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java
+++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java
@@ -1,14 +1,12 @@
package org.baeldung.okhttp;
+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 org.junit.Before;
-import org.junit.Test;
-
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
@@ -16,9 +14,12 @@ 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;
@@ -30,40 +31,42 @@ public class OkHttpGetLiveTest {
@Test
public void whenGetRequest_thenCorrect() throws IOException {
- Request request = new Request.Builder().url(BASE_URL + "/date").build();
+ final 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 {
- 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 {
- Request request = new Request.Builder().url(BASE_URL + "/date").build();
+ final 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();
}
diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java
index 34e1554908..e6b3cc87b0 100644
--- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java
+++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java
@@ -1,27 +1,27 @@
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;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
+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;
@@ -29,31 +29,27 @@ public class OkHttpMiscLiveTest {
@Before
public void init() {
- client = new OkHttpClient();
+ client = new OkHttpClient();
}
@Test
public void whenSetRequestTimeout_thenFail() throws IOException {
- OkHttpClient clientWithTimeout = new OkHttpClient.Builder()
- .readTimeout(1, TimeUnit.SECONDS)
- .build();
+ final OkHttpClient clientWithTimeout = new OkHttpClient.Builder().readTimeout(1, TimeUnit.SECONDS).build();
- 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();
- Call call = clientWithTimeout.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 {
- ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
+ final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
- 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();
@@ -63,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 clientCached = 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 = clientCached.newCall(request).execute();
+ final Response response1 = clientCached.newCall(request).execute();
logResponse(response1);
- Response response2 = clientCached.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());
diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java
index dce3bb174f..9f9220329d 100644
--- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java
+++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java
@@ -1,14 +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.Before;
-import org.junit.Test;
-
import okhttp3.Call;
import okhttp3.Credentials;
import okhttp3.FormBody;
@@ -19,9 +17,12 @@ 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;
@@ -29,77 +30,59 @@ public class OkHttpPostingLiveTest {
@Before
public void init() {
- client = new OkHttpClient();
+ client = new OkHttpClient();
}
@Test
public void whenSendPostRequest_thenCorrect() throws IOException {
- RequestBody formBody = new FormBody.Builder()
- .add("username", "test")
- .add("password", "test")
- .build();
+ final RequestBody formBody = new FormBody.Builder().add("username", "test").add("password", "test").build();
- Request request = new Request.Builder()
- .url(BASE_URL + "/users")
- .post(formBody)
- .build();
+ final 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 {
- String postBody = "test post";
+ final String postBody = "test post";
- 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();
+ 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"), "test post"))
+ .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 {
- String json = "{\"id\":1,\"name\":\"John\"}";
+ final String json = "{\"id\":1,\"name\":\"John\"}";
- RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
+ final RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\"id\":1,\"name\":\"John\"}");
+ final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
- 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 {
- 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();
+ 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();
- Request request = new Request.Builder()
- .url(BASE_URL + "/users/multipart")
- .post(requestBody)
- .build();
+ final 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));
}
diff --git a/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java b/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java
index 3155b5cda9..7828df7304 100644
--- a/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java
+++ b/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java
@@ -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
diff --git a/spring-security-basic-auth/pom.xml b/spring-security-basic-auth/pom.xml
index 009f5584bb..4cb0efb9e2 100644
--- a/spring-security-basic-auth/pom.xml
+++ b/spring-security-basic-auth/pom.xml
@@ -225,42 +225,42 @@
- 4.2.5.RELEASE
- 4.0.4.RELEASE
+ 4.3.4.RELEASE
+ 4.2.0.RELEASE
- 4.3.11.Final
- 5.1.38
+ 5.2.5.Final
+ 5.1.40
- 1.7.13
- 1.1.3
+ 1.7.21
+ 1.1.7
- 5.2.2.Final
+ 5.3.3.Final
1.2
- 3.0.1
+ 3.1.0
19.0
- 3.4
+ 3.5
1.3
4.12
1.10.19
- 4.4.1
- 4.5
+ 4.4.5
+ 4.5.2
2.9.0
- 3.5.1
+ 3.6.0
2.6
2.19.1
2.7
- 1.4.18
+ 1.6.1
diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java b/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java
index 1901489305..db304edb36 100644
--- a/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java
+++ b/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java
@@ -13,28 +13,27 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationFi
@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");
+ 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.authorizeRequests()
- .antMatchers("/securityNone").permitAll()
- .anyRequest().authenticated()
- .and()
- .httpBasic()
- .authenticationEntryPoint(authenticationEntryPoint);
+ .antMatchers("/securityNone").permitAll()
+ .anyRequest().authenticated()
+ .and()
+ .httpBasic()
+ .authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new CustomFilter(),
- BasicAuthenticationFilter.class);
+ BasicAuthenticationFilter.class);
}
}
diff --git a/spring-security-basic-auth/src/main/resources/webSecurityConfig.xml b/spring-security-basic-auth/src/main/resources/webSecurityConfig.xml
index f840d3014e..f6d15980ae 100644
--- a/spring-security-basic-auth/src/main/resources/webSecurityConfig.xml
+++ b/spring-security-basic-auth/src/main/resources/webSecurityConfig.xml
@@ -1,8 +1,8 @@
diff --git a/spring-security-client/spring-security-jsp-authentication/pom.xml b/spring-security-client/spring-security-jsp-authentication/pom.xml
index 74de4d729b..fc5f0cb86a 100644
--- a/spring-security-client/spring-security-jsp-authentication/pom.xml
+++ b/spring-security-client/spring-security-jsp-authentication/pom.xml
@@ -13,7 +13,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.3.3.RELEASE
+ 1.4.2.RELEASE
diff --git a/spring-security-client/spring-security-jsp-authorize/pom.xml b/spring-security-client/spring-security-jsp-authorize/pom.xml
index 25bb21b663..8cedbeb713 100644
--- a/spring-security-client/spring-security-jsp-authorize/pom.xml
+++ b/spring-security-client/spring-security-jsp-authorize/pom.xml
@@ -13,7 +13,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.3.3.RELEASE
+ 1.4.2.RELEASE
diff --git a/spring-security-client/spring-security-jsp-config/pom.xml b/spring-security-client/spring-security-jsp-config/pom.xml
index 2416552d7c..067e6dff60 100644
--- a/spring-security-client/spring-security-jsp-config/pom.xml
+++ b/spring-security-client/spring-security-jsp-config/pom.xml
@@ -13,7 +13,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.3.3.RELEASE
+ 1.4.2.RELEASE
diff --git a/spring-security-client/spring-security-mvc/pom.xml b/spring-security-client/spring-security-mvc/pom.xml
index ec3b1f1782..b6a67d9c2c 100644
--- a/spring-security-client/spring-security-mvc/pom.xml
+++ b/spring-security-client/spring-security-mvc/pom.xml
@@ -13,7 +13,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.3.3.RELEASE
+ 1.4.2.RELEASE
diff --git a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml
index cdbe0946f4..9f819d11c5 100644
--- a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml
+++ b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml
@@ -13,7 +13,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.3.3.RELEASE
+ 1.4.2.RELEASE
diff --git a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml
index 5254f1db1a..5c13c34dea 100644
--- a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml
+++ b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml
@@ -13,7 +13,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.3.3.RELEASE
+ 1.4.2.RELEASE
diff --git a/spring-security-client/spring-security-thymeleaf-config/pom.xml b/spring-security-client/spring-security-thymeleaf-config/pom.xml
index ec145a29c8..cc43b2ffb1 100644
--- a/spring-security-client/spring-security-thymeleaf-config/pom.xml
+++ b/spring-security-client/spring-security-thymeleaf-config/pom.xml
@@ -13,7 +13,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.3.3.RELEASE
+ 1.4.2.RELEASE
diff --git a/spring-security-custom-permission/pom.xml b/spring-security-custom-permission/pom.xml
index 288cc3d6ba..b28c0877c4 100644
--- a/spring-security-custom-permission/pom.xml
+++ b/spring-security-custom-permission/pom.xml
@@ -14,7 +14,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.3.8.RELEASE
+ 1.4.2.RELEASE
@@ -101,38 +101,38 @@
org.apache.derby
derby
- 10.12.1.1
+ ${derby.version}
org.apache.derby
derbyclient
- 10.12.1.1
+ ${derby.version}
org.apache.derby
derbynet
- 10.12.1.1
+ ${derby.version}
org.apache.derby
derbytools
- 10.12.1.1
+ ${derby.version}
taglibs
standard
- 1.1.2
+ ${taglibs-standard.version}
org.springframework.security
spring-security-taglibs
- 4.1.3.RELEASE
+ ${spring-security-taglibs.version}
javax.servlet.jsp.jstl
jstl-api
- 1.2
+ ${jstl.version}
@@ -245,8 +245,12 @@
UTF-8
1.8
+ 10.13.1.1
+ 1.1.2
+ 4.2.0.RELEASE
+ 1.2
2.4.0
- 1.6.0
+ 1.6.1
diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java
index 47616ca61a..631c8dfc58 100644
--- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java
+++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java
@@ -27,8 +27,8 @@ public class SetupData {
@PostConstruct
public void init() {
- initPrivileges();
initOrganizations();
+ initPrivileges();
initUsers();
}
@@ -57,7 +57,6 @@ public class SetupData {
//
final Organization org2 = new Organization("SecondOrg");
organizationRepository.save(org2);
-
}
private void initPrivileges() {
diff --git a/spring-security-custom-permission/src/main/resources/spring-security.xml b/spring-security-custom-permission/src/main/resources/spring-security.xml
index 382dbf5dff..83bc14dda7 100644
--- a/spring-security-custom-permission/src/main/resources/spring-security.xml
+++ b/spring-security-custom-permission/src/main/resources/spring-security.xml
@@ -4,7 +4,7 @@
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/security
- http://www.springframework.org/schema/security/spring-security-4.0.xsd
+ http://www.springframework.org/schema/security/spring-security-4.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml
index ca9b3423cc..59339ead5e 100644
--- a/spring-security-mvc-custom/pom.xml
+++ b/spring-security-mvc-custom/pom.xml
@@ -230,42 +230,42 @@
- 4.2.5.RELEASE
- 4.0.4.RELEASE
+ 4.3.4.RELEASE
+ 4.2.0.RELEASE
- 4.3.11.Final
- 5.1.38
+ 5.2.5.Final
+ 5.1.40
- 1.7.13
- 1.1.3
+ 1.7.21
+ 1.1.7
- 5.2.2.Final
- 3.0.1
+ 5.3.3.Final
+ 3.1.0
1.2
19.0
- 3.4
+ 3.5
1.3
4.12
1.10.19
- 4.5
- 4.4.1
+ 4.5.2
+ 4.4.5
2.9.0
- 3.5.1
+ 3.6.0
2.6
2.19.1
2.7
- 1.4.18
+ 1.6.1
diff --git a/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml
index 603ded74fe..f31f36655c 100644
--- a/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml
+++ b/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml
@@ -2,9 +2,9 @@
diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml
index c292eb6b54..dd772e3343 100644
--- a/spring-security-mvc-digest-auth/pom.xml
+++ b/spring-security-mvc-digest-auth/pom.xml
@@ -225,42 +225,42 @@
- 4.2.5.RELEASE
- 4.0.4.RELEASE
+ 4.3.4.RELEASE
+ 4.2.0.RELEASE
- 4.3.11.Final
- 5.1.38
+ 5.2.5.Final
+ 5.1.40
- 1.7.13
- 1.1.3
+ 1.7.21
+ 1.1.7
- 5.2.2.Final
+ 5.3.3.Final
1.2
- 3.0.1
+ 3.1.0
19.0
- 3.4
+ 3.5
1.3
4.12
1.10.19
- 4.4.1
- 4.5
+ 4.4.5
+ 4.5.2
2.9.0
- 3.5.1
+ 3.6.0
2.6
2.19.1
2.7
- 1.4.18
+ 1.6.1
diff --git a/spring-security-mvc-digest-auth/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-digest-auth/src/main/resources/webSecurityConfig.xml
index 0706267b77..c259901cb9 100644
--- a/spring-security-mvc-digest-auth/src/main/resources/webSecurityConfig.xml
+++ b/spring-security-mvc-digest-auth/src/main/resources/webSecurityConfig.xml
@@ -1,8 +1,8 @@
diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml
index 145321b2f4..242cc527ac 100644
--- a/spring-security-mvc-ldap/pom.xml
+++ b/spring-security-mvc-ldap/pom.xml
@@ -10,7 +10,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.3.8.RELEASE
+ 1.4.2.RELEASE
@@ -69,7 +69,7 @@
- 1.5.5
+ 1.5.7
diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml
index 943eeaa197..b7b64625e8 100644
--- a/spring-security-mvc-login/pom.xml
+++ b/spring-security-mvc-login/pom.xml
@@ -222,42 +222,42 @@
- 4.2.5.RELEASE
- 4.0.4.RELEASE
+ 4.3.4.RELEASE
+ 4.2.0.RELEASE
- 4.3.11.Final
- 5.1.38
+ 5.2.5.Final
+ 5.1.40
- 1.7.13
- 1.1.3
+ 1.7.21
+ 1.1.7
- 5.2.2.Final
- 3.0.1
+ 5.3.3.Final
+ 3.1.0
1.2
19.0
- 3.4
+ 3.5
1.3
4.12
1.10.19
- 4.4.1
- 4.5
+ 4.4.5
+ 4.5.2
2.9.0
- 3.5.1
+ 3.6.0
2.6
2.19.1
2.7
- 1.4.18
+ 1.6.1
diff --git a/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml b/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml
index de073b8aac..516829f5eb 100644
--- a/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml
+++ b/spring-security-mvc-login/src/main/resources/channelWebSecurityConfig.xml
@@ -2,9 +2,9 @@
diff --git a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml
index 7a736d0024..e8056dba6e 100644
--- a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml
+++ b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml
@@ -2,9 +2,9 @@
diff --git a/spring-security-mvc-persisted-remember-me/pom.xml b/spring-security-mvc-persisted-remember-me/pom.xml
index 3f1d78f8ea..f215c39c6d 100644
--- a/spring-security-mvc-persisted-remember-me/pom.xml
+++ b/spring-security-mvc-persisted-remember-me/pom.xml
@@ -113,7 +113,7 @@
- postgresql
+ org.postgresql
postgresql
${postgresql.version}
runtime
@@ -260,23 +260,23 @@
- 4.2.5.RELEASE
- 4.0.4.RELEASE
+ 4.3.4.RELEASE
+ 4.2.0.RELEASE
- 4.3.11.Final
- 5.1.38
- 1.4.190
- 9.1-901.jdbc4
+ 5.2.5.Final
+ 5.1.40
+ 1.4.193
+ 9.4.1212
- 1.7.12
- 1.1.3
+ 1.7.21
+ 1.1.7
- 5.1.3.Final
- 3.0.1
+ 5.3.3.Final
+ 3.1.0
1.2
@@ -288,17 +288,17 @@
4.11
1.10.19
- 4.5
- 4.4.1
+ 4.5.2
+ 4.4.5
2.9.0
- 3.5.1
+ 3.6.0
2.6
2.19.1
2.7
- 1.4.18
+ 1.6.1
diff --git a/spring-security-mvc-persisted-remember-me/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-persisted-remember-me/src/main/resources/webSecurityConfig.xml
index d1f081cb9b..9fc3f7f355 100644
--- a/spring-security-mvc-persisted-remember-me/src/main/resources/webSecurityConfig.xml
+++ b/spring-security-mvc-persisted-remember-me/src/main/resources/webSecurityConfig.xml
@@ -2,11 +2,11 @@
diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml
index e330825bf2..3f129c83ba 100644
--- a/spring-security-mvc-session/pom.xml
+++ b/spring-security-mvc-session/pom.xml
@@ -230,43 +230,43 @@
- 4.2.5.RELEASE
- 4.0.4.RELEASE
+ 4.3.4.RELEASE
+ 4.2.0.RELEASE
- 4.3.11.Final
- 5.1.38
+ 5.2.5.Final
+ 5.1.40
- 1.7.13
- 1.1.3
+ 1.7.21
+ 1.1.7
- 5.2.2.Final
- 3.0.1
+ 5.3.3.Final
+ 3.0.2
1.2
- 3.0.1
+ 3.1.0
19.0
- 3.4
+ 3.5
1.3
4.12
1.10.19
- 4.5
- 4.4.1
+ 4.5.2
+ 4.4.5
2.9.0
- 3.5.1
+ 3.6.0
2.6
2.19.1
2.7
- 1.4.18
+ 1.6.1
diff --git a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml
index 02b74b0933..e8aa2f76bc 100644
--- a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml
+++ b/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml
@@ -2,9 +2,9 @@
diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml
index d3f4de9914..7987eebb66 100644
--- a/spring-security-rest-basic-auth/pom.xml
+++ b/spring-security-rest-basic-auth/pom.xml
@@ -342,30 +342,30 @@
- 4.2.5.RELEASE
- 4.0.4.RELEASE
+ 4.3.4.RELEASE
+ 4.2.0.RELEASE
- 4.3.11.Final
- 5.1.38
+ 5.2.5.Final
+ 5.1.40
- 4.4.4
- 4.5.1
+ 4.4.5
+ 4.5.2
- 1.7.13
- 1.1.3
+ 1.7.21
+ 1.1.7
- 5.2.2.Final
+ 5.3.3.Final
1.2
- 3.0.1
- 2.2.3
+ 3.1.0
+ 2.8.5
19.0
- 3.4
+ 3.5
1.3
@@ -375,10 +375,10 @@
2.9.0
- 3.5.1
+ 3.6.0
2.6
2.19.1
- 1.4.18
+ 1.6.1
diff --git a/spring-security-rest-basic-auth/src/main/resources/webSecurityConfig.xml b/spring-security-rest-basic-auth/src/main/resources/webSecurityConfig.xml
index 6beea901df..6dea965d8b 100644
--- a/spring-security-rest-basic-auth/src/main/resources/webSecurityConfig.xml
+++ b/spring-security-rest-basic-auth/src/main/resources/webSecurityConfig.xml
@@ -2,9 +2,9 @@
diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml
index 296703c27e..4c2fdb4709 100644
--- a/spring-security-rest-custom/pom.xml
+++ b/spring-security-rest-custom/pom.xml
@@ -10,7 +10,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.3.8.RELEASE
+ 1.4.2.RELEASE
@@ -253,40 +253,17 @@
-
- 4.2.5.RELEASE
- 4.0.4.RELEASE
-
-
- 4.3.11.Final
- 5.1.38
-
-
- 1.7.13
- 1.1.3
-
-
- 5.2.2.Final
-
19.0
- 3.4
+ 3.5
-
- 1.3
- 4.12
- 1.10.19
-
- 4.4.1
- 4.5
+ 4.4.5
+ 4.5.2
2.9.0
- 3.5.1
- 2.6
- 2.19.1
- 1.4.18
+ 1.6.1
diff --git a/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml b/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml
index 98fe24f9b9..fa5dc894bf 100644
--- a/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml
+++ b/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml
@@ -2,9 +2,9 @@
diff --git a/spring-security-rest-digest-auth/pom.xml b/spring-security-rest-digest-auth/pom.xml
index 1880e12a74..dc8e12b72b 100644
--- a/spring-security-rest-digest-auth/pom.xml
+++ b/spring-security-rest-digest-auth/pom.xml
@@ -84,10 +84,10 @@
- org.springframework
- spring-web
- ${org.springframework.version}
-
+ org.springframework
+ spring-web
+ ${org.springframework.version}
+
@@ -335,32 +335,32 @@
- 4.2.5.RELEASE
- 4.0.4.RELEASE
+ 4.3.4.RELEASE
+ 4.2.0.RELEASE
- 4.3.11.Final
- 5.1.38
+ 5.2.5.Final
+ 5.1.40
- 4.4.4
- 4.5.1
+ 4.4.5
+ 4.5.2
- 1.7.13
- 1.1.3
+ 1.7.21
+ 1.1.7
- 2.7.8
+ 2.8.5
- 5.2.2.Final
- 3.0.1
+ 5.3.3.Final
+ 3.1.0
1.2
19.0
- 3.4
+ 3.5
1.3
@@ -370,10 +370,10 @@
2.9.0
- 3.5.1
+ 3.6.0
2.6
2.19.1
- 1.4.18
+ 1.6.1
diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml
index ab354d51a7..e9580d357d 100644
--- a/spring-security-rest-full/pom.xml
+++ b/spring-security-rest-full/pom.xml
@@ -463,46 +463,22 @@
-
-
- 4.3.11.Final
- 5.1.40
-
- 2.0.0
- 4.1.4
-
-
- 2.7.8
- 1.4.01
-
-
- 1.7.13
- 1.1.3
+ 2.1.0
- 5.2.2.Final
- 1.4.8
+ 1.4.9
19.0
- 3.4
+ 3.5
- 1.3
4.12
- 1.10.19
-
- 4.4.1
- 4.5
-
2.9.0
- 3.6.0
- 2.6
- 2.19.1
- 1.4.18
+ 1.6.1
1.1.3
diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java
deleted file mode 100644
index a1cd9fcfe1..0000000000
--- a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java
+++ /dev/null
@@ -1,265 +0,0 @@
-package org.baeldung.client;
-
-import static org.apache.commons.codec.binary.Base64.encodeBase64;
-import static org.baeldung.Consts.APPLICATION_PORT;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.notNullValue;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Set;
-
-import org.apache.http.auth.AuthScope;
-import org.apache.http.auth.UsernamePasswordCredentials;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.impl.client.BasicCredentialsProvider;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.baeldung.persistence.model.Foo;
-import org.baeldung.spring.ConfigTest;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-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.test.context.ActiveProfiles;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-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;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class)
-@ActiveProfiles("test")
-public class RestTemplateLiveTest {
-
- private RestTemplate restTemplate;
- private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-security-rest-full/auth/foos";
-
- @Before
- public void beforeTest() {
- restTemplate = new RestTemplate(getClientHttpRequestFactory());
-
- ensureOneEntityExists();
- }
-
- // GET
-
- @Test
- public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException {
- final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
- assertThat(response.getStatusCode(), is(HttpStatus.OK));
- }
-
- @Test
- public void givenResourceUrl_whenSendGetForRestEntity_thenReceiveCorrectJson() throws IOException {
- final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
-
- final ObjectMapper mapper = new ObjectMapper();
- final JsonNode root = mapper.readTree(response.getBody());
-
- final JsonNode name = root.path("name");
- assertNotNull(name);
-
- final JsonNode owner = root.path("id");
- assertThat(owner.asText(), is("1"));
- }
-
- @Test
- public void givenResourceUrl_whenSendGetForObject_thenReturnsRepoObject() {
- final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class);
- assertNotNull(foo.getName());
- assertThat(foo.getId(), is(1L));
- }
-
- // POST
-
- @Test
- public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() {
- final HttpEntity 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_whenPostFor2Objects_thenNewObjectIsCreatedEachTime() {
- final HttpEntity request = new HttpEntity<>(new Foo("bar"));
- final Foo firstInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
- final Foo secondInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
- assertThat(firstInstance, notNullValue());
- assertThat(secondInstance, notNullValue());
- assertThat(firstInstance.getId(), not(secondInstance.getId()));
- }
-
- // HEAD, OPTIONS
-
- @Test
- public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() {
- final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl);
- assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
- assertTrue(httpHeaders.get("bar").contains("baz"));
- }
-
- @Test
- public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() {
- final Set optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl);
- final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE };
- assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
- }
-
- // POST
-
- @Test
- public void givenFooService_whenPostResource_thenResourceIsCreated() {
- final RestTemplate template = new RestTemplate();
-
- final HttpHeaders headers = prepareBasicAuthHeaders();
- final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers);
-
- final ResponseEntity 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"));
- }
-
- // PUT
-
- @Test
- public void givenFooService_whenPutExistingEntity_thenItIsUpdated() {
- final RestTemplate template = new RestTemplate();
- final HttpHeaders headers = prepareBasicAuthHeaders();
- final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers);
-
- // Create Resource
- final ResponseEntity 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 requestUpdate = new HttpEntity<>(updatedInstance, headers);
- template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);
-
- // Check that Resource was updated
- final ResponseEntity 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 request = new HttpEntity<>(new Foo("bar"), headers);
-
- // Create entity
- ResponseEntity 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 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 void ensureOneEntityExists() {
- final Foo instance = new Foo("bar");
- instance.setId(1L);
-
- try {
- restTemplate.getForEntity(fooResourceUrl + "/1", Foo.class);
- } catch (final HttpClientErrorException ex) {
- if (ex.getStatusCode() == HttpStatus.NOT_FOUND) {
- restTemplate.postForEntity(fooResourceUrl, instance, Foo.class);
- }
- }
- }
-
- private ClientHttpRequestFactory getClientHttpRequestFactory() {
- final int timeout = 5;
- final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
-
- final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
- credentialsProvider.setCredentials(new AuthScope("localhost", APPLICATION_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass"));
-
- final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).setDefaultCredentialsProvider(credentialsProvider).build();
-
- return new HttpComponentsClientHttpRequestFactory(client);
- }
-
- 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;
- }
-}
diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/LiveTestSuite.java b/spring-security-rest-full/src/test/java/org/baeldung/web/LiveTestSuite.java
index 4c26350151..c3353fac3c 100644
--- a/spring-security-rest-full/src/test/java/org/baeldung/web/LiveTestSuite.java
+++ b/spring-security-rest-full/src/test/java/org/baeldung/web/LiveTestSuite.java
@@ -1,6 +1,5 @@
package org.baeldung.web;
-import org.baeldung.client.RestTemplateLiveTest;
import org.baeldung.persistence.query.JPASpecificationLiveTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@@ -12,7 +11,6 @@ import org.junit.runners.Suite;
,FooDiscoverabilityLiveTest.class
,FooLiveTest.class
,MyUserLiveTest.class
- ,RestTemplateLiveTest.class
}) //
public class LiveTestSuite {
diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml
index 60f3ed41d1..320e84fa7a 100644
--- a/spring-security-rest/pom.xml
+++ b/spring-security-rest/pom.xml
@@ -1,393 +1,401 @@
- 4.0.0
- com.baeldung
- spring-security-rest
- 0.1-SNAPSHOT
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.baeldung
+ spring-security-rest
+ 0.1-SNAPSHOT
- spring-security-rest
- war
+ spring-security-rest
+ war
-
+
-
+
-
- org.springframework.security
- spring-security-web
- ${org.springframework.security.version}
-
-
- org.springframework.security
- spring-security-config
- ${org.springframework.security.version}
-
+
+ org.springframework.security
+ spring-security-web
+ ${org.springframework.security.version}
+
+
+ org.springframework.security
+ spring-security-config
+ ${org.springframework.security.version}
+
-
+
-
- org.springframework
- spring-core
- ${org.springframework.version}
-
-
- commons-logging
- commons-logging
-
-
-
-
- org.springframework
- spring-context
- ${org.springframework.version}
-
-
- org.springframework
- spring-jdbc
- ${org.springframework.version}
-
-
- org.springframework
- spring-beans
- ${org.springframework.version}
-
-
- org.springframework
- spring-aop
- ${org.springframework.version}
-
-
- org.springframework
- spring-tx
- ${org.springframework.version}
-
-
- org.springframework
- spring-expression
- ${org.springframework.version}
-
+
+ org.springframework
+ spring-core
+ ${org.springframework.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+ org.springframework
+ spring-context
+ ${org.springframework.version}
+
+
+ org.springframework
+ spring-jdbc
+ ${org.springframework.version}
+
+
+ org.springframework
+ spring-beans
+ ${org.springframework.version}
+
+
+ org.springframework
+ spring-aop
+ ${org.springframework.version}
+
+
+ org.springframework
+ spring-tx
+ ${org.springframework.version}
+
+
+ org.springframework
+ spring-expression
+ ${org.springframework.version}
+
-
- org.springframework
- spring-web
- ${org.springframework.version}
-
-
- org.springframework
- spring-webmvc
- ${org.springframework.version}
-
+
+ org.springframework
+ spring-web
+ ${org.springframework.version}
+
+
+ org.springframework
+ spring-webmvc
+ ${org.springframework.version}
+
-
-
- org.springframework.hateoas
- spring-hateoas
- ${org.springframework.hateoas.version}
-
+
+
+ org.springframework.hateoas
+ spring-hateoas
+ ${org.springframework.hateoas.version}
+
-
+
-
- javax.servlet
- javax.servlet-api
- ${javax.servlet-api.version}
- provided
-
+
+ javax.servlet
+ javax.servlet-api
+ ${javax.servlet-api.version}
+ provided
+
-
- javax.servlet
- jstl
- ${jstl.version}
- runtime
-
+
+ javax.servlet
+ jstl
+ ${jstl.version}
+ runtime
+
-
- javax.validation
- validation-api
- ${javax.validation.version}
-
+
+ javax.validation
+ validation-api
+ ${javax.validation.version}
+
-
-
- com.fasterxml.jackson.core
- jackson-databind
- ${jackson.version}
-
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson.version}
+
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
-
-
-
-
- org.slf4j
- slf4j-api
- ${org.slf4j.version}
-
-
- ch.qos.logback
- logback-classic
- ${logback.version}
-
-
-
- org.slf4j
- jcl-over-slf4j
- ${org.slf4j.version}
-
-
-
- org.slf4j
- log4j-over-slf4j
- ${org.slf4j.version}
-
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
-
-
- org.springframework
- spring-test
- ${org.springframework.version}
- test
-
+
+
+ org.slf4j
+ slf4j-api
+ ${org.slf4j.version}
+
+
+ ch.qos.logback
+ logback-classic
+ ${logback.version}
+
+
+
+ org.slf4j
+ jcl-over-slf4j
+ ${org.slf4j.version}
+
+
+
+ org.slf4j
+ log4j-over-slf4j
+ ${org.slf4j.version}
+
-
- org.springframework.security
- spring-security-test
- ${org.springframework.security.version}
- test
-
+
+
+ org.springframework
+ spring-test
+ ${org.springframework.version}
+ test
+
+
+
+ org.springframework.security
+ spring-security-test
+ ${org.springframework.security.version}
+ test
+
-
- com.jayway.restassured
- rest-assured
- ${rest-assured.version}
- test
-
-
- commons-logging
- commons-logging
-
-
-
+
+ com.jayway.restassured
+ rest-assured
+ ${rest-assured.version}
+ test
+
+
+ commons-logging
+ commons-logging
+
+
+
-
- junit
- junit
- ${junit.version}
- test
-
+
+ junit
+ junit
+ ${junit.version}
+ test
+
-
- org.hamcrest
- hamcrest-core
- ${org.hamcrest.version}
- test
-
-
- org.hamcrest
- hamcrest-library
- ${org.hamcrest.version}
- test
-
+
+ org.hamcrest
+ hamcrest-core
+ ${org.hamcrest.version}
+ test
+
+
+ org.hamcrest
+ hamcrest-library
+ ${org.hamcrest.version}
+ test
+
-
- org.mockito
- mockito-core
- ${mockito.version}
- test
-
+
+ org.mockito
+ mockito-core
+ ${mockito.version}
+ test
+
-
-
- io.springfox
- springfox-swagger2
- ${springfox-swagger.version}
-
+
+
+ io.springfox
+ springfox-swagger2
+ ${springfox-swagger.version}
+
-
- io.springfox
- springfox-swagger-ui
- ${springfox-swagger.version}
-
+
+ io.springfox
+ springfox-swagger-ui
+ ${springfox-swagger.version}
+
-
+
+
+ commons-fileupload
+ commons-fileupload
+ ${commons-fileupload.version}
+
-
- spring-security-rest
-
-
- src/main/resources
- true
-
-
+
-
+
+ spring-security-rest
+
+
+ src/main/resources
+ true
+
+
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
-
- 1.8
-
-
+
-
- org.apache.maven.plugins
- maven-war-plugin
- ${maven-war-plugin.version}
-
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ 1.8
+
+
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
- **/*LiveTest.java
-
-
-
-
-
-
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
-
- org.codehaus.cargo
- cargo-maven2-plugin
- ${cargo-maven2-plugin.version}
-
-
- jetty8x
- embedded
-
-
-
-
-
-
- 8082
-
-
-
-
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+ **/*LiveTest.java
+
+
+
+
+
+
-
+
+ org.codehaus.cargo
+ cargo-maven2-plugin
+ ${cargo-maven2-plugin.version}
+
+
+ jetty8x
+ embedded
+
+
+
+
+
+
+ 8082
+
+
+
+
-
+
-
-
- live
-
-
-
- org.codehaus.cargo
- cargo-maven2-plugin
-
-
- start-server
- pre-integration-test
-
- start
-
-
-
- stop-server
- post-integration-test
-
- stop
-
-
-
-
+
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- integration-test
-
- test
-
-
-
- none
-
-
- **/*LiveTest.java
-
-
- cargo
-
-
-
-
-
+
+
+ live
+
+
+
+ org.codehaus.cargo
+ cargo-maven2-plugin
+
+
+ start-server
+ pre-integration-test
+
+ start
+
+
+
+ stop-server
+ post-integration-test
+
+ stop
+
+
+
+
-
-
-
-
-
-
-
-
- 4.2.5.RELEASE
- 4.0.4.RELEASE
- 0.19.0.RELEASE
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ none
+
+
+ **/*LiveTest.java
+
+
+ cargo
+
+
+
+
+
-
- 4.3.11.Final
- 5.1.38
+
+
+
+
-
- 1.7.13
- 1.1.3
-
- 5.2.2.Final
- 3.0.1
- 1.1.0.Final
- 1.2
- 2.7.8
+
+
+ 4.3.4.RELEASE
+ 4.2.0.RELEASE
+ 0.21.0.RELEASE
-
- 19.0
- 3.4
+
+ 5.2.5.Final
+ 5.1.40
-
- 1.3
- 4.12
- 1.10.19
- 2.9.0
+
+ 1.7.21
+ 1.1.7
-
- 2.4.0
+
+ 5.3.3.Final
+ 3.1.0
+ 1.1.0.Final
+ 1.2
+ 2.8.5
- 4.4.1
- 4.5
+
+ 19.0
+ 3.5
+ 1.3.2
- 2.9.0
+
+ 1.3
+ 4.12
+ 1.10.19
+ 2.9.0
-
- 3.5.1
- 2.6
- 2.19.1
- 1.4.18
+
+ 2.6.1
-
+ 4.4.5
+ 4.5.2
+
+ 2.9.0
+
+
+ 3.6.0
+ 2.6
+ 2.19.1
+ 1.6.1
+
+
diff --git a/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java b/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java
new file mode 100644
index 0000000000..bc59b4226a
--- /dev/null
+++ b/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java
@@ -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 processUpload(final MultipartFile file) {
+
+ return new Callable() {
+ public Boolean call() throws Exception {
+ // ...
+ return true;
+ }
+ };
+ }
+
+}
diff --git a/spring-security-rest/src/main/resources/webSecurityConfig.xml b/spring-security-rest/src/main/resources/webSecurityConfig.xml
index 619b53fb7e..cf8357633c 100644
--- a/spring-security-rest/src/main/resources/webSecurityConfig.xml
+++ b/spring-security-rest/src/main/resources/webSecurityConfig.xml
@@ -3,9 +3,9 @@
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/security
- http://www.springframework.org/schema/security/spring-security-4.0.xsd
+ http://www.springframework.org/schema/security/spring-security-4.2.xsd
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"
+ http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"
>
diff --git a/spring-security-rest/src/main/webapp/WEB-INF/api-servlet.xml b/spring-security-rest/src/main/webapp/WEB-INF/api-servlet.xml
index 4ba9642448..5a68371f6c 100644
--- a/spring-security-rest/src/main/webapp/WEB-INF/api-servlet.xml
+++ b/spring-security-rest/src/main/webapp/WEB-INF/api-servlet.xml
@@ -1,6 +1,10 @@
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
+
+
+
\ No newline at end of file
diff --git a/spring-security-rest/src/main/webapp/WEB-INF/web.xml b/spring-security-rest/src/main/webapp/WEB-INF/web.xml
index 3af8709dab..c030a9dd63 100644
--- a/spring-security-rest/src/main/webapp/WEB-INF/web.xml
+++ b/spring-security-rest/src/main/webapp/WEB-INF/web.xml
@@ -1,54 +1,57 @@
-
+ http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+ id="WebApp_ID" version="3.0">
- Spring MVC Application
+ Spring MVC Application
-
-
- contextClass
-
+
+
+ contextClass
+
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
-
-
- contextConfigLocation
- org.baeldung.spring
-
+
+
+ contextConfigLocation
+ org.baeldung.spring
+
-
- org.springframework.web.context.ContextLoaderListener
-
+
+ org.springframework.web.context.ContextLoaderListener
+
-
-
- api
- org.springframework.web.servlet.DispatcherServlet
-
- throwExceptionIfNoHandlerFound
- true
-
-
-
- api
- /api/*
-
+
+
+ api
+ org.springframework.web.servlet.DispatcherServlet
+
+ throwExceptionIfNoHandlerFound
+ true
+
+
+
+ api
+ /api/*
+
-
-
- springSecurityFilterChain
- org.springframework.web.filter.DelegatingFilterProxy
-
-
- springSecurityFilterChain
- /*
-
+
+
+ springSecurityFilterChain
+ org.springframework.web.filter.DelegatingFilterProxy
+
+
+ springSecurityFilterChain
+ /*
+ REQUEST
+ ASYNC
+
-
-
-
+
+
+
\ No newline at end of file
diff --git a/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerTest.java b/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerTest.java
new file mode 100644
index 0000000000..37122ed836
--- /dev/null
+++ b/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerTest.java
@@ -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());
+ }
+
+}
diff --git a/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java b/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java
index 8b55841508..bdce37dd10 100644
--- a/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java
+++ b/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java
@@ -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;
+ }
+
}
\ No newline at end of file
diff --git a/spring-security-x509/pom.xml b/spring-security-x509/pom.xml
index 953af761b5..8596223cf4 100644
--- a/spring-security-x509/pom.xml
+++ b/spring-security-x509/pom.xml
@@ -16,7 +16,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.4.0.RELEASE
+ 1.4.2.RELEASE
diff --git a/spring-session/jetty-session-demo/pom.xml b/spring-session/jetty-session-demo/pom.xml
deleted file mode 100644
index 19f0577d2e..0000000000
--- a/spring-session/jetty-session-demo/pom.xml
+++ /dev/null
@@ -1,76 +0,0 @@
-
-
- 4.0.0
-
- com.baeldung
- jetty-session-demo
- 1.0.0-SNAPSHOT
-
-
- org.springframework.boot
- spring-boot-starter-parent
- 1.4.0.RELEASE
-
-
-
-
-
- org.springframework.boot
- spring-boot-starter-jetty
-
-
-
- org.springframework.boot
- spring-boot-starter-data-redis
-
-
- org.springframework.boot
- spring-boot-starter-security
-
-
- org.springframework.session
- spring-session
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
- org.springframework.boot
- spring-boot-starter-test
- test
-
-
-
-
-
-
- org.springframework.cloud
- spring-cloud-dependencies
- Brixton.RELEASE
- pom
- import
-
-
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- 3.3
-
-
- 1.8
-
-
-
-
-
\ No newline at end of file
diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyController.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyController.java
deleted file mode 100644
index 308b0a8d51..0000000000
--- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyController.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package com.baeldung.spring.session.jettyex;
-
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-@RestController
-public class JettyController {
- @RequestMapping
- public String helloJetty() {
- return "hello Jetty";
- }
-}
\ No newline at end of file
diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java
deleted file mode 100644
index 09f752b261..0000000000
--- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SecurityConfig.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.baeldung.spring.session.jettyex;
-
-import org.springframework.context.annotation.Configuration;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
-import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
-import org.springframework.security.config.http.SessionCreationPolicy;
-
-@Configuration
-@EnableWebSecurity
-public class SecurityConfig extends WebSecurityConfigurerAdapter {
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and()
- .authorizeRequests().anyRequest().hasRole("ADMIN");
- }
-}
diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SessionConfig.java b/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SessionConfig.java
deleted file mode 100644
index 735ae7fb43..0000000000
--- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/SessionConfig.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.baeldung.spring.session.jettyex;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
-import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
-import org.springframework.session.web.http.HeaderHttpSessionStrategy;
-import org.springframework.session.web.http.HttpSessionStrategy;
-
-@Configuration
-@EnableRedisHttpSession
-public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
- @Bean
- public HttpSessionStrategy httpSessionStrategy() {
- return new HeaderHttpSessionStrategy();
- }
-}
diff --git a/spring-session/jetty-session-demo/src/main/resources/application.properties b/spring-session/jetty-session-demo/src/main/resources/application.properties
deleted file mode 100644
index 7f81672eda..0000000000
--- a/spring-session/jetty-session-demo/src/main/resources/application.properties
+++ /dev/null
@@ -1,3 +0,0 @@
-server.port=8081
-spring.redis.host=localhost
-spring.redis.port=6379
\ No newline at end of file
diff --git a/spring-session/pom.xml b/spring-session/pom.xml
index 3a5965c193..c247d8a065 100644
--- a/spring-session/pom.xml
+++ b/spring-session/pom.xml
@@ -4,20 +4,65 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
-
spring-session
1.0.0-SNAPSHOT
- pom
+ jar
-
- jetty-session-demo
- tomcat-session-demo
-
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 1.4.2.RELEASE
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-redis
+
+
+ org.springframework.boot
+ spring-boot-starter-security
+
+
+ org.springframework.session
+ spring-session
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ 1.8
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ **/*ControllerTest.java
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java b/spring-session/src/main/java/com/baeldung/spring/session/SecurityConfig.java
similarity index 70%
rename from spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java
rename to spring-session/src/main/java/com/baeldung/spring/session/SecurityConfig.java
index 691aad3ee5..beaa4da0fe 100644
--- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SecurityConfig.java
+++ b/spring-session/src/main/java/com/baeldung/spring/session/SecurityConfig.java
@@ -1,4 +1,4 @@
-package com.baeldung.spring.session.tomcatex;
+package com.baeldung.spring.session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
@@ -14,16 +14,16 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
- .inMemoryAuthentication()
- .withUser("admin").password("password").roles("ADMIN");
+ .inMemoryAuthentication()
+ .withUser("admin").password("password").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
- .httpBasic().and()
- .authorizeRequests()
- .antMatchers("/tomcat/admin").hasRole("ADMIN")
- .anyRequest().authenticated();
+ .httpBasic().and()
+ .authorizeRequests()
+ .antMatchers("/").hasRole("ADMIN")
+ .anyRequest().authenticated();
}
}
diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java b/spring-session/src/main/java/com/baeldung/spring/session/SessionConfig.java
similarity index 88%
rename from spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java
rename to spring-session/src/main/java/com/baeldung/spring/session/SessionConfig.java
index 5afac6cb6b..5a9bc9ff28 100644
--- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/SessionConfig.java
+++ b/spring-session/src/main/java/com/baeldung/spring/session/SessionConfig.java
@@ -1,4 +1,4 @@
-package com.baeldung.spring.session.tomcatex;
+package com.baeldung.spring.session;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
diff --git a/spring-session/src/main/java/com/baeldung/spring/session/SessionController.java b/spring-session/src/main/java/com/baeldung/spring/session/SessionController.java
new file mode 100644
index 0000000000..ac0479afed
--- /dev/null
+++ b/spring-session/src/main/java/com/baeldung/spring/session/SessionController.java
@@ -0,0 +1,12 @@
+package com.baeldung.spring.session;
+
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+public class SessionController {
+ @RequestMapping("/")
+ public String helloAdmin() {
+ return "hello admin";
+ }
+}
diff --git a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java b/spring-session/src/main/java/com/baeldung/spring/session/SessionWebApplication.java
similarity index 57%
rename from spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java
rename to spring-session/src/main/java/com/baeldung/spring/session/SessionWebApplication.java
index ebb2a8e188..3c605be3a6 100644
--- a/spring-session/jetty-session-demo/src/main/java/com/baeldung/spring/session/jettyex/JettyWebApplication.java
+++ b/spring-session/src/main/java/com/baeldung/spring/session/SessionWebApplication.java
@@ -1,11 +1,11 @@
-package com.baeldung.spring.session.jettyex;
+package com.baeldung.spring.session;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
-public class JettyWebApplication {
+public class SessionWebApplication {
public static void main(String[] args) {
- SpringApplication.run(JettyWebApplication.class, args);
+ SpringApplication.run(SessionWebApplication.class, args);
}
}
diff --git a/spring-session/tomcat-session-demo/src/main/resources/application.properties b/spring-session/src/main/resources/application.properties
similarity index 100%
rename from spring-session/tomcat-session-demo/src/main/resources/application.properties
rename to spring-session/src/main/resources/application.properties
diff --git a/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java b/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java
new file mode 100644
index 0000000000..42d12112a2
--- /dev/null
+++ b/spring-session/src/test/java/com/baeldung/spring/session/SessionControllerTest.java
@@ -0,0 +1,86 @@
+package com.baeldung.spring.session;
+
+import org.apache.tomcat.util.codec.binary.Base64;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.web.client.TestRestTemplate;
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
+import org.springframework.http.*;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+public class SessionControllerTest {
+
+ @Autowired
+ private TestRestTemplate restTemplate;
+ @Autowired
+ private JedisConnectionFactory jedisConnectionFactory;
+
+ private RedisConnection connection;
+
+ @Before
+ public void clearRedisData() {
+ connection = jedisConnectionFactory.getConnection();
+ connection.flushAll();
+ }
+
+ @Test
+ public void testRedisIsEmpty() {
+ Set result = connection.keys("*".getBytes());
+ assertEquals(0, result.size());
+ }
+
+ @Test
+ public void testUnauthenticatedCantAccess() {
+ ResponseEntity result = restTemplate.getForEntity("/", String.class);
+ assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
+ }
+
+ @Test
+ public void testRedisControlsSession() {
+ ResponseEntity result = restTemplate.exchange("/", HttpMethod.GET, makeAuthRequest(), String.class);
+ assertEquals("hello admin", result.getBody()); //login worked
+
+ Set redisResult = connection.keys("*".getBytes());
+ assertTrue(redisResult.size() > 0); //redis is populated with session data
+
+ String sessionCookie = result.getHeaders().get("Set-Cookie").get(0).split(";")[0];
+ result = restTemplate.exchange("/", HttpMethod.GET, makeRequestWithCookie(sessionCookie), String.class);
+ assertEquals("hello admin", result.getBody()); //access with session works worked
+
+ connection.flushAll(); //clear all keys in redis
+
+ result = restTemplate.exchange("/", HttpMethod.GET, makeRequestWithCookie(sessionCookie), String.class);
+ assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());//access denied after sessions are removed in redis
+
+ }
+
+ private HttpEntity makeRequestWithCookie(String sessionCookie) {
+ HttpHeaders headers = new HttpHeaders();
+ headers.add("Cookie", sessionCookie);
+
+ return new HttpEntity<>(headers);
+ }
+
+ private HttpEntity makeAuthRequest() {
+ String plainCreds = "admin:password";
+ byte[] plainCredsBytes = plainCreds.getBytes();
+ byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
+ String base64Creds = new String(base64CredsBytes);
+
+ HttpHeaders headers = new HttpHeaders();
+ headers.add("Authorization", "Basic " + base64Creds);
+
+ return new HttpEntity<>(headers);
+ }
+}
\ No newline at end of file
diff --git a/spring-session/tomcat-session-demo/pom.xml b/spring-session/tomcat-session-demo/pom.xml
deleted file mode 100644
index 7d52082651..0000000000
--- a/spring-session/tomcat-session-demo/pom.xml
+++ /dev/null
@@ -1,85 +0,0 @@
-
-
- 4.0.0
-
- com.baeldung
- tomcat-session-demo
- 1.0.0-SNAPSHOT
-
-
- org.springframework.boot
- spring-boot-starter-parent
- 1.4.0.RELEASE
-
-
-
-
-
- org.springframework.boot
- spring-boot-starter-data-redis
-
-
- org.springframework.boot
- spring-boot-starter-security
-
-
- org.springframework.session
- spring-session
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
- org.springframework.boot
- spring-boot-starter-test
- test
-
-
-
-
-
-
- org.springframework.cloud
- spring-cloud-dependencies
- Brixton.RELEASE
- pom
- import
-
-
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- 3.3
-
-
- 1.8
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
- **/*ControllerTest.java
-
-
-
-
-
-
-
- 2.19.1
-
-
\ No newline at end of file
diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatController.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatController.java
deleted file mode 100644
index a241158294..0000000000
--- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatController.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package com.baeldung.spring.session.tomcatex;
-
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-@RestController
-public class TomcatController {
- @RequestMapping("/tomcat/admin")
- public String helloTomcatAdmin() {
- return "hello tomcat admin";
- }
-}
diff --git a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java b/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java
deleted file mode 100644
index fb4e059dd1..0000000000
--- a/spring-session/tomcat-session-demo/src/main/java/com/baeldung/spring/session/tomcatex/TomcatWebApplication.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.baeldung.spring.session.tomcatex;
-
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-
-@SpringBootApplication
-public class TomcatWebApplication {
- public static void main(String[] args) {
- SpringApplication.run(TomcatWebApplication.class, args);
- }
-}
diff --git a/spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java b/spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java
deleted file mode 100644
index 5bfb7e9411..0000000000
--- a/spring-session/tomcat-session-demo/src/test/java/com/baeldung/spring/session/tomcatex/TomcatControllerTest.java
+++ /dev/null
@@ -1,103 +0,0 @@
-package com.baeldung.spring.session.tomcatex;
-
-import org.apache.tomcat.util.codec.binary.Base64;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.context.embedded.LocalServerPort;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.test.web.client.TestRestTemplate;
-import org.springframework.data.redis.connection.RedisConnection;
-import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
-import org.springframework.http.*;
-import org.springframework.test.context.junit4.SpringRunner;
-
-import java.util.Set;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
-public class TomcatControllerTest {
-
- @Autowired
- private TestRestTemplate restTemplate;
- @LocalServerPort
- private int port;
- @Autowired
- private JedisConnectionFactory jedisConnectionFactory;
- private RedisConnection connection;
-
- @Before
- public void clearRedisData() {
- connection = jedisConnectionFactory.getConnection();
- connection.flushAll();
- }
-
- @Test
- public void testRedisIsEmpty() {
- Set result = connection.keys("*".getBytes());
- assertEquals(0, result.size());
- }
-
- @Test
- public void testForbiddenToProtectedEndpoint() {
- ResponseEntity result = restTemplate.getForEntity("/tomcat/admin", String.class);
- assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
- }
-
- @Test
- public void testLoginAddsRedisKey() {
- ResponseEntity result = makeRequest();
- assertEquals("hello tomcat admin", result.getBody()); //login worked
-
- Set redisResult = connection.keys("*".getBytes());
- assertTrue(redisResult.size() > 0); //redis was populated with data
- }
-
- @Test //requires that the jetty service is running on port 8081
- public void testFailureAccessingJettyResourceWithTomcatSessionToken() {
- //call the jetty server with the token
- ResponseEntity jettyResult = restTemplate.getForEntity("http://localhost:8081", String.class);
- assertEquals(HttpStatus.UNAUTHORIZED, jettyResult.getStatusCode()); //login worked
- }
-
- @Test //requires that the jetty service is running on port 8081
- public void testAccessingJettyResourceWithTomcatSessionToken() {
- //login to get a session token
- ResponseEntity result = makeRequest();
- assertEquals("hello tomcat admin", result.getBody()); //login worked
-
- assertTrue(result.getHeaders().containsKey("Set-Cookie"));
-
- String setCookieValue = result.getHeaders().get("Set-Cookie").get(0);
- String sessionCookie = setCookieValue.split(";")[0];
- String sessionValue = sessionCookie.split("=")[1];
-
- //Add session token to headers
- HttpHeaders headers = new HttpHeaders();
- headers.add("x-auth-token", sessionValue);
-
- //call the jetty server with the token
- HttpEntity request = new HttpEntity<>(headers);
- ResponseEntity jettyResult = restTemplate.exchange("http://localhost:8081", HttpMethod.GET, request, String.class);
- assertEquals("hello Jetty", jettyResult.getBody()); //login worked
-
- }
-
- private ResponseEntity makeRequest() {
- String plainCreds = "admin:password";
- byte[] plainCredsBytes = plainCreds.getBytes();
- byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
- String base64Creds = new String(base64CredsBytes);
-
- HttpHeaders headers = new HttpHeaders();
- headers.add("Authorization", "Basic " + base64Creds);
-
- HttpEntity request = new HttpEntity<>(headers);
- return restTemplate.exchange("http://localhost:" + port + "/tomcat/admin", HttpMethod.GET, request, String.class);
- }
-
-}
\ No newline at end of file
diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml
index 6e74b1c3d1..4369ec4e7c 100644
--- a/spring-social-login/pom.xml
+++ b/spring-social-login/pom.xml
@@ -9,7 +9,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.4.0.RELEASE
+ 1.4.2.RELEASE
diff --git a/spring-spel/pom.xml b/spring-spel/pom.xml
index add5e53348..c3817ce2bd 100644
--- a/spring-spel/pom.xml
+++ b/spring-spel/pom.xml
@@ -8,26 +8,34 @@
spel
1.0-SNAPSHOT
+
+ 4.12
+ 1.3
+ 4.3.4.RELEASE
+ 3.6.0
+ 2.19.1
+
+
junit
junit
- 4.12
+ ${junit.version}
org.hamcrest
hamcrest-all
- 1.3
+ ${hamcrest.version}
org.springframework
spring-context
- 4.0.6.RELEASE
+ ${springframework.version}
org.springframework
spring-test
- 4.0.6.RELEASE
+ ${springframework.version}
test
@@ -35,7 +43,7 @@
maven-compiler-plugin
- 3.3
+ ${maven-compiler-plugin.version}
true
true
@@ -50,7 +58,7 @@
org.apache.maven.plugins
maven-surefire-plugin
- 2.19.1
+ ${maven-surefire-plugin.version}
**/*IntegrationTest.java
diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml
index e59ce77e57..b387539aa1 100644
--- a/spring-thymeleaf/pom.xml
+++ b/spring-thymeleaf/pom.xml
@@ -8,22 +8,27 @@
1.8
- 4.3.3.RELEASE
- 3.0.1
+ 4.3.4.RELEASE
+ 4.2.0.RELEASE
+ 3.1.0
- 1.7.12
- 1.1.3
+ 1.7.21
+ 1.1.7
- 3.0.1.RELEASE
+ 3.0.2.RELEASE
+ 2.1.2
1.1.0.Final
- 5.1.2.Final
+ 5.3.3.Final
+ 5.2.5.Final
+ 4.12
- 3.5.1
+ 3.6.0
2.6
2.19.1
- 1.4.18
+ 1.6.1
+ 2.2
@@ -49,12 +54,12 @@
org.springframework.security
spring-security-web
- 4.1.3.RELEASE
+ ${springframework-security.version}
org.springframework.security
spring-security-config
- 4.1.3.RELEASE
+ ${springframework-security.version}
@@ -71,7 +76,7 @@
nz.net.ultraq.thymeleaf
thymeleaf-layout-dialect
- 2.0.4
+ ${thymeleaf-layout-dialect.version}
@@ -112,14 +117,14 @@
org.hibernate
hibernate-validator
- ${org.hibernate-version}
+ ${hibernate-validator.version}
org.springframework
spring-test
- 4.1.3.RELEASE
+ ${org.springframework-version}
test
@@ -127,7 +132,7 @@
org.springframework.security
spring-security-test
- 4.1.3.RELEASE
+ ${springframework-security.version}
test
@@ -135,7 +140,7 @@
junit
junit
- 4.12
+ ${junit.version}
test
@@ -194,7 +199,7 @@
org.apache.tomcat.maven
tomcat7-maven-plugin
- 2.0
+ ${tomcat7-maven-plugin.version}
tomcat-run
diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml
index dc0d4d295c..c0099173ee 100644
--- a/spring-userservice/pom.xml
+++ b/spring-userservice/pom.xml
@@ -35,7 +35,7 @@
xml-apis
xml-apis
- 1.4.01
+ ${xml-apis.version}
org.javassist
@@ -69,7 +69,7 @@
javax.el
javax.el-api
- 2.2.5
+ ${javax.el-api.version}
@@ -158,52 +158,52 @@
org.apache.derby
derby
- 10.12.1.1
+ ${derby.version}
org.apache.derby
derbyclient
- 10.12.1.1
+ ${derby.version}
org.apache.derby
derbynet
- 10.12.1.1
+ ${derby.version}
org.apache.derby
derbytools
- 10.12.1.1
+ ${derby.version}
taglibs
standard
- 1.1.2
+ ${taglibs-standard.version}
org.springframework.security
spring-security-taglibs
- 4.1.3.RELEASE
+ ${org.springframework.security.version}
javax.servlet.jsp.jstl
jstl-api
- 1.2
+ ${jstl-api.version}
org.springframework.boot
spring-boot-test
- 1.4.1.RELEASE
+ ${spring-boot.version}
org.springframework.boot
spring-boot
- 1.4.1.RELEASE
+ ${spring-boot.version}
javax.servlet
javax.servlet-api
- 3.1.0
+ ${javax.servlet.version}
@@ -288,44 +288,39 @@
- 4.1.3.RELEASE
- 4.3.2.RELEASE
- 3.20.0-GA
+ 4.2.0.RELEASE
+ 4.3.4.RELEASE
+ 1.4.2.RELEASE
+ 3.21.0-GA
- 5.2.2.Final
- 5.1.38
- 1.10.2.RELEASE
- 1.4.192
-
-
- 1.7.13
- 1.1.3
-
+ 5.2.5.Final
+ 5.1.40
+ 1.10.5.RELEASE
+ 1.4.193
+ 10.13.1.1
+
- 5.2.2.Final
-
+ 5.3.3.Final
+ 2.2.5
+ 1.1.2
+ 1.2
+ 3.1.0
+
19.0
- 3.4
-
+ 3.5
+ 1.4.01
+
1.3
4.12
1.10.19
- 4.4.1
- 4.5
-
- 2.9.0
-
- 3.5.1
+ 3.6.0
2.6
2.19.1
- 2.7
- 1.4.18
-
diff --git a/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml b/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml
index 25d1d4d22f..48ef8a8c43 100644
--- a/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml
+++ b/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml
@@ -5,11 +5,11 @@
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.1.xsd
+ xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
+ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
diff --git a/spring-zuul/pom.xml b/spring-zuul/pom.xml
index 75ff467527..2107892667 100644
--- a/spring-zuul/pom.xml
+++ b/spring-zuul/pom.xml
@@ -10,7 +10,7 @@
org.springframework.boot
spring-boot-starter-parent
- 1.3.3.RELEASE
+ 1.4.2.RELEASE
@@ -65,36 +65,18 @@
- 4.2.5.RELEASE
- 4.0.4.RELEASE
-
-
-
- 2.7.2
-
-
- 1.7.12
- 1.1.3
+ 1.2.3.RELEASE
- 19.0
- 3.3.2
+ 3.5
- 1.3
- 4.11
- 1.10.19
-
- 4.4
- 4.4
-
2.9.0
- 3.5.1
+ 3.6.0
2.6
2.19.1
- 1.4.18
diff --git a/spring-zuul/spring-zuul-ui/pom.xml b/spring-zuul/spring-zuul-ui/pom.xml
index 99df27f2f9..f337ed32ba 100644
--- a/spring-zuul/spring-zuul-ui/pom.xml
+++ b/spring-zuul/spring-zuul-ui/pom.xml
@@ -17,7 +17,7 @@
org.springframework.cloud
spring-cloud-starter-zuul
- 1.0.4.RELEASE
+ ${spring-cloud.version}
commons-io
commons-io
- 2.4
+ ${commons-io.version}
org.apache.commons
commons-collections4
- 4.0
+ ${commons-collections4.version}
@@ -90,20 +90,21 @@
+ 1.6.1
+ 1.1.6
+ 2.0.6
+ 2.5
+ 4.1
- 19.0
- 3.4
+ 3.5
4.12
- 3.5.1
- 2.6
+ 3.6.0
2.19.1
- 2.7
- 1.4.18
diff --git a/xmlunit2/pom.xml b/xmlunit2/pom.xml
index c80e3f37b2..d4364292d6 100644
--- a/xmlunit2/pom.xml
+++ b/xmlunit2/pom.xml
@@ -5,42 +5,56 @@
xmlunit2
1.0
XMLUnit-2
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- 3.3
-
-
- 7
-
-
-
-
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ 1.8
+
+
+
+
+
junit
junit
- 4.3
+ ${junit.version}
test
org.hamcrest
hamcrest-all
- 1.3
+ ${hamcrest.version}
-
- org.xmlunit
- xmlunit-matchers
- 2.2.1
-
+
+ org.xmlunit
+ xmlunit-matchers
+ ${xmlunit.version}
+
-
- org.xmlunit
- xmlunit-core
- 2.2.1
-
+
+ org.xmlunit
+ xmlunit-core
+ ${xmlunit.version}
+
+
+
+
+
+ 4.12
+ 1.3
+ 2.3.0
+
+
+ 3.6.0
+
+
diff --git a/xstream/pom.xml b/xstream/pom.xml
index f505019d71..7af8efa659 100644
--- a/xstream/pom.xml
+++ b/xstream/pom.xml
@@ -11,25 +11,25 @@
com.thoughtworks.xstream
xstream
- 1.4.5
+ ${xstream.version}
org.codehaus.jettison
jettison
- 1.3.7
+ ${jettison.version}
junit
junit
- 4.12
+ ${junit.version}
log4j
log4j
- 1.2.17
+ ${log4j.version}
@@ -38,7 +38,7 @@
org.apache.maven.plugins
maven-compiler-plugin
- 3.5.1
+ ${maven-compiler-plugin.version}
1.8
@@ -47,4 +47,17 @@
+
+ 1.4.9
+ 1.3.8
+
+ 1.2.17
+
+ 4.12
+
+
+ 3.6.0
+
+
+
\ No newline at end of file