Merge remote-tracking branch 'upstream/master'
Conflicts: jackson/src/test/java/org/baeldung/jackson/test/JacksonFieldUnitTest.java
This commit is contained in:
+147
-140
File diff suppressed because it is too large
Load Diff
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
CharSequenceReader extends Reader
|
||||
-29
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
+389
File diff suppressed because it is too large
Load Diff
+41
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+48
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+1
-3
@@ -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("");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
+3
-1
@@ -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();
|
||||
|
||||
+7
-25
@@ -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());
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -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)));
|
||||
|
||||
+23
-35
@@ -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();
|
||||
|
||||
-6
@@ -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
|
||||
|
||||
@@ -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>
|
||||
@@ -120,7 +126,7 @@
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
</plugin>
|
||||
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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>
|
||||
@@ -0,0 +1,24 @@
|
||||
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
|
||||
<html>
|
||||
<head>
|
||||
<title>Spring MVC Form Handling</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h2>Submitted Employee Information</h2>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Name :</td>
|
||||
<td>${name}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>ID :</td>
|
||||
<td>${id}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Contact Number :</td>
|
||||
<td>${contactNumber}</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user