Merge pull request #3 from eugenp/master

Merge from parent
This commit is contained in:
Krzysztof Majewski
2020-11-27 19:51:12 +01:00
committed by GitHub
551 changed files with 2279 additions and 19204 deletions
@@ -6,10 +6,12 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zaxxer.hikari.HikariDataSource;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import java.util.HashMap;
import java.util.Map;
@@ -22,11 +24,14 @@ import static org.hibernate.cfg.AvailableSettings.PASS;
*/
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private SessionFactory sessionFactory = createSessionFactory();
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
try (SessionFactory sessionFactory = createSessionFactory()) {
try {
ShippingService service = new ShippingService(sessionFactory, new ShippingDao());
return routeRequest(input, service);
} finally {
flushConnectionPool();
}
}
@@ -105,4 +110,12 @@ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
.buildMetadata()
.buildSessionFactory();
}
private void flushConnectionPool() {
ConnectionProvider connectionProvider = sessionFactory.getSessionFactoryOptions()
.getServiceRegistry()
.getService(ConnectionProvider.class);
HikariDataSource hikariDataSource = connectionProvider.unwrap(HikariDataSource.class);
hikariDataSource.getHikariPoolMXBean().softEvictConnections();
}
}
+1 -1
View File
@@ -4,4 +4,4 @@ This module contains articles about Java 15.
### Relevant articles
- TODO: add article links here
- [Sealed Classes and Interfaces in Java 15](https://www.baeldung.com/java-sealed-classes-interfaces)
+2 -2
View File
@@ -51,8 +51,8 @@
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>
<source>15</source>
<target>15</target>
<source>14</source>
<target>14</target>
</configuration>
</plugin>
<plugin>
@@ -0,0 +1,15 @@
package com.baeldung.whatsnew.records;
/**
* Java record with a header indicating 2 fields.
*/
public record Person(String name, int age) {
/**
* Public constructor that does some basic validation.
*/
public Person {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
}
@@ -0,0 +1,9 @@
package com.baeldung.whatsnew.sealedclasses;
import java.util.Date;
public non-sealed class Employee extends Person {
public Date getHiredDate() {
return new Date();
}
}
@@ -0,0 +1,4 @@
package com.baeldung.whatsnew.sealedclasses;
public final class Manager extends Person {
}
@@ -0,0 +1,21 @@
package com.baeldung.whatsnew.sealedclasses;
import java.util.Date;
public sealed class Person permits Employee, Manager {
/**
* Demonstration of pattern matching for instanceof
*
* @param person A Person object
* @return
*/
public static void patternMatchingDemo(Person person) {
if(person instanceof Employee employee) {
Date hiredDate = employee.getHiredDate();
}
if(person instanceof Employee employee && employee.getHiredDate() != null) {
Date hiredDate = employee.getHiredDate();
}
}
}
@@ -7,3 +7,4 @@ This module contains complete guides about arrays in Java
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
@@ -0,0 +1,6 @@
## Core Java Character
This module contains articles about Java Character Class
### Relevant Articles:
- Character#isAlphabetic vs Character#isLetter
+42
View File
@@ -0,0 +1,42 @@
<?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-char</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-char</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>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
</dependencies>
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<assertj.version>3.11.1</assertj.version>
</properties>
</project>
@@ -0,0 +1,37 @@
package com.baeldung.character;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class CharacterGeneralCategoryTypeUnitTest {
@Test
public void givenACharacter_whenUpperCaseLetter_thenAssertTrue() {
assertTrue(Character.getType('U') == Character.UPPERCASE_LETTER);
}
@Test
public void givenACharacter_whenLowerCaseLetter_thenAssertTrue() {
assertTrue(Character.getType('u') == Character.LOWERCASE_LETTER);
}
@Test
public void givenACharacter_whenTitleCaseLetter_thenAssertTrue() {
assertTrue(Character.getType('\u01f2') == Character.TITLECASE_LETTER);
}
@Test
public void givenACharacter_whenModifierLetter_thenAssertTrue() {
assertTrue(Character.getType('\u02b0') == Character.MODIFIER_LETTER);
}
@Test
public void givenACharacter_whenOtherLetter_thenAssertTrue() {
assertTrue(Character.getType('\u05d0') == Character.OTHER_LETTER);
}
@Test
public void givenACharacter_whenLetterNumber_thenAssertTrue() {
assertTrue(Character.getType('\u2164') == Character.LETTER_NUMBER);
}
}
@@ -0,0 +1,28 @@
package com.baeldung.character;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class IsLetterOrAlphabetUnitTest {
@Test
public void givenACharacter_whenLetter_thenAssertIsLetterTrue() {
assertTrue(Character.isLetter('a'));
}
@Test
public void givenACharacter_whenLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic('a'));
}
@Test
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsLetterFalse() {
assertFalse(Character.isLetter('\u2164'));
}
@Test
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic('\u2164'));
}
}
@@ -8,4 +8,4 @@ This module contains articles about the Java ArrayList collection
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
- [Removing an Element From an ArrayList](https://www.baeldung.com/java-arraylist-remove-element)
- [The Capacity of an ArrayList vs the Size of an Array in Java](https://www.baeldung.com/java-list-capacity-array-size)
@@ -0,0 +1,20 @@
package com.baeldung.listcapacityvsarraysize;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ArrayCreatorUnitTest {
@Test
void whenSizeOfAnArrayIsNonZero_thenReturnNewArrayOfGivenSize() {
Integer[] array = new Integer[10];
assertEquals(10, array.length);
}
@Test
void whenSizeOfAnArrayIsLessThanZero_thenThrowException() {
assertThrows(NegativeArraySizeException.class, () -> { Integer[] array = new Integer[-1]; });
}
}
@@ -0,0 +1,27 @@
package com.baeldung.listcapacityvsarraysize;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
class ArrayListCreatorUnitTest {
@Test
void givenValidCapacityOfList_whenCreateListInvoked_thenCreateNewArrayListWithGivenCapacity() {
ArrayList<Integer> list = new ArrayList<>(100);
assertNotNull(list);
}
@Test
void givenInvalidCapacityOfList_whenCreateListInvoked_thenThrowException() {
assertThrows(IllegalArgumentException.class, () -> new ArrayList<>(-1));
}
@Test
void givenValidCapacityOfList_whenCreateListInvoked_thenCreateNewArrayListWithSizeZero() {
assertEquals(0, new ArrayList<Integer>(100).size());
}
}
@@ -6,3 +6,4 @@
- [AbstractMethodError in Java](https://www.baeldung.com/java-abstractmethoderror)
- [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception)
- [Localizing Exception Messages in Java](https://www.baeldung.com/java-localize-exception-messages)
- [Explanation of ClassCastException in Java](https://www.baeldung.com/java-classcastexception)
@@ -1,9 +1,9 @@
package com.baeldung.exceptions.classcastexception;
public class Reptile implements Animal {
public class Amphibian implements Animal {
@Override
public String getName() {
return "Reptile";
return "Amphibian";
}
}
@@ -1,6 +1,6 @@
package com.baeldung.exceptions.classcastexception;
public class Frog extends Reptile {
public class Frog extends Amphibian {
@Override
public String getName() {
@@ -16,31 +16,42 @@ public class UnzipFile {
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
final File newFile = newFile(destDir, zipEntry);
final FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
if (zipEntry.isDirectory()) {
if (!newFile.isDirectory() && !newFile.mkdirs()) {
throw new IOException("Failed to create directory " + newFile);
}
} else {
File parent = newFile.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("Failed to create directory " + parent);
}
final FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
fos.close();
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
/**
* @see https://snyk.io/research/zip-slip-vulnerability
*/
public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
File destFile = new File(destinationDir, zipEntry.getName());
String destDirPath = destinationDir.getCanonicalPath();
String destFilePath = destFile.getCanonicalPath();
if (!destFilePath.startsWith(destDirPath + File.separator)) {
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
}
return destFile;
}
}
@@ -0,0 +1,68 @@
package com.baeldung.iterationcounter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Stream;
public class IterationCounter {
public static final List<String> IMDB_TOP_MOVIES = Arrays.asList("The Shawshank Redemption",
"The Godfather", "The Godfather II", "The Dark Knight");
public static List<String> getRankingsWithForLoop(List<String> movies) {
List<String> rankings = new ArrayList<>();
for (int i = 0; i < movies.size(); i++) {
String ranking = (i + 1) + ": " + movies.get(i);
rankings.add(ranking);
}
return rankings;
}
public static List<String> getRankingsWithForEachLoop(List<String> movies) {
List<String> rankings = new ArrayList<>();
int i = 0;
for (String movie : movies) {
String ranking = (i + 1) + ": " + movies.get(i);
rankings.add(ranking);
i++;
}
return rankings;
}
public static List<String> getRankingsWithFunctionalForEachLoop(List<String> movies) {
List<String> rankings = new ArrayList<>();
forEachWithCounter(movies, (i, movie) -> {
String ranking = (i + 1) + ": " + movie;
rankings.add(ranking);
});
return rankings;
}
public static <T> void forEachWithCounter(Iterable<T> source, BiConsumer<Integer, T> consumer) {
int i = 0;
for (T item : source) {
consumer.accept(i, item);
i++;
}
}
public static List<String> getRankingsWithStream(Stream<String> movies) {
List<String> rankings = new ArrayList<>();
movies.forEach(withCounter((i, movie) -> {
String ranking = (i + 1) + ": " + movie;
rankings.add(ranking);
}));
return rankings;
}
public static <T> Consumer<T> withCounter(BiConsumer<Integer, T> consumer) {
AtomicInteger counter = new AtomicInteger(0);
return item -> consumer.accept(counter.getAndIncrement(), item);
}
}
@@ -0,0 +1,36 @@
package com.baeldung.iterationcounter;
import org.junit.Test;
import static com.baeldung.iterationcounter.IterationCounter.*;
import static org.assertj.core.api.Assertions.*;
public class IterationCounterUnitTest {
@Test
public void givenRankings_whenCalculateWithForLoop_thenRankingsCorrect() {
assertThat(getRankingsWithForLoop(IMDB_TOP_MOVIES))
.containsExactly("1: The Shawshank Redemption",
"2: The Godfather", "3: The Godfather II", "4: The Dark Knight");
}
@Test
public void givenRankings_whenCalculateWithForEachLoop_thenRankingsCorrect() {
assertThat(getRankingsWithForEachLoop(IMDB_TOP_MOVIES))
.containsExactly("1: The Shawshank Redemption",
"2: The Godfather", "3: The Godfather II", "4: The Dark Knight");
}
@Test
public void givenRankings_whenCalculateWithFunctionalForEach_thenRankingsCorrect() {
assertThat(getRankingsWithFunctionalForEachLoop(IMDB_TOP_MOVIES))
.containsExactly("1: The Shawshank Redemption",
"2: The Godfather", "3: The Godfather II", "4: The Dark Knight");
}
@Test
public void givenRankings_whenCalculateWithStream_thenRankingsCorrect() {
assertThat(getRankingsWithStream(IMDB_TOP_MOVIES.stream()))
.containsExactly("1: The Shawshank Redemption",
"2: The Godfather", "3: The Godfather II", "4: The Dark Knight");
}
}
@@ -8,5 +8,5 @@ This module contains articles about string APIs.
- [Guide to java.util.Formatter](https://www.baeldung.com/java-string-formatter)
- [Guide to StreamTokenizer](https://www.baeldung.com/java-streamtokenizer)
- [CharSequence vs. String in Java](https://www.baeldung.com/java-char-sequence-string)
- [StringBuilder and StringBuffer in Java](https://www.baeldung.com/java-string-builder-string-buffer)
- [StringBuilder vs StringBuffer in Java](https://www.baeldung.com/java-string-builder-string-buffer)
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
+2 -1
View File
@@ -29,7 +29,8 @@
<module>core-java-arrays-convert</module>
<module>core-java-arrays-operations-basic</module>
<module>core-java-arrays-operations-advanced</module>
<module>core-java-char</module>
<module>core-java-collections</module>
<module>core-java-collections-2</module>
<module>core-java-collections-3</module>
@@ -1,11 +0,0 @@
## Core Kotlin Advanced
This module contains articles about advanced topics in Kotlin.
### Relevant articles:
- [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl)
- [Regular Expressions in Kotlin](https://www.baeldung.com/kotlin-regular-expressions)
- [Idiomatic Logging in Kotlin](https://www.baeldung.com/kotlin-logging)
- [Mapping of Data Objects in Kotlin](https://www.baeldung.com/kotlin-data-objects)
- [Reflection with Kotlin](https://www.baeldung.com/kotlin-reflection)
- [Kotlin Contracts](https://www.baeldung.com/kotlin-contracts)
@@ -1,41 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-kotlin-advanced</artifactId>
<name>core-kotlin-advanced</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-kotlin-modules</groupId>
<artifactId>core-kotlin-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test</artifactId>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<kotlin.version>1.3.30</kotlin.version>
<assertj.version>3.10.0</assertj.version>
</properties>
</project>
@@ -1,23 +0,0 @@
package com.baeldung.contract
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@ExperimentalContracts
inline fun <R> myRun(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
@ExperimentalContracts
fun callsInPlace() {
val i: Int
myRun {
i = 1 // Without contract initialization is forbidden due to possible re-assignment
}
println(i) // Without contract variable might be uninitialized
}
@@ -1,43 +0,0 @@
package com.baeldung.contract
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
data class Request(val arg: String)
class Service {
@ExperimentalContracts
fun process(request: Request?) {
validate(request)
println(request.arg)
}
}
@ExperimentalContracts
private fun validate(request: Request?) {
contract {
returns() implies (request != null)
}
if (request == null) {
throw IllegalArgumentException("Undefined request")
}
}
data class MyEvent(val message: String)
@ExperimentalContracts
fun processEvent(event: Any?) {
if (isInterested(event)) {
println(event.message) // Compiler makes smart cast here with the help of contract
}
}
@ExperimentalContracts
fun isInterested(event: Any?): Boolean {
contract {
returns(true) implies (event is MyEvent)
}
return event is MyEvent
}
@@ -1,10 +0,0 @@
package com.baeldung.datamapping
data class User(
val firstName: String,
val lastName: String,
val street: String,
val houseNumber: String,
val phone: String,
val age: Int,
val password: String)
@@ -1,22 +0,0 @@
package com.baeldung.datamapping
import kotlin.reflect.full.memberProperties
fun User.toUserView() = UserView(
name = "$firstName $lastName",
address = "$street $houseNumber",
telephone = phone,
age = age
)
fun User.toUserViewReflection() = with(::UserView) {
val propertiesByName = User::class.memberProperties.associateBy { it.name }
callBy(parameters.associate { parameter ->
parameter to when (parameter.name) {
UserView::name.name -> "$firstName $lastName"
UserView::address.name -> "$street $houseNumber"
UserView::telephone.name -> phone
else -> propertiesByName[parameter.name]?.get(this@toUserViewReflection)
}
})
}
@@ -1,8 +0,0 @@
package com.baeldung.datamapping
data class UserView(
val name: String,
val address: String,
val telephone: String,
val age: Int
)

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