Merge remote-tracking branch 'baeldung/master' into BAEL-4015

This commit is contained in:
Adrian Maghear
2020-11-28 23:01:02 +01:00
649 changed files with 3967 additions and 19761 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();
}
}
@@ -0,0 +1,30 @@
package com.baeldung.java14.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(65));
}
@Test
public void givenACharacter_whenLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic(65));
}
@Test
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsLetterFalse() {
assertFalse(Character.isLetter(837));
}
@Test
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic(837));
}
}
+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,30 @@
package com.baeldung.genericarrays;
import java.lang.reflect.Array;
public class MyStack<E> {
private E[] elements;
private int size = 0;
public MyStack(Class<E> clazz, int capacity) {
elements = (E[]) Array.newInstance(clazz, capacity);
}
public void push(E item) {
if (size == elements.length) {
throw new RuntimeException();
}
elements[size++] = item;
}
public E pop() {
if (size == 0) {
throw new RuntimeException();
}
return elements[--size];
}
public E[] getAllElements() {
return elements;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.genericarrays;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class ListToArrayUnitTest {
@Test
public void givenListOfItems_whenToArray_thenReturnArrayOfItems() {
List<String> items = new LinkedList<>();
items.add("first item");
items.add("second item");
String[] itemsAsArray = items.toArray(new String[0]);
assertEquals("first item", itemsAsArray[0]);
assertEquals("second item", itemsAsArray[1]);
}
}
@@ -0,0 +1,44 @@
package com.baeldung.genericarrays;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MyStackUnitTest {
@Test
public void givenStackWithTwoItems_whenPop_thenReturnLastAdded() {
MyStack<String> myStack = new MyStack<>(String.class, 2);
myStack.push("hello");
myStack.push("example");
assertEquals("example", myStack.pop());
}
@Test (expected = RuntimeException.class)
public void givenStackWithFixedCapacity_whenExceedCapacity_thenThrowException() {
MyStack<Integer> myStack = new MyStack<>(Integer.class, 2);
myStack.push(100);
myStack.push(200);
myStack.push(300);
}
@Test(expected = RuntimeException.class)
public void givenStack_whenPopOnEmptyStack_thenThrowException() {
MyStack<Integer> myStack = new MyStack<>(Integer.class, 1);
myStack.push(100);
myStack.pop();
myStack.pop();
}
@Test
public void givenStackWithItems_whenGetAllElements_thenSizeShouldEqualTotal() {
MyStack<String> myStack = new MyStack<>(String.class, 2);
myStack.push("hello");
myStack.push("example");
String[] items = myStack.getAllElements();
assertEquals(2, items.length);
}
}
@@ -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() {
@@ -0,0 +1,8 @@
package com.baeldung.exceptions.nosuchfielderror;
public class Dependency {
// This needed to be commented post compilation of NoSuchFielDError and Compile
public static String message = "Hello Baeldung!!";
}
@@ -0,0 +1,20 @@
package com.baeldung.exceptions.nosuchfielderror;
public class FieldErrorExample {
public static void main(String... args) {
fetchAndPrint();
}
public static String getDependentMessage() {
return Dependency.message;
}
public static void fetchAndPrint() {
System.out.println(getDependentMessage());
}
}
@@ -0,0 +1,16 @@
package com.baeldung.exceptions.nosuchfielderror;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class FieldErrorExampleUnitTest {
@Test
public void whenDependentMessage_returnMessage() {
String dependentMessage = FieldErrorExample.getDependentMessage();
assertTrue("Hello Baeldung!!".equals(dependentMessage));
}
}
@@ -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");
}
}
@@ -12,12 +12,20 @@
<artifactId>core-java-lang-oop-types</artifactId>
<name>core-java-lang-oop-types</name>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
</dependencies>
<properties>
<commons-codec.version>1.15</commons-codec.version>
</properties>
</project>
@@ -0,0 +1,35 @@
package com.baeldung.enums.extendenum;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Map;
public class Application {
private static final Map<ImmutableOperation, Operator> OPERATION_MAP;
static {
OPERATION_MAP = new EnumMap<>(ImmutableOperation.class);
OPERATION_MAP.put(ImmutableOperation.TO_LOWER, String::toLowerCase);
OPERATION_MAP.put(ImmutableOperation.INVERT_CASE, StringUtils::swapCase);
OPERATION_MAP.put(ImmutableOperation.REMOVE_WHITESPACES, input -> input.replaceAll("\\s", ""));
if (Arrays.stream(ImmutableOperation.values()).anyMatch(it -> !OPERATION_MAP.containsKey(it))) {
throw new IllegalStateException("Unmapped enum constant found!");
}
}
public String applyImmutableOperation(ImmutableOperation operation, String input) {
return OPERATION_MAP.get(operation).apply(input);
}
public String getDescription(StringOperation stringOperation) {
return stringOperation.getDescription();
}
public String applyOperation(StringOperation operation, String input) {
return operation.apply(input);
}
}

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