This commit is contained in:
Jonathan Cook
2020-11-18 08:24:25 +01:00
54 changed files with 853 additions and 107 deletions
@@ -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));
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -0,0 +1,26 @@
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 ApplicationWithEx {
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);
// ImmutableOperation.REMOVE_WHITESPACES is not mapped
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);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.enums.extendenum;
public enum BasicStringOperation implements StringOperation {
TRIM("Removing leading and trailing spaces.") {
@Override
public String apply(String input) {
return input.trim();
}
},
TO_UPPER("Changing all characters into upper case.") {
@Override
public String apply(String input) {
return input.toUpperCase();
}
},
REVERSE("Reversing the given string.") {
@Override
public String apply(String input) {
return new StringBuilder(input).reverse().toString();
}
};
private String description;
public String getDescription() {
return description;
}
BasicStringOperation(String description) {
this.description = description;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.enums.extendenum;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
public enum ExtendedStringOperation implements StringOperation {
MD5_ENCODE("Encoding the given string using the MD5 algorithm.") {
@Override
public String apply(String input) {
return DigestUtils.md5Hex(input);
}
},
BASE64_ENCODE("Encoding the given string using the BASE64 algorithm.") {
@Override
public String apply(String input) {
return new String(new Base64().encode(input.getBytes()));
}
};
private String description;
ExtendedStringOperation(String description) {
this.description = description;
}
@Override
public String getDescription() {
return description;
}
}
@@ -0,0 +1,6 @@
package com.baeldung.enums.extendenum;
public enum ImmutableOperation {
REMOVE_WHITESPACES, TO_LOWER, INVERT_CASE
}
@@ -0,0 +1,5 @@
package com.baeldung.enums.extendenum;
public interface Operator {
String apply(String input);
}
@@ -0,0 +1,7 @@
package com.baeldung.enums.extendenum;
public interface StringOperation {
String getDescription();
String apply(String input);
}
@@ -0,0 +1,43 @@
package com.baeldung.enums.extendenum;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.*;
public class ExtendEnumUnitTest {
private Application app = new Application();
@Test
public void givenAStringAndOperation_whenApplyOperation_thenGetExpectedResult() {
String input = " hello";
String expectedToUpper = " HELLO";
String expectedReverse = "olleh ";
String expectedTrim = "hello";
String expectedBase64 = "IGhlbGxv";
String expectedMd5 = "292a5af68d31c10e31ad449bd8f51263";
assertEquals(expectedTrim, app.applyOperation(BasicStringOperation.TRIM, input));
assertEquals(expectedToUpper, app.applyOperation(BasicStringOperation.TO_UPPER, input));
assertEquals(expectedReverse, app.applyOperation(BasicStringOperation.REVERSE, input));
assertEquals(expectedBase64, app.applyOperation(ExtendedStringOperation.BASE64_ENCODE, input));
assertEquals(expectedMd5, app.applyOperation(ExtendedStringOperation.MD5_ENCODE, input));
}
@Test
public void givenAStringAndImmutableOperation_whenApplyOperation_thenGetExpectedResult() {
String input = " He ll O ";
String expectedToLower = " he ll o ";
String expectedRmWhitespace = "HellO";
String expectedInvertCase = " hE LL o ";
assertEquals(expectedToLower, app.applyImmutableOperation(ImmutableOperation.TO_LOWER, input));
assertEquals(expectedRmWhitespace, app.applyImmutableOperation(ImmutableOperation.REMOVE_WHITESPACES, input));
assertEquals(expectedInvertCase, app.applyImmutableOperation(ImmutableOperation.INVERT_CASE, input));
}
@Test
public void givenUnmappedImmutableOperationValue_whenAppStarts_thenGetException() {
Throwable throwable = assertThrows(ExceptionInInitializerError.class, () -> {
ApplicationWithEx appEx = new ApplicationWithEx();
});
assertTrue(throwable.getCause() instanceof IllegalStateException);
}
}
-1
View File
@@ -1,4 +1,3 @@
README.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
+7
View File
@@ -0,0 +1,7 @@
## DISCORD4J
This module contains articles about Discord4J
### Relevant Articles:
- [Creating a Discord Bot with Discord4J + Spring Boot](https://www.baeldung.com/spring-discord4j-bot)
+8
View File
@@ -23,6 +23,14 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -36,8 +36,6 @@ public class BotConfiguration {
.onErrorResume(listener::handleError)
.subscribe();
}
client.onDisconnect().block();
}
catch ( Exception exception ) {
log.error( "Be sure to use a valid bot token!", exception );
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.docker</groupId>
<artifactId>docker</artifactId>
<version>0.0.1</version>
</parent>
<artifactId>docker-internal-dto</artifactId>
<name>docker-internal-dto</name>
</project>
@@ -0,0 +1,14 @@
package com.baeldung.docker.dto;
public class VariableDto {
private final String value;
public VariableDto(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
+18 -11
View File
@@ -1,21 +1,21 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
<groupId>com.baeldung.docker</groupId>
<artifactId>docker</artifactId>
<version>0.0.1</version>
</parent>
<groupId>com.baeldung.docker</groupId>
<artifactId>spring-boot-docker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-docker</name>
<artifactId>docker-spring-boot</artifactId>
<name>docker-spring-boot</name>
<description>Demo project showing Spring Boot and Docker</description>
<properties>
<java.version>8</java.version>
<java.version>11</java.version>
</properties>
<dependencies>
@@ -24,6 +24,12 @@
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baeldung.docker</groupId>
<artifactId>docker-internal-dto</artifactId>
<version>0.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
@@ -45,6 +51,7 @@
<configuration>
<layers>
<enabled>true</enabled>
<configuration>${project.basedir}/src/layers.xml</configuration>
</layers>
</configuration>
</plugin>
+27
View File
@@ -0,0 +1,27 @@
<layers xmlns="http://www.springframework.org/schema/boot/layers"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/boot/layers
https://www.springframework.org/schema/boot/layers/layers-2.3.xsd">
<application>
<into layer="spring-boot-loader">
<include>org/springframework/boot/loader/**</include>
</into>
<into layer="application" />
</application>
<dependencies>
<into layer="snapshot-dependencies">
<include>*:*:*SNAPSHOT</include>
</into>
<into layer="internal-dependencies">
<include>com.baeldung.docker:*:*</include>
</into>
<into layer="dependencies" />
</dependencies>
<layerOrder>
<layer>dependencies</layer>
<layer>spring-boot-loader</layer>
<layer>internal-dependencies</layer>
<layer>snapshot-dependencies</layer>
<layer>application</layer>
</layerOrder>
</layers>
@@ -9,7 +9,8 @@ RUN java -Djarmode=layertools -jar application.jar extract
FROM adoptopenjdk:11-jre-hotspot
COPY --from=builder dependencies/ ./
COPY --from=builder snapshot-dependencies/ ./
COPY --from=builder spring-boot-loader/ ./
COPY --from=builder internal-dependencies/ ./
COPY --from=builder snapshot-dependencies/ ./
COPY --from=builder application/ ./
ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]
@@ -1,4 +1,4 @@
package com.baeldung.docker;
package com.baeldung.docker.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -1,4 +1,4 @@
package com.baeldung.docker;
package com.baeldung.docker.spring;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.baeldung.docker</groupId>
<artifactId>docker</artifactId>
<version>0.0.1</version>
<name>docker</name>
<description>Demo project showing Spring Boot and Docker</description>
<packaging>pom</packaging>
<properties>
<java.version>11</java.version>
</properties>
<modules>
<module>docker-internal-dto</module>
<module>docker-spring-boot</module>
</modules>
</project>
@@ -0,0 +1,70 @@
package com.baeldung.jpa.index;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Objects;
@Entity
@Table(indexes = {
@Index(columnList = "firstName"),
@Index(name = "fn_index", columnList = "id"),
@Index(name = "multiIndex1", columnList = "firstName, lastName"),
@Index(name = "multiIndex2", columnList = "lastName, firstName"),
@Index(name = "multiSortIndex", columnList = "firstName, lastName DESC"),
@Index(name = "uniqueIndex", columnList = "firstName", unique = true),
@Index(name = "uniqueMultiIndex", columnList = "firstName, lastName", unique = true)
})
public class Student implements Serializable {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Student student = (Student) o;
return Objects.equals(id, student.id) &&
Objects.equals(firstName, student.firstName) &&
Objects.equals(lastName, student.lastName);
}
@Override
public int hashCode() {
return Objects.hash(id, firstName, lastName);
}
}
@@ -40,4 +40,19 @@
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
<persistence-unit name="jpa-index">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.index.Student</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="show_sql" value="true" />
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
</properties>
</persistence-unit>
</persistence>
@@ -8,7 +8,7 @@
</pattern>
</encoder>
</appender>
<logger name="org.hibernate.SQL" level="DEBUG" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
@@ -0,0 +1,50 @@
package com.baeldung.jpa.index;
import org.hibernate.exception.ConstraintViolationException;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.Optional;
public class IndexIntegrationTest {
private static EntityManagerFactory factory;
private static EntityManager entityManager;
@BeforeClass
public static void setup() {
factory = Persistence.createEntityManagerFactory("jpa-index");
entityManager = factory.createEntityManager();
}
@Test
public void givenStudent_whenPersistStudentWithSameFirstName_thenConstraintViolationException() {
Student student = new Student();
student.setFirstName("FirstName");
student.setLastName("LastName");
Student student2 = new Student();
student2.setFirstName("FirstName");
student2.setLastName("LastName2");
entityManager.getTransaction().begin();
entityManager.persist(student);
entityManager.getTransaction().commit();
Assert.assertEquals(1L, (long) student.getId());
entityManager.getTransaction().begin();
try {
entityManager.persist(student2);
entityManager.getTransaction().commit();
Assert.fail("Should raise an exception - unique key violation");
} catch (Exception ex) {
Assert.assertTrue(Optional.of(ex).map(Throwable::getCause).map(Throwable::getCause).filter(x -> x instanceof ConstraintViolationException).isPresent());
} finally {
entityManager.getTransaction().rollback();
}
}
}
@@ -7,7 +7,9 @@ import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -19,7 +21,7 @@ public class ArticleUnitTest {
@BeforeClass
public static void setup() {
Map properties = new HashMap();
Map<String, String> properties = new HashMap<>();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
emFactory = Persistence.createEntityManagerFactory("jpa-h2", properties);
@@ -115,4 +117,53 @@ public class ArticleUnitTest {
assertEquals(Category.MUSIC, persistedArticle.getCategory());
}
@Test
public void shouldFindArticleByCategory() {
// given
Article article = new Article();
article.setId(5);
article.setTitle("static");
article.setCategory(Category.SPORT);
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
String jpql = "select a from Article a where a.category = com.baeldung.jpa.enums.Category.SPORT";
// when
List<Article> articles = em.createQuery(jpql, Article.class).getResultList();
// then
assertEquals(1, articles.size());
assertEquals(Category.SPORT, articles.get(0).getCategory());
assertEquals("static", articles.get(0).getTitle());
}
@Test
public void shouldFindArticleByCategoryParameter() {
// given
Article article = new Article();
article.setId(6);
article.setTitle("dynamic");
article.setCategory(Category.TECHNOLOGY);
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
String jpql = "select a from Article a where a.category = :category";
// when
TypedQuery<Article> query = em.createQuery(jpql, Article.class);
query.setParameter("category", Category.TECHNOLOGY);
List<Article> articles = query.getResultList();
// then
assertEquals(1, articles.size());
assertEquals(Category.TECHNOLOGY, articles.get(0).getCategory());
assertEquals("dynamic", articles.get(0).getTitle());
}
}

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