Merge remote-tracking branch 'upstream/master' into BAEL-2809

# Conflicts:
#	persistence-modules/spring-data-jpa-2/pom.xml
This commit is contained in:
isaolmez 2019-04-21 07:59:16 +03:00
commit c0c5a64b10
28 changed files with 715 additions and 46 deletions

View File

@ -2,4 +2,6 @@
## Relevant articles:
- [String Matching in Groovy](http://www.baeldung.com/)
- [String Matching in Groovy](http://www.baeldung.com/)
- [Groovy def Keyword]

View File

@ -2,7 +2,7 @@
<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>core-groovy</artifactId>
<artifactId>core-groovy-2</artifactId>
<version>1.0-SNAPSHOT</version>
<name>core-groovy-2</name>
<packaging>jar</packaging>
@ -14,12 +14,33 @@
</parent>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>${groovy.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy-all.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-dateutil</artifactId>
<version>${groovy.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-sql</artifactId>
<version>${groovy-sql.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
@ -43,12 +64,39 @@
<executions>
<execution>
<goals>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>compile</goal>
<goal>compileTests</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>junit5</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<includes>
<include>**/*Test5.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
@ -71,10 +119,13 @@
</repositories>
<properties>
<junit.platform.version>1.0.0</junit.platform.version>
<groovy.version>2.5.6</groovy.version>
<groovy-all.version>2.5.6</groovy-all.version>
<groovy-sql.version>2.5.6</groovy-sql.version>
<hsqldb.version>2.4.0</hsqldb.version>
<spock-core.version>1.3-groovy-2.5</spock-core.version>
<gmavenplus-plugin.version>1.6.3</gmavenplus-plugin.version>
<spock-core.version>1.1-groovy-2.4</spock-core.version>
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,79 @@
package com.baeldung.defkeyword
import org.codehaus.groovy.runtime.NullObject
import org.codehaus.groovy.runtime.typehandling.GroovyCastException
import groovy.transform.TypeChecked
import groovy.transform.TypeCheckingMode
@TypeChecked
class DefUnitTest extends GroovyTestCase {
def id
def firstName = "Samwell"
def listOfCountries = ['USA', 'UK', 'FRANCE', 'INDIA']
@TypeChecked(TypeCheckingMode.SKIP)
def multiply(x, y) {
return x*y
}
@TypeChecked(TypeCheckingMode.SKIP)
void testDefVariableDeclaration() {
def list
assert list.getClass() == org.codehaus.groovy.runtime.NullObject
assert list.is(null)
list = [1,2,4]
assert list instanceof ArrayList
}
@TypeChecked(TypeCheckingMode.SKIP)
void testTypeVariables() {
int rate = 200
try {
rate = [12] //GroovyCastException
rate = "nill" //GroovyCastException
} catch(GroovyCastException) {
println "Cannot assign anything other than integer"
}
}
@TypeChecked(TypeCheckingMode.SKIP)
void testDefVariableMultipleAssignment() {
def rate
assert rate == null
assert rate.getClass() == org.codehaus.groovy.runtime.NullObject
rate = 12
assert rate instanceof Integer
rate = "Not Available"
assert rate instanceof String
rate = [1, 4]
assert rate instanceof List
assert divide(12, 3) instanceof BigDecimal
assert divide(1, 0) instanceof String
}
def divide(int x, int y) {
if(y==0) {
return "Should not divide by 0"
} else {
return x/y
}
}
def greetMsg() {
println "Hello! I am Groovy"
}
void testDefVsType() {
def int count
assert count instanceof Integer
}
}

13
httpclient-simple/.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

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

133
httpclient-simple/pom.xml Normal file
View File

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

View File

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

View File

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

View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -3,6 +3,7 @@
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>spring-data-jpa-2</artifactId>
<name>spring-data-jpa</name>
@ -30,6 +31,15 @@
<artifactId>datasource-proxy</artifactId>
<version>1.4.1</version>
</dependency>
</dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,35 @@
package com.baeldung.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.repository.init.Jackson2RepositoryPopulatorFactoryBean;
import org.springframework.data.repository.init.UnmarshallerRepositoryPopulatorFactoryBean;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import com.baeldung.entity.Fruit;
@Configuration
public class JpaPopulators {
@Bean
public Jackson2RepositoryPopulatorFactoryBean getRespositoryPopulator() throws Exception {
Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
factory.setResources(new Resource[] { new ClassPathResource("fruit-data.json") });
return factory;
}
@Bean
public UnmarshallerRepositoryPopulatorFactoryBean repositoryPopulator() {
Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller();
unmarshaller.setClassesToBeBound(Fruit.class);
UnmarshallerRepositoryPopulatorFactoryBean factory = new UnmarshallerRepositoryPopulatorFactoryBean();
factory.setUnmarshaller(unmarshaller);
factory.setResources(new Resource[] { new ClassPathResource("apple-fruit-data.xml"), new ClassPathResource("guava-fruit-data.xml") });
return factory;
}
}

View File

@ -2,7 +2,9 @@ package com.baeldung.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@Entity
public class Fruit {

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<fruit>
<id>1</id>
<name>apple</name>
<color>red</color>
</fruit>

View File

@ -0,0 +1,14 @@
[
{
"_class": "com.baeldung.entity.Fruit",
"name": "apple",
"color": "red",
"id": 1
},
{
"_class": "com.baeldung.entity.Fruit",
"name": "guava",
"color": "green",
"id": 2
}
]

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<fruit>
<id>2</id>
<name>guava</name>
<color>green</color>
</fruit>

View File

@ -0,0 +1,38 @@
package com.baeldung.repository;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.entity.Fruit;
@RunWith(SpringRunner.class)
@SpringBootTest
public class FruitPopulatorTest {
@Autowired
private FruitRepository fruitRepository;
@Test
public void givenFruitJsonPopulatorThenShouldInsertRecordOnStart() {
List<Fruit> fruits = fruitRepository.findAll();
assertEquals("record count is not matching", 2, fruits.size());
fruits.forEach(fruit -> {
if (1 == fruit.getId()) {
assertEquals("apple", fruit.getName());
assertEquals("red", fruit.getColor());
} else if (2 == fruit.getId()) {
assertEquals("guava", fruit.getName());
assertEquals("green", fruit.getColor());
}
});
}
}

View File

@ -376,6 +376,7 @@
<module>cdi</module>
<module>checker-plugin</module>
<module>core-groovy</module>
<module>core-groovy-2</module>
<!-- <module>core-java-10</module> --> <!-- We haven't upgraded to java 10. Fixing in BAEL-10841 -->
<!-- <module>core-java-11</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
<!-- <module>core-java-12</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
@ -436,6 +437,7 @@
<module>hazelcast</module>
<module>helidon</module>
<module>httpclient</module>
<module>httpclient-simple</module>
<module>hystrix</module>
<module>image-processing</module>
@ -1103,6 +1105,7 @@
<module>hazelcast</module>
<module>helidon</module>
<module>httpclient</module>
<module>httpclient-simple</module>
<module>hystrix</module>
<module>image-processing</module>