Merge remote-tracking branch 'upstream/master'

Conflicts:
	jackson/src/test/java/org/baeldung/jackson/test/JacksonFieldUnitTest.java
This commit is contained in:
Rachel Shu 2014-07-22 13:33:48 -04:00
commit b3cf85f838
50 changed files with 2270 additions and 263 deletions

View File

@ -1,176 +1,183 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>core-java</artifactId>
<version>0.1-SNAPSHOT</version>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>core-java</artifactId>
<version>0.1-SNAPSHOT</version>
<name>core-java</name>
<name>core-java</name>
<dependencies>
<dependencies>
<!-- utils -->
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- web -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.3</version>
</dependency>
<!-- marshalling -->
<!-- web -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- marshalling -->
<!-- logging -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- logging -->
<!-- test scoped -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</dependencies>
<plugins>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</build>
</plugins>
<properties>
<!-- Spring -->
<org.springframework.version>4.0.5.RELEASE</org.springframework.version>
<org.springframework.security.version>3.2.4.RELEASE</org.springframework.security.version>
</build>
<!-- persistence -->
<hibernate.version>4.3.5.Final</hibernate.version>
<mysql-connector-java.version>5.1.30</mysql-connector-java.version>
<properties>
<!-- Spring -->
<org.springframework.version>4.0.5.RELEASE</org.springframework.version>
<org.springframework.security.version>3.2.4.RELEASE</org.springframework.security.version>
<!-- marshalling -->
<jackson.version>2.3.3</jackson.version>
<!-- persistence -->
<hibernate.version>4.3.5.Final</hibernate.version>
<mysql-connector-java.version>5.1.30</mysql-connector-java.version>
<!-- logging -->
<org.slf4j.version>1.7.6</org.slf4j.version>
<logback.version>1.1.1</logback.version>
<!-- marshalling -->
<jackson.version>2.3.3</jackson.version>
<!-- various -->
<hibernate-validator.version>5.1.1.Final</hibernate-validator.version>
<!-- logging -->
<org.slf4j.version>1.7.6</org.slf4j.version>
<logback.version>1.1.1</logback.version>
<!-- util -->
<guava.version>17.0</guava.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
<!-- various -->
<hibernate-validator.version>5.1.1.Final</hibernate-validator.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.11</junit.version>
<mockito.version>1.9.5</mockito.version>
<!-- util -->
<guava.version>17.0</guava.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
<httpcore.version>4.3.2</httpcore.version>
<httpclient.version>4.3.3</httpclient.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.11</junit.version>
<mockito.version>1.9.5</mockito.version>
<rest-assured.version>2.3.1</rest-assured.version>
<httpcore.version>4.3.2</httpcore.version>
<httpclient.version>4.3.3</httpclient.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.4</maven-war-plugin.version>
<maven-surefire-plugin.version>2.17</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.6</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.8</cargo-maven2-plugin.version>
<rest-assured.version>2.3.1</rest-assured.version>
</properties>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.4</maven-war-plugin.version>
<maven-surefire-plugin.version>2.17</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.6</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.8</cargo-maven2-plugin.version>
</properties>
</project>

View File

@ -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);
}
}

View File

@ -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"));
}
}

View File

@ -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();
}
}

View File

@ -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
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1 @@
CharSequenceReader extends Reader

View File

@ -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();
}
}

View File

@ -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);
}
}

View File

@ -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();
}
}
}

View File

@ -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);
}
}
}

View File

@ -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);
}
}
}

View File

@ -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<Object> {
@Override
public void serialize(final Object value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeFieldName("");
}
}

View File

@ -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);

View File

@ -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();

View File

@ -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());
}
}

View File

@ -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)));

View File

@ -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<Foo> 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<Foo> 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<Foo> 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<Foo> 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<Foo> 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<Foo> 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<Foo> 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<Foo> 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<Foo> 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<Foo> 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<Bar> barList = query.list();
for (final Bar bar : barList) {
final Set<Foo> fooSet = bar.getFooSet();

View File

@ -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

View File

@ -39,6 +39,12 @@
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.1.Final</version>
</dependency>
<!-- logging -->
<dependency>

View File

@ -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";
}
}

View File

@ -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;
}
}

View File

@ -1,16 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:annotation-driven />
<context:component-scan base-package="org.baeldung.spring.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:view-controller path="/sample.html" view-name="sample" />
<mvc:view-controller path="/sample.html" view-name="sample" />
</beans>

View File

@ -0,0 +1,24 @@
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Employee Information</h2>
<table>
<tr>
<td>Name :</td>
<td>${name}</td>
</tr>
<tr>
<td>ID :</td>
<td>${id}</td>
</tr>
<tr>
<td>Contact Number :</td>
<td>${contactNumber}</td>
</tr>
</table>
</body>
</html>

View File

@ -0,0 +1,33 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>SpringMVCExample</title>
</head>
<body>
<h3>Welcome, Enter The Employee Details</h3>
<form:form method="POST" action="/spring-mvc-xml/addEmployee" commandName="employee">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="id">Id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td><form:label path="contactNumber">Contact Number</form:label></td>
<td><form:input path="contactNumber" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>

View File

@ -0,0 +1,20 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>SpringMVCExample</title>
</head>
<body>
<h3>Pleas enter the correct details</h3>
<table>
<tr>
<td><a href="employee">Retry</a></td>
</tr>
</table>
</body>
</html>

View File

@ -39,7 +39,7 @@
<session-timeout>10</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

View File

@ -0,0 +1,18 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC Examples</title>
</head>
<body>
<h1>Spring MVC Examples</h1>
<ul>
<li><a href="employee">Welcome Page</a></li>
</ul>
</body>
</html>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beansProjectDescription>
<version>1</version>
<pluginVersion><![CDATA[3.5.1.201404300732-RELEASE]]></pluginVersion>
<configSuffixes>
<configSuffix><![CDATA[xml]]></configSuffix>
</configSuffixes>
<enableImports><![CDATA[true]]></enableImports>
<configs>
</configs>
<autoconfigs>
</autoconfigs>
<configSets>
</configSets>
</beansProjectDescription>

View File

@ -0,0 +1,212 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>spring-security-login-error-handling</artifactId>
<name>spring-security-login-error-handling</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.4.RELEASE</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<scope>runtime</scope>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<!-- Validation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- Taglibs -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>SpringSecurityLogin</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<java-version>1.7</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.springframework.security.version>3.2.4.RELEASE</org.springframework.security.version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<!-- logging -->
<org.slf4j.version>1.7.6</org.slf4j.version>
<logback.version>1.1.1</logback.version>
</properties>
</project>

View File

@ -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<? extends GrantedAuthority> 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;
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,20 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -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

View File

@ -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

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<http use-expressions="true">
<intercept-url pattern="/login*" access="permitAll" />
<intercept-url pattern="/logout*" access="permitAll" />
<intercept-url pattern="/registration*" access="permitAll" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/invalidSession*" access="isAnonymous()" />
<intercept-url pattern="/**" access="isAuthenticated()" />
<form-login login-page='/login.html'
authentication-failure-url="/login.html?error=true"
authentication-success-handler-ref="myAuthenticationSuccessHandler"
default-target-url="/homepage.html" />
<session-management invalid-session-url="/invalidSession.html"
session-fixation-protection="none" />
<logout invalidate-session="false" logout-success-url="/logout.html?logSucc=1"
logout-url="/j_spring_security_logout" delete-cookies="JSESSIONID" />
</http>
<beans:bean id="myAuthenticationSuccessHandler"
class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler" />
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER" />
<user name="admin1" password="admin1Pass" authorities="ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
</beans>

View File

@ -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"%>
<html>
<sec:authorize ifAnyGranted="ROLE_USER">
<spring:message code="message.unauth" ></spring:message>
</sec:authorize>
<head></head>
<body>
<head></head>
<sec:authorize ifAnyGranted="ROLE_ADMIN">
<H1> Hello Admin</H1>
</sec:authorize>
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
<a href="<c:url value="/home.html" />">Home</a>
</body>
</html>

View File

