diff --git a/core-java/pom.xml b/core-java/pom.xml index 1986f3e981..5cfd60f746 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -1,176 +1,183 @@ - - 4.0.0 - org.baeldung - core-java - 0.1-SNAPSHOT + + 4.0.0 + org.baeldung + core-java + 0.1-SNAPSHOT - core-java + core-java - + - + - - com.google.guava - guava - ${guava.version} - + + com.google.guava + guava + ${guava.version} + - - org.apache.commons - commons-collections4 - 4.0 - + + org.apache.commons + commons-collections4 + 4.0 + - - commons-io - commons-io - 2.4 - + + commons-io + commons-io + 2.4 + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - + + org.apache.commons + commons-math3 + 3.3 + - + - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - + - + + com.fasterxml.jackson.core + jackson-databind + ${jackson.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} - + - + + 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} + - - junit - junit-dep - ${junit.version} - test - + - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + junit + junit-dep + ${junit.version} + test + - - org.mockito - mockito-core - ${mockito.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 + - - core-java - - - src/main/resources - true - - + - + + core-java + + + src/main/resources + true + + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.7 - 1.7 - - + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.7 + 1.7 + + - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + - + - - - 4.0.5.RELEASE - 3.2.4.RELEASE + - - 4.3.5.Final - 5.1.30 + + + 4.0.5.RELEASE + 3.2.4.RELEASE - - 2.3.3 + + 4.3.5.Final + 5.1.30 - - 1.7.6 - 1.1.1 + + 2.3.3 - - 5.1.1.Final + + 1.7.6 + 1.1.1 - - 17.0 - 3.3.2 + + 5.1.1.Final - - 1.3 - 4.11 - 1.9.5 + + 17.0 + 3.3.2 - 4.3.2 - 4.3.3 + + 1.3 + 4.11 + 1.9.5 - 2.3.1 + 4.3.2 + 4.3.3 - - 3.1 - 2.4 - 2.17 - 2.6 - 1.4.8 + 2.3.1 - + + 3.1 + 2.4 + 2.17 + 2.6 + 1.4.8 + + \ No newline at end of file diff --git a/core-java/src/test/java/org/baeldung/java/CoreJavaRandomUnitTest.java b/core-java/src/test/java/org/baeldung/java/CoreJavaRandomUnitTest.java new file mode 100644 index 0000000000..17a78651ff --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/CoreJavaRandomUnitTest.java @@ -0,0 +1,170 @@ +package org.baeldung.java; + +import java.util.Random; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.math3.random.RandomDataGenerator; +import org.junit.Test; + +public class CoreJavaRandomUnitTest { + + // tests - random long + + @Test + public void givenUsingPlainJava_whenGeneratingRandomLongUnbounded_thenCorrect() { + final long generatedLong = new Random().nextLong(); + + System.out.println(generatedLong); + } + + @Test + public void givenUsingPlainJava_whenGeneratingRandomLongBounded_thenCorrect() { + final long leftLimit = 1L; + final long rightLimit = 10L; + final long generatedLong = leftLimit + (long) (Math.random() * (rightLimit - leftLimit)); + + System.out.println(generatedLong); + } + + @Test + public void givenUsingApacheCommons_whenGeneratingRandomLongBounded_thenCorrect() { + final long leftLimit = 10L; + final long rightLimit = 100L; + final long generatedLong = new RandomDataGenerator().nextLong(leftLimit, rightLimit); + + System.out.println(generatedLong); + } + + // tests - random int + + @Test + public void givenUsingPlainJava_whenGeneratingRandomIntegerUnbounded_thenCorrect() { + final int generatedInteger = new Random().nextInt(); + + System.out.println(generatedInteger); + } + + @Test + public void givenUsingPlainJava_whenGeneratingRandomIntegerBounded_thenCorrect() { + final int leftLimit = 1; + final int rightLimit = 10; + final int generatedInteger = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit)); + + System.out.println(generatedInteger); + } + + @Test + public void givenUsingApache_whenGeneratingRandomIntegerBounded_thenCorrect() { + final int leftLimit = 1; + final int rightLimit = 10; + final int generatedInteger = new RandomDataGenerator().nextInt(leftLimit, rightLimit); + + System.out.println(generatedInteger); + } + + // tests - random float + + @Test + public void givenUsingPlainJava_whenGeneratingRandomFloatUnbouned_thenCorrect() { + final float generatedFloat = new Random().nextFloat(); + + System.out.println(generatedFloat); + } + + @Test + public void givenUsingPlainJava_whenGeneratingRandomFloatBouned_thenCorrect() { + final float leftLimit = 1F; + final float rightLimit = 10F; + final float generatedFloat = leftLimit + new Random().nextFloat() * (rightLimit - leftLimit); + + System.out.println(generatedFloat); + } + + @Test + public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() { + final float leftLimit = 1F; + final float rightLimit = 10F; + final float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); + final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit); + + System.out.println(generatedFloat); + } + + // tests - random double + + @Test + public void givenUsingPlainJava_whenGeneratingRandomDoubleUnbounded_thenCorrect() { + final double generatedDouble = Math.random(); + + System.out.println(generatedDouble); + } + + @Test + public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() { + final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble(); + + System.out.println(generatedDouble); + } + + @Test + public void givenUsingPlainJava_whenGeneratingRandomDoubleBounded_thenCorrect() { + final double leftLimit = 1D; + final double rightLimit = 10D; + final double generatedDouble = leftLimit + new Random().nextDouble() * (rightLimit - leftLimit); + + System.out.println(generatedDouble); + } + + @Test + public void givenUsingApache_whenGeneratingRandomDoubleBounded_thenCorrect() { + final double leftLimit = 1D; + final double rightLimit = 100D; + final double generatedDouble = new RandomDataGenerator().nextUniform(leftLimit, rightLimit); + + System.out.println(generatedDouble); + } + + // tests - random String + + @Test + public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() { + final byte[] array = new byte[7]; // length is bounded by 7 + new Random().nextBytes(array); + final String generatedString = new String(array); + + System.out.println(generatedString); + } + + @Test + public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() { + final int leftLimit = 97; // letter 'a' + final int rightLimit = 122; // letter 'z' + final int targetStringLength = 10; + final StringBuilder buffer = new StringBuilder(targetStringLength); + for (int i = 0; i < targetStringLength; i++) { + final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit)); + buffer.append((char) randomLimitedInt); + } + final String generatedString = new String(buffer); + + System.out.println(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomStringUnbounded_thenCorrect() { + final String generatedString = RandomStringUtils.random(10); + + System.out.println(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() { + final int length = 10; + final boolean useLetters = true; + final boolean useNumbers = false; + final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); + + System.out.println(generatedString); + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java index 0ce720c80a..c139e34afb 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java @@ -1,5 +1,7 @@ package org.baeldung.java.io; +import static org.junit.Assert.assertTrue; + import java.io.File; import java.io.IOException; import java.nio.file.FileSystemException; @@ -17,7 +19,9 @@ public class JavaFileIntegrationTest { @Test public final void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException { final File newFile = new File("src/test/resources/newFile_jdk6.txt"); - newFile.createNewFile(); + final boolean success = newFile.createNewFile(); + + assertTrue(success); } @Test @@ -27,10 +31,15 @@ public class JavaFileIntegrationTest { } @Test - public final void givenUsingApache_whenCreatingFile_thenCorrect() throws IOException { + public final void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException { FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt")); } + @Test + public final void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException { + com.google.common.io.Files.touch(new File("src/test/resources/newFile_guava.txt")); + } + // move a file @Test @@ -76,6 +85,41 @@ public class JavaFileIntegrationTest { FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove.txt"), FileUtils.getFile("src/main/resources/"), true); } - // rename a file + // delete a file + + @Test + public final void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException { + new File("src/test/resources/fileToDelete_jdk6.txt").createNewFile(); + + final File fileToDelete = new File("src/test/resources/fileToDelete_jdk6.txt"); + final boolean success = fileToDelete.delete(); + + assertTrue(success); + } + + @Test + public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException { + // Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt")); + + final Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt"); + Files.delete(fileToDeletePath); + } + + @Test + public final void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException { + FileUtils.touch(new File("src/test/resources/fileToDelete_commonsIo.txt")); + + final File fileToDelete = FileUtils.getFile("src/test/resources/fileToDelete_commonsIo.txt"); + final boolean success = FileUtils.deleteQuietly(fileToDelete); + + assertTrue(success); + } + + @Test + public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException { + // FileUtils.touch(new File("src/test/resources/fileToDelete.txt")); + + FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt")); + } } diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java new file mode 100644 index 0000000000..7cb9276283 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java @@ -0,0 +1,186 @@ +package org.baeldung.java.io; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; +import java.io.Writer; +import java.nio.charset.Charset; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.io.input.CharSequenceReader; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.io.CharSink; +import com.google.common.io.CharSource; +import com.google.common.io.CharStreams; +import com.google.common.io.FileWriteMode; + +@SuppressWarnings("unused") +public class JavaReaderToXUnitTest { + protected final Logger logger = LoggerFactory.getLogger(getClass()); + private static final int DEFAULT_SIZE = 1500000; + + // tests - sandbox + + // tests - Reader to String + + @Test + public void givenUsingPlainJava_whenConvertingReaderIntoStringV1_thenCorrect() throws IOException { + final StringReader reader = new StringReader("With Java 1"); + int intValueOfChar; + String targetString = ""; + while ((intValueOfChar = reader.read()) != -1) { + targetString += (char) intValueOfChar; + } + reader.close(); + } + + @Test + public void givenUsingPlainJava_whenConvertingReaderIntoStringV2_thenCorrect() throws IOException { + final Reader initialReader = new StringReader("With Java 1"); + final char[] arr = new char[8 * 1024]; + final StringBuilder buffer = new StringBuilder(); + int numCharsRead; + while ((numCharsRead = initialReader.read(arr, 0, arr.length)) != -1) { + buffer.append(arr, 0, numCharsRead); + } + initialReader.close(); + final String targetString = buffer.toString(); + } + + @Test + public void givenUsingGuava_whenConvertingReaderIntoString_thenCorrect() throws IOException { + final Reader initialReader = CharSource.wrap("With Google Guava").openStream(); + final String targetString = CharStreams.toString(initialReader); + initialReader.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingReaderIntoString_thenCorrect() throws IOException { + final Reader initialReader = new StringReader("With Apache Commons"); + final String targetString = IOUtils.toString(initialReader); + initialReader.close(); + } + + // tests - Reader WRITE TO File + + @Test + public void givenUsingPlainJava_whenConvertingReaderIntoFile_thenCorrect() throws IOException { + final File sourceFile = new File("src/test/resources/sourceFile.txt"); + sourceFile.createNewFile(); + + final Reader initialReader = new FileReader(sourceFile); + final char[] buffer = new char[(int) sourceFile.length()]; + initialReader.read(buffer); + initialReader.close(); + + final File targetFile = new File("src/test/resources/targetFile.txt"); + targetFile.createNewFile(); + + final Writer targetFileWriter = new FileWriter(targetFile); + targetFileWriter.write(buffer); + targetFileWriter.close(); + } + + @Test + public void givenUsingGuava_whenConvertingReaderIntoFile_thenCorrect() throws IOException { + final Reader initialReader = CharSource.wrap("IDDQD").openStream(); + final File targetFile = new File("src/test/resources/targetFile.txt"); + com.google.common.io.Files.touch(targetFile); + final CharSink charSink = com.google.common.io.Files.asCharSink(targetFile, Charset.defaultCharset(), FileWriteMode.APPEND); + charSink.writeFrom(initialReader); + initialReader.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingReaderIntoFile_thenCorrect() throws IOException { + final Reader initialReader = new CharSequenceReader("CharSequenceReader extends Reader"); + final File targetFile = new File("src/test/resources/targetFile.txt"); + FileUtils.touch(targetFile); + final byte[] buffer = IOUtils.toByteArray(initialReader); + FileUtils.writeByteArrayToFile(targetFile, buffer); + initialReader.close(); + } + + // tests - Reader to byte[] + + @Test + public void givenUsingPlainJava_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException { + final Reader initialReader = new StringReader("With Java"); + + final char[] charArray = new char[8 * 1024]; + final StringBuilder builder = new StringBuilder(); + int numCharsRead; + while ((numCharsRead = initialReader.read(charArray, 0, charArray.length)) != -1) { + builder.append(charArray, 0, numCharsRead); + } + final byte[] targetArray = builder.toString().getBytes(); + + initialReader.close(); + } + + @Test + public void givenUsingGuava_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException { + final Reader initialReader = CharSource.wrap("With Google Guava").openStream(); + + final byte[] targetArray = CharStreams.toString(initialReader).getBytes(); + + initialReader.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException { + final StringReader initialReader = new StringReader("With Commons IO"); + + final byte[] targetArray = IOUtils.toByteArray(initialReader); + + initialReader.close(); + } + + // tests - Reader to InputStream + + @Test + public void givenUsingPlainJava_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException { + final Reader initialReader = new StringReader("With Java"); + + final char[] charBuffer = new char[8 * 1024]; + final StringBuilder builder = new StringBuilder(); + int numCharsRead; + while ((numCharsRead = initialReader.read(charBuffer, 0, charBuffer.length)) != -1) { + builder.append(charBuffer, 0, numCharsRead); + } + final InputStream targetStream = new ByteArrayInputStream(builder.toString().getBytes()); + + initialReader.close(); + targetStream.close(); + } + + @Test + public void givenUsingGuava_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException { + final Reader initialReader = new StringReader("With Guava"); + + final InputStream targetStream = new ByteArrayInputStream(CharStreams.toString(initialReader).getBytes()); + + initialReader.close(); + targetStream.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream() throws IOException { + final Reader initialReader = new StringReader("With Commons IO"); + + final InputStream targetStream = IOUtils.toInputStream(initialReader.toString()); + + initialReader.close(); + targetStream.close(); + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaXToByteArrayUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaXToByteArrayUnitTest.java new file mode 100644 index 0000000000..e45e3e73f4 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/io/JavaXToByteArrayUnitTest.java @@ -0,0 +1,11 @@ +package org.baeldung.java.io; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JavaXToByteArrayUnitTest { + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + // tests - X to Byte Array + +} diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java new file mode 100644 index 0000000000..42ecef4086 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java @@ -0,0 +1,134 @@ +package org.baeldung.java.io; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.nio.charset.Charset; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.io.input.CharSequenceReader; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.io.ByteSource; +import com.google.common.io.ByteStreams; +import com.google.common.io.CharSource; + +public class JavaXToReaderUnitTest { + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + // tests - String to Reader + + @Test + public void givenUsingPlainJava_whenConvertingStringIntoReader_thenCorrect() throws IOException { + final String initialString = "With Plain Java"; + final Reader targetReader = new StringReader(initialString); + targetReader.close(); + } + + @Test + public void givenUsingGuava_whenConvertingStringIntoReader_thenCorrect() throws IOException { + final String initialString = "With Google Guava"; + final Reader targetReader = CharSource.wrap(initialString).openStream(); + targetReader.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingStringIntoReader_thenCorrect() throws IOException { + final String initialString = "With Apache Commons IO"; + final Reader targetReader = new CharSequenceReader(initialString); + targetReader.close(); + } + + // tests - byte array to Reader + + @Test + public void givenUsingPlainJava_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException { + final byte[] initialArray = "Hello world!".getBytes(); + final Reader targetReader = new StringReader(new String(initialArray)); + targetReader.close(); + } + + @Test + public void givenUsingGuava_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException { + final byte[] initialArray = "With Guava".getBytes(); + final String bufferString = new String(initialArray); + final Reader targetReader = CharSource.wrap(bufferString).openStream(); + + targetReader.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException { + final byte[] initialArray = "With Commons IO".getBytes(); + final Reader targetReader = new CharSequenceReader(new String(initialArray)); + targetReader.close(); + } + + // tests - File to Reader + + @Test + public void givenUsingPlainJava_whenConvertingFileIntoReader_thenCorrect() throws IOException { + final File initialFile = new File("src/test/resources/initialFile.txt"); + initialFile.createNewFile(); + final Reader targetReader = new FileReader(initialFile); + targetReader.close(); + } + + @Test + public void givenUsingGuava_whenConvertingFileIntoReader_thenCorrect() throws IOException { + final File initialFile = new File("src/test/resources/initialFile.txt"); + com.google.common.io.Files.touch(initialFile); + final Reader targetReader = com.google.common.io.Files.newReader(initialFile, Charset.defaultCharset()); + targetReader.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingFileIntoReader_thenCorrect() throws IOException { + final File initialFile = new File("src/test/resources/initialFile.txt"); + FileUtils.touch(initialFile); + FileUtils.write(initialFile, "With Commons IO"); + final byte[] buffer = FileUtils.readFileToByteArray(initialFile); + final Reader targetReader = new CharSequenceReader(new String(buffer)); + targetReader.close(); + } + + // tests - InputStream to Reader + + @Test + public void givenUsingPlainJava_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException { + final InputStream initialStream = new ByteArrayInputStream("With Java".getBytes()); + final Reader targetReader = new InputStreamReader(initialStream); + + initialStream.close(); + targetReader.close(); + } + + @Test + public void givenUsingGuava_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException { + final InputStream initialStream = ByteSource.wrap("With Guava".getBytes()).openStream(); + final byte[] buffer = ByteStreams.toByteArray(initialStream); + final Reader targetReader = CharSource.wrap(new String(buffer)).openStream(); + + initialStream.close(); + targetReader.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException { + final InputStream initialStream = IOUtils.toInputStream("With Commons IO"); + final byte[] buffer = IOUtils.toByteArray(initialStream); + final Reader targetReader = new CharSequenceReader(new String(buffer)); + + initialStream.close(); + targetReader.close(); + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java new file mode 100644 index 0000000000..35ec15df16 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java @@ -0,0 +1,53 @@ +package org.baeldung.java.io; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; + +import org.apache.commons.io.output.StringBuilderWriter; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.io.CharSink; + +public class JavaXToWriterUnitTest { + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + // tests - byte[] to Writer + + @Test + public void givenPlainJava_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException { + final byte[] initialArray = "With Java".getBytes(); + + final Writer targetWriter = new StringWriter().append(new String(initialArray)); + + targetWriter.close(); + } + + @Test + public void givenUsingGuava_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException { + final byte[] initialArray = "With Guava".getBytes(); + + final String buffer = new String(initialArray); + final StringWriter stringWriter = new StringWriter(); + final CharSink charSink = new CharSink() { + @Override + public final Writer openStream() throws IOException { + return stringWriter; + } + }; + charSink.write(buffer); + + stringWriter.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException { + final byte[] initialArray = "With Commons IO".getBytes(); + final Writer targetWriter = new StringBuilderWriter(new StringBuilder(new String(initialArray))); + + targetWriter.close(); + } + +} diff --git a/core-java/src/test/resources/sourceFile.txt b/core-java/src/test/resources/sourceFile.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java/src/test/resources/targetFile.txt b/core-java/src/test/resources/targetFile.txt new file mode 100644 index 0000000000..f04ec3d9a9 --- /dev/null +++ b/core-java/src/test/resources/targetFile.txt @@ -0,0 +1 @@ +CharSequenceReader extends Reader \ No newline at end of file diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java deleted file mode 100644 index 5096725ece..0000000000 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.httpclient; - -import java.io.IOException; -import java.util.concurrent.ExecutionException; - -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.conn.ConnectionRequest; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.impl.conn.BasicHttpClientConnectionManager; -import org.junit.Test; - -@SuppressWarnings("unused") -public class HttpClientConnectionManagementTest { - - // tests - - @Test - public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException { - final HttpClientContext context = HttpClientContext.create(); - final BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(); - final HttpRoute route = new HttpRoute(new HttpHost("localhost", 80)); - final ConnectionRequest connRequest = connManager.requestConnection(route, null); - - connManager.shutdown(); - } - -} diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java new file mode 100644 index 0000000000..c5c960f527 --- /dev/null +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java @@ -0,0 +1,389 @@ +package org.baeldung.httpclient.conn; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +import org.apache.http.HeaderElement; +import org.apache.http.HeaderElementIterator; +import org.apache.http.HttpClientConnection; +import org.apache.http.HttpException; +import org.apache.http.HttpHost; +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.config.SocketConfig; +import org.apache.http.conn.ConnectionKeepAliveStrategy; +import org.apache.http.conn.ConnectionRequest; +import org.apache.http.conn.routing.HttpRoute; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.BasicHttpClientConnectionManager; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.message.BasicHeaderElementIterator; +import org.apache.http.protocol.HTTP; +import org.apache.http.protocol.HttpContext; +import org.apache.http.protocol.HttpCoreContext; +import org.apache.http.protocol.HttpRequestExecutor; +import org.apache.http.util.EntityUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +public class HttpClientConnectionManagementTest { + private static final String SERVER1 = "http://www.petrikainulainen.net/"; + private static final String SERVER7 = "http://www.baeldung.com/"; + + private BasicHttpClientConnectionManager basicConnManager; + private PoolingHttpClientConnectionManager poolingConnManager; + + private HttpClientContext context; + private HttpRoute route; + private HttpClientConnection conn1; + private HttpClientConnection conn; + private HttpClientConnection conn2; + + private CloseableHttpResponse response; + private HttpGet get1; + private HttpGet get2; + + private CloseableHttpClient client; + + @Before + public final void before() { + get1 = new HttpGet(SERVER1); + get2 = new HttpGet(SERVER7); + route = new HttpRoute(new HttpHost("www.baeldung.com", 80)); + } + + @After + public final void after() throws IllegalStateException, IOException { + if (conn != null) { + conn.close(); + } + if (conn1 != null) { + conn1.close(); + } + if (conn2 != null) { + conn2.close(); + } + if (poolingConnManager != null) { + poolingConnManager.shutdown(); + } + if (basicConnManager != null) { + basicConnManager.shutdown(); + } + if (client != null) { + client.close(); + } + if (response != null) { + response.close(); + } + } + + // 2 + + @Test + // 2.1 IN ARTCLE + public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException { + basicConnManager = new BasicHttpClientConnectionManager(); + final ConnectionRequest connRequest = basicConnManager.requestConnection(route, null); + assertTrue(connRequest.get(1000, TimeUnit.SECONDS) != null); + } + + @Test + // @Ignore + // 2.2 IN ARTICLE + public final void whenOpeningLowLevelConnectionWithSocketTimeout_thenNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException { + basicConnManager = new BasicHttpClientConnectionManager(); + context = HttpClientContext.create(); + final ConnectionRequest connRequest = basicConnManager.requestConnection(route, null); + conn = connRequest.get(1000, TimeUnit.SECONDS); + if (!conn.isOpen()) { + basicConnManager.connect(conn, route, 1000, context); + } + conn.setSocketTimeout(30000); + + assertTrue(conn.getSocketTimeout() == 30000); + assertTrue(conn.isOpen()); + } + + // 3 + + @Test + // Example 3.1. + public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws InterruptedException, ClientProtocolException, IOException { + poolingConnManager = new PoolingHttpClientConnectionManager(); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + client.execute(get1); + + assertTrue(poolingConnManager.getTotalStats().getLeased() == 1); + } + + @Test + // @Ignore + // Example 3.2. TESTER VERSION + /*tester*/public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException { + poolingConnManager = new PoolingHttpClientConnectionManager(); + final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client1, get1, poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client2, get2, poolingConnManager); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(1000); + assertTrue(poolingConnManager.getTotalStats().getLeased() == 2); + } + + @Test + // @Ignore + // Example 3.2. ARTICLE VERSION + public final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException { + poolingConnManager = new PoolingHttpClientConnectionManager(); + final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client1, get1); + final MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client2, get2); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + } + + // 4 + + @Test + // Example 4.1 + public final void whenIncreasingConnectionPool_thenNoEceptions() { + poolingConnManager = new PoolingHttpClientConnectionManager(); + poolingConnManager.setMaxTotal(5); + poolingConnManager.setDefaultMaxPerRoute(4); + + final HttpHost localhost = new HttpHost("locahost", 80); + poolingConnManager.setMaxPerRoute(new HttpRoute(localhost), 5); + } + + @Test + // @Ignore + // 4.2 Tester Version + /*tester*/public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException { + poolingConnManager = new PoolingHttpClientConnectionManager(); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager); + thread1.start(); + thread2.start(); + thread3.start(); + thread1.join(10000); + thread2.join(10000); + thread3.join(10000); + } + + @Test + // 4.2 Article version + public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteReuqest() throws InterruptedException { + final HttpGet get = new HttpGet("http://www.google.com"); + poolingConnManager = new PoolingHttpClientConnectionManager(); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client, get); + final MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client, get); + final MultiHttpClientConnThread thread3 = new MultiHttpClientConnThread(client, get); + thread1.start(); + thread2.start(); + thread3.start(); + thread1.join(); + thread2.join(); + thread3.join(); + } + + // 5 + + @Test + // @Ignore + // 5.1 + public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() throws ClientProtocolException, IOException { + final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() { + @Override + public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) { + final HeaderElementIterator it = new BasicHeaderElementIterator(myResponse.headerIterator(HTTP.CONN_KEEP_ALIVE)); + while (it.hasNext()) { + final HeaderElement he = it.nextElement(); + final String param = he.getName(); + final String value = he.getValue(); + if (value != null && param.equalsIgnoreCase("timeout")) { + return Long.parseLong(value) * 1000; + } + } + final HttpHost target = (HttpHost) myContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); + if ("localhost".equalsIgnoreCase(target.getHostName())) { + return 10 * 1000; + } else { + return 5 * 1000; + } + } + + }; + client = HttpClients.custom().setKeepAliveStrategy(myStrategy).setConnectionManager(poolingConnManager).build(); + client.execute(get1); + client.execute(get2); + } + + // 6 + + @Test + // @Ignore + // 6.1 + public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException { + basicConnManager = new BasicHttpClientConnectionManager(); + context = HttpClientContext.create(); + + final ConnectionRequest connRequest = basicConnManager.requestConnection(route, null); + conn = connRequest.get(10, TimeUnit.SECONDS); + + basicConnManager.connect(conn, route, 1000, context); + basicConnManager.routeComplete(conn, route, context); + final HttpRequestExecutor exeRequest = new HttpRequestExecutor(); + context.setTargetHost((new HttpHost("www.baeldung.com", 80))); + + final HttpGet get = new HttpGet("http://www.baeldung.com"); + exeRequest.execute(get, conn, context); + conn.isResponseAvailable(1000); + basicConnManager.releaseConnection(conn, null, 1, TimeUnit.SECONDS); + + // + client = HttpClients.custom().setConnectionManager(basicConnManager).build(); + client.execute(get); + } + + @Test + // @Ignore + // 6.2 TESTER VERSION + /*tester*/public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { + poolingConnManager = new PoolingHttpClientConnectionManager(); + poolingConnManager.setDefaultMaxPerRoute(5); + poolingConnManager.setMaxTotal(5); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final MultiHttpClientConnThread[] threads = new MultiHttpClientConnThread[10]; + int countConnMade = 0; + for (int i = 0; i < threads.length; i++) { + threads[i] = new MultiHttpClientConnThread(client, get1, poolingConnManager); + } + for (final MultiHttpClientConnThread thread : threads) { + thread.start(); + } + for (final MultiHttpClientConnThread thread : threads) { + thread.join(10000); + countConnMade++; + if (countConnMade == 0) + assertTrue(thread.getLeasedConn() == 5); + } + } + + @Test + // 6.2 ARTICLE VERSION + // @Ignore + public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException { + final HttpGet get = new HttpGet("http://echo.200please.com"); + poolingConnManager = new PoolingHttpClientConnectionManager(); + poolingConnManager.setDefaultMaxPerRoute(5); + poolingConnManager.setMaxTotal(5); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final MultiHttpClientConnThread[] threads = new MultiHttpClientConnThread[10]; + for (int i = 0; i < threads.length; i++) { + threads[i] = new MultiHttpClientConnThread(client, get, poolingConnManager); + } + for (final MultiHttpClientConnThread thread : threads) { + thread.start(); + } + for (final MultiHttpClientConnThread thread : threads) { + thread.join(10000); + } + } + + // 7 + + @Test + // 7.1 + public final void whenConfiguringTimeOut_thenNoExceptions() { + route = new HttpRoute(new HttpHost("localhost", 80)); + poolingConnManager = new PoolingHttpClientConnectionManager(); + poolingConnManager.setSocketConfig(route.getTargetHost(), SocketConfig.custom().setSoTimeout(5000).build()); + assertTrue(poolingConnManager.getSocketConfig(route.getTargetHost()).getSoTimeout() == 5000); + } + + // 8 + + @Test + // @Ignore + // 8.1 + public final void whenHttpClientChecksStaleConns_thenNoExceptions() { + poolingConnManager = new PoolingHttpClientConnectionManager(); + client = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setStaleConnectionCheckEnabled(true).build()).setConnectionManager(poolingConnManager).build(); + } + + @Test + @Ignore("Very Long Running") + // 8.2 TESTER VERSION + /*tester*/public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException { + poolingConnManager = new PoolingHttpClientConnectionManager(); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager); + final HttpGet get = new HttpGet("http://google.com"); + // test this with new HttpGet("http://iotechperu.com")----First test will fail b/c there is redirect connection at that site + final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager); + staleMonitor.start(); + thread1.start(); + thread1.join(); + thread2.start(); + thread2.join(); + thread3.start(); + assertTrue(poolingConnManager.getTotalStats().getAvailable() == 1); + thread3.join(32000); + assertTrue(poolingConnManager.getTotalStats().getAvailable() == 0); + } + + @Test + // @Ignore + // 8.2 ARTICLE VERSION + public final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException, IOException { + final HttpGet get = new HttpGet("http://google.com"); + poolingConnManager = new PoolingHttpClientConnectionManager(); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager); + staleMonitor.start(); + staleMonitor.join(1000); + } + + // 9 + + @Test(expected = IllegalStateException.class) + // @Ignore + // 9.1 + public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions1() throws InterruptedException, ExecutionException, IOException, HttpException { + poolingConnManager = new PoolingHttpClientConnectionManager(); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final HttpGet get = new HttpGet("http://google.com"); + response = client.execute(get); + + EntityUtils.consume(response.getEntity()); + response.close(); + client.close(); + poolingConnManager.close(); + poolingConnManager.shutdown(); + + client.execute(get); + + assertTrue(response.getEntity() == null); + } + +} diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java new file mode 100644 index 0000000000..2a1c419e41 --- /dev/null +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java @@ -0,0 +1,41 @@ +package org.baeldung.httpclient.conn; + +import java.util.concurrent.TimeUnit; + +import org.apache.http.conn.HttpClientConnectionManager; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; + +public class IdleConnectionMonitorThread extends Thread { + private final HttpClientConnectionManager connMgr; + private volatile boolean shutdown; + + public IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) { + super(); + this.connMgr = connMgr; + } + + // API + + @Override + public final void run() { + try { + while (!shutdown) { + synchronized (this) { + wait(1000); + connMgr.closeExpiredConnections(); + connMgr.closeIdleConnections(30, TimeUnit.SECONDS); + } + } + } catch (final InterruptedException ex) { + shutdown(); + } + } + + public final void shutdown() { + shutdown = true; + synchronized (this) { + notifyAll(); + } + } + +} diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java new file mode 100644 index 0000000000..071b964710 --- /dev/null +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java @@ -0,0 +1,71 @@ +package org.baeldung.httpclient.conn; + +import java.io.IOException; + +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MultiHttpClientConnThread extends Thread { + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private final CloseableHttpClient client; + private final HttpGet get; + + private PoolingHttpClientConnectionManager connManager; + public int leasedConn; + + public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { + this.client = client; + this.get = get; + this.connManager = connManager; + leasedConn = 0; + } + + public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) { + this.client = client; + this.get = get; + } + + // API + + public final int getLeasedConn() { + return leasedConn; + } + + // + + @Override + public final void run() { + try { + logger.debug("Thread Running: " + getName()); + + logger.debug("Thread Running: " + getName()); + + if (connManager != null) { + logger.info("Before - Leased Connections = " + connManager.getTotalStats().getLeased()); + logger.info("Before - Available Connections = " + connManager.getTotalStats().getAvailable()); + } + + final HttpResponse response = client.execute(get); + + if (connManager != null) { + leasedConn = connManager.getTotalStats().getLeased(); + logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased()); + logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable()); + } + + EntityUtils.consume(response.getEntity()); + } catch (final ClientProtocolException ex) { + logger.error("", ex); + } catch (final IOException ex) { + logger.error("", ex); + } + } + +} diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java new file mode 100644 index 0000000000..62cd466596 --- /dev/null +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java @@ -0,0 +1,48 @@ +package org.baeldung.httpclient.conn; + +import java.io.IOException; + +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.base.Preconditions; + +public class TesterVersion_MultiHttpClientConnThread extends Thread { + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private final CloseableHttpClient client; + private final HttpGet get; + private PoolingHttpClientConnectionManager connManager; + + public TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { + this.client = client; + this.get = get; + this.connManager = Preconditions.checkNotNull(connManager); + } + + // + + @Override + public final void run() { + try { + logger.debug("Thread Running: " + getName()); + + logger.info("Before - Leased Connections = " + connManager.getTotalStats().getLeased()); + logger.info("Before - Available Connections = " + connManager.getTotalStats().getAvailable()); + + client.execute(get); + + logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased()); + logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable()); + } catch (final ClientProtocolException ex) { + logger.error("", ex); + } catch (final IOException ex) { + logger.error("", ex); + } + } + +} diff --git a/jackson/src/test/java/org/baeldung/jackson/dtos/MyDtoNullKeySerializer.java b/jackson/src/test/java/org/baeldung/jackson/serialization/MyDtoNullKeySerializer.java similarity index 89% rename from jackson/src/test/java/org/baeldung/jackson/dtos/MyDtoNullKeySerializer.java rename to jackson/src/test/java/org/baeldung/jackson/serialization/MyDtoNullKeySerializer.java index ab8ac6249d..8219abaddf 100644 --- a/jackson/src/test/java/org/baeldung/jackson/dtos/MyDtoNullKeySerializer.java +++ b/jackson/src/test/java/org/baeldung/jackson/serialization/MyDtoNullKeySerializer.java @@ -1,4 +1,4 @@ -package org.baeldung.jackson.dtos; +package org.baeldung.jackson.serialization; import java.io.IOException; @@ -11,9 +11,7 @@ public class MyDtoNullKeySerializer extends JsonSerializer { @Override public void serialize(final Object value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeFieldName(""); - } } diff --git a/jackson/src/test/java/org/baeldung/jackson/test/JacksonFieldUnitTest.java b/jackson/src/test/java/org/baeldung/jackson/test/JacksonFieldUnitTest.java index a06e7267b6..2f0fb6eb4a 100644 --- a/jackson/src/test/java/org/baeldung/jackson/test/JacksonFieldUnitTest.java +++ b/jackson/src/test/java/org/baeldung/jackson/test/JacksonFieldUnitTest.java @@ -17,13 +17,12 @@ import org.junit.Test; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonFieldUnitTest { @Test - public final void givenDifferentAccessLevels_whenPublic_thenSerializable() throws JsonProcessingException { + public final void givenDifferentAccessLevels_whenSerializing_thenPublicFieldsAreSerialized() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); final MyDtoAccessLevel dtoObject = new MyDtoAccessLevel(); @@ -48,7 +47,7 @@ public class JacksonFieldUnitTest { } @Test - public final void givenDifferentAccessLevels_whenGetterAdded_thenDeserializable() throws JsonProcessingException, JsonMappingException, IOException { + public final void givenDifferentAccessLevels_whenGetterAdded_thenDeserializable() throws IOException { final String jsonAsString = "{\"stringValue\":\"dtoString\"}"; final ObjectMapper mapper = new ObjectMapper(); @@ -59,7 +58,7 @@ public class JacksonFieldUnitTest { } @Test - public final void givenDifferentAccessLevels_whenSetterAdded_thenDeserializable() throws JsonProcessingException, JsonMappingException, IOException { + public final void givenDifferentAccessLevels_whenSetterAdded_thenDeserializable() throws IOException { final String jsonAsString = "{\"intValue\":1}"; final ObjectMapper mapper = new ObjectMapper(); @@ -70,7 +69,7 @@ public class JacksonFieldUnitTest { } @Test - public final void givenDifferentAccessLevels_whenSetterAdded_thenStillNotSerializable() throws JsonProcessingException { + public final void givenDifferentAccessLevels_whenSetterAdded_thenStillNotSerializable() throws IOException { final ObjectMapper mapper = new ObjectMapper(); final MyDtoSetter dtoObject = new MyDtoSetter(); @@ -81,7 +80,7 @@ public class JacksonFieldUnitTest { } @Test - public final void givenDifferentAccessLevels_whenSetVisibility_thenSerializable() throws JsonProcessingException { + public final void givenDifferentAccessLevels_whenSetVisibility_thenSerializable() throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); diff --git a/jackson/src/test/java/org/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java b/jackson/src/test/java/org/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java index c973584f9b..d0e0426ff0 100644 --- a/jackson/src/test/java/org/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java +++ b/jackson/src/test/java/org/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java @@ -10,12 +10,12 @@ import java.util.Map; import org.baeldung.jackson.dtos.MyDto; import org.baeldung.jackson.dtos.MyDtoIncludeNonDefault; -import org.baeldung.jackson.dtos.MyDtoNullKeySerializer; import org.baeldung.jackson.dtos.MyDtoWithFilter; import org.baeldung.jackson.dtos.MyMixInForString; import org.baeldung.jackson.dtos.ignore.MyDtoIgnoreField; import org.baeldung.jackson.dtos.ignore.MyDtoIgnoreFieldByName; import org.baeldung.jackson.dtos.ignore.MyDtoIgnoreNull; +import org.baeldung.jackson.serialization.MyDtoNullKeySerializer; import org.junit.Test; import com.fasterxml.jackson.annotation.JsonInclude.Include; @@ -187,6 +187,8 @@ public class JacksonSerializationIgnoreUnitTest { System.out.println(dtoAsString); } + // map + @Test public final void givenIgnoringMapNullValue_whenWritingMapObjectWithNullValue_thenIgnored() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceData.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooFixtures.java similarity index 65% rename from spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceData.java rename to spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooFixtures.java index 5b8696821d..8b16f9b605 100644 --- a/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceData.java +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooFixtures.java @@ -8,26 +8,21 @@ import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.hibernate.service.ServiceRegistry; import com.google.common.collect.Lists; -public class FooSortingPersistenceServiceData { - private static ServiceRegistry serviceRegistry; - private static SessionFactory sessionFactory; - private static Configuration configuration; - private static StandardServiceRegistryBuilder builder; +public class FooFixtures { + private SessionFactory sessionFactory; - public FooSortingPersistenceServiceData() { + public FooFixtures(final SessionFactory sessionFactory) { super(); + + this.sessionFactory = sessionFactory; } - public void createBars() { + // API - configWork(); + public void createBars() { Session session = null; Transaction tx = null; session = sessionFactory.openSession(); @@ -66,8 +61,6 @@ public class FooSortingPersistenceServiceData { } public void createFoos() { - - configWork(); Session session = null; Transaction tx = null; session = sessionFactory.openSession(); @@ -105,15 +98,4 @@ public class FooSortingPersistenceServiceData { } } - public void configWork() { - configuration = new Configuration(); - configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); - configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect"); - configuration.setProperty(AvailableSettings.DRIVER, "com.mysql.jdbc.Driver"); - configuration.setProperty(AvailableSettings.URL, "jdbc:mysql://localhost:3306/HIBERTEST2_TEST"); - configuration.setProperty(AvailableSettings.USER, "root"); - configuration.setProperty(AvailableSettings.PASS, ""); - builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); - sessionFactory = configuration.addPackage("com.cc.example.hibernate").addAnnotatedClass(Foo.class).addAnnotatedClass(Bar.class).configure().buildSessionFactory(builder.build()); - } } diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java index ec90c3779c..3d5c14231e 100644 --- a/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java @@ -34,10 +34,10 @@ import com.google.common.collect.Lists; public class FooPaginationPersistenceIntegrationTest { @Autowired - private SessionFactory sessionFactory; + private IFooService fooService; @Autowired - private IFooService fooService; + private SessionFactory sessionFactory; private Session session; @@ -140,8 +140,9 @@ public class FooPaginationPersistenceIntegrationTest { int i = 0; while (pageSize > i++) { fooPage.add((Foo) resultScroll.get(0)); - if (!resultScroll.next()) + if (!resultScroll.next()) { break; + } } assertThat(fooPage, hasSize(lessThan(10 + 1))); diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceTest.java index 6b1f4318de..3e600816f5 100644 --- a/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceTest.java +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceTest.java @@ -5,8 +5,6 @@ import static org.junit.Assert.assertNull; import java.util.List; import java.util.Set; -import javax.imageio.spi.ServiceRegistry; - import org.baeldung.persistence.model.Bar; import org.baeldung.persistence.model.Foo; import org.baeldung.spring.PersistenceConfig; @@ -15,14 +13,12 @@ import org.hibernate.NullPrecedence; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Order; import org.junit.After; 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; @@ -31,40 +27,32 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) @SuppressWarnings("unchecked") public class FooSortingPersistenceServiceTest { - private SessionFactory sf; - private Session sess; - private static ServiceRegistry serviceRegistry; - private static Configuration configuration; - private static StandardServiceRegistryBuilder builder; + + @Autowired + private SessionFactory sessionFactory; + + private Session session; @Before public void before() { + session = sessionFactory.openSession(); - final FooSortingPersistenceServiceData fooData = new FooSortingPersistenceServiceData(); + session.beginTransaction(); + + final FooFixtures fooData = new FooFixtures(sessionFactory); fooData.createBars(); - configuration = new Configuration(); - configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); - configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect"); - configuration.setProperty(AvailableSettings.DRIVER, "com.mysql.jdbc.Driver"); - configuration.setProperty(AvailableSettings.URL, "jdbc:mysql://localhost:3306/HIBERTEST2_TEST"); - configuration.setProperty(AvailableSettings.USER, "root"); - configuration.setProperty(AvailableSettings.PASS, ""); - configuration.setProperty("hibernate.show_sql", "true"); - builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); - sf = configuration.addPackage("org.baeldung.persistence.model").addAnnotatedClass(Foo.class).addAnnotatedClass(Bar.class).configure().buildSessionFactory(builder.build()); - sess = sf.openSession(); - sess.beginTransaction(); } @After public void after() { - sess.getTransaction().commit(); + session.getTransaction().commit(); + session.close(); } @Test public final void whenHQlSortingByOneAttribute_thenPrintSortedResults() { final String hql = "FROM Foo f ORDER BY f.name"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); @@ -74,7 +62,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenHQlSortingByStringNullLast_thenLastNull() { final String hql = "FROM Foo f ORDER BY f.name NULLS LAST"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List fooList = query.list(); assertNull(fooList.get(fooList.toArray().length - 1).getName()); @@ -86,7 +74,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenSortingByStringNullsFirst_thenReturnNullsFirst() { final String hql = "FROM Foo f ORDER BY f.name NULLS FIRST"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List fooList = query.list(); assertNull(fooList.get(0).getName()); for (final Foo foo : fooList) { @@ -98,7 +86,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenHQlSortingByOneAttribute_andOrderDirection_thenPrintSortedResults() { final String hql = "FROM Foo f ORDER BY f.name ASC"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); @@ -108,7 +96,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenHQlSortingByMultipleAttributes_thenSortedResults() { final String hql = "FROM Foo f ORDER BY f.name, f.id"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); @@ -118,7 +106,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenHQlSortingByMultipleAttributes_andOrderDirection_thenPrintSortedResults() { final String hql = "FROM Foo f ORDER BY f.name DESC, f.id ASC"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); @@ -127,7 +115,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenHQLCriteriaSortingByOneAttr_thenPrintSortedResults() { - final Criteria criteria = sess.createCriteria(Foo.class, "FOO"); + final Criteria criteria = session.createCriteria(Foo.class, "FOO"); criteria.addOrder(Order.asc("id")); final List fooList = criteria.list(); for (final Foo foo : fooList) { @@ -137,7 +125,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenHQLCriteriaSortingByMultipAttr_thenSortedResults() { - final Criteria criteria = sess.createCriteria(Foo.class, "FOO"); + final Criteria criteria = session.createCriteria(Foo.class, "FOO"); criteria.addOrder(Order.asc("name")); criteria.addOrder(Order.asc("id")); final List fooList = criteria.list(); @@ -148,7 +136,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenCriteriaSortingStringNullsLastAsc_thenNullsLast() { - final Criteria criteria = sess.createCriteria(Foo.class, "FOO"); + final Criteria criteria = session.createCriteria(Foo.class, "FOO"); criteria.addOrder(Order.asc("name").nulls(NullPrecedence.LAST)); final List fooList = criteria.list(); assertNull(fooList.get(fooList.toArray().length - 1).getName()); @@ -159,7 +147,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenCriteriaSortingStringNullsFirstDesc_thenNullsFirst() { - final Criteria criteria = sess.createCriteria(Foo.class, "FOO"); + final Criteria criteria = session.createCriteria(Foo.class, "FOO"); criteria.addOrder(Order.desc("name").nulls(NullPrecedence.FIRST)); final List fooList = criteria.list(); assertNull(fooList.get(0).getName()); @@ -171,7 +159,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenSortingBars_thenBarsWithSortedFoos() { final String hql = "FROM Bar b ORDER BY b.id"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List barList = query.list(); for (final Bar bar : barList) { final Set fooSet = bar.getFooSet(); diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java index aeeb810258..3960aa79ea 100644 --- a/spring-hibernate4/src/test/java/org/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java @@ -2,10 +2,7 @@ package org.baeldung.persistence.service; import org.baeldung.persistence.model.Child; import org.baeldung.persistence.model.Parent; -import org.baeldung.persistence.service.IChildService; -import org.baeldung.persistence.service.IParentService; import org.baeldung.spring.PersistenceConfig; -import org.hibernate.SessionFactory; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -24,9 +21,6 @@ public class ParentServicePersistenceIntegrationTest { @Autowired private IChildService childService; - @Autowired - private SessionFactory sessionFactory; - // tests @Test diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 7238c7ec60..581de439c6 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -39,6 +39,12 @@ runtime + + org.hibernate + hibernate-validator + 5.1.1.Final + + @@ -120,7 +126,7 @@ maven-war-plugin ${maven-war-plugin.version} - + org.apache.maven.plugins maven-surefire-plugin diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/EmployeeController.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/EmployeeController.java new file mode 100644 index 0000000000..007788a843 --- /dev/null +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/EmployeeController.java @@ -0,0 +1,33 @@ +package org.baeldung.spring.controller; + +import javax.validation.Valid; + +import org.baeldung.spring.form.Employee; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +@Controller +public class EmployeeController { + + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } + + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("id", employee.getId()); + return "employeeAdded"; + } + +} diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Employee.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Employee.java new file mode 100644 index 0000000000..5de3d3c899 --- /dev/null +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Employee.java @@ -0,0 +1,39 @@ +package org.baeldung.spring.form; + +public class Employee { + + private String name; + private long id; + private String contactNumber; + + public Employee() { + super(); + } + + // + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getContactNumber() { + return contactNumber; + } + + public void setContactNumber(final String contactNumber) { + this.contactNumber = contactNumber; + } + +} diff --git a/spring-mvc-xml/src/main/resources/webMvcConfig.xml b/spring-mvc-xml/src/main/resources/webMvcConfig.xml index 5f6e26643b..278f6c5533 100644 --- a/spring-mvc-xml/src/main/resources/webMvcConfig.xml +++ b/spring-mvc-xml/src/main/resources/webMvcConfig.xml @@ -1,16 +1,23 @@ - - - - - + + + + + + - + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeAdded.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeAdded.jsp new file mode 100644 index 0000000000..1457bc5fc8 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeAdded.jsp @@ -0,0 +1,24 @@ +<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> + + +Spring MVC Form Handling + + + +

Submitted Employee Information

+ + + + + + + + + + + + + +
Name :${name}
ID :${id}
Contact Number :${contactNumber}
+ + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp new file mode 100644 index 0000000000..97b81b7693 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp @@ -0,0 +1,33 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +SpringMVCExample + + +

Welcome, Enter The Employee Details

+ + + + + + + + + + + + + + + + + + +
Name
Id
Contact Number
+
+ + + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/error.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/error.jsp new file mode 100644 index 0000000000..8f3d83af17 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/error.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +SpringMVCExample + + + +

Pleas enter the correct details

+ + + + +
Retry
+ + + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml index 671813ac90..1a4128fb50 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml @@ -39,7 +39,7 @@ 10 - index.html + index.jsp \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/index.jsp b/spring-mvc-xml/src/main/webapp/index.jsp new file mode 100644 index 0000000000..1ecfcec9d7 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/index.jsp @@ -0,0 +1,18 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Spring MVC Examples + + + +

Spring MVC Examples

+ + + + \ No newline at end of file diff --git a/spring-security-login-error-handling/.springBeans b/spring-security-login-error-handling/.springBeans new file mode 100644 index 0000000000..8096aa036b --- /dev/null +++ b/spring-security-login-error-handling/.springBeans @@ -0,0 +1,15 @@ + + + 1 + + + + + + + + + + + + diff --git a/spring-security-login-error-handling/pom.xml b/spring-security-login-error-handling/pom.xml new file mode 100644 index 0000000000..d26e2d0d44 --- /dev/null +++ b/spring-security-login-error-handling/pom.xml @@ -0,0 +1,212 @@ + + + 4.0.0 + org.baeldung + spring-security-login-error-handling + spring-security-login-error-handling + war + 1.0.0-BUILD-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.1.4.RELEASE + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework + spring-context + + + + commons-logging + commons-logging + + + + + org.springframework + spring-core + + + org.springframework + spring-webmvc + + + org.springframework + spring-jdbc + + + org.springframework + spring-beans + + + org.springframework + spring-aop + + + org.springframework + spring-tx + + + org.springframework + spring-expression + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.springframework.security + spring-security-config + runtime + + + + + org.aspectj + aspectjrt + + + + + org.hibernate + hibernate-validator + + + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + org.slf4j + jcl-over-slf4j + + + + org.slf4j + log4j-over-slf4j + + + + + javax.inject + javax.inject + 1 + + + + + javax.servlet + servlet-api + 2.5 + provided + + + javax.servlet.jsp + jsp-api + 2.1 + provided + + + javax.servlet + jstl + + + + + org.springframework.security + spring-security-taglibs + + + + + junit + junit + test + + + + + + SpringSecurityLogin + + + src/main/resources + true + + + + + + maven-eclipse-plugin + + + org.springframework.ide.eclipse.core.springnature + + + org.springframework.ide.eclipse.core.springbuilder + + true + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + -Xlint:all + true + true + + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.codehaus.mojo + exec-maven-plugin + + org.test.int1.Main + + + + + + + 1.7 + 3.1.1.RELEASE + 3.2.4.RELEASE + 1.6.10 + + + 1.7.6 + 1.1.1 + + + + diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-login-error-handling/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java new file mode 100644 index 0000000000..825eaba71e --- /dev/null +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -0,0 +1,81 @@ +package org.baeldung.security; + +import java.io.IOException; +import java.util.Collection; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.web.DefaultRedirectStrategy; +import org.springframework.security.web.RedirectStrategy; +import org.springframework.security.web.WebAttributes; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; + +public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler { + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); + + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { + handle(request, response, authentication); + HttpSession session = request.getSession(false); + if (session != null) { + session.setMaxInactiveInterval(30); + } + clearAuthenticationAttributes(request); + } + + protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { + String targetUrl = determineTargetUrl(authentication); + + if (response.isCommitted()) { + logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); + return; + } + + redirectStrategy.sendRedirect(request, response, targetUrl); + } + + protected String determineTargetUrl(Authentication authentication) { + boolean isUser = false; + boolean isAdmin = false; + Collection authorities = authentication.getAuthorities(); + for (GrantedAuthority grantedAuthority : authorities) { + if (grantedAuthority.getAuthority().equals("ROLE_USER")) { + isUser = true; + break; + } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) { + isAdmin = true; + break; + } + } + if (isUser) { + return "/homepage.html"; + } else if (isAdmin) { + return "/console.html"; + } else { + throw new IllegalStateException(); + } + } + + protected void clearAuthenticationAttributes(HttpServletRequest request) { + HttpSession session = request.getSession(false); + if (session == null) { + return; + } + session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); + } + + public void setRedirectStrategy(RedirectStrategy redirectStrategy) { + this.redirectStrategy = redirectStrategy; + } + + protected RedirectStrategy getRedirectStrategy() { + return redirectStrategy; + } +} \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java new file mode 100644 index 0000000000..2d83d6a5d9 --- /dev/null +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java @@ -0,0 +1,78 @@ +package org.baeldung.spring; + +import java.util.Locale; + +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ReloadableResourceBundleMessageSource; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.i18n.CookieLocaleResolver; +import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // API + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + + registry.addViewController("/login.html"); + registry.addViewController("/logout.html"); + registry.addViewController("/homepage.html"); + registry.addViewController("/home.html"); + registry.addViewController("/invalidSession.html"); + registry.addViewController("/console.html"); + registry.addViewController("/admin.html"); + registry.addViewController("/registration.html"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + + return bean; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); + localeChangeInterceptor.setParamName("lang"); + registry.addInterceptor(localeChangeInterceptor); + } + + @Bean + public LocaleResolver localeResolver() { + CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); + cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH); + return cookieLocaleResolver; + } + + @Bean + public MessageSource messageSource() { + ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); + messageSource.setBasename("classpath:messages"); + messageSource.setUseCodeAsDefaultMessage(true); + messageSource.setDefaultEncoding("UTF-8"); + messageSource.setCacheSeconds(0); + return messageSource; + } + +} \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java new file mode 100644 index 0000000000..3e793a33f6 --- /dev/null +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -0,0 +1,14 @@ +package org.baeldung.spring; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; + +@Configuration +@ImportResource({ "classpath:webSecurityConfig.xml" }) +public class SecSecurityConfig { + + public SecSecurityConfig() { + super(); + } + +} diff --git a/spring-security-login-error-handling/src/main/resources/logback.xml b/spring-security-login-error-handling/src/main/resources/logback.xml new file mode 100644 index 0000000000..1146dade63 --- /dev/null +++ b/spring-security-login-error-handling/src/main/resources/logback.xml @@ -0,0 +1,20 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/resources/messages_en.properties b/spring-security-login-error-handling/src/main/resources/messages_en.properties new file mode 100644 index 0000000000..3e05a6b76a --- /dev/null +++ b/spring-security-login-error-handling/src/main/resources/messages_en.properties @@ -0,0 +1,9 @@ +message.username=Username required +message.password=Password required +message.unauth=Unauthorized Access !! +message.badCredentials=Invalid Username or Password +message.sessionExpired=Session Timed Out +message.logoutError=Sorry, error logging out +message.logoutSucc=You logged out successfully +message.regSucc=You registrated correctly, please log in +message.regError=There was a registration error please go back to registration \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/resources/messages_es_ES.properties b/spring-security-login-error-handling/src/main/resources/messages_es_ES.properties new file mode 100644 index 0000000000..842a899e43 --- /dev/null +++ b/spring-security-login-error-handling/src/main/resources/messages_es_ES.properties @@ -0,0 +1,9 @@ +message.username=Por favor ingrese el nombre de usuario +message.password=Por favor ingrese una clave +message.unauth=Acceso denegado !! +message.badCredentials=Usuario o clave invalida +message.sessionExpired=La sesion expiro +message.logoutError=Lo sentimos, hubo problemas en logout +message.logoutSucc=Logout con exito +message.regSucc=Se registro correctamente, por favor ingrese +message.regError=Hubo un error, por favor vuelva a registrarse \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml b/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml new file mode 100644 index 0000000000..46550f03da --- /dev/null +++ b/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-security-login-error-handling/src/main/webapp/WEB-INF/mvc-servlet.xml new file mode 100644 index 0000000000..b885d2c10a --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -0,0 +1,10 @@ + + + + + + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/admin.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/admin.jsp new file mode 100644 index 0000000000..12f9f7aba9 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/admin.jsp @@ -0,0 +1,23 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> +<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> + + + + + + + + + + + +

