[BAEL-3936] Merged with upstream and fixed conflicts

This commit is contained in:
Kostas Karavitis 2020-04-28 20:35:04 +03:00
commit f964a31ffc
155 changed files with 2738 additions and 609 deletions

View File

@ -1,4 +1,4 @@
package com.baeldung.java14.helpfulnullpointerexceptions;
package com.baeldung.java14.npe;
public class HelpfulNullPointerException {

View File

@ -4,4 +4,5 @@
### Relevant Articles:
- [Using a Mutex Object in Java](https://www.baeldung.com/java-mutex)
- [Testing Multi-Threaded Code in Java] (https://www.baeldung.com/java-testing-multithreaded)

View File

@ -15,6 +15,38 @@
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.thread-weaver</groupId>
<artifactId>threadweaver</artifactId>
<version>0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.tempus-fugit</groupId>
<artifactId>tempus-fugit</artifactId>
<version>1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.multithreadedtc</groupId>
<artifactId>multithreadedtc</artifactId>
<version>1.01</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jcstress</groupId>
<artifactId>jcstress-core</artifactId>
<version>0.5</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-concurrency-2</finalName>
@ -24,6 +56,51 @@
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<compilerVersion>${javac.target}</compilerVersion>
<source>${javac.target}</source>
<target>${javac.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<id>main</id>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>jcstress</finalName>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jcstress.Main</mainClass>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/TestList</resource>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<javac.target>1.8</javac.target>
</properties>
</project>

View File

@ -1,5 +1,6 @@
package com.baeldung.concurrent;
import org.junit.Ignore;
import org.junit.Test;
import edu.umd.cs.mtc.MultithreadedTestCase;
@ -25,9 +26,10 @@ public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase {
@SuppressWarnings("deprecation")
@Override
public void finish() {
assertEquals(2, counter.getCount());
assertEquals(2, counter.getCount());
}
@Ignore
@Test
public void testCounter() throws Throwable {
TestFramework.runManyTimes(new MyCounterMultithreadedTCUnitTest(), 1000);

View File

@ -6,6 +6,7 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Ignore;
import org.junit.Test;
public class MyCounterSimpleUnitTest {
@ -18,7 +19,8 @@ public class MyCounterSimpleUnitTest {
assertEquals(500, counter.getCount());
}
// @Test
@Ignore
@Test
public void testCounterWithConcurrency() throws InterruptedException {
int numberOfThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(10);
@ -34,7 +36,8 @@ public class MyCounterSimpleUnitTest {
assertEquals(numberOfThreads, counter.getCount());
}
// @Test
@Ignore
@Test
public void testSummationWithConcurrencyAndWait() throws InterruptedException {
int numberOfThreads = 2;
ExecutorService service = Executors.newFixedThreadPool(10);

View File

@ -3,6 +3,7 @@ package com.baeldung.concurrent;
import static org.junit.Assert.assertEquals;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
@ -20,6 +21,7 @@ public class MyCounterTempusFugitUnitTest {
private static MyCounter counter = new MyCounter();
@Ignore
@Test
@Concurrent(count = 2)
@Repeating(repetition = 10)

View File

@ -2,6 +2,7 @@ package com.baeldung.concurrent;
import static org.junit.Assert.assertEquals;
import org.junit.Ignore;
import org.junit.Test;
import com.google.testing.threadtester.AnnotatedTestRunner;
@ -34,6 +35,7 @@ public class MyCounterThreadWeaverUnitTest {
assertEquals(2, counter.getCount());
}
@Ignore
@Test
public void testCounter() {
new AnnotatedTestRunner().runTests(this.getClass(), MyCounter.class);

View File

@ -1,7 +0,0 @@
=========
## Core Java Concurrency Testing Examples
### Relevant Articles:
- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded)

View File

@ -1,93 +0,0 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-concurrency-testing</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-testing</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.thread-weaver</groupId>
<artifactId>threadweaver</artifactId>
<version>0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.tempus-fugit</groupId>
<artifactId>tempus-fugit</artifactId>
<version>1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.multithreadedtc</groupId>
<artifactId>multithreadedtc</artifactId>
<version>1.01</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jcstress</groupId>
<artifactId>jcstress-core</artifactId>
<version>0.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<compilerVersion>${javac.target}</compilerVersion>
<source>${javac.target}</source>
<target>${javac.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<id>main</id>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>jcstress</finalName>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jcstress.Main</mainClass>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/TestList</resource>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,19 +0,0 @@
<?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

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

View File

@ -11,4 +11,5 @@ This module contains articles about string operations.
- [Case-Insensitive String Matching in Java](https://www.baeldung.com/java-case-insensitive-string-matching)
- [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives)
- [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64)
- [Encode a String to UTF-8 in Java](https://www.baeldung.com/java-string-encode-utf-8)
- More articles: [[<-- prev]](../core-java-string-operations)

View File

@ -0,0 +1,73 @@
package com.baeldung.encodetoutf8;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import org.apache.commons.codec.binary.StringUtils;
import org.junit.Test;
public class StringEncodeUnitTest {
@Test
public void givenGermanAsciiString_whenComparing_thenCompareNotEquals() {
String germanString = "Entwickeln Sie mit Vergnügen";
byte[] germanBytes = germanString.getBytes();
String asciiEncodedString = new String(germanBytes, StandardCharsets.US_ASCII);
assertNotEquals(germanString, asciiEncodedString);
}
@Test
public void givenUsAsciiString_whenComparing_thenCompareNotEquals() {
String englishString = "Develop with pleasure";
byte[] englishBytes = englishString.getBytes();
String asciiEncondedEnglishString = new String(englishBytes, StandardCharsets.US_ASCII);
assertEquals(englishString, asciiEncondedEnglishString);
}
/*
* ApacheCommonsCodecEncode
*/
@Test
public void givenSomeUnencodedString_whenApacheCommonsCodecEncode_thenCompareEquals() {
String rawString = "Entwickeln Sie mit Vergnügen";
byte[] bytes = StringUtils.getBytesUtf8(rawString);
String utf8EncodedString = StringUtils.newStringUtf8(bytes);
assertEquals(rawString, utf8EncodedString);
}
/*
* CoreJavaEncode
*/
@Test
public void givenSomeUnencodedString_whenCoreJavaEncode_thenCompareEquals() {
String rawString = "Entwickeln Sie mit Vergnügen";
byte[] bytes = rawString.getBytes(StandardCharsets.UTF_8);
String utf8EncodedString = new String(bytes, StandardCharsets.UTF_8);
assertEquals(rawString, utf8EncodedString);
}
/*
* Java7StandardCharsetsEncode
*/
@Test
public void givenSomeUnencodedString_whenJava7StandardCharsetsEncode_thenCompareEquals() {
String rawString = "Entwickeln Sie mit Vergnügen";
ByteBuffer buffer = StandardCharsets.UTF_8.encode(rawString);
String utf8EncodedString = StandardCharsets.UTF_8.decode(buffer)
.toString();
assertEquals(rawString, utf8EncodedString);
}
}

View File

@ -96,7 +96,7 @@
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<asspectj.version>1.8.9</asspectj.version>
<powermock.version>2.0.0-RC.4</powermock.version>
<powermock.version>2.0.0</powermock.version>
<jmockit.version>1.44</jmockit.version>
<!-- plugins -->
<maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version>

View File

@ -0,0 +1,23 @@
package com.baeldung.objectclass;
import lombok.Data;
@Data
public class Borrower extends User {
private double totalLoanAmount;
public double requestLoan(double amount) {
totalLoanAmount = amount;
return totalLoanAmount;
}
public double increaseLoan(double increaseBy) {
return totalLoanAmount + increaseBy;
}
public double payLoan(double amount) {
return totalLoanAmount - amount;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.objectclass;
public class Lender extends User {
private double totalInvestmentAmount;
public double invest(double amount) {
totalInvestmentAmount = amount;
return totalInvestmentAmount;
}
public double increaseInvestment(double increaseBy) {
return totalInvestmentAmount + increaseBy;
}
public double collectDividends() {
return totalInvestmentAmount * 0.07;
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.objectclass;
import lombok.Data;
@Data
public class User {
private String firstName;
private String lastName;
}

View File

@ -0,0 +1,74 @@
package com.baeldung.objectclass;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class CreditAppUnitTest {
@Test
public void givenLender_whenInstanceOf_thenReturnTrue() {
User lender = new Lender();
assertTrue(lender instanceof Lender);
assertTrue(lender instanceof User);
}
@Test
public void givenUser_whenInstanceOfLender_thenDowncast() {
User user = new Lender();
Lender lender = null;
if(user instanceof Lender) {
lender = (Lender) user;
}
assertNotNull(lender);
}
@Test
public void givenUser_whenIsInstanceOfLender_thenDowncast() {
User user = new Lender();
Lender lender = null;
if(Lender.class.isInstance(user)) {
lender = (Lender) user;
}
assertNotNull(lender);
}
@Test
public void givenBorrower_whenLoanAmountIsDouble_thenRequestLoan() {
Borrower borrower = new Borrower();
double amount = 100.0;
//if(amount instanceof Double) // Compilation error, no autoboxing
if(Double.class.isInstance(amount)) {
borrower.requestLoan(amount);
}
assertEquals(100, borrower.getTotalLoanAmount());
}
@Test
public void givenBorrower_whenLoanAmountIsNotString_thenRequestLoan() {
Borrower borrower = new Borrower();
Double amount = 100.0;
//if(amount instanceof String) // Compilation error, incompatible operands
if(!String.class.isInstance(amount)) {
borrower.requestLoan(amount);
}
assertEquals(100, borrower.getTotalLoanAmount());
}
@Test
public void givenLender_whenGetClass_thenEqualsLenderType() {
User lender = new Lender();
assertEquals(Lender.class, lender.getClass());
assertNotEquals(User.class, lender.getClass());
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.foldvsreduce
import org.junit.Test
import org.junit.jupiter.api.assertThrows
import java.lang.RuntimeException
import kotlin.test.assertEquals
class FoldAndReduceTest {
@Test
fun testReduceLimitations() {
val numbers: List<Int> = listOf(1, 2, 3)
val sum: Number = numbers.reduce { acc, next -> acc + next }
assertEquals(6, sum)
val emptyList = listOf<Int>()
assertThrows<RuntimeException> { emptyList.reduce { acc, next -> acc + next } }
// doesn't compile
// val sum = numbers.reduce { acc, next -> acc.toLong() + next.toLong()}
}
@Test
fun testFold() {
val numbers: List<Int> = listOf(1, 2, 3)
val sum: Int = numbers.fold(0, { acc, next -> acc + next })
assertEquals(6, sum)
//change result type
val sumLong: Long = numbers.fold(0L, { acc, next -> acc + next.toLong() })
assertEquals(6L, sumLong)
val emptyList = listOf<Int>()
val emptySum = emptyList.fold(0, { acc, next -> acc + next })
assertEquals(0, emptySum)
//power of changing result type
val (even, odd) = numbers.fold(Pair(listOf<Int>(), listOf<Int>()), { acc, next ->
if (next % 2 == 0) Pair(acc.first + next, acc.second)
else Pair(acc.first, acc.second + next)
})
assertEquals(listOf(2), even)
assertEquals(listOf(1, 3), odd)
}
@Test
fun testVariationsOfFold() {
val numbers = listOf(1, 2, 3)
val reversed = numbers.foldRight(listOf<Int>(), { next, acc -> acc + next})
assertEquals(listOf(3,2,1), reversed)
val reversedIndexes = numbers.foldRightIndexed(listOf<Int>(), { i, _, acc -> acc + i })
assertEquals(listOf(2,1,0), reversedIndexes)
}
}

3
gradle/gradle-employee-app/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/.idea
/.gradle
/build

View File

@ -0,0 +1,38 @@
plugins {
id 'java-library'
id 'application'
}
apply plugin: 'application'
mainClassName = 'employee.EmployeeApp'
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
println 'This is executed during configuration phase'
task configured {
println 'The project is configured'
}
task wrapper(type: Wrapper){
gradleVersion = '5.3.1'
}
repositories {
jcenter()
}
dependencies {
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.10'
testImplementation('junit:junit:4.13')
testRuntime('junit:junit:4.13')
}
test {
useJUnit()
}

View File

@ -0,0 +1,9 @@
package employee;
public class Employee {
String name;
String emailAddress;
int yearOfBirth;
}

View File

@ -0,0 +1,16 @@
package employee;
public class EmployeeApp {
public static void main(String[] args){
Employee employee = new Employee();
employee.name = "John";
employee.emailAddress = "john@baeldung.com";
employee.yearOfBirth = 1978;
System.out.println("Name: " + employee.name);
System.out.println("Email Address: " + employee.emailAddress);
System.out.println("Year Of Birth:" + employee.yearOfBirth);
}
}

View File

@ -0,0 +1,31 @@
package employee;
import employee.Employee;
import org.junit.*;
import static org.junit.Assert.*;
public class EmployeeAppTest {
@Test
public void testData(){
Employee testEmp = this.getEmployeeTest();
assertEquals(testEmp.name, "John");
assertEquals(testEmp.emailAddress, "john@baeldung.com");
assertEquals(testEmp.yearOfBirth, 1978);
}
private Employee getEmployeeTest(){
Employee employee = new Employee();
employee.name = "John";
employee.emailAddress = "john@baeldung.com";
employee.yearOfBirth = 1978;
return employee;
}
}

View File

@ -1,10 +1,10 @@
rootProject.name = 'gradletutorial'
include 'greeting-library'
include 'greeting-library-java'
include 'greeter'
include 'gradletaskdemo'
include 'junit5'
include 'gradle-employee-app'
println 'This will be executed during the initialization phase.'

View File

@ -256,10 +256,9 @@
</execution>
</executions>
<configuration>
<wsdlDirectory>src/main/resources</wsdlDirectory>
<wsdlFiles>
<wsdlFile>country.wsdl</wsdlFile>
</wsdlFiles>
<wsdlUrls>
<wsdlUrl>http://localhost:8888/ws/country?wsdl</wsdlUrl>
</wsdlUrls>
<keep>true</keep>
<packageName>com.baeldung.soap.ws.client.generated</packageName>
<sourceDestDir>src/main/java</sourceDestDir>

View File

@ -12,11 +12,11 @@ import javax.xml.ws.WebServiceFeature;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.3.2
* JAX-WS RI 2.2.9-b130926.1035
* Generated source version: 2.2
*
*/
@WebServiceClient(name = "CountryServiceImplService", targetNamespace = "http://server.ws.soap.baeldung.com/", wsdlLocation = "file:src/main/resources/country.wsdl")
@WebServiceClient(name = "CountryServiceImplService", targetNamespace = "http://server.ws.soap.baeldung.com/", wsdlLocation = "http://localhost:8888/ws/country?wsdl")
public class CountryServiceImplService extends Service {
private final static URL COUNTRYSERVICEIMPLSERVICE_WSDL_LOCATION;
@ -27,7 +27,7 @@ public class CountryServiceImplService extends Service {
URL url = null;
WebServiceException e = null;
try {
url = new URL("file:src/main/resources/country.wsdl");
url = new URL("http://localhost:8888/ws/country?wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}

View File

@ -1,40 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. --><!-- Generated by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. -->
<definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy"
xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://server.ws.soap.baeldung.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://server.ws.soap.baeldung.com/" name="CountryServiceImplService">
<types>
<xsd:schema>
<xsd:import namespace="http://server.ws.soap.baeldung.com/" schemaLocation="http://localhost:8888/ws/country?xsd=1"></xsd:import>
</xsd:schema>
</types>
<message name="findByName">
<part name="arg0" type="xsd:string"></part>
</message>
<message name="findByNameResponse">
<part name="return" type="tns:country"></part>
</message>
<portType name="CountryService">
<operation name="findByName">
<input wsam:Action="http://server.ws.soap.baeldung.com/CountryService/findByNameRequest" message="tns:findByName"></input>
<output wsam:Action="http://server.ws.soap.baeldung.com/CountryService/findByNameResponse" message="tns:findByNameResponse"></output>
</operation>
</portType>
<binding name="CountryServiceImplPortBinding" type="tns:CountryService">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"></soap:binding>
<operation name="findByName">
<soap:operation soapAction=""></soap:operation>
<input>
<soap:body use="literal" namespace="http://server.ws.soap.baeldung.com/"></soap:body>
</input>
<output>
<soap:body use="literal" namespace="http://server.ws.soap.baeldung.com/"></soap:body>
</output>
</operation>
</binding>
<service name="CountryServiceImplService">
<port name="CountryServiceImplPort" binding="tns:CountryServiceImplPortBinding">
<soap:address location="http://localhost:8888/ws/country"></soap:address>
</port>
</service>
</definitions>

View File

@ -1,20 +1,17 @@
package com.baeldung.batch.understanding;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Properties;
import javax.batch.operations.JobOperator;
import javax.batch.runtime.BatchRuntime;
import javax.batch.runtime.BatchStatus;
import javax.batch.runtime.JobExecution;
import javax.batch.runtime.Metric;
import javax.batch.runtime.StepExecution;
import com.baeldung.batch.understanding.BatchTestHelper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Disabled;
@Disabled("Should be fixed in BAEL-3812")
class CustomCheckPointUnitTest {
@Test
public void givenChunk_whenCustomCheckPoint_thenCommitCountIsThree() throws Exception {

View File

@ -1,6 +1,8 @@
package com.baeldung.batch.understanding;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
@ -13,9 +15,7 @@ import javax.batch.runtime.JobExecution;
import javax.batch.runtime.StepExecution;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Disabled;
@Disabled("Should be fixed in BAEL-3812")
class JobSequenceUnitTest {
@Test
public void givenTwoSteps_thenBatch_CompleteWithSuccess() throws Exception {

View File

@ -1,17 +1,16 @@
package com.baeldung.batch.understanding;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Properties;
import javax.batch.operations.JobOperator;
import javax.batch.runtime.BatchRuntime;
import javax.batch.runtime.BatchStatus;
import javax.batch.runtime.JobExecution;
import java.util.Properties;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
@Disabled("Should be fixed in BAEL-3812")
class SimpleBatchLetUnitTest {
@Test
public void givenBatchLet_thenBatch_CompleteWithSuccess() throws Exception {

View File

@ -1,6 +1,7 @@
package com.baeldung.batch.understanding;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.Map;
@ -14,9 +15,7 @@ import javax.batch.runtime.Metric;
import javax.batch.runtime.StepExecution;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Disabled;
@Disabled("Should be fixed in BAEL-3812")
class SimpleChunkUnitTest {
@Test
public void givenChunk_thenBatch_CompletesWithSucess() throws Exception {

View File

@ -1,19 +1,18 @@
package com.baeldung.batch.understanding;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Properties;
import javax.batch.operations.JobOperator;
import javax.batch.runtime.BatchRuntime;
import javax.batch.runtime.BatchStatus;
import javax.batch.runtime.JobExecution;
import javax.batch.runtime.StepExecution;
import java.util.List;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import org.junit.jupiter.api.Test;
@Disabled("Should be fixed in BAEL-3812")
class SimpleErrorChunkUnitTest {
@Test

View File

@ -0,0 +1 @@
db-url=jdbc:h2:mem:jberet-repo;DB_CLOSE_DELAY=-1

View File

@ -1013,7 +1013,7 @@
<properties>
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
<spring.web.version>0.24.0-RC.0</spring.web.version>
<spring.web.version>0.24.0</spring.web.version>
<!-- Build properties -->
<maven.version>3.0.0</maven.version>
<java.version>1.8</java.version>

View File

@ -910,6 +910,6 @@
<sonar.tests>${project.basedir}/src/test/</sonar.tests>
<!-- jhipster-needle-maven-property -->
<zalando.version>0.24.0-RC.0</zalando.version>
<zalando.version>0.24.0</zalando.version>
</properties>
</project>

View File

@ -835,7 +835,7 @@
<properties>
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
<spring.web.version>0.24.0-RC.0</spring.web.version>
<spring.web.version>0.24.0</spring.web.version>
<!-- Build properties -->
<maven.version>3.0.0</maven.version>
<java.version>1.8</java.version>

2
kaniko/dockerfile Normal file
View File

@ -0,0 +1,2 @@
FROM ubuntu
ENTRYPOINT ["/bin/bash", "-c", "echo hello"]

19
kaniko/pod.yaml Normal file
View File

@ -0,0 +1,19 @@
apiVersion: v1
kind: Pod
metadata:
name: kaniko
spec:
containers:
- name: kaniko
image: gcr.io/kaniko-project/executor:latest
args: ["--dockerfile=/workspace/dockerfile",
"--context=dir://workspace",
"--no-push"]
volumeMounts:
- name: dockerfile-storage
mountPath: /workspace
restartPolicy: Never
volumes:
- name: dockerfile-storage
persistentVolumeClaim:
claimName: dockerfile-claim

11
kaniko/volume-claim.yaml Normal file
View File

@ -0,0 +1,11 @@
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: dockerfile-claim
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 8Gi
storageClassName: local-storage

14
kaniko/volume.yaml Normal file
View File

@ -0,0 +1,14 @@
apiVersion: v1
kind: PersistentVolume
metadata:
name: dockerfile
labels:
type: local
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
storageClassName: local-storage
hostPath:
path: /home/docker/kaniko # Path to the local mount directory that was setup

View File

@ -128,6 +128,21 @@
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.rosuda.REngine</groupId>
<artifactId>Rserve</artifactId>
<version>${rserve.version}</version>
</dependency>
<dependency>
<groupId>com.github.jbytecode</groupId>
<artifactId>RCaller</artifactId>
<version>${rcaller.version}</version>
</dependency>
<dependency>
<groupId>org.renjin</groupId>
<artifactId>renjin-script-engine</artifactId>
<version>${renjin.version}</version>
</dependency>
</dependencies>
<repositories>
@ -137,6 +152,13 @@
<url>http://repo.numericalmethod.com/maven/</url>
<layout>default</layout>
</repository>
<!-- Needed for Renjin -->
<repository>
<id>bedatadriven</id>
<name>bedatadriven public repo</name>
<url>https://nexus.bedatadriven.com/content/groups/public/</url>
</repository>
</repositories>
<properties>
@ -153,6 +175,27 @@
<assertj.version>3.6.2</assertj.version>
<slf4j.version>1.7.25</slf4j.version>
<awaitility.version>3.0.0</awaitility.version>
<renjin.version>RELEASE</renjin.version>
<rcaller.version>3.0</rcaller.version>
<rserve.version>1.8.1</rserve.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<!-- Excludes FastR classes from compilations since they require GraalVM -->
<excludes>
<exclude>com/baeldung/r/FastRMean.java</exclude>
</excludes>
<testExcludes>
<exclude>com/baeldung/r/FastRMeanUnitTest.java</exclude>
</testExcludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,33 @@
package com.baeldung.r;
import java.io.IOException;
import java.net.URISyntaxException;
/**
* FastR showcase.
*
* @author Donato Rimenti
*/
public class FastRMean {
/**
* Invokes the customMean R function passing the given values as arguments.
*
* @param values the input to the mean script
* @return the result of the R script
*/
public double mean(int[] values) {
Context polyglot = Context.newBuilder()
.allowAllAccess(true)
.build();
String meanScriptContent = RUtils.getMeanScriptContent();
polyglot.eval("R", meanScriptContent);
Value rBindings = polyglot.getBindings("R");
Value rInput = rBindings.getMember("c")
.execute(values);
return rBindings.getMember("customMean")
.execute(rInput)
.asDouble();
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.r;
import java.io.IOException;
import java.net.URISyntaxException;
import com.github.rcaller.rstuff.RCaller;
import com.github.rcaller.rstuff.RCallerOptions;
import com.github.rcaller.rstuff.RCode;
/**
* RCaller showcase.
*
* @author Donato Rimenti
*/
public class RCallerMean {
/**
* Invokes the customMean R function passing the given values as arguments.
*
* @param values the input to the mean script
* @return the result of the R script
* @throws IOException if any error occurs
* @throws URISyntaxException if any error occurs
*/
public double mean(int[] values) throws IOException, URISyntaxException {
String fileContent = RUtils.getMeanScriptContent();
RCode code = RCode.create();
code.addRCode(fileContent);
code.addIntArray("input", values);
code.addRCode("result <- customMean(input)");
RCaller caller = RCaller.create(code, RCallerOptions.create());
caller.runAndReturnResult("result");
return caller.getParser()
.getAsDoubleArray("result")[0];
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.r;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
/**
* Utility class for loading the script.R content.
*
* @author Donato Rimenti
*/
public class RUtils {
/**
* Loads the script.R and returns its content as a string.
*
* @return the script.R content as a string
* @throws IOException if any error occurs
* @throws URISyntaxException if any error occurs
*/
static String getMeanScriptContent() throws IOException, URISyntaxException {
URI rScriptUri = RUtils.class.getClassLoader()
.getResource("script.R")
.toURI();
Path inputScript = Paths.get(rScriptUri);
return Files.lines(inputScript)
.collect(Collectors.joining());
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.r;
import java.io.IOException;
import java.net.URISyntaxException;
import javax.script.ScriptException;
import org.renjin.script.RenjinScriptEngine;
import org.renjin.sexp.DoubleArrayVector;
/**
* Renjin showcase.
*
* @author Donato Rimenti
*/
public class RenjinMean {
/**
* Invokes the customMean R function passing the given values as arguments.
*
* @param values the input to the mean script
* @return the result of the R script
* @throws IOException if any error occurs
* @throws URISyntaxException if any error occurs
* @throws ScriptException if any error occurs
*/
public double mean(int[] values) throws IOException, URISyntaxException, ScriptException {
RenjinScriptEngine engine = new RenjinScriptEngine();
String meanScriptContent = RUtils.getMeanScriptContent();
engine.put("input", values);
engine.eval(meanScriptContent);
DoubleArrayVector result = (DoubleArrayVector) engine.eval("customMean(input)");
return result.asReal();
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.r;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngineException;
import org.rosuda.REngine.Rserve.RConnection;
/**
* Rserve showcase.
*
* @author Donato Rimenti
*/
public class RserveMean {
/**
* Connects to the Rserve istance listening on 127.0.0.1:6311 and invokes the
* customMean R function passing the given values as arguments.
*
* @param values the input to the mean script
* @return the result of the R script
* @throws REngineException if any error occurs
* @throws REXPMismatchException if any error occurs
*/
public double mean(int[] values) throws REngineException, REXPMismatchException {
RConnection c = new RConnection();
c.assign("input", values);
return c.eval("customMean(input)")
.asDouble();
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.r;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Test for {@link FastRMean}.
*
* @author Donato Rimenti
*/
@Ignore
public class FastRMeanUnitTest {
/**
* Object to test.
*/
private FastRMean fastrMean = new FastRMean();
/**
* Test for {@link FastRMeanUnitTest#mean(int[])}.
*/
@Test
public void givenValues_whenMean_thenCorrect() {
int[] input = { 1, 2, 3, 4, 5 };
double result = fastrMean.mean(input);
Assert.assertEquals(3.0, result, 0.000001);
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.r;
import java.io.IOException;
import java.net.URISyntaxException;
import javax.script.ScriptException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Test for {@link RCallerMean}.
*
* @author Donato Rimenti
*/
@Ignore
public class RCallerMeanIntegrationTest {
/**
* Object to test.
*/
private RCallerMean rcallerMean = new RCallerMean();
/**
* Test for {@link RCallerMeanIntegrationTest#mean(int[])}.
*
* @throws ScriptException if an error occurs
* @throws URISyntaxException if an error occurs
*/
@Test
public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException {
int[] input = { 1, 2, 3, 4, 5 };
double result = rcallerMean.mean(input);
Assert.assertEquals(3.0, result, 0.000001);
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.r;
import java.io.IOException;
import java.net.URISyntaxException;
import javax.script.ScriptException;
import org.junit.Test;
import org.junit.Assert;
/**
* Test for {@link RenjinMean}.
*
* @author Donato Rimenti
*/
public class RenjinMeanUnitTest {
/**
* Object to test.
*/
private RenjinMean renjinMean = new RenjinMean();
/**
* Test for {@link RenjinMeanUnitTest#mean(int[])}.
*
* @throws ScriptException if an error occurs
* @throws URISyntaxException if an error occurs
* @throws IOException if an error occurs
*/
@Test
public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException, ScriptException {
int[] input = { 1, 2, 3, 4, 5 };
double result = renjinMean.mean(input);
Assert.assertEquals(3.0, result, 0.000001);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.r;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngineException;
/**
* Test for {@link RserveMean}.
*
* @author Donato Rimenti
*/
@Ignore
public class RserveMeanIntegrationTest {
/**
* Object to test.
*/
private RserveMean rserveMean = new RserveMean();
/**
* Test for {@link RserveMeanIntegrationTest#mean(int[])}.
*
* @throws REXPMismatchException if an error occurs
* @throws REngineException if an error occurs
*/
@Test
public void givenValues_whenMean_thenCorrect() throws REngineException, REXPMismatchException {
int[] input = { 1, 2, 3, 4, 5 };
double result = rserveMean.mean(input);
Assert.assertEquals(3.0, result, 0.000001);
}
}

View File

@ -0,0 +1,3 @@
customMean <- function(vector) {
mean(vector)
}

View File

@ -1,6 +0,0 @@
## Maven and Java 11
This module contains articles about Maven with Java 11+.
### Relevant Articles:

View File

@ -1,17 +0,0 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.daomodule</groupId>
<artifactId>daomodule</artifactId>
<version>1.0</version>
<name>daomodule</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
</parent>
</project>

View File

@ -1,12 +0,0 @@
package com.baeldung.dao;
import java.util.List;
import java.util.Optional;
public interface Dao<T> {
Optional<T> findById(int id);
List<T> findAll();
}

View File

@ -1,3 +0,0 @@
module com.baeldung.dao {
exports com.baeldung.dao;
}

View File

@ -1,22 +0,0 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<version>1.0</version>
<name>entitymodule</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
</parent>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>

View File

@ -1,19 +0,0 @@
package com.baeldung.entity;
public class User {
private final String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "User{" + "name=" + name + '}';
}
}

View File

@ -1,3 +0,0 @@
module com.baeldung.entity {
exports com.baeldung.entity;
}

View File

@ -1,38 +0,0 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.mainappmodule</groupId>
<artifactId>mainappmodule</artifactId>
<version>1.0</version>
<name>mainappmodule</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
<entitymodule.version>1.0</entitymodule.version>
<daomodule.version>1.0</daomodule.version>
<userdaomodule.version>1.0</userdaomodule.version>
</parent>
<dependencies>
<dependency>
<groupId>com.baeldung.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<version>${entitymodule.version}</version>
</dependency>
<dependency>
<groupId>com.baeldung.daomodule</groupId>
<artifactId>daomodule</artifactId>
<version>${daomodule.version}</version>
</dependency>
<dependency>
<groupId>com.baeldung.userdaomodule</groupId>
<artifactId>userdaomodule</artifactId>
<version>${userdaomodule.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -1,19 +0,0 @@
package com.baeldung.mainapp;
import com.baeldung.dao.Dao;
import com.baeldung.entity.User;
import com.baeldung.userdao.UserDao;
import java.util.HashMap;
import java.util.Map;
public class Application {
public static void main(String[] args) {
Map<Integer, User> users = new HashMap<>();
users.put(1, new User("Julie"));
users.put(2, new User("David"));
Dao userDao = new UserDao(users);
userDao.findAll().forEach(System.out::println);
}
}

View File

@ -1,6 +0,0 @@
module com.baeldung.mainapp {
requires com.baeldung.entity;
requires com.baeldung.userdao;
requires com.baeldung.dao;
uses com.baeldung.dao.Dao;
}

View File

@ -1,66 +0,0 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
<name>multimodule-maven-project</name>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung.maven-java-11</groupId>
<artifactId>maven-java-11</artifactId>
<version>1.0</version>
</parent>
<modules>
<module>entitymodule</module>
<module>daomodule</module>
<module>userdaomodule</module>
<module>mainappmodule</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler.plugin.version}</version>
<configuration>
<source>${source.version}</source>
<target>${target.version}</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>4.12</junit.version>
<assertj.version>3.12.2</assertj.version>
<compiler.plugin.version>3.8.0</compiler.plugin.version>
<source.version>11</source.version>
<target.version>11</target.version>
</properties>
</project>

View File

@ -1,42 +0,0 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.userdaomodule</groupId>
<artifactId>userdaomodule</artifactId>
<version>1.0</version>
<name>userdaomodule</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.multimodule-maven-project</groupId>
<artifactId>multimodule-maven-project</artifactId>
<version>1.0</version>
</parent>
<dependencies>
<dependency>
<groupId>com.baeldung.entitymodule</groupId>
<artifactId>entitymodule</artifactId>
<version>${entitymodule.version}1.0</version>
</dependency>
<dependency>
<groupId>com.baeldung.daomodule</groupId>
<artifactId>daomodule</artifactId>
<version>${daomodule.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<entitymodule.version>1.0</entitymodule.version>
<daomodule.version>1.0</daomodule.version>
</properties>
</project>

View File

@ -1,32 +0,0 @@
package com.baeldung.userdao;
import com.baeldung.dao.Dao;
import com.baeldung.entity.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class UserDao implements Dao<User> {
private final Map<Integer, User> users;
public UserDao() {
users = new HashMap<>();
}
public UserDao(Map<Integer, User> users) {
this.users = users;
}
@Override
public List<User> findAll() {
return new ArrayList<>(users.values());
}
@Override
public Optional<User> findById(int id) {
return Optional.ofNullable(users.get(id));
}
}

View File

@ -1,6 +0,0 @@
module com.baeldung.userdao {
requires com.baeldung.entity;
requires com.baeldung.dao;
provides com.baeldung.dao.Dao with com.baeldung.userdao.UserDao;
exports com.baeldung.userdao;
}

View File

@ -1,36 +0,0 @@
package com.baeldung.userdao.test;
import com.baeldung.dao.Dao;
import com.baeldung.entity.User;
import com.baeldung.userdao.UserDao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Before;
import org.junit.Test;
public class UserDaoUnitTest {
private Dao userDao;
@Before
public void setUpUserDaoInstance() {
Map<Integer, User> users = new HashMap<>();
users.put(1, new User("Julie"));
users.put(2, new User("David"));
userDao = new UserDao(users);
}
@Test
public void givenUserDaoIntance_whenCalledFindById_thenCorrect() {
assertThat(userDao.findById(1), isA(Optional.class));
}
@Test
public void givenUserDaoIntance_whenCalledFindAll_thenCorrect() {
assertThat(userDao.findAll(), isA(List.class));
}
}

View File

@ -1,27 +0,0 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.maven-java-11</groupId>
<artifactId>maven-java-11</artifactId>
<version>1.0</version>
<name>maven-java-11</name>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>multimodule-maven-project</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,35 @@
package com.baeldung.s;
public class TextManipulator {
private String text;
public TextManipulator(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void appendText(String newText) {
text = text.concat(newText);
}
public void findWordAndReplace(String word, String replacementWord) {
if (text.contains(word)) {
text = text.replace(word, replacementWord);
} else System.out.println("Word you want to replace is not found in the text");
}
public void findWordAndDelete(String word) {
if (text.contains(word)) {
text = text.replace(word, "");
} else System.out.println("Word you want to delete is not found in the text");
}
/*
* Bad practice when implementing SRP principle, not in the scope of this class
public void printText() {
System.out.println(textManipulator.getText());
}*/
}

View File

@ -0,0 +1,23 @@
package com.baeldung.s;
import java.util.Arrays;
public class TextPrinter {
TextManipulator textManipulator;
public TextPrinter(TextManipulator textManipulator) {
this.textManipulator = textManipulator;
}
public void printText() {
System.out.println(textManipulator.getText());
}
public void printOutEachWordOfText() {
System.out.println(Arrays.toString(textManipulator.getText().split(" ")));
}
public void printRangeOfCharacters(int startingIndex, int endIndex) {
System.out.println(textManipulator.getText().substring(startingIndex, endIndex));
}
}

View File

@ -139,7 +139,7 @@
<properties>
<hibernate.version>5.4.14.Final</hibernate.version>
<eclipselink.version>2.7.4-RC1</eclipselink.version>
<eclipselink.version>2.7.4</eclipselink.version>
<postgres.version>42.2.5</postgres.version>
<javax.persistence-api.version>2.2</javax.persistence-api.version>
<assertj.version>3.11.1</assertj.version>

View File

@ -106,7 +106,7 @@
<properties>
<hibernate.version>5.4.0.Final</hibernate.version>
<eclipselink.version>2.7.4-RC1</eclipselink.version>
<eclipselink.version>2.7.4</eclipselink.version>
<postgres.version>42.2.5</postgres.version>
<javax.persistence-api.version>2.2</javax.persistence-api.version>
<maven-processor-plugin.version>3.3.3</maven-processor-plugin.version>

View File

@ -9,9 +9,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-1</relativePath>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencyManagement>
@ -19,7 +19,7 @@
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-releasetrain</artifactId>
<version>Hopper-SR10</version>
<version>Lovelace-SR16</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -174,7 +174,7 @@
<start-class>com.baeldung.Application</start-class>
<spring.version>4.3.4.RELEASE</spring.version>
<httpclient.version>4.5.2</httpclient.version>
<spring-data-dynamodb.version>4.4.1</spring-data-dynamodb.version>
<spring-data-dynamodb.version>5.1.0</spring-data-dynamodb.version>
<aws-java-sdk-dynamodb.version>1.11.64</aws-java-sdk-dynamodb.version>
<bootstrap.version>3.3.7-1</bootstrap.version>
<sqlite4java.version>1.0.392</sqlite4java.version>

View File

@ -44,8 +44,8 @@ public class DynamoDBConfig {
return new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey);
}
@Bean(name = "mvcHandlerMappingIntrospector")
public HandlerMappingIntrospector mvcHandlerMappingIntrospector() {
@Bean(name = "mvcHandlerMappingIntrospectorCustom")
public HandlerMappingIntrospector mvcHandlerMappingIntrospectorCustom() {
return new HandlerMappingIntrospector(context);
}
}

View File

@ -1,12 +1,13 @@
package com.baeldung.spring.data.dynamodb.repositories;
import com.baeldung.spring.data.dynamodb.model.ProductInfo;
import java.util.Optional;
import org.socialsignin.spring.data.dynamodb.repository.EnableScan;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
import com.baeldung.spring.data.dynamodb.model.ProductInfo;
@EnableScan
public interface ProductInfoRepository extends CrudRepository<ProductInfo, String> {
List<ProductInfo> findById(String id);
Optional<ProductInfo> findById(String id);
}

View File

@ -13,3 +13,12 @@
- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations)
- [Spring Data MongoDB Transactions](https://www.baeldung.com/spring-data-mongodb-transactions )
- [ZonedDateTime with Spring Data MongoDB](https://www.baeldung.com/spring-data-mongodb-zoneddatetime)
## Spring Data MongoDB Live Testing
There are 3 scripts to simplify running live tests:
1. [`live-test-setup.sh`](src/live-test/resources/live-test-setup.sh) builds a docker image with the necessary setup and runs it. The environment is ready, when the log stops - it takes approximately 30 seconds.
2. [`live-test.sh`](src/live-test/resources/live-test.sh) runs the live tests (but no other tests).
3. [`live-test-teardown.sh`](src/live-test/resources/live-test-teardown.sh) stops and removes the docker image.

View File

@ -0,0 +1,8 @@
FROM mongo:4.2.1
COPY init-session.js /docker-entrypoint-initdb.d/
EXPOSE 27017
HEALTHCHECK --interval=5s --timeout=3s --start-period=10s CMD mongo db.stats()
CMD ["mongod", "--replSet", "rs0"]

View File

@ -0,0 +1 @@
rs.initiate();

View File

@ -0,0 +1,5 @@
#!/bin/bash
docker image build -t spring-data-mongodb:live-test .
docker run -p 27017:27017 --name spring-data-mongodb-live-test spring-data-mongodb:live-test

View File

@ -0,0 +1,4 @@
#!/bin/bash
docker stop spring-data-mongodb-live-test
docker rm spring-data-mongodb-live-test

View File

@ -0,0 +1,3 @@
#!/bin/bash
mvn clean compile test -P live-all -f ../../../pom.xml

View File

@ -62,24 +62,6 @@ public class MongoTransactionalLiveTest {
}
}
@Test(expected = MongoCommandException.class)
@Transactional
public void whenCountDuringMongoTransaction_thenException() {
userRepository.save(new User("John", 30));
userRepository.save(new User("Ringo", 35));
userRepository.count();
}
@Test
@Transactional
public void whenQueryDuringMongoTransaction_thenSuccess() {
userRepository.save(new User("Jane", 20));
userRepository.save(new User("Nick", 33));
List<User> users = mongoTemplate.find(new Query(), User.class);
assertTrue(users.size() > 1);
}
// ==== Using test instead of before and after due to @transactional doesn't allow list collection
@Test

38
pom.xml
View File

@ -652,6 +652,7 @@
<module>spring-core</module>
<module>spring-core-2</module>
<module>spring-core-3</module>
<module>spring-core-4</module>
<module>spring-cucumber</module>
<module>spring-data-rest</module>
@ -812,7 +813,8 @@
<module>libraries</module> <!-- very long running -->
<module>vaadin</module>
<module>vavr</module>
<module>vavr</module>
<module>vavr-2</module>
</modules>
</profile>
@ -1157,6 +1159,7 @@
<module>spring-core</module>
<module>spring-core-2</module>
<module>spring-core-3</module>
<module>spring-core-4</module>
<module>spring-cucumber</module>
<module>spring-data-rest</module>
@ -1310,10 +1313,41 @@
<module>libraries</module> <!-- very long running -->
<module>vaadin</module>
<module>vavr</module>
<module>vavr</module>
<module>vavr-2</module>
</modules>
</profile>
<profile>
<id>live-all</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/SpringContextTest.java</exclude>
<exclude>**/*UnitTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
<exclude>**/*JdbcTest.java</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>

View File

@ -0,0 +1,13 @@
package com.baeldung.springwithgroovy
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import com.baeldung.springwithgroovy.SpringBootGroovyApplication
@SpringBootApplication
class SpringBootGroovyApplication {
static void main(String[] args) {
SpringApplication.run SpringBootGroovyApplication, args
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.springwithgroovy.controller
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import com.baeldung.springwithgroovy.entity.Todo
import com.baeldung.springwithgroovy.service.TodoService
@RestController
@RequestMapping('todo')
public class TodoController {
@Autowired
TodoService todoService
@GetMapping
List<Todo> getAllTodoList(){
todoService.findAll()
}
@PostMapping
Todo saveTodo(@RequestBody Todo todo){
todoService.saveTodo todo
}
@PutMapping
Todo updateTodo(@RequestBody Todo todo){
todoService.updateTodo todo
}
@DeleteMapping('/{todoId}')
deleteTodo(@PathVariable Integer todoId){
todoService.deleteTodo todoId
}
@GetMapping('/{todoId}')
Todo getTodoById(@PathVariable Integer todoId){
todoService.findById todoId
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.springwithgroovy.entity
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.Table
@Entity
@Table(name = 'todo')
class Todo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id
@Column
String task
@Column
Boolean isCompleted
}

View File

@ -0,0 +1,9 @@
package com.baeldung.springwithgroovy.repository
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import com.baeldung.springwithgroovy.entity.Todo
@Repository
interface TodoRepository extends JpaRepository<Todo, Integer> {}

View File

@ -0,0 +1,16 @@
package com.baeldung.springwithgroovy.service
import com.baeldung.springwithgroovy.entity.Todo
interface TodoService {
List<Todo> findAll()
Todo findById(Integer todoId)
Todo saveTodo(Todo todo)
Todo updateTodo(Todo todo)
Todo deleteTodo(Integer todoId)
}

View File

@ -0,0 +1,40 @@
package com.baeldung.springwithgroovy.service.impl
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import com.baeldung.springwithgroovy.entity.Todo
import com.baeldung.springwithgroovy.repository.TodoRepository
import com.baeldung.springwithgroovy.service.TodoService
@Service
class TodoServiceImpl implements TodoService {
@Autowired
TodoRepository todoRepository
@Override
List<Todo> findAll() {
todoRepository.findAll()
}
@Override
Todo findById(Integer todoId) {
todoRepository.findById todoId get()
}
@Override
Todo saveTodo(Todo todo){
todoRepository.save todo
}
@Override
Todo updateTodo(Todo todo){
todoRepository.save todo
}
@Override
Todo deleteTodo(Integer todoId){
todoRepository.deleteById todoId
}
}

View File

@ -0,0 +1,97 @@
package com.baeldung.springwithgroovy
import static org.junit.jupiter.api.Assertions.assertEquals
import static org.junit.jupiter.api.Assertions.assertTrue
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.test.context.event.annotation.BeforeTestClass
import org.springframework.test.context.junit4.SpringRunner
import com.baeldung.springwithgroovy.entity.Todo
import io.restassured.RestAssured
import io.restassured.response.Response
class TodoAppUnitTest {
static API_ROOT = 'http://localhost:8081/todo'
static readingTodoId
static writingTodoId
@BeforeClass
static void populateDummyData() {
Todo readingTodo = new Todo(task: 'Reading', isCompleted: false)
Todo writingTodo = new Todo(task: 'Writing', isCompleted: false)
final Response readingResponse =
RestAssured.given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(readingTodo).post(API_ROOT)
Todo cookingTodoResponse = readingResponse.as Todo.class
readingTodoId = cookingTodoResponse.getId()
final Response writingResponse =
RestAssured.given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(writingTodo).post(API_ROOT)
Todo writingTodoResponse = writingResponse.as Todo.class
writingTodoId = writingTodoResponse.getId()
}
@Test
void whenGetAllTodoList_thenOk(){
final Response response = RestAssured.get(API_ROOT)
assertEquals HttpStatus.OK.value(),response.getStatusCode()
assertTrue response.as(List.class).size() > 0
}
@Test
void whenGetTodoById_thenOk(){
final Response response =
RestAssured.get("$API_ROOT/$readingTodoId")
assertEquals HttpStatus.OK.value(),response.getStatusCode()
Todo todoResponse = response.as Todo.class
assertEquals readingTodoId,todoResponse.getId()
}
@Test
void whenUpdateTodoById_thenOk(){
Todo todo = new Todo(id:readingTodoId, isCompleted: true)
final Response response =
RestAssured.given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(todo).put(API_ROOT)
assertEquals HttpStatus.OK.value(),response.getStatusCode()
Todo todoResponse = response.as Todo.class
assertTrue todoResponse.getIsCompleted()
}
@Test
void whenDeleteTodoById_thenOk(){
final Response response =
RestAssured.given()
.delete("$API_ROOT/$writingTodoId")
assertEquals HttpStatus.OK.value(),response.getStatusCode()
}
@Test
void whenSaveTodo_thenOk(){
Todo todo = new Todo(task: 'Blogging', isCompleted: false)
final Response response =
RestAssured.given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(todo).post(API_ROOT)
assertEquals HttpStatus.OK.value(),response.getStatusCode()
}
}

View File

@ -63,7 +63,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-boot.version>1.5.2.RELEASE</spring-boot.version>
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
<greeter.version>0.0.1-SNAPSHOT</greeter.version>
</properties>

View File

@ -8,9 +8,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-1</relativePath>
<relativePath>../../../parent-boot-2</relativePath>
</parent>
<dependencies>

View File

@ -51,7 +51,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<greeter.version>0.0.1-SNAPSHOT</greeter.version>
<spring-boot.version>1.5.2.RELEASE</spring-boot.version>
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
</properties>
</project>

View File

@ -8,9 +8,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-1</relativePath>
<relativePath>../../../parent-boot-2</relativePath>
</parent>
</project>

View File

@ -24,6 +24,12 @@
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
@ -72,7 +78,7 @@
</build>
<properties>
<spring-boot.version>1.5.10.RELEASE</spring-boot.version>
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
<custom.property>Custom Property Value</custom.property>
<apache-maven.version>2.7</apache-maven.version>
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>

Some files were not shown because too many files have changed in this diff Show More