This commit is contained in:
Jonathan Cook 2020-06-29 12:16:23 +02:00
commit 126923a3f3
95 changed files with 1352 additions and 245 deletions

4
.gitignore vendored
View File

@ -85,7 +85,3 @@ transaction.log
*-shell.log
apache-cxf/cxf-aegis/baeldung.xml
apache-fop/src/test/resources/input.xml
apache-fop/src/test/resources/output_herold.pdf
apache-fop/src/test/resources/output_html2fo.pdf
apache-fop/src/test/resources/output_jtidy.pdf

View File

@ -1,44 +0,0 @@
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.groovy</groupId>
<artifactId>determine-datatype</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>groovy-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.0.6</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.junit/junit5-engine -->
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit5-engine</artifactId>
<version>${junit5.version}</version>
</dependency>
</dependencies>
<properties>
<junit5.version>5.0.0-ALPHA</junit5.version>
</properties>
</project>

View File

@ -1,14 +0,0 @@
package com.baeldung.groovy.determine.datatype
class Person {
private int ageAsInt
private Double ageAsDouble
private String ageAsString
Person() {}
Person(int ageAsInt) { this.ageAsInt = ageAsInt}
Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble}
Person(String ageAsString) { this.ageAsString = ageAsString}
}
class Student extends Person {}

View File

@ -1,55 +0,0 @@
package com.baeldung.groovy.determine.datatype;
import org.junit.Assert
import org.junit.Test;
public class PersonTest {
@Test
public void givenWhenParameterTypeIsInteger_thenReturnTrue() {
Person personObj = new Person(10)
Assert.assertTrue(personObj.ageAsInt instanceof Integer);
}
@Test
public void givenWhenParameterTypeIsDouble_thenReturnTrue() {
Person personObj = new Person(10.0)
Assert.assertTrue((personObj.ageAsDouble).getClass() == Double)
}
@Test
public void givenWhenParameterTypeIsString_thenReturnTrue() {
Person personObj = new Person("10 years")
Assert.assertTrue(personObj.ageAsString.class == String)
}
@Test
public void givenClassName_WhenParameterIsInteger_thenReturnTrue() {
Assert.assertTrue(Person.class.getDeclaredField('ageAsInt').type == int.class)
}
@Test
public void givenWhenObjectIsInstanceOfType_thenReturnTrue() {
Person personObj = new Person()
Assert.assertTrue(personObj instanceof Person)
}
@Test
public void givenWhenInstanceIsOfSubtype_thenReturnTrue() {
Student studentObj = new Student()
Assert.assertTrue(studentObj in Person)
}
@Test
public void givenGroovyList_WhenFindClassName_thenReturnTrue() {
def ageList = ['ageAsString','ageAsDouble', 10]
Assert.assertTrue(ageList.class == ArrayList)
Assert.assertTrue(ageList.getClass() == ArrayList)
}
@Test
public void givenGrooyMap_WhenFindClassName_thenReturnTrue() {
def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0]
Assert.assertFalse(ageMap.class == LinkedHashMap)
}
}

View File

@ -72,7 +72,7 @@ public class JavaFolderSizeUnitTest {
public void whenGetFolderSizeUsingGuava_thenCorrect() {
final File folder = new File(path);
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
final Iterable<File> files = com.google.common.io.Files.fileTraverser().breadthFirst(folder);
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
assertEquals(EXPECTED_SIZE, size);

View File

@ -0,0 +1,5 @@
## Core Java JVM Cookbooks and Examples
This module contains articles about working with the Java Virtual Machine (JVM).
### Relevant Articles:

View File

@ -0,0 +1,43 @@
<?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-jvm-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-jvm-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<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>
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>${jol-core.version}</version>
</dependency>
</dependencies>
<properties>
<assertj.version>3.6.1</assertj.version>
<jol-core.version>0.10</jol-core.version>
</properties>
</project>

View File

@ -91,7 +91,7 @@ public class MemoryLayoutUnitTest {
private boolean first;
private char second;
private double third;
private int forth;
private int fourth;
private boolean fifth;
}

View File

@ -22,15 +22,15 @@ public class PersonWithEquals {
this.birthDate = birthDate;
}
public String firstName() {
public String getFirstName() {
return firstName;
}
public String lastName() {
public String getLastName() {
return lastName;
}
public LocalDate birthDate() {
public LocalDate getBirthDate() {
return birthDate;
}

View File

@ -22,6 +22,18 @@ public class PersonWithEqualsAndComparable implements Comparable<PersonWithEqual
this.birthDate = birthDate;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public LocalDate getBirthDate() {
return birthDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;

View File

@ -23,15 +23,15 @@ public class PersonWithEqualsAndComparableUsingComparator implements Comparable<
this.birthDate = birthDate;
}
public String firstName() {
public String getFirstName() {
return firstName;
}
public String lastName() {
public String getLastName() {
return lastName;
}
public LocalDate birthDate() {
public LocalDate getBirthDate() {
return birthDate;
}
@ -52,9 +52,9 @@ public class PersonWithEqualsAndComparableUsingComparator implements Comparable<
@Override
public int compareTo(PersonWithEqualsAndComparableUsingComparator o) {
return Comparator.comparing(PersonWithEqualsAndComparableUsingComparator::lastName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::firstName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::birthDate, Comparator.nullsLast(Comparator.naturalOrder()))
return Comparator.comparing(PersonWithEqualsAndComparableUsingComparator::getLastName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::getFirstName)
.thenComparing(PersonWithEqualsAndComparableUsingComparator::getBirthDate, Comparator.nullsLast(Comparator.naturalOrder()))
.compare(this, o);
}
}

View File

@ -22,6 +22,18 @@ public class PersonWithEqualsAndWrongComparable implements Comparable<PersonWith
this.birthDate = birthDate;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public LocalDate getBirthDate() {
return birthDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;

View File

@ -8,4 +8,12 @@ public class PersonWithoutEquals {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}

View File

@ -21,11 +21,10 @@ public enum PizzaStatus {
private static Map<Integer, PizzaStatus> timeToDeliveryToEnumValuesMapping = new HashMap<>();
static {
PizzaStatus[] pizzaStatuses = PizzaStatus.values();
for (int pizzaStatusIndex = 0; pizzaStatusIndex < pizzaStatuses.length; pizzaStatusIndex++) {
for (PizzaStatus pizzaStatus : PizzaStatus.values()) {
timeToDeliveryToEnumValuesMapping.put(
pizzaStatuses[pizzaStatusIndex].getTimeToDelivery(),
pizzaStatuses[pizzaStatusIndex]
pizzaStatus.getTimeToDelivery(),
pizzaStatus
);
}
}

View File

@ -20,7 +20,7 @@ class ComparatorInterfaceUnitTest {
Comparator<PersonWithEquals> compareByFirstNames = new Comparator<PersonWithEquals>() {
@Override
public int compare(PersonWithEquals o1, PersonWithEquals o2) {
return o1.firstName().compareTo(o2.firstName());
return o1.getFirstName().compareTo(o2.getFirstName());
}
};
people.sort(compareByFirstNames);
@ -37,7 +37,7 @@ class ComparatorInterfaceUnitTest {
people.add(joe);
people.add(allan);
Comparator<PersonWithEquals> compareByFirstNames = Comparator.comparing(PersonWithEquals::firstName);
Comparator<PersonWithEquals> compareByFirstNames = Comparator.comparing(PersonWithEquals::getFirstName);
people.sort(compareByFirstNames);
assertThat(people).containsExactly(allan, joe);

View File

@ -63,8 +63,8 @@ class GuavaUnitTest {
PersonWithEquals joe = new PersonWithEquals("Joe", "Portman");
int comparisonResult = ComparisonChain.start()
.compare(natalie.lastName(), joe.lastName())
.compare(natalie.firstName(), joe.firstName())
.compare(natalie.getLastName(), joe.getLastName())
.compare(natalie.getFirstName(), joe.getFirstName())
.result();
assertThat(comparisonResult).isPositive();

View File

@ -1,7 +1,12 @@
package com.baeldung.inttoenum;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.util.Arrays;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
public class IntToEnumUnitTest {
@ -9,19 +14,33 @@ public class IntToEnumUnitTest {
@Test
public void whenIntToEnumUsingValuesMethod_thenReturnEnumObject() {
int timeToDeliveryForOrderedPizzaStatus = 5;
PizzaStatus[] pizzaStatuses = PizzaStatus.values();
PizzaStatus pizzaOrderedStatus = null;
for (int pizzaStatusIndex = 0; pizzaStatusIndex < pizzaStatuses.length; pizzaStatusIndex++) {
if (pizzaStatuses[pizzaStatusIndex].getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus) {
pizzaOrderedStatus = pizzaStatuses[pizzaStatusIndex];
for (PizzaStatus pizzaStatus : PizzaStatus.values()) {
if (pizzaStatus.getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus) {
pizzaOrderedStatus = pizzaStatus;
}
}
assertEquals(pizzaOrderedStatus, PizzaStatus.ORDERED);
assertThat(pizzaOrderedStatus).isEqualTo(PizzaStatus.ORDERED);
}
@Test
public void whenIntToEnumUsingMap_thenReturnEnumObject() {
int timeToDeliveryForOrderedPizzaStatus = 5;
assertEquals(PizzaStatus.castIntToEnum(timeToDeliveryForOrderedPizzaStatus), PizzaStatus.ORDERED);
assertThat(PizzaStatus.castIntToEnum(timeToDeliveryForOrderedPizzaStatus)).isEqualTo(PizzaStatus.ORDERED);
}
@Test
public void whenIntToEnumUsingStream_thenReturnEnumObject() {
int timeToDeliveryForOrderedPizzaStatus = 5;
Optional<PizzaStatus> pizzaStatus = Arrays.stream(PizzaStatus.values())
.filter(p -> p.getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus)
.findFirst();
assertThat(pizzaStatus).hasValue(PizzaStatus.ORDERED);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.macaddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class GetAllMacAddressesDemo {
public static void main(String[] args) throws SocketException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = networkInterfaces.nextElement();
byte[] hardwareAddress = ni.getHardwareAddress();
if (hardwareAddress != null) {
String[] hexadecimalFormat = new String[hardwareAddress.length];
for (int i = 0; i < hardwareAddress.length; i++) {
hexadecimalFormat[i] = String.format("%02X", hardwareAddress[i]);
}
System.out.println(String.join("-", hexadecimalFormat));
}
}
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.macaddress;
import org.junit.Test;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import static org.junit.Assert.assertEquals;
public class MacAddressUnitTest {
@Test
public void givenNetworkInterface_whenUsingLocalHost_thenGetMacAddress() throws UnknownHostException, SocketException {
InetAddress localHost = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(localHost);
byte[] macAddress = ni.getHardwareAddress();
assertEquals(6, macAddress.length);
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.deserialization;
import java.io.IOException;
import java.io.Serializable;
public class DefaultSerial implements Serializable {
private String name;
public static void main(String[] args) throws IOException, ClassNotFoundException {
String digest = "rO0ABXNyACpjb20uYmFlbGR1bmcuZGVzZXJpY"
+ "WxpemF0aW9uLkRlZmF1bHRTZXJpYWx9iVz3Lz/mdAIAAHhw";
DefaultSerial instance = (DefaultSerial) DeserializationUtility.deSerializeObjectFromString(digest);
}
}

View File

@ -80,6 +80,7 @@
<module>core-java-jndi</module>
<!-- <module>core-java-jpms</module> --> <!-- We haven't upgraded to java 10. Fixing in BAEL-10841 -->
<module>core-java-jvm</module>
<module>core-java-jvm-2</module>
<module>core-java-lambdas</module>
<module>core-java-lang</module>

View File

@ -6,6 +6,7 @@ interface Page<T> {
fun elements(): MutableList<T>
}
operator fun <T> Page<T>.invoke(index: Int): T = elements()[index]
operator fun <T> Page<T>.get(index: Int): T = elements()[index]
operator fun <T> Page<T>.get(start: Int, endExclusive: Int): List<T> = elements().subList(start, endExclusive)
operator fun <T> Page<T>.set(index: Int, value: T) {

View File

@ -14,6 +14,11 @@ class PageTest {
assertEquals(page[1, 3], listOf("Kotlin", "Scala"))
}
@Test
fun `Invoke convention should work as expected`() {
assertEquals(page(1), "Kotlin")
}
@Test
fun `In convention should work on a page as expected`() {
assertTrue("Kotlin" in page)

View File

@ -0,0 +1,75 @@
package com.baeldung.circularbuffer;
public class CircularBuffer<E> {
private static final int DEFAULT_CAPACITY = 8;
private final int capacity;
private final E[] data;
private volatile int writeSequence, readSequence;
@SuppressWarnings("unchecked")
public CircularBuffer(int capacity) {
this.capacity = (capacity < 1) ? DEFAULT_CAPACITY : capacity;
this.data = (E[]) new Object[capacity];
this.readSequence = 0;
this.writeSequence = -1;
}
public boolean offer(E element) {
if (isNotFull()) {
int nextWriteSeq = writeSequence + 1;
data[nextWriteSeq % capacity] = element;
writeSequence++;
return true;
}
return false;
}
public E poll() {
if (isNotEmpty()) {
E nextValue = data[readSequence % capacity];
readSequence++;
return nextValue;
}
return null;
}
public int capacity() {
return capacity;
}
public int size() {
return (writeSequence - readSequence) + 1;
}
public boolean isEmpty() {
return writeSequence < readSequence;
}
public boolean isFull() {
return size() >= capacity;
}
private boolean isNotEmpty() {
return !isEmpty();
}
private boolean isNotFull() {
return !isFull();
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.circularbuffer;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class CircularBufferUnitTest {
private final String[] shapes = { "Circle", "Triangle", "Rectangle", "Square", "Rhombus", "Trapezoid", "Pentagon", "Pentagram", "Hexagon", "Hexagram" };
private final int defaultCapacity = shapes.length;
@Test
public void givenCircularBuffer_whenAnElementIsEnqueued_thenSizeIsOne() {
CircularBuffer<String> buffer = new CircularBuffer<>(defaultCapacity);
assertTrue(buffer.offer("Square"));
assertEquals(1, buffer.size());
}
@Test
public void givenCircularBuffer_whenAnElementIsDequeued_thenElementMatchesEnqueuedElement() {
CircularBuffer<String> buffer = new CircularBuffer<>(defaultCapacity);
buffer.offer("Triangle");
String shape = buffer.poll();
assertEquals("Triangle", shape);
}
@Test
public void givenCircularBuffer_whenAnElementIsEnqueuedAndDeququed_thenBufferIsEmpty() {
CircularBuffer<String> buffer = new CircularBuffer<>(defaultCapacity);
buffer.offer("Rectangle");
assertFalse(buffer.isEmpty());
assertEquals(1, buffer.size());
buffer.poll();
assertTrue(buffer.isEmpty());
}
@Test
public void givenCircularBuffer_whenFilledToCapacity_thenNoMoreElementsCanBeEnqueued() {
int capacity = shapes.length;
CircularBuffer<String> buffer = new CircularBuffer<>(capacity);
assertTrue(buffer.isEmpty());
for (String shape : shapes) {
buffer.offer(shape);
}
assertTrue(buffer.isFull());
assertFalse(buffer.offer("Octagon"));
}
@Test
public void givenCircularBuffer_whenBufferIsEmpty_thenReturnsNull() {
CircularBuffer<String> buffer = new CircularBuffer<>(1);
assertTrue(buffer.isEmpty());
assertNull(buffer.poll());
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.circularbuffer;
import static org.junit.Assert.assertArrayEquals;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import org.junit.jupiter.api.Test;
public class ProducerConsumerLiveTest {
private final String[] shapes = { "Circle", "Triangle", "Rectangle", "Square", "Rhombus", "Trapezoid", "Pentagon", "Pentagram", "Hexagon", "Hexagram" };
@Test
public void givenACircularBuffer_whenInterleavingProducerConsumer_thenElementsMatch() throws Exception {
CircularBuffer<String> buffer = new CircularBuffer<String>(shapes.length);
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(new Producer<String>(buffer, shapes));
Future<String[]> consumed = executorService.submit(new Consumer<String>(buffer, shapes.length));
String[] shapesConsumed = consumed.get(5L, TimeUnit.SECONDS);
assertArrayEquals(shapes, shapesConsumed);
}
static class Producer<T> implements Runnable {
private CircularBuffer<T> buffer;
private T[] items;
public Producer(CircularBuffer<T> buffer, T[] items) {
this.buffer = buffer;
this.items = items;
}
@Override
public void run() {
for (int i = 0; i < items.length;) {
if (buffer.offer(items[i])) {
System.out.println("Produced: " + items[i]);
i++;
LockSupport.parkNanos(5);
}
}
}
}
@SuppressWarnings("unchecked")
static class Consumer<T> implements Callable<T[]> {
private CircularBuffer<T> buffer;
private int expectedCount;
public Consumer(CircularBuffer<T> buffer, int expectedCount) {
this.buffer = buffer;
this.expectedCount = expectedCount;
}
@Override
public T[] call() throws Exception {
T[] items = (T[]) new Object[expectedCount];
for (int i = 0; i < items.length;) {
T item = buffer.poll();
if (item != null) {
items[i++] = item;
LockSupport.parkNanos(5);
System.out.println("Consumed: " + item);
}
}
return items;
}
}
}

2
gradle-5/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
**/build/**
/build/

View File

@ -1,54 +1,21 @@
plugins {
id "application"
}
apply plugin :"java"
description = "Java MainClass execution examples"
group = "com.baeldung"
version = "0.0.1"
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
ext {
javaMainClass = "com.baeldung.gradle.exec.MainClass"
plugins{
id "nebula.lint" version "16.9.0"
}
jar {
manifest {
attributes(
"Main-Class": javaMainClass
)
description = "Gradle 5 root project"
allprojects {
apply plugin :"java"
apply plugin :"nebula.lint"
gradleLint {
rules=['unused-dependency']
reportFormat = 'text'
}
}
group = "com.baeldung"
version = "0.0.1"
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
application {
mainClassName = javaMainClass
}
task runWithJavaExec(type: JavaExec) {
group = "Execution"
description = "Run the main class with JavaExecTask"
classpath = sourceSets.main.runtimeClasspath
main = javaMainClass
}
task runWithExec(type: Exec) {
dependsOn build
group = "Execution"
description = "Run the main class with ExecTask"
commandLine "java", "-classpath", sourceSets.main.runtimeClasspath.getAsPath(), javaMainClass
}
task runWithExecJarExecutable(type: Exec) {
dependsOn jar
group = "Execution"
description = "Run the output executable jar with ExecTask"
commandLine "java", "-jar", jar.archiveFile.get()
}
task runWithExecJarOnClassPath(type: Exec) {
dependsOn jar
group = "Execution"
description = "Run the mainClass from the output jar in classpath with ExecTask"
commandLine "java", "-classpath", jar.archiveFile.get() , javaMainClass
repositories {
jcenter()
}
}

View File

@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.5.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip

1
gradle-5/java-exec/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build/

View File

@ -0,0 +1,47 @@
apply plugin: "application"
description = "Java MainClass execution examples"
ext {
javaMainClass = "com.baeldung.gradle.exec.MainClass"
}
jar {
manifest {
attributes(
"Main-Class": javaMainClass
)
}
}
application {
mainClassName = javaMainClass
}
task runWithJavaExec(type: JavaExec) {
group = "Execution"
description = "Run the main class with JavaExecTask"
classpath = sourceSets.main.runtimeClasspath
main = javaMainClass
}
task runWithExec(type: Exec) {
dependsOn build
group = "Execution"
description = "Run the main class with ExecTask"
commandLine "java", "-classpath", sourceSets.main.runtimeClasspath.getAsPath(), javaMainClass
}
task runWithExecJarExecutable(type: Exec) {
dependsOn jar
group = "Execution"
description = "Run the output executable jar with ExecTask"
commandLine "java", "-jar", jar.archiveFile.get()
}
task runWithExecJarOnClassPath(type: Exec) {
dependsOn jar
group = "Execution"
description = "Run the mainClass from the output jar in classpath with ExecTask"
commandLine "java", "-classpath", jar.archiveFile.get() , javaMainClass
}

3
gradle-5/settings.gradle Normal file
View File

@ -0,0 +1,3 @@
rootProject.name='gradle-5-articles'
include 'java-exec'
include 'unused-dependencies'

View File

@ -0,0 +1 @@
/build/

View File

@ -0,0 +1,8 @@
description = "Gradle Unused Dependencies example"
dependencies {
implementation('com.google.guava:guava:29.0-jre')
implementation('org.apache.httpcomponents:httpclient:4.5.12')
testImplementation('junit:junit:4.12')
}

View File

@ -0,0 +1,39 @@
package com.baeldung.unused;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.http.ssl.SSLContextBuilder;
import com.google.common.collect.ImmutableList;
public class UnusedDependencies {
public static void main(String[] args) {
System.out.println("Hello world");
useGuava();
useHttpCore();
useHttpClientWithReflection();
}
private static void useGuava() {
List<String> list = ImmutableList.of("Baledung", "is", "cool");
System.out.println(list.stream()
.collect(Collectors.joining(" ")));
}
private static void useHttpCore() {
SSLContextBuilder.create();
}
private static void useHttpClientWithReflection() {
try {
Class<?> httpBuilder = Class.forName("org.apache.http.impl.client.HttpClientBuilder");
Method create = httpBuilder.getMethod("create", null);
create.invoke(httpBuilder, null);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -14,3 +14,4 @@ This module contains articles about Google Guava collections
- [Guava Lists](https://www.baeldung.com/guava-lists)
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](https://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
- [Guide to Guava Table](https://www.baeldung.com/guava-table)
- [Guava CharMatcher](https://www.baeldung.com/guava-string-charmatcher)

View File

@ -117,7 +117,7 @@ public class GuavaStringUnitTest {
@Test
public void whenRemoveSpecialCharacters_thenRemoved() {
final String input = "H*el.lo,}12";
final CharMatcher matcher = CharMatcher.JAVA_LETTER_OR_DIGIT;
final CharMatcher matcher = CharMatcher.javaLetterOrDigit();
final String result = matcher.retainFrom(input);
assertEquals("Hello12", result);
@ -127,7 +127,7 @@ public class GuavaStringUnitTest {
public void whenRemoveNonASCIIChars_thenRemoved() {
final String input = "あhello₤";
String result = CharMatcher.ASCII.retainFrom(input);
String result = CharMatcher.ascii().retainFrom(input);
assertEquals("hello", result);
result = CharMatcher.inRange('0', 'z').retainFrom(input);
@ -138,13 +138,13 @@ public class GuavaStringUnitTest {
public void whenValidateString_thenValid() {
final String input = "hello";
boolean result = CharMatcher.JAVA_LOWER_CASE.matchesAllOf(input);
boolean result = CharMatcher.javaLowerCase().matchesAllOf(input);
assertTrue(result);
result = CharMatcher.is('e').matchesAnyOf(input);
assertTrue(result);
result = CharMatcher.JAVA_DIGIT.matchesNoneOf(input);
result = CharMatcher.javaDigit().matchesNoneOf(input);
assertTrue(result);
}

View File

@ -0,0 +1,76 @@
package com.baeldung.divisionbyzero;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class DivisionByZeroUnitTest {
@Test
void givenInt_whenDividedByZero_thenThrowException() {
assertThrows(ArithmeticException.class, () -> {
int result = 12 / 0;
});
}
@Test
void whenDividingIntZeroByZero_thenThrowException() {
assertThrows(ArithmeticException.class, () -> {
int result = 0 / 0;
});
}
@Test
void whenDividingFloatingNumberByZero_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> {
float result = 0f / 0;
});
assertDoesNotThrow(() -> {
double result = 0d / 0;
});
}
@Test
void givenPositiveFloatingNumber_whenDividedByZero_thenReturnPositiveInfinity() {
assertEquals(Float.POSITIVE_INFINITY, 12f / 0);
assertEquals(Double.POSITIVE_INFINITY, 12d / 0);
}
@Test
void givenNegativeFloatingNumber_whenDividedByZero_thenReturnNegativeInfinity() {
assertEquals(Float.NEGATIVE_INFINITY, -12f / 0);
assertEquals(Double.NEGATIVE_INFINITY, -12d / 0);
}
@Test
void givenPositiveFloatingNumber_whenDividedByNegativeZero_thenReturnNegativeInfinity() {
assertEquals(Float.NEGATIVE_INFINITY, 12f / -0f);
assertEquals(Double.NEGATIVE_INFINITY, 12f / -0f);
}
@Test
void whenDividingFloatingNumberZeroByZero_thenReturnNaN() {
assertEquals(Float.NaN, 0f / 0);
assertEquals(Double.NaN, 0d / 0);
}
@Test
void givenABitRepresentationWithAllExponentBitsZeroesAndAllFractionBitsZeroes_whenTransformingItToFloat_thenReturnPositiveZero() {
assertEquals(0f, Float.intBitsToFloat(0b00000000000000000000000000000000));
assertEquals(-0f, Float.intBitsToFloat(0b10000000000000000000000000000000));
}
@Test
void givenABitRepresentationWithAllExponentBitsOnesAndAllFractionBitsZeroes_whenTransformingItToFloat_thenReturnInfinity() {
assertEquals(Float.POSITIVE_INFINITY, Float.intBitsToFloat(0b01111111100000000000000000000000));
assertEquals(Float.NEGATIVE_INFINITY, Float.intBitsToFloat(0b11111111100000000000000000000000));
}
@Test
void givenABitRepresentationWithAllExponentBitsOnesAndNotAllFractionBitsZeroes_whenTransformingItToFloat_thenReturnNan() {
assertEquals(Float.NaN, Float.intBitsToFloat(0b11111111100000010000000000000000));
assertEquals(Float.NaN, Float.intBitsToFloat(0b11111111100000011000000000100000));
assertEquals(Float.NaN, Float.intBitsToFloat(0b11111111100000011100000000000000));
assertEquals(Float.NaN, Float.intBitsToFloat(0b11111111100000011110000000000000));
}
}

View File

@ -8,7 +8,7 @@ This module contains articles about test libraries.
- [Introduction to JSONassert](https://www.baeldung.com/jsonassert)
- [Serenity BDD and Screenplay](https://www.baeldung.com/serenity-screenplay)
- [Serenity BDD with Spring and JBehave](https://www.baeldung.com/serenity-spring-jbehave)
- [Introduction to Awaitlity](https://www.baeldung.com/awaitlity-testing)
- [Introduction to Awaitility](https://www.baeldung.com/awaitlity-testing)
- [Introduction to Hoverfly in Java](https://www.baeldung.com/hoverfly)
- [Testing with Hamcrest](https://www.baeldung.com/java-junit-hamcrest-guide)
- [Introduction To DBUnit](https://www.baeldung.com/java-dbunit)

View File

@ -42,7 +42,7 @@
</dependencies>
<properties>
<guava.version>23.0</guava.version>
<guava.version>29.0-jre</guava.version>
<commons.io.version>2.6</commons.io.version>
<jmh.version>1.19</jmh.version>
<modelmapper.version>2.3.7</modelmapper.version>

View File

@ -4,7 +4,7 @@ This module contains articles about Hibernate 5. Let's not add more articles her
### Relevant articles:
- [An Overview of Identifiers in Hibernate](https://www.baeldung.com/hibernate-identifiers)
- [An Overview of Identifiers in Hibernate/JPA](https://www.baeldung.com/hibernate-identifiers)
- [Hibernate Interceptors](https://www.baeldung.com/hibernate-interceptor)
- [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle)
- [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy)
@ -12,4 +12,4 @@ This module contains articles about Hibernate 5. Let's not add more articles her
- [Hibernate 5 Bootstrapping API](https://www.baeldung.com/hibernate-5-bootstrapping-api)
- [Guide to the Hibernate EntityManager](https://www.baeldung.com/hibernate-entitymanager)
- [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0)
- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object)
- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object)

View File

@ -33,7 +33,7 @@
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${redisson.version}</version>
<version>${jedis.version}</version>
</dependency>
<dependency>
<groupId>com.github.kstyrc</groupId>
@ -48,12 +48,19 @@
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</dependency>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport-native-epoll</artifactId>
<version>${epoll.version}</version>
</dependency>
</dependencies>
<properties>
<embedded-redis.version>0.6</embedded-redis.version>
<redisson.version>3.3.0</redisson.version>
<redisson.version>3.13.1</redisson.version>
<jedis.version>3.3.0</jedis.version>
<epoll.version>4.1.50.Final</epoll.version>
</properties>
</project>

View File

@ -1,9 +1,11 @@
package com.baeldung;
import java.io.Serializable;
/**
* Created by johnson on 3/9/17.
*/
public class CustomMessage {
public class CustomMessage implements Serializable {
private String message;
public CustomMessage() {

View File

@ -1,6 +1,8 @@
package com.baeldung;
public class Ledger {
import java.io.Serializable;
public class Ledger implements Serializable {
public Ledger() {
}

View File

@ -1,13 +1,10 @@
{
"singleServerConfig": {
"idleConnectionTimeout": 10000,
"pingTimeout": 1000,
"connectTimeout": 10000,
"timeout": 3000,
"retryAttempts": 3,
"retryInterval": 1500,
"reconnectionTimeout": 3000,
"failedAttempts": 3,
"password": null,
"subscriptionsPerConnection": 5,
"clientName": null,
@ -17,11 +14,9 @@
"connectionMinimumIdleSize": 10,
"connectionPoolSize": 64,
"database": 0,
"dnsMonitoring": false,
"dnsMonitoringInterval": 5000
},
"threads": 0,
"nettyThreads": 0,
"codec": null,
"useLinuxNativeEpoll": false
"codec": null
}

View File

@ -1,12 +1,9 @@
singleServerConfig:
idleConnectionTimeout: 10000
pingTimeout: 1000
connectTimeout: 10000
timeout: 3000
retryAttempts: 3
retryInterval: 1500
reconnectionTimeout: 3000
failedAttempts: 3
password: null
subscriptionsPerConnection: 5
clientName: null
@ -16,9 +13,7 @@ singleServerConfig:
connectionMinimumIdleSize: 10
connectionPoolSize: 64
database: 0
dnsMonitoring: false
dnsMonitoringInterval: 5000
threads: 0
nettyThreads: 0
codec: !<org.redisson.codec.JsonJacksonCodec> {}
useLinuxNativeEpoll: false
codec: !<org.redisson.codec.JsonJacksonCodec> {}

View File

@ -48,7 +48,7 @@ public class RedissonConfigurationIntegrationTest {
public void givenJavaConfig_thenRedissonConnectToRedis() {
Config config = new Config();
config.useSingleServer()
.setAddress(String.format("127.0.0.1:%s", port));
.setAddress(String.format("redis://127.0.0.1:%s", port));
client = Redisson.create(config);

View File

@ -7,6 +7,7 @@ import org.redisson.Redisson;
import org.redisson.RedissonMultiLock;
import org.redisson.api.*;
import org.redisson.client.RedisClient;
import org.redisson.client.RedisClientConfig;
import org.redisson.client.RedisConnection;
import org.redisson.client.codec.StringCodec;
import org.redisson.client.protocol.RedisCommands;
@ -103,10 +104,10 @@ public class RedissonIntegrationTest {
public void givenTopicSubscribedToAChannel_thenReceiveMessageFromChannel() throws ExecutionException, InterruptedException {
CompletableFuture<String> future = new CompletableFuture<>();
RTopic<CustomMessage> subscribeTopic = client.getTopic("baeldung");
subscribeTopic.addListener((channel, customMessage) -> future.complete(customMessage.getMessage()));
RTopic subscribeTopic = client.getTopic("baeldung");
subscribeTopic.addListener(CustomMessage.class, (channel, customMessage) -> future.complete(customMessage.getMessage()));
RTopic<CustomMessage> publishTopic = client.getTopic("baeldung");
RTopic publishTopic = client.getTopic("baeldung");
long clientsReceivedMessage
= publishTopic.publish(new CustomMessage("This is a message"));
@ -203,10 +204,10 @@ public class RedissonIntegrationTest {
batch.getMap("ledgerMap").fastPutAsync("1", "2");
batch.getMap("ledgerMap").putAsync("2", "5");
List<?> result = batch.execute();
BatchResult<?> batchResult = batch.execute();
RMap<String, String> map = client.getMap("ledgerMap");
assertTrue(result.size() > 0 && map.get("1").equals("2"));
assertTrue(batchResult.getResponses().size() > 0 && map.get("1").equals("2"));
}
@Test
@ -220,7 +221,9 @@ public class RedissonIntegrationTest {
@Test
public void givenLowLevelRedisCommands_thenExecuteLowLevelCommandsOnRedis(){
RedisClient client = new RedisClient("localhost", 6379);
RedisClientConfig redisClientConfig = new RedisClientConfig();
redisClientConfig.setAddress("localhost", 6379);
RedisClient client = RedisClient.create(redisClientConfig);
RedisConnection conn = client.connect();
conn.sync(StringCodec.INSTANCE, RedisCommands.SET, "test", 0);

View File

@ -6,7 +6,7 @@
- [Guide to Elasticsearch in Java](https://www.baeldung.com/elasticsearch-java)
- [Geospatial Support in ElasticSearch](https://www.baeldung.com/elasticsearch-geo-spatial)
- [A Simple Tagging Implementation with Elasticsearch](https://www.baeldung.com/elasticsearch-tagging)
- [Introduction to Spring Data Elasticsearch test 2](https://www.baeldung.com/spring-data-elasticsearch-test-2)
- [Introduction to Spring Data Elasticsearch (evaluation)](https://www.baeldung.com/spring-data-elasticsearch-test-2)
### Build the Project with Tests Running
```

View File

@ -1,5 +1,9 @@
logging.level.root=INFO
management.endpoints.web.exposure.include.=*
management.endpoints.web.exposure.include=*
info.app.name=Spring Boot 2 actuator Application
management.endpoint.health.group.custom.include=diskSpace,ping
management.endpoint.health.group.custom.show-components=always
management.endpoint.health.group.custom.show-details=always
management.endpoint.health.group.custom.status.http-mapping.up=207

View File

@ -0,0 +1,84 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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.customerservice</groupId>
<artifactId>customer-service</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>customer-service</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-2</relativePath>
</parent>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baeldung.orderservice</groupId>
<artifactId>order-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>exec</classifier>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.customerservice;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Customer {
private int id;
private String firstName;
private String lastName;
}

View File

@ -0,0 +1,25 @@
package com.baeldung.customerservice;
import com.baeldung.orderservice.client.OrderClient;
import com.baeldung.orderservice.client.OrderClientImpl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
/**
* Spring Boot application starter class
*/
@SpringBootApplication
public class CustomerApplication {
public static void main(String[] args) {
SpringApplication.run(CustomerApplication.class, args);
}
@Bean
public OrderClient getOrderClient() {
return new OrderClientImpl(new RestTemplateBuilder());
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.customerservice;
import com.baeldung.orderservice.client.OrderClient;
import com.baeldung.orderservice.client.OrderDTO;
import com.baeldung.orderservice.client.OrderResponse;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@RestController
public class CustomerService {
@Autowired
private OrderClient orderClient;
private List<Customer> customers = Arrays.asList(
new Customer(1, "John", "Smith"),
new Customer(2, "Deny", "Dominic"));
@GetMapping
public List<Customer> getAllCustomers() {
return customers;
}
@GetMapping("/{id}")
public Customer getCustomerById(@PathVariable int id) {
return customers.stream()
.filter(customer -> customer.getId() == id)
.findFirst()
.orElseThrow(IllegalArgumentException::new);
}
@PostMapping(value = "/order")
public String sendOrder(@RequestBody Map<String, Object> body) {
OrderDTO dto = new OrderDTO();
dto.setCustomerId((Integer) body.get("customerId"));
dto.setItemId((String) body.get("itemId"));
OrderResponse response = orderClient.order(dto);
return response.getStatus();
}
}

View File

@ -0,0 +1,4 @@
#Spring Boot server configuration
server.servlet.context-path=/customer-service
server.port=8001

View File

@ -0,0 +1,2 @@
local.server.port=8001
server.servlet.context-path=/customer-service

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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.orderservice</groupId>
<artifactId>order-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>order-client</name>
<description>Order service client module</description>
<url>http://projects.spring.io/spring-boot/</url>
<parent>
<groupId>com.baeldung.orderservice</groupId>
<artifactId>order-service</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
</project>

View File

@ -0,0 +1,6 @@
package com.baeldung.orderservice.client;
public interface OrderClient {
OrderResponse order(OrderDTO orderDTO);
}

View File

@ -0,0 +1,35 @@
package com.baeldung.orderservice.client;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class OrderClientImpl implements OrderClient {
private RestTemplate restTemplate;
public OrderClientImpl(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}
@Override
public OrderResponse order(OrderDTO orderDTO) {
String serviceUrl = "http://localhost:8002/order-service";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<OrderDTO> request = new HttpEntity<>(orderDTO, headers);
OrderResponse orderResponse = restTemplate.postForObject(serviceUrl + "/create", request, OrderResponse.class);
return orderResponse;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.orderservice.client;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class OrderDTO {
private int customerId;
private String itemId;
}

View File

@ -0,0 +1,15 @@
package com.baeldung.orderservice.client;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class OrderResponse {
private int orderId;
private String productId;
private String status;
}

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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.orderservice</groupId>
<artifactId>order-server</artifactId>
<version>1.0.0-SNAPSHOT</version>
<parent>
<artifactId>order-service</artifactId>
<groupId>com.baeldung.orderservice</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.baeldung.orderservice</groupId>
<artifactId>order-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,18 @@
package com.baeldung.orderservice;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Order {
private Integer id;
private Integer customerId;
private String itemId;
private String date;
}

View File

@ -0,0 +1,17 @@
package com.baeldung.orderservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
/**
* Spring Boot application starter class
*/
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.orderservice;
import com.baeldung.orderservice.client.OrderDTO;
import com.baeldung.orderservice.client.OrderResponse;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class OrderService {
private List<Order> orders = Arrays.asList(
new Order(1, 1, "A101", "2020/02/14"),
new Order(2, 1, "A101", "2020/02/14"),
new Order(3, 2, "A150", "2020/02/17"));
@GetMapping
public List<Order> getAllOrders() {
return orders;
}
@GetMapping("/{id}")
public List<Order> getOrdersByCustomer(@PathVariable int id) {
return orders.stream()
.filter(order -> order.getCustomerId() == id).collect(Collectors.toList());
}
@PostMapping("/create")
public OrderResponse createOrder(@RequestBody OrderDTO request) {
int lastIndex = orders.size();
Order order = new Order();
order.setId(lastIndex + 1);
order.setCustomerId(request.getCustomerId());
order.setItemId(request.getItemId());
String date = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
order.setDate(date);
return new OrderResponse(order.getId(), order.getItemId(), "CREATED");
}
}

View File

@ -0,0 +1,4 @@
#Spring Boot server configuration
server.servlet.context-path=/order-service
server.port=8002

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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.orderservice</groupId>
<artifactId>order-service</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>order-service</name>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-2</relativePath>
</parent>
<modules>
<module>order-client</module>
<module>order-server</module>
</modules>
<properties>
<java.version>1.8</java.version>
<commons-lang.version>2.6</commons-lang.version>
<structure-maven.version>0.0.2</structure-maven.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<orderservice.mainclass>com.baeldung.orderservice.OrderApplication</orderservice.mainclass>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons-lang.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.qunix</groupId>
<artifactId>structure-maven-plugin</artifactId>
<version>${structure-maven.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>${orderservice.mainclass}</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>exec</classifier>
</configuration>
</execution>
<execution>
<id>start-application</id>
<configuration>
<mainClass>com.baeldung.orderservice.OrderApplication</mainClass>
<classesDirectory>../order-server/target/classes</classesDirectory>
</configuration>
<goals>
<goal>start</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.qunix</groupId>
<artifactId>structure-maven-plugin</artifactId>
<version>${structure-maven.version}</version>
<inherited>false</inherited>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>modules</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -20,6 +20,9 @@
<module>svc-book</module>
<module>svc-rating</module>
<module>zipkin</module>
<module>customer-service</module>
<module>order-service</module>
<module>shared-dto</module>
</modules>
</project>

View File

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>shared-dto</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>shared-dto</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-2</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<structure-maven.version>0.0.2</structure-maven.version>
</properties>
<dependencies>
<dependency>
<groupId>org.qunix</groupId>
<artifactId>structure-maven-plugin</artifactId>
<version>${structure-maven.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.qunix</groupId>
<artifactId>structure-maven-plugin</artifactId>
<version>${structure-maven.version}</version>
<inherited>false</inherited>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>files</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -0,0 +1,16 @@
package com.baeldung.deliverydto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CustomerDTO {
private String firstName;
private String lastName;
private String homeAddress;
private String contactNumber;
// constructor, getters, setters
}

View File

@ -0,0 +1,15 @@
package com.baeldung.shared;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CustomerDTO {
private String firstName;
private String lastName;
private String cardNumber;
// constructor, getters, setters
}

View File

@ -0,0 +1,16 @@
package com.baeldung.shared;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class OrderDTO {
private int customerId;
private String itemId;
}

View File

@ -7,7 +7,6 @@ This module contains articles about Spring MVC
- [Template Engines for Spring](https://www.baeldung.com/spring-template-engines)
- [Spring 5 and Servlet 4 The PushBuilder](https://www.baeldung.com/spring-5-push)
- [Servlet Redirect vs Forward](https://www.baeldung.com/servlet-redirect-forward)
- [Apache Tiles Integration with Spring MVC](https://www.baeldung.com/spring-mvc-apache-tiles)
- [Guide to Spring Email](https://www.baeldung.com/spring-email)
- [Using ThymeLeaf and FreeMarker Emails Templates with Spring](https://www.baeldung.com/spring-email-templates)
- [Request Method Not Supported (405) in Spring](https://www.baeldung.com/spring-request-method-not-supported-405)

View File

@ -99,12 +99,6 @@
<version>${jade.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>${apache-tiles.version}</version>
</dependency>
<!--Testing -->
<dependency>
<groupId>org.springframework</groupId>
@ -178,7 +172,6 @@
<xstream.version>1.4.9</xstream.version>
<scribejava.version>5.1.0</scribejava.version>
<json.version>20180130</json.version>
<apache-tiles.version>3.0.8</apache-tiles.version>
<javax.mail.version>1.6.1</javax.mail.version>
</properties>

View File

@ -23,8 +23,6 @@ public class WebInitializer implements WebApplicationInitializer {
ctx.register(EmailConfiguration.class);
// ctx.setServletContext(container);
//ctx.register(TilesApplicationConfiguration.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(ctx));

View File

@ -20,7 +20,7 @@ import com.baeldung.matrix.config.MatrixWebConfig;
@WebAppConfiguration
@ContextConfiguration(classes = { MatrixWebConfig.class, MultipartPostRequestController.class })
@RunWith(SpringJUnit4ClassRunner.class)
public class MultipartPostRequestUnitTest {
public class MultipartPostRequestControllerUnitTest {
@Autowired
private WebApplicationContext webApplicationContext;

View File

@ -1,3 +1,4 @@
### Relevant Articles:
- [Spring MVC Themes](https://www.baeldung.com/spring-mvc-themes)
- [Apache Tiles Integration with Spring MVC](https://www.baeldung.com/spring-mvc-apache-tiles)

View File

@ -74,6 +74,12 @@
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>${apache-tiles.version}</version>
</dependency>
</dependencies>
@ -115,6 +121,7 @@
<hsqldb.version>2.5.0</hsqldb.version>
<hibernate.version>5.4.9.Final</hibernate.version>
<deploy-path>enter-location-of-server</deploy-path>
<apache-tiles.version>3.0.8</apache-tiles.version>
</properties>
</project>

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.configuration;
package com.baeldung.themes.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@ -12,7 +12,7 @@ import org.springframework.web.servlet.view.tiles3.TilesViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.baeldung.spring.controller.tiles")
@ComponentScan(basePackages = "com.baeldung.themes")
public class TilesApplicationConfiguration implements WebMvcConfigurer {
/**

View File

@ -14,6 +14,7 @@ public class WebInitializer implements WebApplicationInitializer {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(DataSourceConfig.class);
context.register(ThemeMVCConfig.class);
//context.register(TilesApplicationConfiguration.class);
servletContext.addListener(new ContextLoaderListener(context));

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.controller.tiles;
package com.baeldung.themes.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;

View File

@ -0,0 +1,12 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
<h2>Welcome to Apache Tiles integration with Spring MVC</h2>
</body>
</html>

View File

@ -0,0 +1,12 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC</title>
</head>
<body>
<h2>Spring MVC configured to work with Apache Tiles</h2>
</body>
</html>

View File

@ -0,0 +1,36 @@
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap;
flex-flow: row wrap;
text-align: center;
}
.flex-container > * {
padding: 15px;
-webkit-flex: 1 100%;
flex: 1 100%;
}
.article {
text-align: left;
}
header {background: black;color:white;}
footer {background: #aaa;color:white;}
.nav {background:#eee;}
.nav ul {
list-style-type: none;
padding: 0;
}
.nav ul a {
text-decoration: none;
}
@media all and (min-width: 768px) {
.nav {text-align:left;-webkit-flex: 1 auto;flex:1 auto;-webkit-order:1;order:1;}
.article {-webkit-flex:5 0px;flex:5 0px;-webkit-order:2;order:2;}
footer {-webkit-order:3;order:3;}
}

View File

@ -1,4 +1,4 @@
## Relevant articles:
- [Spring Security Kerberos Integration](https://www.baeldung.com/spring-security-kerberos-integration)
- [Spring Security Kerberos Integration With MiniKdc](https://www.baeldung.com/spring-security-kerberos-integration)
- [Introduction to SPNEGO/Kerberos Authentication in Spring](https://www.baeldung.com/spring-security-kerberos)

View File

@ -83,8 +83,4 @@
</plugins>
</build>
<properties>
<spring-boot.version>2.1.2.RELEASE</spring-boot.version>
</properties>
</project>