Hello Admin

+
+ + ">Logout + ">Home + + + + diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/console.jsp new file mode 100644 index 0000000000..05a930731b --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/console.jsp @@ -0,0 +1,23 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> + + + + +

This is the landing page for the admin

+ + + This text is only visible to a user +
+
+ + + This text is only visible to an admin +
+
+ + ">Logout + ">Administrator Page + + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/home.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/home.jsp new file mode 100644 index 0000000000..fe6e572b99 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/home.jsp @@ -0,0 +1,13 @@ +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ page session="true" %> + + + Home + + +

+ Welcome back home! +

+ + + diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/homepage.jsp new file mode 100644 index 0000000000..fab96383df --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/homepage.jsp @@ -0,0 +1,28 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> +<%@ page session="true" %> + + + + + +

This is the homepage for the user

+ + + This text is only visible to a user +
+
+ + + This text is only visible to an admin +
+
+ + ">Logout + ">Home + ">Administrator Page + + + + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/invalidSession.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/invalidSession.jsp new file mode 100644 index 0000000000..175c498117 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/invalidSession.jsp @@ -0,0 +1,12 @@ +<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> + + + Home + + +

+ +

+ + + diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/login.jsp new file mode 100644 index 0000000000..95559b0455 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/login.jsp @@ -0,0 +1,77 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="sec" + uri="http://www.springframework.org/security/tags"%> +<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> + +<%@ page session="false"%> + +
+ +
+
+ +
+ +
+
+ + +
+ +
+ Register +
+ + + + + + + + + +

Login

+ English | + Spanish +
+ + + + + + + + + + + + + +
User:
Password:
+ +
+
Current Locale : ${pageContext.response.locale} + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/logout.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/logout.jsp new file mode 100644 index 0000000000..e8618b74e3 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/logout.jsp @@ -0,0 +1,24 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="sec" + uri="http://www.springframework.org/security/tags"%> +<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> + +
+ +
+
+ +
+ +
+
+ + + +Logged Out + + + + Login + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/registration.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/registration.jsp new file mode 100644 index 0000000000..474a1817b5 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/registration.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=US-ASCII" + pageEncoding="US-ASCII"%> + + + + +Registration + + +

This is the registration page

+ + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/web.xml b/spring-security-login-error-handling/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..463b309377 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,41 @@ + + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + org.baeldung.spring + + + org.springframework.web.context.ContextLoaderListener + + + mvc + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc + / + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + localizationFilter + org.springframework.web.filter.RequestContextFilter + + + localizationFilter + /* + + \ No newline at end of file diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index cb5d3c4561..173f3bed6f 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -371,13 +371,13 @@ - 4.0.5.RELEASE + 4.0.6.RELEASE 3.2.4.RELEASE 4.3.5.Final - 5.1.30 - 1.6.0.RELEASE + 5.1.31 + 1.6.1.RELEASE