Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2019-05-21 13:40:38 +02:00
commit 6d3a51ba25
182 changed files with 3117 additions and 425 deletions

View File

@ -1,5 +1,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">
<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>core-java-11</artifactId>
@ -12,7 +14,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
<relativePath>../..</relativePath>
</parent>
<dependencies>
@ -21,6 +23,12 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -41,6 +49,7 @@
<maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version>
<guava.version>27.1-jre</guava.version>
<assertj.version>3.11.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,19 @@
package com.baeldung.predicate.not;
public class Person {
private static final int ADULT_AGE = 18;
private int age;
public Person(int age) {
this.age = age;
}
public boolean isAdult() {
return age >= ADULT_AGE;
}
public boolean isNotAdult() {
return !isAdult();
}
}

View File

@ -7,7 +7,7 @@ import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
public class AppUnitTest
extends TestCase
{
/**
@ -15,7 +15,7 @@ public class AppTest
*
* @param testName name of the test case
*/
public AppTest( String testName )
public AppUnitTest(String testName )
{
super( testName );
}
@ -25,7 +25,7 @@ public class AppTest
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
return new TestSuite( AppUnitTest.class );
}
/**

View File

@ -32,7 +32,7 @@ import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
public class HttpClientTest {
public class HttpClientUnitTest {
@Test
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {

View File

@ -19,7 +19,7 @@ import java.time.Duration;
import org.junit.Test;
public class HttpRequestTest {
public class HttpRequestUnitTest {
@Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {

View File

@ -14,7 +14,7 @@ import java.net.http.HttpResponse;
import org.junit.Test;
public class HttpResponseTest {
public class HttpResponseUnitTest {
@Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {

View File

@ -0,0 +1,61 @@
package com.baeldung.predicate.not;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.function.Predicate.not;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class PersonUnitTest {
private List<Person> people;
@BeforeEach
void preparePeople() {
people = Arrays.asList(
new Person(1),
new Person(18),
new Person(2)
);
}
@Test
void givenPeople_whenFilterIsAdult_thenOneResult() {
List<Person> adults = people.stream()
.filter(Person::isAdult)
.collect(Collectors.toList());
assertThat(adults).size().isEqualTo(1);
}
@Test
void givenPeople_whenFilterIsAdultNegated_thenTwoResults() {
List<Person> nonAdults = people.stream()
.filter(person -> !person.isAdult())
.collect(Collectors.toList());
assertThat(nonAdults).size().isEqualTo(2);
}
@Test
void givenPeople_whenFilterIsNotAdult_thenTwoResults() {
List<Person> nonAdults = people.stream()
.filter(Person::isNotAdult)
.collect(Collectors.toList());
assertThat(nonAdults).size().isEqualTo(2);
}
@Test
void givenPeople_whenFilterNotIsAdult_thenTwoResults() {
List<Person> nonAdults = people.stream()
.filter(not(Person::isAdult))
.collect(Collectors.toList());
assertThat(nonAdults).size().isEqualTo(2);
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.string;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
public class StringAPITest {
@Test
public void whenPositiveArgument_thenReturnIndentedString() {
String multilineStr = "This is\na multiline\nstring.";
String outputStr = " This is\n a multiline\n string.\n";
String postIndent = multilineStr.indent(3);
assertThat(postIndent, equalTo(outputStr));
}
@Test
public void whenNegativeArgument_thenReturnReducedIndentedString() {
String multilineStr = " This is\n a multiline\n string.";
String outputStr = " This is\n a multiline\n string.\n";
String postIndent = multilineStr.indent(-2);
assertThat(postIndent, equalTo(outputStr));
}
@Test
public void whenTransformUsingLamda_thenReturnTransformedString() {
String result = "hello".transform(input -> input + " world!");
assertThat(result, equalTo("hello world!"));
}
@Test
public void whenTransformUsingParseInt_thenReturnInt() {
int result = "42".transform(Integer::parseInt);
assertThat(result, equalTo(42));
}
}

View File

@ -0,0 +1,91 @@
package com.baeldung.delay;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class Delay {
public static void main(String args[]) throws InterruptedException {
threadSleep(4, 1);
timeunitSleep(4, 1);
delayedServiceTask(5);
fixedRateServiceTask(5);
System.out.println("Done.");
return;
}
private static void threadSleep(Integer iterations, Integer secondsToSleep) {
for (Integer i = 0; i < iterations; i++) {
System.out.println("This is loop iteration number " + i.toString());
try {
Thread.sleep(secondsToSleep * 1000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
private static void timeunitSleep(Integer iterations, Integer secondsToSleep) {
for (Integer i = 0; i < iterations; i++) {
System.out.println("This is loop iteration number " + i.toString());
try {
TimeUnit.SECONDS.sleep(secondsToSleep);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
private static void delayedServiceTask(Integer delayInSeconds) {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.schedule(Delay::someTask1, delayInSeconds, TimeUnit.SECONDS);
}
private static void fixedRateServiceTask(Integer delayInSeconds) {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> sf = executorService.scheduleAtFixedRate(Delay::someTask2, 0, delayInSeconds,
TimeUnit.SECONDS);
try {
TimeUnit.SECONDS.sleep(20);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
sf.cancel(true);
}
private static void someTask1() {
System.out.println("Task 1 completed.");
}
private static void someTask2() {
System.out.println("Task 2 completed.");
}
}

View File

@ -0,0 +1,10 @@
=========
## Core Java Collections Array List Cookbooks and Examples
### Relevant Articles:
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)

View File

@ -0,0 +1,46 @@
<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-collections-array-list</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-array-list</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>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>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<assertj.version>3.11.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,28 @@
package com.baeldung.java.list;
public class Flower {
private String name;
private int petals;
public Flower(String name, int petals) {
this.name = name;
this.petals = petals;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPetals() {
return petals;
}
public void setPetals(int petals) {
this.petals = petals;
}
}

View File

@ -0,0 +1,13 @@
<?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>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,17 @@
=========
## Core Java Collections List Cookbooks and Examples
### Relevant Articles:
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal)
- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int)
- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance)
- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list)

View File

@ -0,0 +1,76 @@
<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-collections-list-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-list-2</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>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>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.sf.trove4j</groupId>
<artifactId>trove4j</artifactId>
<version>${trove4j.version}</version>
</dependency>
<dependency>
<groupId>it.unimi.dsi</groupId>
<artifactId>fastutil</artifactId>
<version>${fastutil.version}</version>
</dependency>
<dependency>
<groupId>colt</groupId>
<artifactId>colt</artifactId>
<version>${colt.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-core.version}</version>
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<assertj.version>3.11.1</assertj.version>
<trove4j.version>3.0.2</trove4j.version>
<fastutil.version>8.1.0</fastutil.version>
<colt.version>1.2.0</colt.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
<?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>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -3,31 +3,14 @@
## Core Java Collections List Cookbooks and Examples
### Relevant Articles:
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Java Get Random Item/Element From a List](http://www.baeldung.com/java-random-list-element)
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal)
- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int)
- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance)
- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list)

View File

@ -36,42 +36,12 @@
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.sf.trove4j</groupId>
<artifactId>trove4j</artifactId>
<version>${trove4j.version}</version>
</dependency>
<dependency>
<groupId>it.unimi.dsi</groupId>
<artifactId>fastutil</artifactId>
<version>${fastutil.version}</version>
</dependency>
<dependency>
<groupId>colt</groupId>
<artifactId>colt</artifactId>
<version>${colt.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-core.version}</version>
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.11.1</assertj.version>
<trove4j.version>3.0.2</trove4j.version>
<fastutil.version>8.1.0</fastutil.version>
<colt.version>1.2.0</colt.version>
</properties>
</project>

View File

@ -0,0 +1,30 @@
<?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>consumermodule</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<parent>
<groupId>com.baeldung.decoupling-pattern1</groupId>
<artifactId>decoupling-pattern1</artifactId>
<version>1.0</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,13 @@
package com.baeldung.consumermodule;
import com.baeldung.servicemodule.external.TextService;
import com.baeldung.servicemodule.external.TextServiceFactory;
public class Application {
public static void main(String args[]) {
TextService textService = TextServiceFactory.getTextService("lowercase");
System.out.println(textService.processText("Hello from Baeldung!"));
}
}

View File

@ -0,0 +1,3 @@
module com.baeldung.consumermodule {
requires com.baeldung.servicemodule;
}

View File

@ -0,0 +1,35 @@
<?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.decoupling-pattern1</groupId>
<artifactId>decoupling-pattern1</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<modules>
<module>servicemodule</module>
<module>consumermodule</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,24 @@
<?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.servicemodule</groupId>
<artifactId>servicemodule</artifactId>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.decoupling-pattern1</groupId>
<artifactId>decoupling-pattern1</artifactId>
<version>1.0</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,7 @@
package com.baeldung.servicemodule.external;
public interface TextService {
String processText(String text);
}

View File

@ -0,0 +1,14 @@
package com.baeldung.servicemodule.external;
import com.baeldung.servicemodule.internal.LowercaseTextService;
import com.baeldung.servicemodule.internal.UppercaseTextService;
public class TextServiceFactory {
private TextServiceFactory() {}
public static TextService getTextService(String name) {
return name.equalsIgnoreCase("lowercase") ? new LowercaseTextService(): new UppercaseTextService();
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.servicemodule.internal;
import com.baeldung.servicemodule.external.TextService;
public class LowercaseTextService implements TextService {
@Override
public String processText(String text) {
return text.toLowerCase();
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.servicemodule.internal;
import com.baeldung.servicemodule.external.TextService;
public class UppercaseTextService implements TextService {
@Override
public String processText(String text) {
return text.toUpperCase();
}
}

View File

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

View File

@ -0,0 +1,38 @@
<?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>
<artifactId>com.baeldung.decoupling-pattern2</artifactId>
<groupId>decoupling-pattern2</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.consumermodule</groupId>
<artifactId>consumermodule</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.baeldung.providermodule</groupId>
<artifactId>providermodule</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,15 @@
package com.baeldung.consumermodule;
import com.baeldung.servicemodule.TextService;
import java.util.ServiceLoader;
public class Application {
public static void main(String[] args) {
ServiceLoader<TextService> services = ServiceLoader.load(TextService.class);
for (final TextService service: services) {
System.out.println("The service " + service.getClass().getSimpleName() + " says: " + service.parseText("Hello from Baeldung!"));
}
}
}

View File

@ -0,0 +1,4 @@
module com.baeldung.consumermodule {
requires com.baeldung.servicemodule;
uses com.baeldung.servicemodule.TextService;
}

View File

@ -0,0 +1,34 @@
<?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.decoupling-pattern2</groupId>
<artifactId>decoupling-pattern2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>servicemodule</module>
<module>providermodule</module>
<module>consumermodule</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -0,0 +1,34 @@
<?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.providermodule</groupId>
<artifactId>providermodule</artifactId>
<version>1.0</version>
<parent>
<artifactId>com.baeldung.decoupling-pattern2</artifactId>
<groupId>decoupling-pattern2</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,10 @@
package com.baeldung.providermodule;
import com.baeldung.servicemodule.TextService;
public class LowercaseTextService implements TextService {
@Override
public String parseText(String text) {
return text.toLowerCase();
}
}

View File

@ -0,0 +1,4 @@
module com.baeldung.providermodule {
requires com.baeldung.servicemodule;
provides com.baeldung.servicemodule.TextService with com.baeldung.providermodule.LowercaseTextService;
}

View File

@ -0,0 +1,25 @@
<?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>
<parent>
<artifactId>>com.baeldung.decoupling-pattern2</artifactId>
<groupId>decoupling-pattern2</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule</artifactId>
<version>1.0</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,6 @@
package com.baeldung.servicemodule;
public interface TextService {
String parseText(String text);
}

View File

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

View File

@ -0,0 +1,15 @@
package com.baeldung.ddd.order.doubledispatch;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
public class AmountBasedDiscountPolicy implements DiscountPolicy {
@Override
public double discount(Order order) {
if (order.totalCost()
.isGreaterThan(Money.of(CurrencyUnit.USD, 500.00))) {
return 0.10;
} else
return 0;
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.ddd.order.doubledispatch;
public interface DiscountPolicy {
double discount(Order order);
}

View File

@ -0,0 +1,8 @@
package com.baeldung.ddd.order.doubledispatch;
public class FlatDiscountPolicy implements DiscountPolicy {
@Override
public double discount(Order order) {
return 0.01;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.ddd.order.doubledispatch;
import java.math.RoundingMode;
import java.util.List;
import org.joda.money.Money;
import com.baeldung.ddd.order.OrderLine;
import com.baeldung.ddd.order.doubledispatch.visitor.OrderVisitor;
import com.baeldung.ddd.order.doubledispatch.visitor.Visitable;
public class Order extends com.baeldung.ddd.order.Order implements Visitable<OrderVisitor> {
public Order(List<OrderLine> orderLines) {
super(orderLines);
}
public Money totalCost(SpecialDiscountPolicy discountPolicy) {
return totalCost().multipliedBy(1 - applyDiscountPolicy(discountPolicy), RoundingMode.HALF_UP);
}
protected double applyDiscountPolicy(SpecialDiscountPolicy discountPolicy) {
return discountPolicy.discount(this);
}
@Override
public void accept(OrderVisitor visitor) {
visitor.visit(this);
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.ddd.order.doubledispatch;
public interface SpecialDiscountPolicy extends DiscountPolicy {
double discount(SpecialOrder order);
}

View File

@ -0,0 +1,36 @@
package com.baeldung.ddd.order.doubledispatch;
import java.util.List;
import com.baeldung.ddd.order.OrderLine;
import com.baeldung.ddd.order.doubledispatch.visitor.OrderVisitor;
public class SpecialOrder extends Order {
private boolean eligibleForExtraDiscount;
public SpecialOrder(List<OrderLine> orderLines) {
super(orderLines);
this.eligibleForExtraDiscount = false;
}
public SpecialOrder(List<OrderLine> orderLines, boolean eligibleForSpecialDiscount) {
super(orderLines);
this.eligibleForExtraDiscount = eligibleForSpecialDiscount;
}
public boolean isEligibleForExtraDiscount() {
return eligibleForExtraDiscount;
}
@Override
protected double applyDiscountPolicy(SpecialDiscountPolicy discountPolicy) {
return discountPolicy.discount(this);
}
@Override
public void accept(OrderVisitor visitor) {
visitor.visit(this);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.ddd.order.doubledispatch.visitor;
import com.baeldung.ddd.order.doubledispatch.Order;
import com.baeldung.ddd.order.doubledispatch.SpecialOrder;
public class HtmlOrderViewCreator implements OrderVisitor {
private String html;
public String getHtml() {
return html;
}
@Override
public void visit(Order order) {
html = String.format("<p>Regular order total cost: %s</p>", order.totalCost());
}
@Override
public void visit(SpecialOrder order) {
html = String.format("<h1>Special Order</h1><p>total cost: %s</p>", order.totalCost());
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.ddd.order.doubledispatch.visitor;
import com.baeldung.ddd.order.doubledispatch.Order;
import com.baeldung.ddd.order.doubledispatch.SpecialOrder;
public interface OrderVisitor {
void visit(Order order);
void visit(SpecialOrder order);
}

View File

@ -0,0 +1,5 @@
package com.baeldung.ddd.order.doubledispatch.visitor;
public interface Visitable<V> {
void accept(V visitor);
}

View File

@ -92,7 +92,7 @@ class JpaOrder {
}
void removeLineItem(int line) {
JpaOrderLine removedLine = orderLines.remove(line);
orderLines.remove(line);
}
void setCurrencyUnit(String currencyUnit) {

View File

@ -15,7 +15,7 @@ class JpaProduct {
public JpaProduct(BigDecimal price, String currencyUnit) {
super();
this.price = price;
currencyUnit = currencyUnit;
this.currencyUnit = currencyUnit;
}
@Override

View File

@ -0,0 +1,17 @@
package com.baeldung.ddd.order;
import java.util.Arrays;
import java.util.List;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
public class OrderFixtureUtils {
public static List<OrderLine> anyOrderLines() {
return Arrays.asList(new OrderLine(new Product(Money.of(CurrencyUnit.USD, 100)), 1));
}
public static List<OrderLine> orderLineItemsWorthNDollars(int totalCost) {
return Arrays.asList(new OrderLine(new Product(Money.of(CurrencyUnit.USD, totalCost)), 1));
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.ddd.order.doubledispatch;
import static org.assertj.core.api.Assertions.assertThat;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.baeldung.ddd.order.OrderFixtureUtils;
public class DoubleDispatchDiscountPolicyUnitTest {
// @formatter:off
@DisplayName(
"given regular order with items worth $100 total, " +
"when apply 10% discount policy, " +
"then cost after discount is $90"
)
// @formatter:on
@Test
void test() throws Exception {
// given
Order order = new Order(OrderFixtureUtils.orderLineItemsWorthNDollars(100));
SpecialDiscountPolicy discountPolicy = new SpecialDiscountPolicy() {
@Override
public double discount(Order order) {
return 0.10;
}
@Override
public double discount(SpecialOrder order) {
return 0;
}
};
// when
Money totalCostAfterDiscount = order.totalCost(discountPolicy);
// then
assertThat(totalCostAfterDiscount).isEqualTo(Money.of(CurrencyUnit.USD, 90));
}
// @formatter:off
@DisplayName(
"given special order eligible for extra discount with items worth $100 total, " +
"when apply 20% discount policy for extra discount orders, " +
"then cost after discount is $80"
)
// @formatter:on
@Test
void test1() throws Exception {
// given
boolean eligibleForExtraDiscount = true;
Order order = new SpecialOrder(OrderFixtureUtils.orderLineItemsWorthNDollars(100), eligibleForExtraDiscount);
SpecialDiscountPolicy discountPolicy = new SpecialDiscountPolicy() {
@Override
public double discount(Order order) {
return 0;
}
@Override
public double discount(SpecialOrder order) {
if (order.isEligibleForExtraDiscount())
return 0.20;
return 0.10;
}
};
// when
Money totalCostAfterDiscount = order.totalCost(discountPolicy);
// then
assertThat(totalCostAfterDiscount).isEqualTo(Money.of(CurrencyUnit.USD, 80.00));
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.ddd.order.doubledispatch;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.baeldung.ddd.order.doubledispatch.Order;
import com.baeldung.ddd.order.OrderFixtureUtils;
import com.baeldung.ddd.order.OrderLine;
import com.baeldung.ddd.order.doubledispatch.visitor.HtmlOrderViewCreator;
public class HtmlOrderViewCreatorUnitTest {
// @formatter:off
@DisplayName(
"given collection of regular and special orders, " +
"when create HTML view using visitor for each order, " +
"then the dedicated view is created for each order"
)
// @formatter:on
@Test
void test() throws Exception {
// given
List<OrderLine> anyOrderLines = OrderFixtureUtils.anyOrderLines();
List<Order> orders = Arrays.asList(new Order(anyOrderLines), new SpecialOrder(anyOrderLines));
HtmlOrderViewCreator htmlOrderViewCreator = new HtmlOrderViewCreator();
// when
orders.get(0)
.accept(htmlOrderViewCreator);
String regularOrderHtml = htmlOrderViewCreator.getHtml();
orders.get(1)
.accept(htmlOrderViewCreator);
String specialOrderHtml = htmlOrderViewCreator.getHtml();
// then
assertThat(regularOrderHtml).containsPattern("<p>Regular order total cost: .*</p>");
assertThat(specialOrderHtml).containsPattern("<h1>Special Order</h1><p>total cost: .*</p>");
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.ddd.order.doubledispatch;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.baeldung.ddd.order.doubledispatch.Order;
import com.baeldung.ddd.order.OrderFixtureUtils;
import com.baeldung.ddd.order.OrderLine;
import com.baeldung.ddd.order.doubledispatch.SpecialDiscountPolicy;
import com.baeldung.ddd.order.doubledispatch.SpecialOrder;
public class MethodOverloadExampleUnitTest {
// @formatter:off
@DisplayName(
"given discount policy accepting special orders, " +
"when apply the policy on special order declared as regular order, " +
"then regular discount method is used"
)
// @formatter:on
@Test
void test() throws Exception {
// given
SpecialDiscountPolicy specialPolicy = new SpecialDiscountPolicy() {
@Override
public double discount(Order order) {
return 0.01;
}
@Override
public double discount(SpecialOrder order) {
return 0.10;
}
};
Order specialOrder = new SpecialOrder(anyOrderLines());
// when
double discount = specialPolicy.discount(specialOrder);
// then
assertThat(discount).isEqualTo(0.01);
}
private List<OrderLine> anyOrderLines() {
return OrderFixtureUtils.anyOrderLines();
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.ddd.order.doubledispatch;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.baeldung.ddd.order.OrderFixtureUtils;
public class SingleDispatchDiscountPolicyUnitTest {
// @formatter:off
@DisplayName(
"given two discount policies, " +
"when use these policies, " +
"then single dispatch chooses the implementation based on runtime type"
)
// @formatter:on
@Test
void test() throws Exception {
// given
DiscountPolicy flatPolicy = new FlatDiscountPolicy();
DiscountPolicy amountPolicy = new AmountBasedDiscountPolicy();
Order orderWorth501Dollars = orderWorthNDollars(501);
// when
double flatDiscount = flatPolicy.discount(orderWorth501Dollars);
double amountDiscount = amountPolicy.discount(orderWorth501Dollars);
// then
assertThat(flatDiscount).isEqualTo(0.01);
assertThat(amountDiscount).isEqualTo(0.1);
}
private Order orderWorthNDollars(int totalCost) {
return new Order(OrderFixtureUtils.orderLineItemsWorthNDollars(totalCost));
}
}

View File

@ -1,4 +1,8 @@
# Guava
### Relevant Articles:
## Relevant Articles:
- [Guava Sets](http://www.baeldung.com/guava-sets)
- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)
- [Guide to Guava Multiset](https://www.baeldung.com/guava-multiset)

View File

@ -1,14 +1,9 @@
package org.baeldung.guava;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import com.google.common.base.Function;
import java.util.*;
public class GuavaMapFromSet<K, V> extends AbstractMap<K, V> {
private class SingleEntry implements Entry<K, V> {

View File

@ -1,15 +1,14 @@
package org.baeldung.guava;
import static org.junit.Assert.assertTrue;
import com.google.common.base.Function;
import org.junit.Test;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.junit.Test;
import com.google.common.base.Function;
import static org.junit.Assert.assertTrue;
public class GuavaMapFromSetUnitTest {

View File

@ -1,13 +1,12 @@
package org.baeldung.guava;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
import com.google.common.collect.ImmutableRangeSet;
import com.google.common.collect.Range;
import com.google.common.collect.RangeSet;
import com.google.common.collect.TreeRangeSet;
import org.junit.Test;
import static org.junit.Assert.*;
public class GuavaRangeSetUnitTest {
@ -122,6 +121,5 @@ public class GuavaRangeSetUnitTest {
.add(Range.closed(0, 2))
.add(Range.closed(3, 5))
.add(Range.closed(5, 8)).build();
}
}

View File

@ -0,0 +1,131 @@
package org.baeldung.guava;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.*;
import org.junit.Test;
import java.util.List;
import java.util.Set;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class GuavaSetOperationsUnitTest {
@Test
public void whenCalculatingUnionOfSets_thenCorrect() {
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
final Set<Character> union = Sets.union(first, second);
assertThat(union, containsInAnyOrder('a', 'b', 'c', 'd'));
}
@Test
public void whenCalculatingCartesianProductOfSets_thenCorrect() {
final Set<Character> first = ImmutableSet.of('a', 'b');
final Set<Character> second = ImmutableSet.of('c', 'd');
final Set<List<Character>> result = Sets.cartesianProduct(ImmutableList.of(first, second));
final Function<List<Character>, String> func = new Function<List<Character>, String>() {
@Override
public final String apply(final List<Character> input) {
return Joiner
.on(" ").join(input);
}
};
final Iterable<String> joined = Iterables.transform(result, func);
assertThat(joined, containsInAnyOrder("a c", "a d", "b c", "b d"));
}
@Test
public void whenCalculatingSetIntersection_thenCorrect() {
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
final Set<Character> intersection = Sets.intersection(first, second);
assertThat(intersection, containsInAnyOrder('b', 'c'));
}
@Test
public void whenCalculatingSetSymmetricDifference_thenCorrect() {
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
final Set<Character> intersection = Sets.symmetricDifference(first, second);
assertThat(intersection, containsInAnyOrder('a', 'd'));
}
@Test
public void whenCalculatingPowerSet_thenCorrect() {
final Set<Character> chars = ImmutableSet.of('a', 'b');
final Set<Set<Character>> result = Sets.powerSet(chars);
final Set<Character> empty = ImmutableSet.<Character> builder().build();
final Set<Character> a = ImmutableSet.of('a');
final Set<Character> b = ImmutableSet.of('b');
final Set<Character> aB = ImmutableSet.of('a', 'b');
assertThat(result, contains(empty, a, b, aB));
}
@Test
public void whenCreatingRangeOfIntegersSet_thenCreated() {
final int start = 10;
final int end = 30;
final ContiguousSet<Integer> set = ContiguousSet.create(Range.closed(start, end), DiscreteDomain.integers());
assertEquals(21, set.size());
assertEquals(10, set.first().intValue());
assertEquals(30, set.last().intValue());
}
@Test
public void whenUsingRangeSet_thenCorrect() {
final RangeSet<Integer> rangeSet = TreeRangeSet.create();
rangeSet.add(Range.closed(1, 10));
rangeSet.add(Range.closed(12, 15));
assertEquals(2, rangeSet.asRanges().size());
rangeSet.add(Range.closed(10, 12));
assertTrue(rangeSet.encloses(Range.closed(1, 15)));
assertEquals(1, rangeSet.asRanges().size());
}
@Test
public void whenInsertDuplicatesInMultiSet_thenInserted() {
final Multiset<String> names = HashMultiset.create();
names.add("John");
names.add("Adam", 3);
names.add("John");
assertEquals(2, names.count("John"));
names.remove("John");
assertEquals(1, names.count("John"));
assertEquals(3, names.count("Adam"));
names.remove("Adam", 2);
assertEquals(1, names.count("Adam"));
}
@Test
public void whenGetTopOcurringElementsWithMultiSet_thenCorrect() {
final Multiset<String> names = HashMultiset.create();
names.add("John");
names.add("Adam", 5);
names.add("Jane");
names.add("Tom", 2);
final Set<String> sorted = Multisets.copyHighestCountFirst(names).elementSet();
final List<String> topTwo = Lists.newArrayList(sorted).subList(0, 2);
assertEquals(2, topTwo.size());
assertEquals("Adam", topTwo.get(0));
assertEquals("Tom", topTwo.get(1));
}
}

View File

@ -11,13 +11,10 @@
- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection)
- [Guava Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial)
- [Guava Lists](http://www.baeldung.com/guava-lists)
- [Guava Sets](http://www.baeldung.com/guava-sets)
- [Guava Maps](http://www.baeldung.com/guava-maps)
- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap)
- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map)

View File

@ -111,120 +111,6 @@ public class GuavaCollectionTypesUnitTest {
assertThat(immutable, contains("John", "Adam", "Jane", "Tom"));
}
// sets
@Test
public void whenCalculateUnionOfSets_thenCorrect() {
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
final Set<Character> union = Sets.union(first, second);
assertThat(union, containsInAnyOrder('a', 'b', 'c', 'd'));
}
@Test
public void whenCalculateSetsProduct_thenCorrect() {
final Set<Character> first = ImmutableSet.of('a', 'b');
final Set<Character> second = ImmutableSet.of('c', 'd');
final Set<List<Character>> result = Sets.cartesianProduct(ImmutableList.of(first, second));
final Function<List<Character>, String> func = new Function<List<Character>, String>() {
@Override
public final String apply(final List<Character> input) {
return Joiner.on(" ").join(input);
}
};
final Iterable<String> joined = Iterables.transform(result, func);
assertThat(joined, containsInAnyOrder("a c", "a d", "b c", "b d"));
}
@Test
public void whenCalculatingSetIntersection_thenCorrect() {
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
final Set<Character> intersection = Sets.intersection(first, second);
assertThat(intersection, containsInAnyOrder('b', 'c'));
}
@Test
public void whenCalculatingSetSymmetricDifference_thenCorrect() {
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
final Set<Character> intersection = Sets.symmetricDifference(first, second);
assertThat(intersection, containsInAnyOrder('a', 'd'));
}
@Test
public void whenCalculatingPowerSet_thenCorrect() {
final Set<Character> chars = ImmutableSet.of('a', 'b');
final Set<Set<Character>> result = Sets.powerSet(chars);
final Set<Character> empty = ImmutableSet.<Character> builder().build();
final Set<Character> a = ImmutableSet.of('a');
final Set<Character> b = ImmutableSet.of('b');
final Set<Character> aB = ImmutableSet.of('a', 'b');
assertThat(result, contains(empty, a, b, aB));
}
@Test
public void whenCreateRangeOfIntegersSet_thenCreated() {
final int start = 10;
final int end = 30;
final ContiguousSet<Integer> set = ContiguousSet.create(Range.closed(start, end), DiscreteDomain.integers());
assertEquals(21, set.size());
assertEquals(10, set.first().intValue());
assertEquals(30, set.last().intValue());
}
@Test
public void whenCreateRangeSet_thenCreated() {
final RangeSet<Integer> rangeSet = TreeRangeSet.create();
rangeSet.add(Range.closed(1, 10));
rangeSet.add(Range.closed(12, 15));
assertEquals(2, rangeSet.asRanges().size());
rangeSet.add(Range.closed(10, 12));
assertTrue(rangeSet.encloses(Range.closed(1, 15)));
assertEquals(1, rangeSet.asRanges().size());
}
@Test
public void whenInsertDuplicatesInMultiSet_thenInserted() {
final Multiset<String> names = HashMultiset.create();
names.add("John");
names.add("Adam", 3);
names.add("John");
assertEquals(2, names.count("John"));
names.remove("John");
assertEquals(1, names.count("John"));
assertEquals(3, names.count("Adam"));
names.remove("Adam", 2);
assertEquals(1, names.count("Adam"));
}
@Test
public void whenGetTopUsingMultiSet_thenCorrect() {
final Multiset<String> names = HashMultiset.create();
names.add("John");
names.add("Adam", 5);
names.add("Jane");
names.add("Tom", 2);
final Set<String> sorted = Multisets.copyHighestCountFirst(names).elementSet();
final List<String> topTwo = Lists.newArrayList(sorted).subList(0, 2);
assertEquals(2, topTwo.size());
assertEquals("Adam", topTwo.get(0));
assertEquals("Tom", topTwo.get(1));
}
@Test
public void whenCreateImmutableMap_thenCreated() {
final Map<String, Integer> salary = ImmutableMap.<String, Integer> builder().put("John", 1000).put("Jane", 1500).put("Adam", 2000).put("Tom", 2000).build();

View File

@ -2,3 +2,4 @@
- [Java Localization Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring)
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)

View File

@ -0,0 +1,58 @@
package com.baeldung.initialization;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
public class StringInitializationUnitTest {
private String fieldString;
void printDeclaredOnlyString() {
String localVarString = null;
System.out.println(localVarString); // compilation error
System.out.println(fieldString);
}
@Test
public void givenDeclaredFeldStringAndNullString_thenCompareEquals() {
String localVarString = null;
assertEquals(fieldString, localVarString);
}
@Test
public void givenTwoStringsWithSameLiteral_thenCompareReferencesEquals() {
String literalOne = "Baeldung";
String literalTwo = "Baeldung";
assertTrue(literalOne == literalTwo);
}
@Test
public void givenTwoStringsUsingNew_thenCompareReferencesNotEquals() {
String newStringOne = new String("Baeldung");
String newStringTwo = new String("Baeldung");
assertFalse(newStringOne == newStringTwo);
}
@Test
public void givenEmptyLiteralStringsAndNewObject_thenCompareEquals() {
String emptyLiteral = "";
String emptyNewString = new String("");
assertEquals(emptyLiteral, emptyNewString);
}
@Test
public void givenEmptyStringObjects_thenCompareEquals() {
String emptyNewString = new String("");
String emptyNewStringTwo = new String();
assertEquals(emptyNewString, emptyNewStringTwo);
}
}

View File

@ -10,6 +10,10 @@ import java.util.Map;
import java.util.UUID;
import javax.ejb.EJB;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.CDI;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
@ -48,67 +52,30 @@ public class CarServiceIntegrationTest {
@EJB
private CarServiceEjbSingleton carServiceEjbSingleton;
private static Map<String, UUID> idMap = new HashMap<>();
@Before
public void setUp() {
// populate idMap only on first run
if (idMap.isEmpty()) {
LOG.info("setUp::carServiceBean: {}", carServiceBean.getId());
idMap.put("carServiceBeanId", carServiceBean.getId());
LOG.info("setUp::carServiceSingleton: {}", carServiceSingleton.getId());
idMap.put("carServiceSingletonId", carServiceSingleton.getId());
LOG.info("setUp::carServiceEjbSingleton: {}", carServiceEjbSingleton.getId());
idMap.put("carServiceEjbSingletonId", carServiceEjbSingleton.getId());
}
@Test
public void givenASingleton_whenGetBeanIsCalledTwice_thenTheSameInstanceIsReturned() {
CarServiceSingleton one = getBean(CarServiceSingleton.class);
CarServiceSingleton two = getBean(CarServiceSingleton.class);
assertTrue(one == two);
}
@Test
public void givenRun1_whenGetId_thenSingletonIdEqual() {
int testRun = 1;
public void givenAPojo_whenGetBeanIsCalledTwice_thenDifferentInstancesAreReturned() {
CarServiceBean one = getBean(CarServiceBean.class);
CarServiceBean two = getBean(CarServiceBean.class);
assertTrue(one != two);
}
assertNotNull(carServiceBean);
assertNotNull(carServiceSingleton);
assertNotNull(carServiceEjbSingleton);
UUID carServiceBeanId = carServiceBean.getId();
assertEquals(idMap.get("carServiceBeanId"), carServiceBeanId);
LOG.info("Test run {}::carServiceBeanId: {}", testRun, carServiceBeanId);
UUID carServiceSingletonId = carServiceSingleton.getId();
assertEquals(idMap.get("carServiceSingletonId"), carServiceSingletonId);
LOG.info("Test run {}::carServiceSingletonId: {}", testRun, carServiceSingletonId);
UUID carServiceEjbSingletonId = carServiceEjbSingleton.getId();
assertEquals(idMap.get("carServiceEjbSingletonId"), carServiceEjbSingletonId);
LOG.info("Test run {}::carServiceEjbSingletonId: {}", testRun, carServiceEjbSingletonId);
@SuppressWarnings("unchecked")
private <T> T getBean(Class<T> beanClass) {
BeanManager bm = CDI.current().getBeanManager();
Bean<T> bean = (Bean<T>) bm.getBeans(beanClass).iterator().next();
CreationalContext<T> ctx = bm.createCreationalContext(bean);
return (T) bm.getReference(bean, beanClass, ctx);
}
@Test
public void givenRun2_whenGetId_thenSingletonIdEqual() {
int testRun = 2;
assertNotNull(carServiceBean);
assertNotNull(carServiceSingleton);
assertNotNull(carServiceEjbSingleton);
UUID carServiceBeanId = carServiceBean.getId();
assertNotEquals(idMap.get("carServiceBeanId"), carServiceBeanId);
LOG.info("Test run {}::carServiceBeanId: {}", testRun, carServiceBeanId);
UUID carServiceSingletonId = carServiceSingleton.getId();
assertEquals(idMap.get("carServiceSingletonId"), carServiceSingletonId);
LOG.info("Test run {}::carServiceSingletonId: {}", testRun, carServiceSingletonId);
UUID carServiceEjbSingletonId = carServiceEjbSingleton.getId();
assertEquals(idMap.get("carServiceEjbSingletonId"), carServiceEjbSingletonId);
LOG.info("Test run {}::carServiceEjbSingletonId: {}", testRun, carServiceEjbSingletonId);
}
@Test
public void givenRun3_whenSingleton_thenNoLocking() {
public void givenCDI_whenConcurrentAccess_thenLockingIsNotProvided() {
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
@ -124,7 +91,7 @@ public class CarServiceIntegrationTest {
}
@Test
public void givenRun4_whenEjb_thenLocking() {
public void givenEJB_whenConcurrentAccess_thenLockingIsProvided() {
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override

View File

@ -18,14 +18,16 @@
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxkotlin</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>

View File

@ -0,0 +1,157 @@
package com.baeldung.kotlin.rxkotlin
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.functions.BiFunction
import io.reactivex.rxkotlin.*
import io.reactivex.subjects.PublishSubject
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
class RxKotlinTest {
@Test
fun whenBooleanArrayToObserver_thenBooleanObserver() {
val observable = listOf(true, false, false).toObservable()
observable.test().assertValues(true, false, false)
}
@Test
fun whenBooleanArrayToFlowable_thenBooleanFlowable() {
val flowable = listOf(true, false, false).toFlowable()
flowable.buffer(2).test().assertValues(listOf(true, false), listOf(false))
}
@Test
fun whenIntArrayToObserver_thenIntObserver() {
val observable = listOf(1, 1, 2, 3).toObservable()
observable.test().assertValues(1, 1, 2, 3)
}
@Test
fun whenIntArrayToFlowable_thenIntFlowable() {
val flowable = listOf(1, 1, 2, 3).toFlowable()
flowable.buffer(2).test().assertValues(listOf(1, 1), listOf(2, 3))
}
@Test
fun whenObservablePairToMap_thenSingleNoDuplicates() {
val list = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3), Pair("a", 4))
val observable = list.toObservable()
val map = observable.toMap()
assertEquals(mapOf(Pair("a", 4), Pair("b", 2), Pair("c", 3)), map.blockingGet())
}
@Test
fun whenObservablePairToMap_thenSingleWithDuplicates() {
val list = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3), Pair("a", 4))
val observable = list.toObservable()
val map = observable.toMultimap()
assertEquals(
mapOf(Pair("a", listOf(1, 4)), Pair("b", listOf(2)), Pair("c", listOf(3))),
map.blockingGet())
}
@Test
fun whenMergeAll_thenStream() {
val subject = PublishSubject.create<Observable<String>>()
val observable = subject.mergeAll()
val testObserver = observable.test()
subject.onNext(Observable.just("first", "second"))
testObserver.assertValues("first", "second")
subject.onNext(Observable.just("third", "fourth"))
subject.onNext(Observable.just("fifth"))
testObserver.assertValues("first", "second", "third", "fourth", "fifth")
}
@Test
fun whenConcatAll_thenStream() {
val subject = PublishSubject.create<Observable<String>>()
val observable = subject.concatAll()
val testObserver = observable.test()
subject.onNext(Observable.just("first", "second"))
testObserver.assertValues("first", "second")
subject.onNext(Observable.just("third", "fourth"))
subject.onNext(Observable.just("fifth"))
testObserver.assertValues("first", "second", "third", "fourth", "fifth")
}
@Test
fun whenSwitchLatest_thenStream() {
val subject = PublishSubject.create<Observable<String>>()
val observable = subject.switchLatest()
val testObserver = observable.test()
subject.onNext(Observable.just("first", "second"))
testObserver.assertValues("first", "second")
subject.onNext(Observable.just("third", "fourth"))
subject.onNext(Observable.just("fifth"))
testObserver.assertValues("first", "second", "third", "fourth", "fifth")
}
@Test
fun whenMergeAllMaybes_thenObservable() {
val subject = PublishSubject.create<Maybe<Int>>()
val observable = subject.mergeAllMaybes()
val testObserver = observable.test()
subject.onNext(Maybe.just(1))
subject.onNext(Maybe.just(2))
subject.onNext(Maybe.empty())
testObserver.assertValues(1, 2)
subject.onNext(Maybe.error(Exception("")))
subject.onNext(Maybe.just(3))
testObserver.assertValues(1, 2).assertError(Exception::class.java)
}
@Test
fun whenMerge_thenStream() {
val observables = mutableListOf(Observable.just("first", "second"))
val observable = observables.merge()
observables.add(Observable.just("third", "fourth"))
observables.add(Observable.error(Exception("e")))
observables.add(Observable.just("fifth"))
observable.test().assertValues("first", "second", "third", "fourth").assertError(Exception::class.java)
}
@Test
fun whenMergeDelayError_thenStream() {
val observables = mutableListOf<Observable<String>>(Observable.error(Exception("e1")))
val observable = observables.mergeDelayError()
observables.add(Observable.just("1", "2"))
observables.add(Observable.error(Exception("e2")))
observables.add(Observable.just("3"))
observable.test().assertValues("1", "2", "3").assertError(Exception::class.java)
}
@Test
fun whenCast_thenUniformType() {
val observable = Observable.just<Number>(1, 1, 2, 3)
observable.cast<Int>().test().assertValues(1, 1, 2, 3)
}
@Test
fun whenOfType_thenFilter() {
val observable = Observable.just(1, "and", 2, "and")
observable.ofType<Int>().test().assertValues(1, 2)
}
@Test
fun whenFunction_thenCompletable() {
var value = 0
val completable = { value = 3 }.toCompletable()
assertFalse(completable.test().isCancelled)
assertEquals(3, value)
}
@Test
fun whenHelper_thenMoreIdiomaticKotlin() {
val zipWith = Observable.just(1).zipWith(Observable.just(2)) { a, b -> a + b }
zipWith.subscribeBy(onNext = { println(it) })
val zip = Observables.zip(Observable.just(1), Observable.just(2)) { a, b -> a + b }
zip.subscribeBy(onNext = { println(it) })
val zipOrig = Observable.zip(Observable.just(1), Observable.just(2), BiFunction<Int, Int, Int> { a, b -> a + b })
zipOrig.subscribeBy(onNext = { println(it) })
}
}

View File

@ -54,9 +54,8 @@ dependencies {
testCompile group: 'org.jetbrains.spek', name: 'spek-subject-extension', version: '1.1.5'
testCompile group: 'org.jetbrains.spek', name: 'spek-junit-platform-engine', version: '1.1.5'
implementation 'com.beust:klaxon:3.0.1'
implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0'
}
task runServer(type: JavaExec) {
main = 'APIServer'
classpath = sourceSets.main.runtimeClasspath

View File

@ -0,0 +1,75 @@
package com.baeldung.jpa.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import com.baeldung.util.Gender;
@Entity
@Table(name="STUDENT")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "STUDENT_NAME", length = 50, nullable = false, unique = false)
private String name;
@Transient
private Integer age;
@Temporal(TemporalType.DATE)
private Date birthDate;
@Enumerated(EnumType.STRING)
private Gender gender;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
}

View File

@ -0,0 +1,91 @@
package com.baeldung.jpa.enums;
import javax.persistence.*;
@Entity
public class Article {
@Id
private int id;
private String title;
@Enumerated(EnumType.ORDINAL)
private Status status;
@Enumerated(EnumType.STRING)
private Type type;
@Basic
private int priorityValue;
@Transient
private Priority priority;
private Category category;
public Article() {
}
@PostLoad
void fillTransient() {
if (priorityValue > 0) {
this.priority = Priority.of(priorityValue);
}
}
@PrePersist
void fillPersistent() {
if (priority != null) {
this.priorityValue = priority.getPriority();
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Priority getPriority() {
return priority;
}
public void setPriority(Priority priority) {
this.priority = priority;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.jpa.enums;
import java.util.stream.Stream;
public enum Category {
SPORT("S"), MUSIC("M"), TECHNOLOGY("T");
private String code;
Category(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.jpa.enums;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.stream.Stream;
@Converter(autoApply = true)
public class CategoryConverter implements AttributeConverter<Category, String> {
@Override
public String convertToDatabaseColumn(Category category) {
if (category == null) {
return null;
}
return category.getCode();
}
@Override
public Category convertToEntityAttribute(final String code) {
if (code == null) {
return null;
}
return Stream.of(Category.values())
.filter(c -> c.getCode().equals(code))
.findFirst()
.orElseThrow(IllegalArgumentException::new);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.jpa.enums;
import java.util.stream.Stream;
public enum Priority {
LOW(100), MEDIUM(200), HIGH(300);
private int priority;
private Priority(int priority) {
this.priority = priority;
}
public int getPriority() {
return priority;
}
public static Priority of(int priority) {
return Stream.of(Priority.values())
.filter(p -> p.getPriority() == priority)
.findFirst()
.orElseThrow(IllegalArgumentException::new);
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.jpa.enums;
public enum Status {
OPEN, REVIEW, APPROVED, REJECTED;
}

View File

@ -0,0 +1,5 @@
package com.baeldung.jpa.enums;
enum Type {
INTERNAL, EXTERNAL;
}

View File

@ -0,0 +1,6 @@
package com.baeldung.util;
public enum Gender {
MALE,
FEMALE
}

View File

@ -26,6 +26,8 @@
<persistence-unit name="jpa-h2">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.stringcast.Message</class>
<class>com.baeldung.jpa.enums.Article</class>
<class>com.baeldung.jpa.enums.CategoryConverter</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
@ -146,4 +148,19 @@
</properties>
</persistence-unit>
<persistence-unit name="jpa-entity-definition">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.entity.Student</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="show_sql" value="true" />
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,91 @@
package com.baeldung.jpa.entity;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.util.Gender;
public class StudentEntityIntegrationTest {
private EntityManagerFactory emf;
private EntityManager em;
@Before
public void setup() {
emf = Persistence.createEntityManagerFactory("jpa-entity-definition");
em = emf.createEntityManager();
}
@Test
public void persistStudentThenRetrieveTheDetails() {
Student student = createStudentWithRelevantDetails();
persist(student);
clearThePersistenceContext();
List<Student> students = getStudentsFromTable();
checkAssertionsWith(students);
}
@After
public void destroy() {
if (em != null) {
em.close();
}
if (emf != null) {
emf.close();
}
}
private void clearThePersistenceContext() {
em.clear();
}
private void checkAssertionsWith(List<Student> students) {
assertEquals(1, students.size());
Student john = students.get(0);
assertEquals(1L, john.getId().longValue());
assertEquals(null, john.getAge());
assertEquals("John", john.getName());
}
private List<Student> getStudentsFromTable() {
String selectQuery = "SELECT student FROM Student student";
TypedQuery<Student> selectFromStudentTypedQuery = em.createQuery(selectQuery, Student.class);
List<Student> students = selectFromStudentTypedQuery.getResultList();
return students;
}
private void persist(Student student) {
em.getTransaction().begin();
em.persist(student);
em.getTransaction().commit();
}
private Student createStudentWithRelevantDetails() {
Student student = new Student();
student.setAge(20); // the 'age' field has been annotated with @Transient
student.setName("John");
Date date = getDate();
student.setBirthDate(date);
student.setGender(Gender.MALE);
return student;
}
private Date getDate() {
LocalDate localDate = LocalDate.of(2008, 7, 20);
return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
}
}

View File

@ -0,0 +1,118 @@
package com.baeldung.jpa.enums;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ArticleUnitTest {
private static EntityManager em;
private static EntityManagerFactory emFactory;
@BeforeClass
public static void setup() {
Map properties = new HashMap();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
emFactory = Persistence.createEntityManagerFactory("jpa-h2", properties);
em = emFactory.createEntityManager();
}
@Test
public void shouldPersistStatusEnumOrdinalValue() {
// given
Article article = new Article();
article.setId(1);
article.setTitle("ordinal title");
article.setStatus(Status.OPEN);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 1);
assertEquals(1, persistedArticle.getId());
assertEquals("ordinal title", persistedArticle.getTitle());
assertEquals(Status.OPEN, persistedArticle.getStatus());
}
@Test
public void shouldPersistTypeEnumStringValue() {
// given
Article article = new Article();
article.setId(2);
article.setTitle("string title");
article.setType(Type.EXTERNAL);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 2);
assertEquals(2, persistedArticle.getId());
assertEquals("string title", persistedArticle.getTitle());
assertEquals(Type.EXTERNAL, persistedArticle.getType());
}
@Test
public void shouldPersistPriorityIntValue() {
// given
Article article = new Article();
article.setId(3);
article.setTitle("callback title");
article.setPriority(Priority.HIGH);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 3);
assertEquals(3, persistedArticle.getId());
assertEquals("callback title", persistedArticle.getTitle());
assertEquals(Priority.HIGH, persistedArticle.getPriority());
}
@Test
public void shouldPersistCategoryEnumConvertedValue() {
// given
Article article = new Article();
article.setId(4);
article.setTitle("converted title");
article.setCategory(Category.MUSIC);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 4);
assertEquals(4, persistedArticle.getId());
assertEquals("converted title", persistedArticle.getTitle());
assertEquals(Category.MUSIC, persistedArticle.getCategory());
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.like.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Movie {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String title;
private String director;
private String rating;
private int duration;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
}

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