Merge remote-tracking branch 'upstream/master'
This commit is contained in:
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.algorithms.enumstatemachine;
|
||||
|
||||
public enum LeaveRequestState {
|
||||
|
||||
Submitted {
|
||||
@Override
|
||||
public LeaveRequestState nextState() {
|
||||
System.out.println("Starting the Leave Request and sending to Team Leader for approval.");
|
||||
return Escalated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String responsiblePerson() {
|
||||
return "Employee";
|
||||
}
|
||||
},
|
||||
Escalated {
|
||||
@Override
|
||||
public LeaveRequestState nextState() {
|
||||
System.out.println("Reviewing the Leave Request and escalating to Department Manager.");
|
||||
return Approved;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String responsiblePerson() {
|
||||
return "Team Leader";
|
||||
}
|
||||
},
|
||||
Approved {
|
||||
@Override
|
||||
public LeaveRequestState nextState() {
|
||||
System.out.println("Approving the Leave Request.");
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String responsiblePerson() {
|
||||
return "Department Manager";
|
||||
}
|
||||
};
|
||||
|
||||
public abstract String responsiblePerson();
|
||||
|
||||
public abstract LeaveRequestState nextState();
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.algorithms.enumstatemachine;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LeaveRequestStateUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() {
|
||||
LeaveRequestState state = LeaveRequestState.Escalated;
|
||||
|
||||
assertEquals(state.responsiblePerson(), "Team Leader");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() {
|
||||
LeaveRequestState state = LeaveRequestState.Approved;
|
||||
|
||||
assertEquals(state.responsiblePerson(), "Department Manager");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() {
|
||||
LeaveRequestState state = LeaveRequestState.Submitted;
|
||||
|
||||
state = state.nextState();
|
||||
assertEquals(state, LeaveRequestState.Escalated);
|
||||
|
||||
state = state.nextState();
|
||||
assertEquals(state, LeaveRequestState.Approved);
|
||||
|
||||
state = state.nextState();
|
||||
assertEquals(state, LeaveRequestState.Approved);
|
||||
}
|
||||
}
|
||||
@@ -26,3 +26,4 @@
|
||||
- [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)
|
||||
|
||||
@@ -14,4 +14,5 @@
|
||||
- [ExecutorService - Waiting for Threads to Finish](http://www.baeldung.com/java-executor-wait-for-threads)
|
||||
- [wait and notify() Methods in Java](http://www.baeldung.com/java-wait-notify)
|
||||
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
|
||||
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
|
||||
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
|
||||
- [What is Thread-Safety and How to Achieve it](https://www.baeldung.com/java-thread-safety)
|
||||
|
||||
@@ -62,7 +62,7 @@ public class NewDirectoryUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUnexistingNestedDirectories_whenMkdirs_thenTrue() {
|
||||
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
|
||||
File newDirectory = new File(System.getProperty("java.io.tmpdir") + File.separator + "new_directory");
|
||||
File nestedDirectory = new File(newDirectory, "nested_directory");
|
||||
assertFalse(newDirectory.exists());
|
||||
assertFalse(nestedDirectory.exists());
|
||||
|
||||
+30
-34
@@ -1,60 +1,56 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
|
||||
import com.google.common.io.ByteSource;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static java.nio.channels.Channels.newChannel;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
class InputStreamToByteBufferUnitTest {
|
||||
public class InputStreamToByteBufferUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUsingCoreClasses_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
|
||||
File inputFile = getFile();
|
||||
ByteBuffer bufferByte = ByteBuffer.allocate((int) inputFile.length());
|
||||
FileInputStream in = new FileInputStream(inputFile);
|
||||
in.getChannel().read(bufferByte);
|
||||
public void givenUsingCoreClasses_whenByteArrayInputStreamToAByteBuffer_thenLengthMustMatch() throws IOException {
|
||||
byte[] input = new byte[] { 0, 1, 2 };
|
||||
InputStream initialStream = new ByteArrayInputStream(input);
|
||||
ByteBuffer byteBuffer = ByteBuffer.allocate(3);
|
||||
while (initialStream.available() > 0) {
|
||||
byteBuffer.put((byte) initialStream.read());
|
||||
}
|
||||
|
||||
assertEquals(bufferByte.position(), inputFile.length());
|
||||
assertEquals(byteBuffer.position(), input.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIo_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
|
||||
File inputFile = getFile();
|
||||
ByteBuffer bufferByte = ByteBuffer.allocateDirect((int) inputFile.length());
|
||||
ReadableByteChannel readableByteChannel = new FileInputStream(inputFile).getChannel();
|
||||
IOUtils.readFully(readableByteChannel, bufferByte);
|
||||
|
||||
assertEquals(bufferByte.position(), inputFile.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
|
||||
File inputFile = getFile();
|
||||
FileInputStream in = new FileInputStream(inputFile);
|
||||
byte[] targetArray = ByteStreams.toByteArray(in);
|
||||
public void givenUsingGuava__whenByteArrayInputStreamToAByteBuffer_thenLengthMustMatch() throws IOException {
|
||||
InputStream initialStream = ByteSource
|
||||
.wrap(new byte[] { 0, 1, 2 })
|
||||
.openStream();
|
||||
byte[] targetArray = ByteStreams.toByteArray(initialStream);
|
||||
ByteBuffer bufferByte = ByteBuffer.wrap(targetArray);
|
||||
bufferByte.rewind();
|
||||
while (bufferByte.hasRemaining()) {
|
||||
bufferByte.get();
|
||||
}
|
||||
|
||||
assertEquals(bufferByte.position(), inputFile.length());
|
||||
|
||||
assertEquals(bufferByte.position(), targetArray.length);
|
||||
}
|
||||
|
||||
private File getFile() {
|
||||
ClassLoader classLoader = new InputStreamToByteBufferUnitTest().getClass().getClassLoader();
|
||||
@Test
|
||||
public void givenUsingCommonsIo_whenByteArrayInputStreamToAByteBuffer_thenLengthMustMatch() throws IOException {
|
||||
byte[] input = new byte[] { 0, 1, 2 };
|
||||
InputStream initialStream = new ByteArrayInputStream(input);
|
||||
ByteBuffer byteBuffer = ByteBuffer.allocate(3);
|
||||
ReadableByteChannel channel = newChannel(initialStream);
|
||||
IOUtils.readFully(channel, byteBuffer);
|
||||
|
||||
String fileName = "frontenac-2257154_960_720.jpg";
|
||||
|
||||
return new File(classLoader.getResource(fileName).getFile());
|
||||
assertEquals(byteBuffer.position(), input.length);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.forEach
|
||||
|
||||
|
||||
class Country(val name : String, val cities : List<City>)
|
||||
|
||||
class City(val name : String, val streets : List<String>)
|
||||
|
||||
class World {
|
||||
|
||||
private val streetsOfAmsterdam = listOf("Herengracht", "Prinsengracht")
|
||||
private val streetsOfBerlin = listOf("Unter den Linden","Tiergarten")
|
||||
private val streetsOfMaastricht = listOf("Grote Gracht", "Vrijthof")
|
||||
private val countries = listOf(
|
||||
Country("Netherlands", listOf(City("Maastricht", streetsOfMaastricht),
|
||||
City("Amsterdam", streetsOfAmsterdam))),
|
||||
Country("Germany", listOf(City("Berlin", streetsOfBerlin))))
|
||||
|
||||
fun allCountriesIt() {
|
||||
countries.forEach { println(it.name) }
|
||||
}
|
||||
|
||||
fun allCountriesItExplicit() {
|
||||
countries.forEach { it -> println(it.name) }
|
||||
}
|
||||
|
||||
//here we cannot refer to 'it' anymore inside the forEach
|
||||
fun allCountriesExplicit() {
|
||||
countries.forEach { c -> println(c.name) }
|
||||
}
|
||||
|
||||
fun allNested() {
|
||||
countries.forEach {
|
||||
println(it.name)
|
||||
it.cities.forEach {
|
||||
println(" ${it.name}")
|
||||
it.streets.forEach { println(" $it") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun allTable() {
|
||||
countries.forEach { c ->
|
||||
c.cities.forEach { p ->
|
||||
p.streets.forEach { println("${c.name} ${p.name} $it") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun main(args : Array<String>) {
|
||||
|
||||
val world = World()
|
||||
|
||||
world.allCountriesExplicit()
|
||||
|
||||
world.allNested()
|
||||
|
||||
world.allTable()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.voidtypes
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class VoidTypesUnitTest {
|
||||
|
||||
fun returnTypeAsVoid(): Void? {
|
||||
println("Function can have Void as return type")
|
||||
return null
|
||||
}
|
||||
|
||||
fun unitReturnTypeForNonMeaningfulReturns(): Unit {
|
||||
println("No meaningful return")
|
||||
}
|
||||
|
||||
fun unitReturnTypeIsImplicit() {
|
||||
println("Unit Return type is implicit")
|
||||
}
|
||||
|
||||
fun alwaysThrowException(): Nothing {
|
||||
throw IllegalArgumentException()
|
||||
}
|
||||
|
||||
fun invokeANothingOnlyFunction() {
|
||||
alwaysThrowException()
|
||||
|
||||
var name = "Tom"
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenJavaVoidFunction_thenMappedToKotlinUnit() {
|
||||
assertTrue(System.out.println() is Unit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenVoidReturnType_thenReturnsNullOnly() {
|
||||
assertNull(returnTypeAsVoid())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenUnitReturnTypeDeclared_thenReturnsOfTypeUnit() {
|
||||
assertTrue(unitReturnTypeForNonMeaningfulReturns() is Unit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenUnitReturnTypeNotDeclared_thenReturnsOfTypeUnit() {
|
||||
assertTrue(unitReturnTypeIsImplicit() is Unit)
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ public class Customer {
|
||||
return this.points > points;
|
||||
}
|
||||
|
||||
public boolean hasOverThousandPoints() {
|
||||
public boolean hasOverHundredPoints() {
|
||||
return this.points > 100;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.stream.sum;
|
||||
|
||||
public class ArithmeticUtils {
|
||||
|
||||
public static int add(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.stream.sum;
|
||||
|
||||
public class Item {
|
||||
|
||||
private int id;
|
||||
private Integer price;
|
||||
|
||||
public Item(int id, Integer price) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
// Standard getters and setters
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Integer getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(Integer price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.stream.sum;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StreamSumCalculator {
|
||||
|
||||
public static Integer getSumUsingCustomizedAccumulator(List<Integer> integers) {
|
||||
return integers.stream()
|
||||
.reduce(0, ArithmeticUtils::add);
|
||||
|
||||
}
|
||||
|
||||
public static Integer getSumUsingJavaAccumulator(List<Integer> integers) {
|
||||
return integers.stream()
|
||||
.reduce(0, Integer::sum);
|
||||
|
||||
}
|
||||
|
||||
public static Integer getSumUsingReduce(List<Integer> integers) {
|
||||
return integers.stream()
|
||||
.reduce(0, (a, b) -> a + b);
|
||||
|
||||
}
|
||||
|
||||
public static Integer getSumUsingCollect(List<Integer> integers) {
|
||||
|
||||
return integers.stream()
|
||||
.collect(Collectors.summingInt(Integer::intValue));
|
||||
|
||||
}
|
||||
|
||||
public static Integer getSumUsingSum(List<Integer> integers) {
|
||||
|
||||
return integers.stream()
|
||||
.mapToInt(Integer::intValue)
|
||||
.sum();
|
||||
}
|
||||
|
||||
public static Integer getSumOfMapValues(Map<Object, Integer> map) {
|
||||
|
||||
return map.values()
|
||||
.stream()
|
||||
.mapToInt(Integer::valueOf)
|
||||
.sum();
|
||||
}
|
||||
|
||||
public static Integer getSumIntegersFromString(String str) {
|
||||
|
||||
Integer sum = Arrays.stream(str.split(" "))
|
||||
.filter((s) -> s.matches("\\d+"))
|
||||
.mapToInt(Integer::valueOf)
|
||||
.sum();
|
||||
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.stream.sum;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StreamSumCalculatorWithObject {
|
||||
|
||||
public static Integer getSumUsingCustomizedAccumulator(List<Item> items) {
|
||||
return items.stream()
|
||||
.map(x -> x.getPrice())
|
||||
.reduce(0, ArithmeticUtils::add);
|
||||
}
|
||||
|
||||
public static Integer getSumUsingJavaAccumulator(List<Item> items) {
|
||||
return items.stream()
|
||||
.map(x -> x.getPrice())
|
||||
.reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
public static Integer getSumUsingReduce(List<Item> items) {
|
||||
return items.stream()
|
||||
.map(item -> item.getPrice())
|
||||
.reduce(0, (a, b) -> a + b);
|
||||
}
|
||||
|
||||
public static Integer getSumUsingCollect(List<Item> items) {
|
||||
return items.stream()
|
||||
.map(x -> x.getPrice())
|
||||
.collect(Collectors.summingInt(Integer::intValue));
|
||||
}
|
||||
|
||||
public static Integer getSumUsingSum(List<Item> items) {
|
||||
return items.stream()
|
||||
.mapToInt(x -> x.getPrice())
|
||||
.sum();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.stream.filter;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StreamCountUnitTest {
|
||||
|
||||
private List<Customer> customers;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
|
||||
Customer sarah = new Customer("Sarah M.", 200);
|
||||
Customer charles = new Customer("Charles B.", 150);
|
||||
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
|
||||
customers = Arrays.asList(john, sarah, charles, mary);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenCount_thenGetListSize() {
|
||||
long count = customers
|
||||
.stream()
|
||||
.count();
|
||||
|
||||
assertThat(count).isEqualTo(4L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenFilterByPointsOver100AndCount_thenGetTwo() {
|
||||
long countBigCustomers = customers
|
||||
.stream()
|
||||
.filter(c -> c.getPoints() > 100)
|
||||
.count();
|
||||
|
||||
assertThat(countBigCustomers).isEqualTo(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenFilterByPointsAndNameAndCount_thenGetOne() {
|
||||
long count = customers
|
||||
.stream()
|
||||
.filter(c -> c.getPoints() > 10 && c.getName().startsWith("Charles"))
|
||||
.count();
|
||||
|
||||
assertThat(count).isEqualTo(1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenNoneMatchesFilterAndCount_thenGetZero() {
|
||||
long count = customers
|
||||
.stream()
|
||||
.filter(c -> c.getPoints() > 500)
|
||||
.count();
|
||||
|
||||
assertThat(count).isEqualTo(0L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenUsingMethodOverHundredPointsAndCount_thenGetTwo() {
|
||||
long count = customers
|
||||
.stream()
|
||||
.filter(Customer::hasOverHundredPoints)
|
||||
.count();
|
||||
|
||||
assertThat(count).isEqualTo(2L);
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,7 @@ public class StreamFilterUnitTest {
|
||||
|
||||
List<Customer> customersWithMoreThan100Points = customers
|
||||
.stream()
|
||||
.filter(Customer::hasOverThousandPoints)
|
||||
.filter(Customer::hasOverHundredPoints)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(customersWithMoreThan100Points).hasSize(2);
|
||||
@@ -81,7 +81,7 @@ public class StreamFilterUnitTest {
|
||||
.flatMap(c -> c
|
||||
.map(Stream::of)
|
||||
.orElseGet(Stream::empty))
|
||||
.filter(Customer::hasOverThousandPoints)
|
||||
.filter(Customer::hasOverHundredPoints)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(customersWithMoreThan100Points).hasSize(2);
|
||||
@@ -156,4 +156,5 @@ public class StreamFilterUnitTest {
|
||||
})
|
||||
.collect(Collectors.toList())).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.baeldung.stream.sum;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class StreamSumUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenListOfIntegersWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() {
|
||||
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Integer sum = StreamSumCalculator.getSumUsingCustomizedAccumulator(integers);
|
||||
assertEquals(15, sum.intValue());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfIntegersWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() {
|
||||
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Integer sum = StreamSumCalculator.getSumUsingJavaAccumulator(integers);
|
||||
assertEquals(15, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfIntegersWhenSummingUsingReduceThenCorrectValueReturned() {
|
||||
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Integer sum = StreamSumCalculator.getSumUsingReduce(integers);
|
||||
assertEquals(15, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfIntegersWhenSummingUsingCollectThenCorrectValueReturned() {
|
||||
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Integer sum = StreamSumCalculator.getSumUsingCollect(integers);
|
||||
assertEquals(15, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfIntegersWhenSummingUsingSumThenCorrectValueReturned() {
|
||||
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Integer sum = StreamSumCalculator.getSumUsingSum(integers);
|
||||
assertEquals(15, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfItemsWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() {
|
||||
Item item1 = new Item(1, 10);
|
||||
Item item2 = new Item(2, 15);
|
||||
Item item3 = new Item(3, 25);
|
||||
Item item4 = new Item(4, 40);
|
||||
|
||||
List<Item> items = Arrays.asList(item1, item2, item3, item4);
|
||||
|
||||
Integer sum = StreamSumCalculatorWithObject.getSumUsingCustomizedAccumulator(items);
|
||||
assertEquals(90, sum.intValue());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfItemsWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() {
|
||||
Item item1 = new Item(1, 10);
|
||||
Item item2 = new Item(2, 15);
|
||||
Item item3 = new Item(3, 25);
|
||||
Item item4 = new Item(4, 40);
|
||||
|
||||
List<Item> items = Arrays.asList(item1, item2, item3, item4);
|
||||
|
||||
Integer sum = StreamSumCalculatorWithObject.getSumUsingJavaAccumulator(items);
|
||||
assertEquals(90, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfItemsWhenSummingUsingReduceThenCorrectValueReturned() {
|
||||
Item item1 = new Item(1, 10);
|
||||
Item item2 = new Item(2, 15);
|
||||
Item item3 = new Item(3, 25);
|
||||
Item item4 = new Item(4, 40);
|
||||
|
||||
List<Item> items = Arrays.asList(item1, item2, item3, item4);
|
||||
|
||||
Integer sum = StreamSumCalculatorWithObject.getSumUsingReduce(items);
|
||||
assertEquals(90, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfItemsWhenSummingUsingCollectThenCorrectValueReturned() {
|
||||
Item item1 = new Item(1, 10);
|
||||
Item item2 = new Item(2, 15);
|
||||
Item item3 = new Item(3, 25);
|
||||
Item item4 = new Item(4, 40);
|
||||
|
||||
List<Item> items = Arrays.asList(item1, item2, item3, item4);
|
||||
|
||||
Integer sum = StreamSumCalculatorWithObject.getSumUsingCollect(items);
|
||||
assertEquals(90, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfItemsWhenSummingUsingSumThenCorrectValueReturned() {
|
||||
Item item1 = new Item(1, 10);
|
||||
Item item2 = new Item(2, 15);
|
||||
Item item3 = new Item(3, 25);
|
||||
Item item4 = new Item(4, 40);
|
||||
|
||||
List<Item> items = Arrays.asList(item1, item2, item3, item4);
|
||||
|
||||
Integer sum = StreamSumCalculatorWithObject.getSumUsingSum(items);
|
||||
assertEquals(90, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapWhenSummingThenCorrectValueReturned() {
|
||||
Map<Object, Integer> map = new HashMap<Object, Integer>();
|
||||
map.put(1, 10);
|
||||
map.put(2, 15);
|
||||
map.put(3, 25);
|
||||
map.put(4, 40);
|
||||
|
||||
Integer sum = StreamSumCalculator.getSumOfMapValues(map);
|
||||
assertEquals(90, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringWhenSummingThenCorrectValueReturned() {
|
||||
String string = "Item1 10 Item2 25 Item3 30 Item4 45";
|
||||
|
||||
Integer sum = StreamSumCalculator.getSumIntegersFromString(string);
|
||||
assertEquals(110, sum.intValue());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -15,3 +15,4 @@
|
||||
- [Intro to Apache Storm](https://www.baeldung.com/apache-storm)
|
||||
- [Guide to Ebean ORM](https://www.baeldung.com/ebean-orm)
|
||||
- [Introduction to Kafka Connectors](https://www.baeldung.com/kafka-connectors-guide)
|
||||
- [Kafka Connect Example with MQTT and MongoDB](https://www.baeldung.com/kafka-connect-mqtt-mongodb)
|
||||
|
||||
@@ -1 +1,5 @@
|
||||
log4j.rootLogger=INFO, stdout
|
||||
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.stdout.Target=System.out
|
||||
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
|
||||
@@ -675,6 +675,30 @@
|
||||
<version>${mockftpserver.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack</groupId>
|
||||
<artifactId>smack-tcp</artifactId>
|
||||
<version>${smack.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack</groupId>
|
||||
<artifactId>smack-im</artifactId>
|
||||
<version>${smack.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack</groupId>
|
||||
<artifactId>smack-extensions</artifactId>
|
||||
<version>${smack.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack</groupId>
|
||||
<artifactId>smack-java7</artifactId>
|
||||
<version>${smack.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
@@ -896,6 +920,7 @@
|
||||
<derive4j.version>1.1.0</derive4j.version>
|
||||
<mockftpserver.version>2.7.1</mockftpserver.version>
|
||||
<commons-net.version>3.6</commons-net.version>
|
||||
<smack.version>4.3.1</smack.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.smack;
|
||||
|
||||
import org.jivesoftware.smack.AbstractXMPPConnection;
|
||||
import org.jivesoftware.smack.chat2.Chat;
|
||||
import org.jivesoftware.smack.chat2.ChatManager;
|
||||
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
|
||||
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
|
||||
import org.jxmpp.jid.impl.JidCreate;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class StanzaThread implements Runnable {
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(StanzaThread.class);
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
XMPPTCPConnectionConfiguration config = null;
|
||||
try {
|
||||
config = XMPPTCPConnectionConfiguration.builder()
|
||||
.setUsernameAndPassword("baeldung2","baeldung2")
|
||||
.setXmppDomain("jabb3r.org")
|
||||
.setHost("jabb3r.org")
|
||||
.build();
|
||||
|
||||
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
|
||||
connection.connect();
|
||||
connection.login();
|
||||
|
||||
ChatManager chatManager = ChatManager.getInstanceFor(connection);
|
||||
|
||||
Chat chat = chatManager.chatWith(JidCreate.from("[email protected]").asEntityBareJidOrThrow());
|
||||
|
||||
chat.send("Hello!");
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.smack;
|
||||
|
||||
import org.jivesoftware.smack.AbstractXMPPConnection;
|
||||
import org.jivesoftware.smack.SmackException;
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.chat2.ChatManager;
|
||||
import org.jivesoftware.smack.filter.StanzaTypeFilter;
|
||||
import org.jivesoftware.smack.packet.Message;
|
||||
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
|
||||
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.jxmpp.stringprep.XmppStringprepException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
public class SmackIntegrationTest {
|
||||
|
||||
private static AbstractXMPPConnection connection;
|
||||
private Logger logger = LoggerFactory.getLogger(SmackIntegrationTest.class);
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws IOException, InterruptedException, XMPPException, SmackException {
|
||||
|
||||
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
|
||||
.setUsernameAndPassword("baeldung","baeldung")
|
||||
.setXmppDomain("jabb3r.org")
|
||||
.setHost("jabb3r.org")
|
||||
.build();
|
||||
|
||||
XMPPTCPConnectionConfiguration config2 = XMPPTCPConnectionConfiguration.builder()
|
||||
.setUsernameAndPassword("baeldung2","baeldung2")
|
||||
.setXmppDomain("jabb3r.org")
|
||||
.setHost("jabb3r.org")
|
||||
.build();
|
||||
|
||||
connection = new XMPPTCPConnection(config);
|
||||
connection.connect();
|
||||
connection.login();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendMessageWithChat_thenReceiveMessage() throws XmppStringprepException, InterruptedException {
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
ChatManager chatManager = ChatManager.getInstanceFor(connection);
|
||||
final String[] expected = {null};
|
||||
|
||||
new StanzaThread().run();
|
||||
|
||||
chatManager.addIncomingListener((entityBareJid, message, chat) -> {
|
||||
logger.info("Message arrived: " + message.getBody());
|
||||
expected[0] = message.getBody();
|
||||
latch.countDown();
|
||||
});
|
||||
|
||||
latch.await();
|
||||
Assert.assertEquals("Hello!", expected[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendMessage_thenReceiveMessageWithFilter() throws XmppStringprepException, InterruptedException {
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
final String[] expected = {null};
|
||||
|
||||
new StanzaThread().run();
|
||||
|
||||
connection.addAsyncStanzaListener(stanza -> {
|
||||
if (stanza instanceof Message) {
|
||||
Message message = (Message) stanza;
|
||||
expected[0] = message.getBody();
|
||||
latch.countDown();
|
||||
}
|
||||
}, StanzaTypeFilter.MESSAGE);
|
||||
|
||||
latch.await();
|
||||
Assert.assertEquals("Hello!", expected[0]);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -76,11 +76,11 @@
|
||||
|
||||
<properties>
|
||||
<!-- lombok: https://projectlombok.org/changelog.html -->
|
||||
<lombok.version>1.16.18</lombok.version>
|
||||
<lombok.version>1.18.4</lombok.version>
|
||||
<!-- various -->
|
||||
<hibernate-jpa-2.1-api.version>1.0.0.Final</hibernate-jpa-2.1-api.version>
|
||||
<!-- delombok maven plugin -->
|
||||
<delombok-maven-plugin.version>1.16.10.0</delombok-maven-plugin.version>
|
||||
<delombok-maven-plugin.version>1.18.4.0</delombok-maven-plugin.version>
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
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>java-jpa</artifactId>
|
||||
<name>java-jpa</name>
|
||||
|
||||
<name>java-jpa</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
@@ -24,10 +24,34 @@
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--Compile time JPA API-->
|
||||
<dependency>
|
||||
<groupId>javax.persistence</groupId>
|
||||
<artifactId>javax.persistence-api</artifactId>
|
||||
<version>2.2</version>
|
||||
</dependency>
|
||||
|
||||
<!--Runtime JPA implementation-->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.persistence</groupId>
|
||||
<artifactId>eclipselink</artifactId>
|
||||
<version>${eclipselink.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>${postgres.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.3.1.Final</hibernate.version>
|
||||
<hibernate.version>5.4.0.Final</hibernate.version>
|
||||
<h2.version>1.4.197</h2.version>
|
||||
<eclipselink.version>2.7.4-RC1</eclipselink.version>
|
||||
<postgres.version>42.2.5</postgres.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.jpa.datetime;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
import java.sql.Date;
|
||||
import java.sql.Time;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.*;
|
||||
import java.util.Calendar;
|
||||
|
||||
public class DateTimeEntityRepository {
|
||||
private EntityManagerFactory emf = null;
|
||||
|
||||
public DateTimeEntityRepository() {
|
||||
emf = Persistence.createEntityManagerFactory("java8-datetime-postgresql");
|
||||
}
|
||||
|
||||
public JPA22DateTimeEntity find(Long id) {
|
||||
EntityManager entityManager = emf.createEntityManager();
|
||||
|
||||
JPA22DateTimeEntity dateTimeTypes = entityManager.find(JPA22DateTimeEntity.class, id);
|
||||
|
||||
entityManager.close();
|
||||
return dateTimeTypes;
|
||||
}
|
||||
|
||||
public void save(Long id) {
|
||||
JPA22DateTimeEntity dateTimeTypes = new JPA22DateTimeEntity();
|
||||
dateTimeTypes.setId(id);
|
||||
|
||||
//java.sql types: date/time
|
||||
dateTimeTypes.setSqlTime(Time.valueOf(LocalTime.now()));
|
||||
dateTimeTypes.setSqlDate(Date.valueOf(LocalDate.now()));
|
||||
dateTimeTypes.setSqlTimestamp(Timestamp.valueOf(LocalDateTime.now()));
|
||||
|
||||
//java.util types: date/calendar
|
||||
java.util.Date date = new java.util.Date();
|
||||
dateTimeTypes.setUtilTime(date);
|
||||
dateTimeTypes.setUtilDate(date);
|
||||
dateTimeTypes.setUtilTimestamp(date);
|
||||
|
||||
//Calendar
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
dateTimeTypes.setCalendarTime(calendar);
|
||||
dateTimeTypes.setCalendarDate(calendar);
|
||||
dateTimeTypes.setCalendarTimestamp(calendar);
|
||||
|
||||
//java.time types
|
||||
dateTimeTypes.setLocalTime(LocalTime.now());
|
||||
dateTimeTypes.setLocalDate(LocalDate.now());
|
||||
dateTimeTypes.setLocalDateTime(LocalDateTime.now());
|
||||
|
||||
//java.time types with offset
|
||||
dateTimeTypes.setOffsetTime(OffsetTime.now());
|
||||
dateTimeTypes.setOffsetDateTime(OffsetDateTime.now());
|
||||
|
||||
EntityManager entityManager = emf.createEntityManager();
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(dateTimeTypes);
|
||||
entityManager.getTransaction().commit();
|
||||
entityManager.close();
|
||||
}
|
||||
|
||||
public void clean() {
|
||||
emf.close();
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
package com.baeldung.jpa.datetime;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.sql.Date;
|
||||
import java.sql.Time;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.*;
|
||||
import java.util.Calendar;
|
||||
|
||||
@Entity
|
||||
public class JPA22DateTimeEntity {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
|
||||
//java.sql types
|
||||
private Time sqlTime;
|
||||
private Date sqlDate;
|
||||
private Timestamp sqlTimestamp;
|
||||
|
||||
//java.util types
|
||||
@Temporal(TemporalType.TIME)
|
||||
private java.util.Date utilTime;
|
||||
|
||||
@Temporal(TemporalType.DATE)
|
||||
private java.util.Date utilDate;
|
||||
|
||||
@Temporal(TemporalType.TIMESTAMP)
|
||||
private java.util.Date utilTimestamp;
|
||||
|
||||
//Calendar
|
||||
@Temporal(TemporalType.TIME)
|
||||
private Calendar calendarTime;
|
||||
|
||||
@Temporal(TemporalType.DATE)
|
||||
private Calendar calendarDate;
|
||||
|
||||
@Temporal(TemporalType.TIMESTAMP)
|
||||
private Calendar calendarTimestamp;
|
||||
|
||||
// java.time types
|
||||
@Column(name = "local_time", columnDefinition = "TIME")
|
||||
private LocalTime localTime;
|
||||
|
||||
@Column(name = "local_date", columnDefinition = "DATE")
|
||||
private LocalDate localDate;
|
||||
|
||||
@Column(name = "local_date_time", columnDefinition = "TIMESTAMP")
|
||||
private LocalDateTime localDateTime;
|
||||
|
||||
@Column(name = "offset_time", columnDefinition = "TIME WITH TIME ZONE")
|
||||
private OffsetTime offsetTime;
|
||||
|
||||
@Column(name = "offset_date_time", columnDefinition = "TIMESTAMP WITH TIME ZONE")
|
||||
private OffsetDateTime offsetDateTime;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Time getSqlTime() {
|
||||
return sqlTime;
|
||||
}
|
||||
|
||||
public void setSqlTime(Time sqlTime) {
|
||||
this.sqlTime = sqlTime;
|
||||
}
|
||||
|
||||
public Date getSqlDate() {
|
||||
return sqlDate;
|
||||
}
|
||||
|
||||
public void setSqlDate(Date sqlDate) {
|
||||
this.sqlDate = sqlDate;
|
||||
}
|
||||
|
||||
public Timestamp getSqlTimestamp() {
|
||||
return sqlTimestamp;
|
||||
}
|
||||
|
||||
public void setSqlTimestamp(Timestamp sqlTimestamp) {
|
||||
this.sqlTimestamp = sqlTimestamp;
|
||||
}
|
||||
|
||||
public java.util.Date getUtilTime() {
|
||||
return utilTime;
|
||||
}
|
||||
|
||||
public void setUtilTime(java.util.Date utilTime) {
|
||||
this.utilTime = utilTime;
|
||||
}
|
||||
|
||||
public java.util.Date getUtilDate() {
|
||||
return utilDate;
|
||||
}
|
||||
|
||||
public void setUtilDate(java.util.Date utilDate) {
|
||||
this.utilDate = utilDate;
|
||||
}
|
||||
|
||||
public java.util.Date getUtilTimestamp() {
|
||||
return utilTimestamp;
|
||||
}
|
||||
|
||||
public void setUtilTimestamp(java.util.Date utilTimestamp) {
|
||||
this.utilTimestamp = utilTimestamp;
|
||||
}
|
||||
|
||||
public Calendar getCalendarTime() {
|
||||
return calendarTime;
|
||||
}
|
||||
|
||||
public void setCalendarTime(Calendar calendarTime) {
|
||||
this.calendarTime = calendarTime;
|
||||
}
|
||||
|
||||
public Calendar getCalendarDate() {
|
||||
return calendarDate;
|
||||
}
|
||||
|
||||
public void setCalendarDate(Calendar calendarDate) {
|
||||
this.calendarDate = calendarDate;
|
||||
}
|
||||
|
||||
public Calendar getCalendarTimestamp() {
|
||||
return calendarTimestamp;
|
||||
}
|
||||
|
||||
public void setCalendarTimestamp(Calendar calendarTimestamp) {
|
||||
this.calendarTimestamp = calendarTimestamp;
|
||||
}
|
||||
|
||||
public LocalTime getLocalTime() {
|
||||
return localTime;
|
||||
}
|
||||
|
||||
public void setLocalTime(LocalTime localTime) {
|
||||
this.localTime = localTime;
|
||||
}
|
||||
|
||||
public LocalDate getLocalDate() {
|
||||
return localDate;
|
||||
}
|
||||
|
||||
public void setLocalDate(LocalDate localDate) {
|
||||
this.localDate = localDate;
|
||||
}
|
||||
|
||||
public LocalDateTime getLocalDateTime() {
|
||||
return localDateTime;
|
||||
}
|
||||
|
||||
public void setLocalDateTime(LocalDateTime localDateTime) {
|
||||
this.localDateTime = localDateTime;
|
||||
}
|
||||
|
||||
public OffsetTime getOffsetTime() {
|
||||
return offsetTime;
|
||||
}
|
||||
|
||||
public void setOffsetTime(OffsetTime offsetTime) {
|
||||
this.offsetTime = offsetTime;
|
||||
}
|
||||
|
||||
public OffsetDateTime getOffsetDateTime() {
|
||||
return offsetDateTime;
|
||||
}
|
||||
|
||||
public void setOffsetDateTime(OffsetDateTime offsetDateTime) {
|
||||
this.offsetDateTime = offsetDateTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.jpa.datetime;
|
||||
|
||||
public class MainApp {
|
||||
|
||||
public static void main(String... args) {
|
||||
|
||||
DateTimeEntityRepository dateTimeEntityRepository = new DateTimeEntityRepository();
|
||||
|
||||
//Persist
|
||||
dateTimeEntityRepository.save(100L);
|
||||
|
||||
//Find
|
||||
JPA22DateTimeEntity dateTimeEntity = dateTimeEntityRepository.find(100L);
|
||||
|
||||
dateTimeEntityRepository.clean();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,12 +2,14 @@
|
||||
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
|
||||
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
|
||||
version="2.1">
|
||||
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
|
||||
version="2.2">
|
||||
|
||||
<persistence-unit name="java-jpa-scheduled-day">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.sqlresultsetmapping.ScheduledDay</class>
|
||||
<class>com.baeldung.sqlresultsetmapping.Employee</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"
|
||||
@@ -24,6 +26,7 @@
|
||||
<persistence-unit name="jpa-h2">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.stringcast.Message</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"/>
|
||||
@@ -39,6 +42,7 @@
|
||||
<persistence-unit name="jpa-db">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.model.Car</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung"/>
|
||||
@@ -66,4 +70,22 @@
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="java8-datetime-postgresql" transaction-type="RESOURCE_LOCAL">
|
||||
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.datetime.JPA22DateTimeEntity</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/java8-datetime2"/>
|
||||
<property name="javax.persistence.jdbc.user" value="postgres"/>
|
||||
<property name="javax.persistence.jdbc.password" value="postgres"/>
|
||||
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
|
||||
|
||||
<!-- configure logging -->
|
||||
<property name="eclipselink.logging.level" value="INFO"/>
|
||||
<property name="eclipselink.logging.level.sql" value="FINE"/>
|
||||
<property name="eclipselink.logging.parameters" value="true"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
||||
@@ -5,3 +5,5 @@
|
||||
- [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql)
|
||||
- [Configuring a Tomcat Connection Pool in Spring Boot](https://www.baeldung.com/spring-boot-tomcat-connection-pool)
|
||||
- [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot)
|
||||
- [Integrating Spring Boot with HSQLDB](https://www.baeldung.com/spring-boot-hsqldb)
|
||||
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.springbootdatasourceconfig.application;
|
||||
|
||||
import com.baeldung.springbootdatasourceconfig.application.entities.User;
|
||||
import com.baeldung.springbootdatasourceconfig.application.repositories.UserRepository;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CommandLineRunner run(UserRepository userRepository) throws Exception {
|
||||
return (String[] args) -> {
|
||||
User user1 = new User("John", "[email protected]");
|
||||
User user2 = new User("Julie", "[email protected]");
|
||||
userRepository.save(user1);
|
||||
userRepository.save(user2);
|
||||
userRepository.findAll().forEach(user -> System.out.println(user.getName()));
|
||||
};
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user