Merge branch 'master' into master
This commit is contained in:
commit
550c59b473
|
@ -1,18 +0,0 @@
|
|||
package com.baeldung;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class UnitTest {
|
||||
/**
|
||||
* Stub test
|
||||
*/
|
||||
@Test
|
||||
public void givenPreconditions_whenCondition_shouldResult() {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,165 @@
|
|||
package com.baeldung.filechannel;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.MappedByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileChannelUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenFile_whenReadWithFileChannelUsingRandomAccessFile_thenCorrect() throws IOException {
|
||||
|
||||
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
FileChannel channel = reader.getChannel();
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();) {
|
||||
|
||||
int bufferSize = 1024;
|
||||
if (bufferSize > channel.size()) {
|
||||
bufferSize = (int) channel.size();
|
||||
}
|
||||
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
|
||||
|
||||
while (channel.read(buff) > 0) {
|
||||
out.write(buff.array(), 0, buff.position());
|
||||
buff.clear();
|
||||
}
|
||||
|
||||
String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8);
|
||||
|
||||
assertEquals("Hello world", fileContent);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenReadWithFileChannelUsingFileInputStream_thenCorrect() throws IOException {
|
||||
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
FileInputStream fin = new FileInputStream("src/test/resources/test_read.in");
|
||||
FileChannel channel = fin.getChannel();) {
|
||||
|
||||
int bufferSize = 1024;
|
||||
if (bufferSize > channel.size()) {
|
||||
bufferSize = (int) channel.size();
|
||||
}
|
||||
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
|
||||
|
||||
while (channel.read(buff) > 0) {
|
||||
out.write(buff.array(), 0, buff.position());
|
||||
buff.clear();
|
||||
}
|
||||
String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8);
|
||||
|
||||
assertEquals("Hello world", fileContent);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenReadAFileSectionIntoMemoryWithFileChannel_thenCorrect() throws IOException {
|
||||
|
||||
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
FileChannel channel = reader.getChannel();
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();) {
|
||||
|
||||
MappedByteBuffer buff = channel.map(FileChannel.MapMode.READ_ONLY, 6, 5);
|
||||
|
||||
if (buff.hasRemaining()) {
|
||||
byte[] data = new byte[buff.remaining()];
|
||||
buff.get(data);
|
||||
assertEquals("world", new String(data, StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWriteWithFileChannelUsingRandomAccessFile_thenCorrect() throws IOException {
|
||||
String file = "src/test/resources/test_write_using_filechannel.txt";
|
||||
try (RandomAccessFile writer = new RandomAccessFile(file, "rw");
|
||||
FileChannel channel = writer.getChannel();) {
|
||||
ByteBuffer buff = ByteBuffer.wrap("Hello world".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
channel.write(buff);
|
||||
|
||||
// now we verify whether the file was written correctly
|
||||
RandomAccessFile reader = new RandomAccessFile(file, "r");
|
||||
assertEquals("Hello world", reader.readLine());
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenWriteAFileUsingLockAFileSectionWithFileChannel_thenCorrect() throws IOException {
|
||||
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "rw");
|
||||
FileChannel channel = reader.getChannel();
|
||||
FileLock fileLock = channel.tryLock(6, 5, Boolean.FALSE);) {
|
||||
|
||||
assertNotNull(fileLock);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenReadWithFileChannelGetPosition_thenCorrect() throws IOException {
|
||||
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
FileChannel channel = reader.getChannel();) {
|
||||
|
||||
int bufferSize = 1024;
|
||||
if (bufferSize > channel.size()) {
|
||||
bufferSize = (int) channel.size();
|
||||
}
|
||||
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
|
||||
|
||||
while (channel.read(buff) > 0) {
|
||||
out.write(buff.array(), 0, buff.position());
|
||||
buff.clear();
|
||||
}
|
||||
|
||||
// the original file is 11 bytes long, so that's where the position pointer should be
|
||||
assertEquals(11, channel.position());
|
||||
|
||||
channel.position(4);
|
||||
assertEquals(4, channel.position());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFileSize_thenCorrect() throws IOException {
|
||||
|
||||
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
FileChannel channel = reader.getChannel();) {
|
||||
|
||||
// the original file is 11 bytes long, so that's where the position pointer should be
|
||||
assertEquals(11, channel.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTruncateFile_thenCorrect() throws IOException {
|
||||
String input = "this is a test input";
|
||||
|
||||
FileOutputStream fout = new FileOutputStream("src/test/resources/test_truncate.txt");
|
||||
FileChannel channel = fout.getChannel();
|
||||
|
||||
ByteBuffer buff = ByteBuffer.wrap(input.getBytes());
|
||||
channel.write(buff);
|
||||
buff.flip();
|
||||
|
||||
channel = channel.truncate(5);
|
||||
assertEquals(5, channel.size());
|
||||
|
||||
fout.close();
|
||||
channel.close();
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
this
|
|
@ -0,0 +1 @@
|
|||
Hello world
|
|
@ -5,7 +5,7 @@ version '1.0-SNAPSHOT'
|
|||
|
||||
|
||||
buildscript {
|
||||
ext.kotlin_version = '1.2.41'
|
||||
ext.kotlin_version = '1.3.30'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
|
@ -26,8 +26,6 @@ sourceCompatibility = 1.8
|
|||
compileKotlin { kotlinOptions.jvmTarget = "1.8" }
|
||||
compileTestKotlin { kotlinOptions.jvmTarget = "1.8" }
|
||||
|
||||
kotlin { experimental { coroutines "enable" } }
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
jcenter()
|
||||
|
@ -39,10 +37,22 @@ sourceSets {
|
|||
srcDirs 'com/baeldung/ktor'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
testLogging {
|
||||
events "passed", "skipped", "failed"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile "ch.qos.logback:logback-classic:1.2.1"
|
||||
testCompile group: 'junit', name: 'junit', version: '4.12'
|
||||
}
|
||||
implementation "ch.qos.logback:logback-classic:1.2.1"
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib:${kotlin_version}"
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter:5.4.2'
|
||||
testImplementation 'junit:junit:4.12'
|
||||
testImplementation 'org.assertj:assertj-core:3.12.2'
|
||||
testImplementation 'org.mockito:mockito-core:2.27.0'
|
||||
testImplementation "org.jetbrains.kotlin:kotlin-test:${kotlin_version}"
|
||||
testImplementation "org.jetbrains.kotlin:kotlin-test-junit5:${kotlin_version}"
|
||||
}
|
||||
|
|
Binary file not shown.
|
@ -1,5 +1,5 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip
|
||||
|
|
|
@ -1,5 +1,21 @@
|
|||
#!/usr/bin/env sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
|
@ -28,7 +44,7 @@ APP_NAME="Gradle"
|
|||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS=""
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
|
|
@ -1,3 +1,19 @@
|
|||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem http://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
|
@ -14,7 +30,7 @@ set APP_BASE_NAME=%~n0
|
|||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS=
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
|
|
@ -20,9 +20,21 @@
|
|||
<version>${kotlin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit.jupiter.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>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy</artifactId>
|
||||
<version>${byte-buddy.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -37,6 +49,12 @@
|
|||
<version>${kotlin.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-test-junit5</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -69,10 +87,11 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<kotlin.version>1.2.71</kotlin.version>
|
||||
<junit.platform.version>1.1.1</junit.platform.version>
|
||||
<junit.vintage.version>5.2.0</junit.vintage.version>
|
||||
<kotlin.version>1.3.30</kotlin.version>
|
||||
<junit.jupiter.version>5.4.2</junit.jupiter.version>
|
||||
<mockito.version>2.27.0</mockito.version>
|
||||
<byte-buddy.version>1.9.12</byte-buddy.version>
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,79 @@
|
|||
package com.baeldung.console
|
||||
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.mockito.Mockito.`when`
|
||||
import org.mockito.Mockito.mock
|
||||
import java.io.BufferedReader
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.Console
|
||||
import java.io.InputStreamReader
|
||||
import java.io.PrintStream
|
||||
import java.util.*
|
||||
|
||||
|
||||
class ConsoleIOUnitTest {
|
||||
|
||||
@Test
|
||||
fun givenText_whenPrint_thenPrintText() {
|
||||
val expectedTest = "Hello from Kotlin"
|
||||
val out = ByteArrayOutputStream()
|
||||
System.setOut(PrintStream(out))
|
||||
|
||||
print(expectedTest)
|
||||
out.flush()
|
||||
val printedText = String(out.toByteArray())
|
||||
|
||||
assertThat(printedText).isEqualTo(expectedTest)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenInput_whenRead_thenReadText() {
|
||||
val expectedTest = "Hello from Kotlin"
|
||||
val input = ByteArrayInputStream(expectedTest.toByteArray())
|
||||
System.setIn(input)
|
||||
|
||||
val readText = readLine()
|
||||
|
||||
assertThat(readText).isEqualTo(expectedTest)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenInput_whenReadWithScanner_thenReadText() {
|
||||
val expectedTest = "Hello from Kotlin"
|
||||
val scanner = Scanner(ByteArrayInputStream(expectedTest.toByteArray()))
|
||||
|
||||
val readText = scanner.nextLine()
|
||||
|
||||
assertThat(readText).isEqualTo(expectedTest)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenInput_whenReadWithBufferedReader_thenReadText() {
|
||||
val expectedTest = "Hello from Kotlin"
|
||||
val reader = BufferedReader(InputStreamReader(ByteArrayInputStream(expectedTest.toByteArray())))
|
||||
|
||||
val readText = reader.readLine()
|
||||
|
||||
assertThat(readText).isEqualTo(expectedTest)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenInput_whenReadWithConsole_thenReadText() {
|
||||
val expectedTest = "Hello from Kotlin"
|
||||
val console = mock(Console::class.java)
|
||||
`when`(console.readLine()).thenReturn(expectedTest)
|
||||
|
||||
val readText = console.readLine()
|
||||
|
||||
assertThat(readText).isEqualTo(expectedTest)
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
fun resetIO() {
|
||||
System.setOut(System.out)
|
||||
System.setIn(System.`in`)
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
mock-maker-inline
|
|
@ -8,7 +8,8 @@ import kotlin.test.assertEquals
|
|||
|
||||
class InputStreamToStringTest {
|
||||
private val fileName = "src/test/resources/inputstream2string.txt"
|
||||
private val fileFullContent = "Computer programming can be a hassle\r\n" +
|
||||
private val endOfLine = System.lineSeparator()
|
||||
private val fileFullContent = "Computer programming can be a hassle$endOfLine" +
|
||||
"It's like trying to take a defended castle"
|
||||
|
||||
@Test
|
||||
|
@ -46,7 +47,7 @@ class InputStreamToStringTest {
|
|||
} finally {
|
||||
reader.close()
|
||||
}
|
||||
assertEquals(fileFullContent.replace("\r\n", ""), content.toString())
|
||||
assertEquals(fileFullContent.replace(endOfLine, ""), content.toString())
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,13 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
|
@ -0,0 +1,37 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>guava-collections-set</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>guava-collections-set</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>guava-collections-set</finalName>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<guava.version>27.1-jre</guava.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,92 @@
|
|||
package org.baeldung.guava;
|
||||
|
||||
import com.google.common.collect.HashMultiset;
|
||||
import com.google.common.collect.Multiset;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
public class GuavaMultiSetUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenAddingValues_shouldReturnCorrectCount() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
bookStore.add("Potter");
|
||||
bookStore.add("Potter");
|
||||
bookStore.add("Potter");
|
||||
|
||||
assertThat(bookStore.contains("Potter")).isTrue();
|
||||
assertThat(bookStore.count("Potter")).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenRemovingValues_shouldReturnCorrectCount() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
bookStore.add("Potter");
|
||||
bookStore.add("Potter");
|
||||
|
||||
bookStore.remove("Potter");
|
||||
assertThat(bookStore.contains("Potter")).isTrue();
|
||||
assertThat(bookStore.count("Potter")).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenSetCount_shouldReturnCorrectCount() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
bookStore.setCount("Potter", 50);
|
||||
assertThat(bookStore.count("Potter")).isEqualTo(50);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenSettingNegativeCount_shouldThrowException() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
assertThatThrownBy(() -> bookStore.setCount("Potter", -1))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenSettingCountWithEmptySet_shouldBeSuccessful() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
assertThat(bookStore.setCount("Potter", 0, 2)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenSettingCountWithCorrectValue_shouldBeSuccessful() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
bookStore.add("Potter");
|
||||
bookStore.add("Potter");
|
||||
|
||||
assertThat(bookStore.setCount("Potter", 2, 52)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenSettingCountWithIncorrectValue_shouldFail() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
bookStore.add("Potter");
|
||||
bookStore.add("Potter");
|
||||
|
||||
assertThat(bookStore.setCount("Potter", 5, 52)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMap_compareMultiSetOperations() {
|
||||
Map<String, Integer> bookStore = new HashMap<>();
|
||||
bookStore.put("Potter", 3);
|
||||
|
||||
assertThat(bookStore.containsKey("Potter")).isTrue();
|
||||
assertThat(bookStore.get("Potter")).isEqualTo(3);
|
||||
|
||||
bookStore.put("Potter", 2);
|
||||
assertThat(bookStore.get("Potter")).isEqualTo(2);
|
||||
|
||||
bookStore.put("Potter", null);
|
||||
assertThat(bookStore.containsKey("Potter")).isTrue();
|
||||
|
||||
bookStore.put("Potter", -1);
|
||||
assertThat(bookStore.containsKey("Potter")).isTrue();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
|
@ -0,0 +1,10 @@
|
|||
=========
|
||||
## HttpClient 4.x Cookbooks and Examples
|
||||
|
||||
###The Course
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [HttpClient 4 – Get the Status Code](http://www.baeldung.com/httpclient-status-code)
|
|
@ -0,0 +1,133 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>httpclient-simple</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>httpclient-simple</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<!-- http client -->
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>fluent-hc</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpmime</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpasyncclient</artifactId>
|
||||
<version>${httpasyncclient.version}</version> <!-- 4.0.2 --> <!-- 4.1-beta1 -->
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.tomakehurst</groupId>
|
||||
<artifactId>wiremock</artifactId>
|
||||
<version>${wiremock.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>httpclient</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>live</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*LiveTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<test.mime>json</test.mime>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<httpasyncclient.version>4.1.4</httpasyncclient.version>
|
||||
<!-- testing -->
|
||||
<wiremock.version>2.5.1</wiremock.version>
|
||||
<httpclient.version>4.5.8</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
|
||||
<!-- maven plugins -->
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,19 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%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>
|
|
@ -0,0 +1,26 @@
|
|||
package org.baeldung.httpclient;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public final class ResponseUtil {
|
||||
private ResponseUtil() {
|
||||
}
|
||||
|
||||
public static void closeResponse(CloseableHttpResponse response) throws IOException {
|
||||
if (response == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
entity.getContent().close();
|
||||
}
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
|
@ -8,7 +8,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||
### Relevant Articles:
|
||||
|
||||
- [HttpClient 4 – Send Custom Cookie](http://www.baeldung.com/httpclient-4-cookies)
|
||||
- [HttpClient 4 – Get the Status Code](http://www.baeldung.com/httpclient-status-code)
|
||||
- [HttpClient 4 – Cancel Request](http://www.baeldung.com/httpclient-cancel-request)
|
||||
- [HttpClient 4 Cookbook](http://www.baeldung.com/httpclient4)
|
||||
- [Unshorten URLs with HttpClient](http://www.baeldung.com/unshorten-url-httpclient)
|
||||
|
|
|
@ -122,11 +122,10 @@
|
|||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<httpasyncclient.version>4.1.2</httpasyncclient.version>
|
||||
<httpasyncclient.version>4.1.4</httpasyncclient.version>
|
||||
<!-- testing -->
|
||||
<wiremock.version>2.5.1</wiremock.version>
|
||||
<httpcore.version>4.4.5</httpcore.version>
|
||||
<httpclient.version>4.5.3</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
|
||||
<httpclient.version>4.5.8</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
|
||||
<!-- maven plugins -->
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
</properties>
|
||||
|
|
|
@ -4,7 +4,6 @@ import static org.hamcrest.Matchers.equalTo;
|
|||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
|
@ -18,8 +17,7 @@ import org.apache.http.client.CredentialsProvider;
|
|||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.SSLContexts;
|
||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.TrustStrategy;
|
||||
import org.apache.http.impl.client.BasicCookieStore;
|
||||
import org.apache.http.impl.client.BasicCredentialsProvider;
|
||||
|
@ -31,6 +29,7 @@ import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
|
|||
import org.apache.http.nio.reactor.ConnectingIOReactor;
|
||||
import org.apache.http.protocol.BasicHttpContext;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.ssl.SSLContexts;
|
||||
import org.junit.Test;
|
||||
|
||||
public class HttpAsyncClientLiveTest {
|
||||
|
@ -104,7 +103,7 @@ public class HttpAsyncClientLiveTest {
|
|||
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
|
||||
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
|
||||
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslContext).build();
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext).build();
|
||||
|
||||
client.start();
|
||||
final HttpGet request = new HttpGet(HOST_WITH_SSL);
|
||||
|
|
|
@ -1,32 +1,31 @@
|
|||
package org.baeldung.httpclient;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.SSLSocketFactory;
|
||||
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
|
||||
import org.apache.http.conn.ssl.TrustStrategy;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.PoolingClientConnectionManager;
|
||||
import org.apache.http.ssl.SSLContextBuilder;
|
||||
import org.apache.http.ssl.SSLContexts;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLHandshakeException;
|
||||
import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLHandshakeException;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.config.Registry;
|
||||
import org.apache.http.config.RegistryBuilder;
|
||||
import org.apache.http.conn.socket.ConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
|
||||
import org.apache.http.conn.ssl.TrustStrategy;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
import org.apache.http.ssl.SSLContextBuilder;
|
||||
import org.apache.http.ssl.SSLContexts;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* This test requires a localhost server over HTTPS <br>
|
||||
* It should only be manually run, not part of the automated build
|
||||
|
@ -50,16 +49,22 @@ public class HttpsClientSslLiveTest {
|
|||
.getStatusCode(), equalTo(200));
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Test
|
||||
public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
|
||||
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
|
||||
final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
|
||||
final SchemeRegistry registry = new SchemeRegistry();
|
||||
registry.register(new Scheme("https", 443, sf));
|
||||
final ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
|
||||
|
||||
final SSLContext sslContext = SSLContexts.custom()
|
||||
.loadTrustMaterial(null, acceptingTrustStrategy)
|
||||
.build();
|
||||
|
||||
final CloseableHttpClient httpClient = new DefaultHttpClient(ccm);
|
||||
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
|
||||
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).build();
|
||||
PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
|
||||
|
||||
final CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setSSLSocketFactory(sslsf)
|
||||
.setConnectionManager(clientConnectionManager)
|
||||
.build();
|
||||
|
||||
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
|
||||
final HttpResponse response = httpClient.execute(getMethod);
|
||||
|
@ -76,10 +81,9 @@ public class HttpsClientSslLiveTest {
|
|||
.loadTrustMaterial(null, acceptingTrustStrategy)
|
||||
.build();
|
||||
|
||||
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
|
||||
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
|
||||
|
||||
final CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
|
||||
.setSSLSocketFactory(sslsf)
|
||||
.build();
|
||||
|
||||
|
|
|
@ -327,7 +327,8 @@ public class HttpClientConnectionManagementLiveTest {
|
|||
// 8.1
|
||||
public final void whenHttpClientChecksStaleConns_thenNoExceptions() {
|
||||
poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||
client = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setStaleConnectionCheckEnabled(true).build()).setConnectionManager(poolingConnManager).build();
|
||||
poolingConnManager.setValidateAfterInactivity(1000);
|
||||
client = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().build()).setConnectionManager(poolingConnManager).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -22,6 +22,20 @@
|
|||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- YAML -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-yaml</artifactId>
|
||||
<version>2.9.8</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Allow use of LocalDate -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>2.9.8</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
|
|
|
@ -0,0 +1,68 @@
|
|||
package com.baeldung.jackson.entities;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Order {
|
||||
private String orderNo;
|
||||
private LocalDate date;
|
||||
private String customerName;
|
||||
private List<OrderLine> orderLines;
|
||||
|
||||
public Order() {
|
||||
|
||||
}
|
||||
|
||||
public Order(String orderNo, LocalDate date, String customerName, List<OrderLine> orderLines) {
|
||||
super();
|
||||
this.orderNo = orderNo;
|
||||
this.date = date;
|
||||
this.customerName = customerName;
|
||||
this.orderLines = orderLines;
|
||||
}
|
||||
|
||||
public String getOrderNo() {
|
||||
return orderNo;
|
||||
}
|
||||
|
||||
public void setOrderNo(String orderNo) {
|
||||
this.orderNo = orderNo;
|
||||
}
|
||||
|
||||
public LocalDate getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(LocalDate date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public String getCustomerName() {
|
||||
return customerName;
|
||||
}
|
||||
|
||||
public void setCustomerName(String customerName) {
|
||||
this.customerName = customerName;
|
||||
}
|
||||
|
||||
public List<OrderLine> getOrderLines() {
|
||||
if (orderLines == null) {
|
||||
orderLines = new ArrayList<>();
|
||||
}
|
||||
return orderLines;
|
||||
}
|
||||
|
||||
public void setOrderLines(List<OrderLine> orderLines) {
|
||||
if (orderLines == null) {
|
||||
orderLines = new ArrayList<>();
|
||||
}
|
||||
this.orderLines = orderLines;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Order [orderNo=" + orderNo + ", date=" + date + ", customerName=" + customerName + ", orderLines=" + orderLines + "]";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.jackson.entities;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class OrderLine {
|
||||
private String item;
|
||||
private int quantity;
|
||||
private BigDecimal unitPrice;
|
||||
|
||||
public OrderLine() {
|
||||
|
||||
}
|
||||
|
||||
public OrderLine(String item, int quantity, BigDecimal unitPrice) {
|
||||
super();
|
||||
this.item = item;
|
||||
this.quantity = quantity;
|
||||
this.unitPrice = unitPrice;
|
||||
}
|
||||
|
||||
public String getItem() {
|
||||
return item;
|
||||
}
|
||||
|
||||
public void setItem(String item) {
|
||||
this.item = item;
|
||||
}
|
||||
|
||||
public int getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(int quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public BigDecimal getUnitPrice() {
|
||||
return unitPrice;
|
||||
}
|
||||
|
||||
public void setUnitPrice(BigDecimal unitPrice) {
|
||||
this.unitPrice = unitPrice;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "OrderLine [item=" + item + ", quantity=" + quantity + ", unitPrice=" + unitPrice + "]";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
orderNo: A001
|
||||
date: 2019-04-17
|
||||
customerName: Customer, Joe
|
||||
orderLines:
|
||||
- item: No. 9 Sprockets
|
||||
quantity: 12
|
||||
unitPrice: 1.23
|
||||
- item: Widget (10mm)
|
||||
quantity: 4
|
||||
unitPrice: 3.45
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
package com.baeldung.jackson.yaml;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.entities.Order;
|
||||
import com.baeldung.jackson.entities.OrderLine;
|
||||
import com.fasterxml.jackson.core.JsonGenerationException;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator.Feature;
|
||||
|
||||
public class YamlUnitTest {
|
||||
private ObjectMapper mapper;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mapper = new ObjectMapper(new YAMLFactory().disable(Feature.WRITE_DOC_START_MARKER));
|
||||
mapper.findAndRegisterModules();
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenYamlInput_ObjectCreated() throws JsonParseException, JsonMappingException, IOException {
|
||||
Order order = mapper.readValue(new File("src/main/resources/orderInput.yaml"), Order.class);
|
||||
assertEquals("A001", order.getOrderNo());
|
||||
assertEquals(LocalDate.parse("2019-04-17", DateTimeFormatter.ISO_DATE), order.getDate());
|
||||
assertEquals("Customer, Joe", order.getCustomerName());
|
||||
assertEquals(2, order.getOrderLines()
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenYamlObject_FileWritten() throws JsonGenerationException, JsonMappingException, IOException {
|
||||
List<OrderLine> lines = new ArrayList<>();
|
||||
lines.add(new OrderLine("Copper Wire (200ft)", 1, new BigDecimal(50.67).setScale(2, RoundingMode.HALF_UP)));
|
||||
lines.add(new OrderLine("Washers (1/4\")", 24, new BigDecimal(.15).setScale(2, RoundingMode.HALF_UP)));
|
||||
Order order = new Order(
|
||||
"B-9910",
|
||||
LocalDate.parse("2019-04-18", DateTimeFormatter.ISO_DATE),
|
||||
"Customer, Jane",
|
||||
lines);
|
||||
mapper.writeValue(new File("src/main/resources/orderOutput.yaml"), order);
|
||||
|
||||
File outputYaml = new File("src/main/resources/orderOutput.yaml");
|
||||
assertTrue(outputYaml.exists());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
|
@ -0,0 +1,13 @@
|
|||
=========
|
||||
### Jackson Articles that are also part of the e-book
|
||||
|
||||
###The Course
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
### Relevant Articles:
|
||||
- [Jackson Ignore Properties on Marshalling](http://www.baeldung.com/jackson-ignore-properties-on-serialization)
|
||||
- [Jackson Unmarshalling json with Unknown Properties](http://www.baeldung.com/jackson-deserialize-json-unknown-properties)
|
||||
- [Jackson Annotation Examples](http://www.baeldung.com/jackson-annotations)
|
||||
- [Intro to the Jackson ObjectMapper](http://www.baeldung.com/jackson-object-mapper-tutorial)
|
||||
- [Ignore Null Fields with Jackson](http://www.baeldung.com/jackson-ignore-null-fields)
|
||||
- [Jackson – Change Name of Field](http://www.baeldung.com/jackson-name-of-property)
|
|
@ -0,0 +1,131 @@
|
|||
<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>
|
||||
<artifactId>jackson-simple</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>jackson-simple</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
<!--jackson for xml -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-xml</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- marshalling -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.module</groupId>
|
||||
<artifactId>jackson-module-jsonSchema</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jdk8</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>json-schema-validator</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>json-path</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>jackson-simple</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.8</commons-lang3.version>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<gson.version>2.8.5</gson.version>
|
||||
<commons-collections4.version>4.2</commons-collections4.version>
|
||||
|
||||
<!-- testing -->
|
||||
<rest-assured.version>3.1.1</rest-assured.version>
|
||||
<assertj.version>3.11.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,19 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%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>
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.jackson.bidirection;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
||||
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
|
||||
|
||||
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
|
||||
public class ItemWithIdentity {
|
||||
public int id;
|
||||
public String itemName;
|
||||
public UserWithIdentity owner;
|
||||
|
||||
public ItemWithIdentity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ItemWithIdentity(final int id, final String itemName, final UserWithIdentity owner) {
|
||||
this.id = id;
|
||||
this.itemName = itemName;
|
||||
this.owner = owner;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.jackson.bidirection;
|
||||
|
||||
public class ItemWithIgnore {
|
||||
public int id;
|
||||
public String itemName;
|
||||
public UserWithIgnore owner;
|
||||
|
||||
public ItemWithIgnore() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ItemWithIgnore(final int id, final String itemName, final UserWithIgnore owner) {
|
||||
this.id = id;
|
||||
this.itemName = itemName;
|
||||
this.owner = owner;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.jackson.bidirection;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonManagedReference;
|
||||
|
||||
public class ItemWithRef {
|
||||
public int id;
|
||||
public String itemName;
|
||||
|
||||
@JsonManagedReference
|
||||
public UserWithRef owner;
|
||||
|
||||
public ItemWithRef() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ItemWithRef(final int id, final String itemName, final UserWithRef owner) {
|
||||
this.id = id;
|
||||
this.itemName = itemName;
|
||||
this.owner = owner;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.jackson.bidirection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
||||
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
|
||||
|
||||
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
|
||||
public class UserWithIdentity {
|
||||
public int id;
|
||||
public String name;
|
||||
public List<ItemWithIdentity> userItems;
|
||||
|
||||
public UserWithIdentity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public UserWithIdentity(final int id, final String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
userItems = new ArrayList<ItemWithIdentity>();
|
||||
}
|
||||
|
||||
public void addItem(final ItemWithIdentity item) {
|
||||
userItems.add(item);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.jackson.bidirection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
|
||||
public class UserWithIgnore {
|
||||
public int id;
|
||||
public String name;
|
||||
|
||||
@JsonIgnore
|
||||
public List<ItemWithIgnore> userItems;
|
||||
|
||||
public UserWithIgnore() {
|
||||
super();
|
||||
}
|
||||
|
||||
public UserWithIgnore(final int id, final String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
userItems = new ArrayList<ItemWithIgnore>();
|
||||
}
|
||||
|
||||
public void addItem(final ItemWithIgnore item) {
|
||||
userItems.add(item);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.jackson.bidirection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonBackReference;
|
||||
|
||||
public class UserWithRef {
|
||||
public int id;
|
||||
public String name;
|
||||
|
||||
@JsonBackReference
|
||||
public List<ItemWithRef> userItems;
|
||||
|
||||
public UserWithRef() {
|
||||
super();
|
||||
}
|
||||
|
||||
public UserWithRef(final int id, final String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
userItems = new ArrayList<ItemWithRef>();
|
||||
}
|
||||
|
||||
public void addItem(final ItemWithRef item) {
|
||||
userItems.add(item);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.jackson.date;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
|
||||
|
||||
public class CustomDateDeserializer extends StdDeserializer<Date> {
|
||||
|
||||
private static final long serialVersionUID = -5451717385630622729L;
|
||||
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
|
||||
public CustomDateDeserializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public CustomDateDeserializer(final Class<?> vc) {
|
||||
super(vc);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Date deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException {
|
||||
final String date = jsonparser.getText();
|
||||
try {
|
||||
return formatter.parse(date);
|
||||
} catch (final ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.jackson.date;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class CustomDateSerializer extends StdSerializer<Date> {
|
||||
|
||||
private static final long serialVersionUID = -2894356342227378312L;
|
||||
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
|
||||
public CustomDateSerializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public CustomDateSerializer(final Class<Date> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException {
|
||||
gen.writeString(formatter.format(value));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.jackson.date;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
||||
public class EventWithFormat {
|
||||
public String name;
|
||||
|
||||
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
|
||||
public Date eventDate;
|
||||
|
||||
public EventWithFormat() {
|
||||
super();
|
||||
}
|
||||
|
||||
public EventWithFormat(final String name, final Date eventDate) {
|
||||
this.name = name;
|
||||
this.eventDate = eventDate;
|
||||
}
|
||||
|
||||
public Date getEventDate() {
|
||||
return eventDate;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.jackson.date;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
public class EventWithSerializer {
|
||||
public String name;
|
||||
|
||||
@JsonDeserialize(using = CustomDateDeserializer.class)
|
||||
@JsonSerialize(using = CustomDateSerializer.class)
|
||||
public Date eventDate;
|
||||
|
||||
public EventWithSerializer() {
|
||||
super();
|
||||
}
|
||||
|
||||
public EventWithSerializer(final String name, final Date eventDate) {
|
||||
this.name = name;
|
||||
this.eventDate = eventDate;
|
||||
}
|
||||
|
||||
public Date getEventDate() {
|
||||
return eventDate;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.jackson.deserialization;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.dtos.ItemWithSerializer;
|
||||
import com.baeldung.jackson.dtos.User;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
|
||||
import com.fasterxml.jackson.databind.node.IntNode;
|
||||
|
||||
public class ItemDeserializerOnClass extends StdDeserializer<ItemWithSerializer> {
|
||||
|
||||
private static final long serialVersionUID = 5579141241817332594L;
|
||||
|
||||
public ItemDeserializerOnClass() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public ItemDeserializerOnClass(final Class<?> vc) {
|
||||
super(vc);
|
||||
}
|
||||
|
||||
/**
|
||||
* {"id":1,"itemNr":"theItem","owner":2}
|
||||
*/
|
||||
@Override
|
||||
public ItemWithSerializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
|
||||
final JsonNode node = jp.getCodec()
|
||||
.readTree(jp);
|
||||
final int id = (Integer) ((IntNode) node.get("id")).numberValue();
|
||||
final String itemName = node.get("itemName")
|
||||
.asText();
|
||||
final int userId = (Integer) ((IntNode) node.get("owner")).numberValue();
|
||||
|
||||
return new ItemWithSerializer(id, itemName, new User(userId, null));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.jackson.dtos;
|
||||
|
||||
public class Item {
|
||||
public int id;
|
||||
public String itemName;
|
||||
public User owner;
|
||||
|
||||
public Item() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Item(final int id, final String itemName, final User owner) {
|
||||
this.id = id;
|
||||
this.itemName = itemName;
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getItemName() {
|
||||
return itemName;
|
||||
}
|
||||
|
||||
public User getOwner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.jackson.dtos;
|
||||
|
||||
import com.baeldung.jackson.deserialization.ItemDeserializerOnClass;
|
||||
import com.baeldung.jackson.serialization.ItemSerializerOnClass;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
@JsonSerialize(using = ItemSerializerOnClass.class)
|
||||
@JsonDeserialize(using = ItemDeserializerOnClass.class)
|
||||
public class ItemWithSerializer {
|
||||
public final int id;
|
||||
public final String itemName;
|
||||
public final User owner;
|
||||
|
||||
public ItemWithSerializer(final int id, final String itemName, final User owner) {
|
||||
this.id = id;
|
||||
this.itemName = itemName;
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getItemName() {
|
||||
return itemName;
|
||||
}
|
||||
|
||||
public User getOwner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.jackson.dtos;
|
||||
|
||||
public class MyDto {
|
||||
|
||||
private String stringValue;
|
||||
private int intValue;
|
||||
private boolean booleanValue;
|
||||
|
||||
public MyDto() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MyDto(final String stringValue, final int intValue, final boolean booleanValue) {
|
||||
super();
|
||||
|
||||
this.stringValue = stringValue;
|
||||
this.intValue = intValue;
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public String getStringValue() {
|
||||
return stringValue;
|
||||
}
|
||||
|
||||
public void setStringValue(final String stringValue) {
|
||||
this.stringValue = stringValue;
|
||||
}
|
||||
|
||||
public int getIntValue() {
|
||||
return intValue;
|
||||
}
|
||||
|
||||
public void setIntValue(final int intValue) {
|
||||
this.intValue = intValue;
|
||||
}
|
||||
|
||||
public boolean isBooleanValue() {
|
||||
return booleanValue;
|
||||
}
|
||||
|
||||
public void setBooleanValue(final boolean booleanValue) {
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.jackson.dtos;
|
||||
|
||||
public class User {
|
||||
public int id;
|
||||
public String name;
|
||||
|
||||
public User() {
|
||||
super();
|
||||
}
|
||||
|
||||
public User(final int id, final String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.jackson.dtos.withEnum;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
public enum DistanceEnumWithValue {
|
||||
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||
|
||||
private String unit;
|
||||
private final double meters;
|
||||
|
||||
private DistanceEnumWithValue(String unit, double meters) {
|
||||
this.unit = unit;
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public double getMeters() {
|
||||
return meters;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.jackson.exception;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonRootName;
|
||||
|
||||
@JsonRootName(value = "user")
|
||||
public class UserWithRoot {
|
||||
public int id;
|
||||
public String name;
|
||||
|
||||
public UserWithRoot() {
|
||||
super();
|
||||
}
|
||||
|
||||
public UserWithRoot(final int id, final String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.jackson.jsonview;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonView;
|
||||
|
||||
public class Item {
|
||||
@JsonView(Views.Public.class)
|
||||
public int id;
|
||||
|
||||
@JsonView(Views.Public.class)
|
||||
public String itemName;
|
||||
|
||||
@JsonView(Views.Internal.class)
|
||||
public String ownerName;
|
||||
|
||||
public Item() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Item(final int id, final String itemName, final String ownerName) {
|
||||
this.id = id;
|
||||
this.itemName = itemName;
|
||||
this.ownerName = ownerName;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getItemName() {
|
||||
return itemName;
|
||||
}
|
||||
|
||||
public String getOwnerName() {
|
||||
return ownerName;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.jackson.jsonview;
|
||||
|
||||
public class Views {
|
||||
public static class Public {
|
||||
}
|
||||
|
||||
public static class Internal extends Public {
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.jackson.serialization;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.dtos.ItemWithSerializer;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class ItemSerializerOnClass extends StdSerializer<ItemWithSerializer> {
|
||||
|
||||
private static final long serialVersionUID = -1760959597313610409L;
|
||||
|
||||
public ItemSerializerOnClass() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public ItemSerializerOnClass(final Class<ItemWithSerializer> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void serialize(final ItemWithSerializer value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
|
||||
jgen.writeStartObject();
|
||||
jgen.writeNumberField("id", value.id);
|
||||
jgen.writeStringField("itemName", value.itemName);
|
||||
jgen.writeNumberField("owner", value.owner.id);
|
||||
jgen.writeEndObject();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
|
@ -6,9 +6,7 @@
|
|||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
### Relevant Articles:
|
||||
- [Jackson Ignore Properties on Marshalling](http://www.baeldung.com/jackson-ignore-properties-on-serialization)
|
||||
- [Jackson – Unmarshall to Collection/Array](http://www.baeldung.com/jackson-collection-array)
|
||||
- [Jackson Unmarshalling json with Unknown Properties](http://www.baeldung.com/jackson-deserialize-json-unknown-properties)
|
||||
- [Jackson – Custom Serializer](http://www.baeldung.com/jackson-custom-serialization)
|
||||
- [Getting Started with Custom Deserialization in Jackson](http://www.baeldung.com/jackson-deserialization)
|
||||
- [Jackson Exceptions – Problems and Solutions](http://www.baeldung.com/jackson-exception)
|
||||
|
@ -17,10 +15,8 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||
- [Jackson JSON Tutorial](http://www.baeldung.com/jackson)
|
||||
- [Jackson – Working with Maps and nulls](http://www.baeldung.com/jackson-map-null-values-or-null-key)
|
||||
- [Jackson – Decide What Fields Get Serialized/Deserialized](http://www.baeldung.com/jackson-field-serializable-deserializable-or-not)
|
||||
- [Jackson Annotation Examples](http://www.baeldung.com/jackson-annotations)
|
||||
- [Working with Tree Model Nodes in Jackson](http://www.baeldung.com/jackson-json-node-tree-model)
|
||||
- [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson)
|
||||
- [Intro to the Jackson ObjectMapper](http://www.baeldung.com/jackson-object-mapper-tutorial)
|
||||
- [XML Serialization and Deserialization with Jackson](http://www.baeldung.com/jackson-xml-serialization-and-deserialization)
|
||||
- [More Jackson Annotations](http://www.baeldung.com/jackson-advanced-annotations)
|
||||
- [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance)
|
||||
|
@ -31,9 +27,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||
- [Jackson – JsonMappingException (No serializer found for class)](http://www.baeldung.com/jackson-jsonmappingexception)
|
||||
- [How To Serialize Enums as JSON Objects with Jackson](http://www.baeldung.com/jackson-serialize-enums)
|
||||
- [Jackson – Marshall String to JsonNode](http://www.baeldung.com/jackson-json-to-jsonnode)
|
||||
- [Ignore Null Fields with Jackson](http://www.baeldung.com/jackson-ignore-null-fields)
|
||||
- [Jackson – Unmarshall to Collection/Array](http://www.baeldung.com/jackson-collection-array)
|
||||
- [Jackson – Change Name of Field](http://www.baeldung.com/jackson-name-of-property)
|
||||
- [Serialize Only Fields that meet a Custom Criteria with Jackson](http://www.baeldung.com/jackson-serialize-field-custom-criteria)
|
||||
- [Mapping Nested Values with Jackson](http://www.baeldung.com/jackson-nested-values)
|
||||
- [Convert XML to JSON Using Jackson](https://www.baeldung.com/jackson-convert-xml-json)
|
||||
|
|
|
@ -12,8 +12,6 @@ import org.junit.runners.Suite;
|
|||
,JacksonDeserializationUnitTest.class
|
||||
,JacksonDeserializationUnitTest.class
|
||||
,JacksonPrettyPrintUnitTest.class
|
||||
,JacksonSerializationIgnoreUnitTest.class
|
||||
,JacksonSerializationUnitTest.class
|
||||
,SandboxUnitTest.class
|
||||
,JacksonFieldUnitTest.class
|
||||
}) // @formatter:on
|
||||
|
|
|
@ -202,10 +202,10 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<kotlin.version>1.3.10</kotlin.version>
|
||||
<kotlin.version>1.3.30</kotlin.version>
|
||||
<kotlinx.version>1.0.0</kotlinx.version>
|
||||
<ktor.io.version>0.9.5</ktor.io.version>
|
||||
<assertj.version>3.11.0</assertj.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<assertj.version>3.12.0</assertj.version>
|
||||
<junit.platform.version>1.3.2</junit.platform.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,52 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<artifactId>hibernate-mapping</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2database.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>hibernate-mapping</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/test/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.3.7.Final</hibernate.version>
|
||||
<h2database.version>1.4.196</h2database.version>
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue