This commit is contained in:
Jonathan Cook 2020-11-18 08:24:25 +01:00
commit 4980a2a40f
54 changed files with 853 additions and 107 deletions

View File

@ -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));
}
}

View File

@ -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;
}
}

View File

@ -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]);
}
}

View File

@ -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);
}
}

View File

@ -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>

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.enums.extendenum;
public enum ImmutableOperation {
REMOVE_WHITESPACES, TO_LOWER, INVERT_CASE
}

View File

@ -0,0 +1,5 @@
package com.baeldung.enums.extendenum;
public interface Operator {
String apply(String input);
}

View File

@ -0,0 +1,7 @@
package com.baeldung.enums.extendenum;
public interface StringOperation {
String getDescription();
String apply(String input);
}

View File

@ -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);
}
}

View File

@ -1,4 +1,3 @@
README.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/

7
discord4j/README.md Normal file
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)

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>

View File

@ -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 );

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>

View File

@ -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;
}
}

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>

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>

View File

@ -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"]

View File

@ -1,4 +1,4 @@
package com.baeldung.docker;
package com.baeldung.docker.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

View File

@ -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
docker/pom.xml Normal file
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>

View File

@ -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);
}
}

View File

@ -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>

View File

@ -8,7 +8,7 @@
</pattern>
</encoder>
</appender>
<logger name="org.hibernate.SQL" level="DEBUG" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>

View File

@ -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();
}
}
}

View File

@ -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());
}
}

View File

@ -697,7 +697,6 @@
<module>spring-reactor</module>
<module>spring-remoting</module>
<module>spring-rest-angular</module>
<module>spring-rest-compress</module>
<module>spring-rest-http</module>
<module>spring-rest-http-2</module>
<module>spring-rest-query-language</module>
@ -1200,7 +1199,6 @@
<module>spring-reactor</module>
<module>spring-remoting</module>
<module>spring-rest-angular</module>
<module>spring-rest-compress</module>
<module>spring-rest-http</module>
<module>spring-rest-query-language</module>
<module>spring-rest-shell</module>

View File

@ -26,6 +26,7 @@
<module>spring-boot-artifacts</module>
<module>spring-boot-autoconfiguration</module>
<module>spring-boot-basic-customization</module>
<module>spring-boot-basic-customization-2</module>
<module>spring-boot-bootstrap</module>
<module>spring-boot-client</module>
<module>spring-boot-config-jpa-error</module>

View File

@ -0,0 +1,7 @@
## Spring Boot Basic Customization 2
This module contains articles about Spring Boot customization 2
### Relevant Articles:
- [DispatcherServlet and web.xml in Spring Boot](https://www.baeldung.com/)

View File

@ -0,0 +1,33 @@
<?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.spring-boot-modules</groupId>
<artifactId>spring-boot-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<artifactId>spring-boot-basic-customization-2</artifactId>
<packaging>jar</packaging>
<name>spring-boot-basic-customization-2</name>
<description>Module For Spring Boot Basic Customization 2</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,15 @@
package com.baeldung.dispatchservlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Configuration;
@SpringBootApplication
public class DispatchServletApplication {
public static void main(String[] args) {
SpringApplication.run(DispatchServletApplication.class, args);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.dispatchservlet.conf;
import com.baeldung.dispatchservlet.listener.CustomListener;
import com.baeldung.dispatchservlet.servlet.CustomServlet;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.ServletContextListener;
@Configuration
public class WebConf {
@Bean
public ServletRegistrationBean customServletBean() {
ServletRegistrationBean bean
= new ServletRegistrationBean(new CustomServlet(), "/servlet");
return bean;
}
@Bean
public ServletListenerRegistrationBean<ServletContextListener> customListenerBean() {
ServletListenerRegistrationBean<ServletContextListener> bean = new ServletListenerRegistrationBean();
bean.setListener(new CustomListener());
return bean;
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.dispatchservlet.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/")
public class Controller {
@GetMapping
public String getRequest(){
return "Baeldung DispatcherServlet";
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.dispatchservlet.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import java.io.IOException;
@Component
public class CustomFilter implements Filter {
Logger logger = LoggerFactory.getLogger(CustomFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
logger.info("CustomFilter is invoked");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.dispatchservlet.listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class CustomListener implements ServletContextListener {
Logger logger = LoggerFactory.getLogger(CustomListener.class);
@Override
public void contextInitialized(ServletContextEvent sce) {
logger.info("CustomListener is initialized");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
logger.info("CustomListener is destroyed");
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.dispatchservlet.servlet;
import com.baeldung.dispatchservlet.filter.CustomFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CustomServlet extends HttpServlet {
Logger logger = LoggerFactory.getLogger(CustomServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
logger.info("CustomServlet doGet() method is invoked");
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
logger.info("CustomServlet doPost() method is invoked");
super.doPost(req, resp);
}
}

View File

@ -1,6 +0,0 @@
## Spring REST Compress
This module contains articles about request compression with Spring
### Relevant Articles:
- [How to compress requests using the Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-compressing-requests)

View File

@ -1,65 +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>spring-rest-compress</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-rest-compress</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<java.version>1.8</java.version>
<commons-io.version>2.6</commons-io.version>
</properties>
</project>

View File

@ -8,3 +8,4 @@ This module contains articles about Spring RestTemplate
- [Proxies With RestTemplate](https://www.baeldung.com/java-resttemplate-proxy)
- [A Custom Media Type for a Spring REST API](https://www.baeldung.com/spring-rest-custom-media-type)
- [RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json)
- [How to compress requests using the Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-compressing-requests)

View File

@ -20,7 +20,30 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.rest.compress;
package com.baeldung.compress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,14 +1,14 @@
package com.baeldung.spring.rest.compress;
import org.apache.commons.codec.Charsets;
import org.apache.commons.io.IOUtils;
package com.baeldung.compress;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.IOUtils;
public class GzipUtils {
/**
@ -19,7 +19,7 @@ public class GzipUtils {
* @throws Exception
*/
public static byte[] compress(String text) throws Exception {
return GzipUtils.compress(text.getBytes(Charsets.UTF_8));
return GzipUtils.compress(text.getBytes(StandardCharsets.UTF_8));
}
/**
@ -46,7 +46,7 @@ public class GzipUtils {
*/
public static String decompress(byte[] body) throws IOException {
try (GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(body))) {
return IOUtils.toString(gzipInputStream, Charsets.UTF_8);
return IOUtils.toString(gzipInputStream, StandardCharsets.UTF_8);
}
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.rest.compress;
package com.baeldung.compress;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.rest.compress;
package com.baeldung.compress;
public class Message {

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.rest.compress;
package com.baeldung.compress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.rest.compress;
package com.baeldung.compress;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.rest.compress;
package com.baeldung.compress;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.rest.compress;
package com.baeldung.compress;
import org.junit.Test;

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.rest.compress;
package com.baeldung.compress;
import org.junit.Test;
import org.junit.runner.RunWith;