@ -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" %>
<html>
<head></head>
<body>
<h1>This is the landing page for the admin</h1>
<security:authorize access="hasRole('ROLE_USER')">
This text is only visible to a user
<br/>
</security:authorize>
<security:authorize access="hasRole('ROLE_ADMIN')">
This text is only visible to an admin
<br/>
</security:authorize>
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
<a href="<c:url value="/admin.html" />">Administrator Page</a>
</body>
</html>

View File

@ -0,0 +1,13 @@
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="true" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Welcome back home!
</h1>
</body>
</html>

View File

@ -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" %>
<html>
<head></head>
<body>
<body>
<h1>This is the homepage for the user</h1>
<sec:authorize access="hasRole('ROLE_USER')">
This text is only visible to a user
<br />
</sec:authorize>
<sec:authorize access="hasRole('ROLE_ADMIN')">
This text is only visible to an admin
<br />
</sec:authorize>
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
<a href="<c:url value="/home.html" />">Home</a>
<a href="<c:url value="/admin.html" />">Administrator Page</a>
</body>
</body>
</html>

View File

@ -0,0 +1,12 @@
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
<spring:message code="message.sessionExpired" ></spring:message>
</h1>
</body>
</html>

View File

@ -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"%>
<fmt:setBundle basename="messages" />
<%@ page session="false"%>
<c:if test="${param.error != null}">
<div id="error">
<spring:message code="message.badCredentials"></spring:message>
</div>
</c:if>
<c:if test="${param.regSucc == 1}">
<div id="error">
<spring:message code="message.regSucc"></spring:message>
</div>
</c:if>
<c:if test="${param.regError == 1}">
<div id="error">
<spring:message code="message.regError"></spring:message>
</div>
<a href="registration.html">Register</a>
</c:if>
<fmt:message key="message.password" var="noPass" />
<fmt:message key="message.username" var="noUser" />
<html>
<head>
<script type="text/javascript">
function validate() {
if (document.f.j_username.value == ""
&& document.f.j_password.value == "") {
alert("${noUser} & ${noPass}");
document.f.j_username.focus();
return false;
}
if (document.f.j_username.value == "") {
alert("${noUser}");
document.f.j_username.focus();
return false;
}
if (document.f.j_password.value == "") {
alert("${noPass}");
document.f.j_password.focus();
return false;
}
}
</script>
</head>
<body>
<h1>Login</h1>
<a href="?lang=en">English</a> |
<a href="?lang=es_ES">Spanish</a>
<form name='f' action="j_spring_security_check" method='POST'
onsubmit="return validate();">
<table>
<tr>
<td>User:</td>
<td><input type='text' name='j_username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password' /></td>
</tr>
<tr>
<td><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
<br> Current Locale : ${pageContext.response.locale}
</body>
</html>

View File

@ -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"%>
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
<div id="error">
<spring:message code="message.logoutError"></spring:message>
</div>
</c:if>
<c:if test="${param.logSucc == 1}">
<div id="success">
<spring:message code="message.logoutSucc"></spring:message>
</div>
</c:if>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Logged Out</title>
</head>
<body>
<a href="login.html">Login</a>
</body>
</html>

View File

@ -0,0 +1,12 @@
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Registration</title>
</head>
<body>
<H1> This is the registration page</H1>
</body>
</html>

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.baeldung.spring</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>localizationFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>localizationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

View File

@ -371,13 +371,13 @@
<properties>
<!-- Spring -->
<org.springframework.version>4.0.5.RELEASE</org.springframework.version>
<org.springframework.version>4.0.6.RELEASE</org.springframework.version>
<org.springframework.security.version>3.2.4.RELEASE</org.springframework.security.version>
<!-- persistence -->
<hibernate.version>4.3.5.Final</hibernate.version>
<mysql-connector-java.version>5.1.30</mysql-connector-java.version>
<spring-data-jpa.version>1.6.0.RELEASE</spring-data-jpa.version>
<mysql-connector-java.version>5.1.31</mysql-connector-java.version>
<spring-data-jpa.version>1.6.1.RELEASE</spring-data-jpa.version>
<!-- marshalling -->