Merge pull request #72 from eugenp/master

update
This commit is contained in:
Maiklins 2020-09-14 16:37:48 +02:00 committed by GitHub
commit 914851bd2b
121 changed files with 1300 additions and 323 deletions

100
aws-lambda/lambda/pom.xml Normal file
View File

@ -0,0 +1,100 @@
<?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>aws-lambda-examples</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>aws-lambda-examples</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-dynamodb</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-core</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>${aws-lambda-java-core.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>${aws-lambda-java-events.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>${json-simple.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<json-simple.version>1.1.1</json-simple.version>
<commons-io.version>2.5</commons-io.version>
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
<gson.version>2.8.2</gson.version>
<aws-java-sdk.version>1.11.241</aws-java-sdk.version>
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
</properties>
</project>

View File

@ -5,95 +5,19 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 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> <modelVersion>4.0.0</modelVersion>
<artifactId>aws-lambda</artifactId> <artifactId>aws-lambda</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>aws-lambda</name> <name>aws-lambda</name>
<packaging>jar</packaging> <packaging>pom</packaging>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent> </parent>
<dependencies> <modules>
<dependency> <module>lambda</module>
<groupId>com.amazonaws</groupId> <module>shipping-tracker/ShippingFunction</module>
<artifactId>aws-java-sdk-dynamodb</artifactId> </modules>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-core</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>${aws-lambda-java-core.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>${aws-lambda-java-events.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>${json-simple.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<json-simple.version>1.1.1</json-simple.version>
<commons-io.version>2.5</commons-io.version>
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
<gson.version>2.8.2</gson.version>
<aws-java-sdk.version>1.11.241</aws-java-sdk.version>
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
</properties>
</project> </project>

View File

@ -0,0 +1 @@
.aws-sam/

View File

@ -0,0 +1,73 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>ShippingFunction</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Shipping Tracker Lambda Function</name>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<hibernate.version>5.4.21.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-hikaricp</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.16</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.1</version>
<configuration>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,108 @@
package com.baeldung.lambda.shipping;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
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 org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import java.util.HashMap;
import java.util.Map;
import static org.hibernate.cfg.AvailableSettings.*;
import static org.hibernate.cfg.AvailableSettings.PASS;
/**
* Handler for requests to Lambda function.
*/
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
try (SessionFactory sessionFactory = createSessionFactory()) {
ShippingService service = new ShippingService(sessionFactory, new ShippingDao());
return routeRequest(input, service);
}
}
private APIGatewayProxyResponseEvent routeRequest(APIGatewayProxyRequestEvent input, ShippingService service) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("X-Custom-Header", "application/json");
Object result = "OK";
switch (input.getResource()) {
case "/consignment":
result = service.createConsignment(
fromJson(input.getBody(), Consignment.class));
break;
case "/consignment/{id}":
result = service.view(input.getPathParameters().get("id"));
break;
case "/consignment/{id}/item":
service.addItem(input.getPathParameters().get("id"),
fromJson(input.getBody(), Item.class));
break;
case "/consignment/{id}/checkin":
service.checkIn(input.getPathParameters().get("id"),
fromJson(input.getBody(), Checkin.class));
break;
}
return new APIGatewayProxyResponseEvent()
.withHeaders(headers)
.withStatusCode(200)
.withBody(toJson(result));
}
private static <T> String toJson(T object) {
try {
return OBJECT_MAPPER.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private static <T> T fromJson(String json, Class<T> type) {
try {
return OBJECT_MAPPER.readValue(json, type);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private static SessionFactory createSessionFactory() {
Map<String, String> settings = new HashMap<>();
settings.put(URL, System.getenv("DB_URL"));
settings.put(DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
settings.put(DEFAULT_SCHEMA, "shipping");
settings.put(DRIVER, "org.postgresql.Driver");
settings.put(USER, System.getenv("DB_USER"));
settings.put(PASS, System.getenv("DB_PASSWORD"));
settings.put("hibernate.hikari.connectionTimeout", "20000");
settings.put("hibernate.hikari.minimumIdle", "1");
settings.put("hibernate.hikari.maximumPoolSize", "2");
settings.put("hibernate.hikari.idleTimeout", "30000");
// commented out as we only need them on first use
// settings.put(HBM2DDL_AUTO, "create-only");
// settings.put(HBM2DDL_DATABASE_ACTION, "create");
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(settings)
.build();
return new MetadataSources(registry)
.addAnnotatedClass(Consignment.class)
.addAnnotatedClass(Item.class)
.addAnnotatedClass(Checkin.class)
.buildMetadata()
.buildSessionFactory();
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.lambda.shipping;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class Checkin {
private String timeStamp;
private String location;
@Column(name = "timestamp")
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
@Column(name = "location")
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.lambda.shipping;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import static javax.persistence.FetchType.EAGER;
@Entity(name = "consignment")
@Table(name = "consignment")
public class Consignment {
private String id;
private String source;
private String destination;
private boolean isDelivered;
private List<Item> items = new ArrayList<>();
private List<Checkin> checkins = new ArrayList<>();
@Id
@Column(name = "consignment_id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(name = "source")
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
@Column(name = "destination")
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
@Column(name = "delivered", columnDefinition = "boolean")
public boolean isDelivered() {
return isDelivered;
}
public void setDelivered(boolean delivered) {
isDelivered = delivered;
}
@ElementCollection(fetch = EAGER)
@CollectionTable(name = "consignment_item", joinColumns = @JoinColumn(name = "consignment_id"))
@OrderColumn(name = "item_index")
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
@ElementCollection(fetch = EAGER)
@CollectionTable(name = "consignment_checkin", joinColumns = @JoinColumn(name = "consignment_id"))
@OrderColumn(name = "checkin_index")
public List<Checkin> getCheckins() {
return checkins;
}
public void setCheckins(List<Checkin> checkins) {
this.checkins = checkins;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.lambda.shipping;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class Item {
private String location;
private String description;
private String timeStamp;
@Column(name = "location")
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
@Column(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name = "timestamp")
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.lambda.shipping;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.Optional;
public class ShippingDao {
/**
* Save a consignment to the database
* @param consignment the consignment to save
*/
public void save(Session session, Consignment consignment) {
Transaction transaction = session.beginTransaction();
session.save(consignment);
transaction.commit();
}
/**
* Find a consignment in the database by id
*/
public Optional<Consignment> find(Session session, String id) {
return Optional.ofNullable(session.get(Consignment.class, id));
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.lambda.shipping;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.util.Comparator;
import java.util.UUID;
public class ShippingService {
private SessionFactory sessionFactory;
private ShippingDao shippingDao;
public ShippingService(SessionFactory sessionFactory, ShippingDao shippingDao) {
this.sessionFactory = sessionFactory;
this.shippingDao = shippingDao;
}
public String createConsignment(Consignment consignment) {
try (Session session = sessionFactory.openSession()) {
consignment.setDelivered(false);
consignment.setId(UUID.randomUUID().toString());
shippingDao.save(session, consignment);
return consignment.getId();
}
}
public void addItem(String consignmentId, Item item) {
try (Session session = sessionFactory.openSession()) {
shippingDao.find(session, consignmentId)
.ifPresent(consignment -> addItem(session, consignment, item));
}
}
private void addItem(Session session, Consignment consignment, Item item) {
consignment.getItems()
.add(item);
shippingDao.save(session, consignment);
}
public void checkIn(String consignmentId, Checkin checkin) {
try (Session session = sessionFactory.openSession()) {
shippingDao.find(session, consignmentId)
.ifPresent(consignment -> checkIn(session, consignment, checkin));
}
}
private void checkIn(Session session, Consignment consignment, Checkin checkin) {
consignment.getCheckins().add(checkin);
consignment.getCheckins().sort(Comparator.comparing(Checkin::getTimeStamp));
if (checkin.getLocation().equals(consignment.getDestination())) {
consignment.setDelivered(true);
}
shippingDao.save(session, consignment);
}
public Consignment view(String consignmentId) {
try (Session session = sessionFactory.openSession()) {
return shippingDao.find(session, consignmentId)
.orElseGet(Consignment::new);
}
}
}

View File

@ -0,0 +1,47 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
shipping-tracker
Sample SAM Template for shipping-tracker
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 20
Resources:
ShippingFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ShippingFunction
Handler: com.baeldung.lambda.shipping.App::handleRequest
Runtime: java8
MemorySize: 512
Environment:
Variables:
DB_URL: jdbc:postgresql://postgres/postgres
DB_USER: postgres
DB_PASSWORD: password
Events:
CreateConsignment:
Type: Api
Properties:
Path: /consignment
Method: post
AddItem:
Type: Api
Properties:
Path: /consignment/{id}/item
Method: post
CheckIn:
Type: Api
Properties:
Path: /consignment/{id}/checkin
Method: post
ViewConsignment:
Type: Api
Properties:
Path: /consignment/{id}
Method: get

View File

@ -4,4 +4,5 @@ This module contains articles about Java 11 core features
### Relevant articles ### Relevant articles
- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional) - [Guide to Java 8 Optional](https://www.baeldung.com/java-optional)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [Guide to Java 8s Collectors](https://www.baeldung.com/java-8-collectors)

View File

@ -17,6 +17,11 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>
@ -42,6 +47,7 @@
<properties> <properties>
<maven.compiler.source.version>11</maven.compiler.source.version> <maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version> <maven.compiler.target.version>11</maven.compiler.target.version>
<guava.version>29.0-jre</guava.version>
<assertj.version>3.17.2</assertj.version> <assertj.version>3.17.2</assertj.version>
</properties> </properties>

View File

@ -1,4 +1,4 @@
package com.baeldung.java.reflection; package com.baeldung.reflection;
public abstract class Animal implements Eating { public abstract class Animal implements Eating {

View File

@ -1,4 +1,4 @@
package com.baeldung.java.reflection; package com.baeldung.reflection;
public class Bird extends Animal { public class Bird extends Animal {
private boolean walks; private boolean walks;

View File

@ -1,4 +1,4 @@
package com.baeldung.java.reflection; package com.baeldung.reflection;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;

View File

@ -1,4 +1,4 @@
package com.baeldung.java.reflection; package com.baeldung.reflection;
public interface Eating { public interface Eating {
String eats(); String eats();

View File

@ -1,4 +1,4 @@
package com.baeldung.java.reflection; package com.baeldung.reflection;
public class Goat extends Animal implements Locomotion { public class Goat extends Animal implements Locomotion {

View File

@ -1,4 +1,4 @@
package com.baeldung.java.reflection; package com.baeldung.reflection;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;

View File

@ -1,4 +1,4 @@
package com.baeldung.java.reflection; package com.baeldung.reflection;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.lang.reflect.Field; import java.lang.reflect.Field;

View File

@ -1,4 +1,4 @@
package com.baeldung.java.reflection; package com.baeldung.reflection;
@Greeter(greet="Good morning") @Greeter(greet="Good morning")
public class Greetings { public class Greetings {

View File

@ -1,4 +1,4 @@
package com.baeldung.java.reflection; package com.baeldung.reflection;
public interface Locomotion { public interface Locomotion {
String getLocomotion(); String getLocomotion();

View File

@ -1,4 +1,4 @@
package com.baeldung.java.reflection; package com.baeldung.reflection;
public class Operations { public class Operations {

View File

@ -1,4 +1,4 @@
package com.baeldung.java.reflection; package com.baeldung.reflection;
public class Person { public class Person {
private String name; private String name;

View File

@ -1,18 +1,11 @@
package com.baeldung.streams.collectors; package com.baeldung.collectors;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import org.junit.Test; import org.junit.Test;
import java.util.Arrays; import java.util.*;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import java.util.function.BinaryOperator; import java.util.function.BinaryOperator;
import java.util.function.Function; import java.util.function.Function;
@ -20,19 +13,7 @@ import java.util.function.Supplier;
import java.util.stream.Collector; import java.util.stream.Collector;
import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newHashSet;
import static java.util.stream.Collectors.averagingDouble; import static java.util.stream.Collectors.*;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.partitioningBy;
import static java.util.stream.Collectors.summarizingDouble;
import static java.util.stream.Collectors.summingDouble;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatThrownBy;
@ -48,6 +29,14 @@ public class Java8CollectorsUnitTest {
assertThat(result).containsAll(givenList); assertThat(result).containsAll(givenList);
} }
@Test
public void whenCollectingToUnmodifiableList_shouldCollectToUnmodifiableList() {
final List<String> result = givenList.stream().collect(toUnmodifiableList());
assertThatThrownBy(() -> result.add("foo"))
.isInstanceOf(UnsupportedOperationException.class);
}
@Test @Test
public void whenCollectingToSet_shouldCollectToSet() throws Exception { public void whenCollectingToSet_shouldCollectToSet() throws Exception {
final Set<String> result = givenList.stream().collect(toSet()); final Set<String> result = givenList.stream().collect(toSet());
@ -55,6 +44,14 @@ public class Java8CollectorsUnitTest {
assertThat(result).containsAll(givenList); assertThat(result).containsAll(givenList);
} }
@Test
public void whenCollectingToUnmodifiableSet_shouldCollectToUnmodifiableSet() {
final Set<String> result = givenList.stream().collect(toUnmodifiableSet());
assertThatThrownBy(() -> result.add("foo"))
.isInstanceOf(UnsupportedOperationException.class);
}
@Test @Test
public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception { public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception {
final Set<String> result = listWithDuplicates.stream().collect(toSet()); final Set<String> result = listWithDuplicates.stream().collect(toSet());
@ -84,6 +81,15 @@ public class Java8CollectorsUnitTest {
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2); assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
} }
@Test
public void whenCollectingToUnmodifiableMap_shouldCollectToUnmodifiableMap() {
final Map<String, Integer> result = givenList.stream()
.collect(toUnmodifiableMap(Function.identity(), String::length));
assertThatThrownBy(() -> result.put("foo", 3))
.isInstanceOf(UnsupportedOperationException.class);
}
@Test @Test
public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception { public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception {
final Map<String, Integer> result = listWithDuplicates.stream().collect( final Map<String, Integer> result = listWithDuplicates.stream().collect(

View File

@ -1,4 +1,4 @@
package com.baeldung.java.reflection; package com.baeldung.reflection;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;

View File

@ -1,4 +1,4 @@
package com.baeldung.java.reflection; package com.baeldung.reflection;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
@ -32,23 +32,23 @@ public class ReflectionUnitTest {
final Class<?> clazz = goat.getClass(); final Class<?> clazz = goat.getClass();
assertEquals("Goat", clazz.getSimpleName()); assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); assertEquals("com.baeldung.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName());
} }
@Test @Test
public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException { public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException {
final Class<?> clazz = Class.forName("com.baeldung.java.reflection.Goat"); final Class<?> clazz = Class.forName("com.baeldung.reflection.Goat");
assertEquals("Goat", clazz.getSimpleName()); assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); assertEquals("com.baeldung.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName());
} }
@Test @Test
public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException { public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException {
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat"); final Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal"); final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
final int goatMods = goatClass.getModifiers(); final int goatMods = goatClass.getModifiers();
final int animalMods = animalClass.getModifiers(); final int animalMods = animalClass.getModifiers();
@ -63,7 +63,7 @@ public class ReflectionUnitTest {
final Class<?> goatClass = goat.getClass(); final Class<?> goatClass = goat.getClass();
final Package pkg = goatClass.getPackage(); final Package pkg = goatClass.getPackage();
assertEquals("com.baeldung.java.reflection", pkg.getName()); assertEquals("com.baeldung.reflection", pkg.getName());
} }
@Test @Test
@ -81,8 +81,8 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException { public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException {
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat"); final Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal"); final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
final Class<?>[] goatInterfaces = goatClass.getInterfaces(); final Class<?>[] goatInterfaces = goatClass.getInterfaces();
final Class<?>[] animalInterfaces = animalClass.getInterfaces(); final Class<?>[] animalInterfaces = animalClass.getInterfaces();
@ -94,16 +94,16 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException { public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException {
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat"); final Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
final Constructor<?>[] constructors = goatClass.getConstructors(); final Constructor<?>[] constructors = goatClass.getConstructors();
assertEquals(1, constructors.length); assertEquals(1, constructors.length);
assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName()); assertEquals("com.baeldung.reflection.Goat", constructors[0].getName());
} }
@Test @Test
public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException { public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException {
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal"); final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
final Field[] fields = animalClass.getDeclaredFields(); final Field[] fields = animalClass.getDeclaredFields();
final List<String> actualFields = getFieldNames(fields); final List<String> actualFields = getFieldNames(fields);
@ -114,7 +114,7 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException { public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException {
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal"); final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
final Method[] methods = animalClass.getDeclaredMethods(); final Method[] methods = animalClass.getDeclaredMethods();
final List<String> actualMethods = getMethodNames(methods); final List<String> actualMethods = getMethodNames(methods);
@ -124,7 +124,7 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException { public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird"); final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Constructor<?>[] constructors = birdClass.getConstructors(); final Constructor<?>[] constructors = birdClass.getConstructors();
assertEquals(3, constructors.length); assertEquals(3, constructors.length);
@ -132,7 +132,7 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception { public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird"); final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
birdClass.getConstructor(); birdClass.getConstructor();
birdClass.getConstructor(String.class); birdClass.getConstructor(String.class);
birdClass.getConstructor(String.class, boolean.class); birdClass.getConstructor(String.class, boolean.class);
@ -140,7 +140,7 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception { public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird"); final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Constructor<?> cons1 = birdClass.getConstructor(); final Constructor<?> cons1 = birdClass.getConstructor();
final Constructor<?> cons2 = birdClass.getConstructor(String.class); final Constructor<?> cons2 = birdClass.getConstructor(String.class);
@ -159,7 +159,7 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException { public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird"); final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Field[] fields = birdClass.getFields(); final Field[] fields = birdClass.getFields();
assertEquals(1, fields.length); assertEquals(1, fields.length);
assertEquals("CATEGORY", fields[0].getName()); assertEquals("CATEGORY", fields[0].getName());
@ -168,7 +168,7 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception { public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird"); final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Field field = birdClass.getField("CATEGORY"); final Field field = birdClass.getField("CATEGORY");
assertEquals("CATEGORY", field.getName()); assertEquals("CATEGORY", field.getName());
@ -176,7 +176,7 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException { public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird"); final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Field[] fields = birdClass.getDeclaredFields(); final Field[] fields = birdClass.getDeclaredFields();
assertEquals(1, fields.length); assertEquals(1, fields.length);
assertEquals("walks", fields[0].getName()); assertEquals("walks", fields[0].getName());
@ -184,7 +184,7 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception { public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird"); final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Field field = birdClass.getDeclaredField("walks"); final Field field = birdClass.getDeclaredField("walks");
assertEquals("walks", field.getName()); assertEquals("walks", field.getName());
@ -192,14 +192,14 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClassField_whenGetsType_thenCorrect() throws Exception { public void givenClassField_whenGetsType_thenCorrect() throws Exception {
final Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks"); final Field field = Class.forName("com.baeldung.reflection.Bird").getDeclaredField("walks");
final Class<?> fieldClass = field.getType(); final Class<?> fieldClass = field.getType();
assertEquals("boolean", fieldClass.getSimpleName()); assertEquals("boolean", fieldClass.getSimpleName());
} }
@Test @Test
public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception { public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird"); final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Bird bird = (Bird) birdClass.getConstructor().newInstance(); final Bird bird = (Bird) birdClass.getConstructor().newInstance();
final Field field = birdClass.getDeclaredField("walks"); final Field field = birdClass.getDeclaredField("walks");
field.setAccessible(true); field.setAccessible(true);
@ -216,7 +216,7 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception { public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird"); final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Field field = birdClass.getField("CATEGORY"); final Field field = birdClass.getField("CATEGORY");
field.setAccessible(true); field.setAccessible(true);
@ -225,7 +225,7 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException { public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird"); final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Method[] methods = birdClass.getMethods(); final Method[] methods = birdClass.getMethods();
final List<String> methodNames = getMethodNames(methods); final List<String> methodNames = getMethodNames(methods);
@ -235,7 +235,7 @@ public class ReflectionUnitTest {
@Test @Test
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException { public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird"); final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods()); final List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
final List<String> expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats"); final List<String> expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats");
@ -248,24 +248,17 @@ public class ReflectionUnitTest {
@Test @Test
public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception { public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird"); final Bird bird = new Bird();
final Method walksMethod = birdClass.getDeclaredMethod("walks"); final Method walksMethod = bird.getClass().getDeclaredMethod("walks");
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class); final Method setWalksMethod = bird.getClass().getDeclaredMethod("setWalks", boolean.class);
assertFalse(walksMethod.isAccessible());
assertFalse(setWalksMethod.isAccessible());
walksMethod.setAccessible(true);
setWalksMethod.setAccessible(true);
assertTrue(walksMethod.isAccessible());
assertTrue(setWalksMethod.isAccessible());
assertTrue(walksMethod.canAccess(bird));
assertTrue(setWalksMethod.canAccess(bird));
} }
@Test @Test
public void givenMethod_whenInvokes_thenCorrect() throws Exception { public void givenMethod_whenInvokes_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird"); final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
final Bird bird = (Bird) birdClass.getConstructor().newInstance(); final Bird bird = (Bird) birdClass.getConstructor().newInstance();
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class); final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
final Method walksMethod = birdClass.getDeclaredMethod("walks"); final Method walksMethod = birdClass.getDeclaredMethod("walks");

View File

@ -0,0 +1,143 @@
package com.baeldung.collections.mapfirstpair;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
public class MapFirstPairUnitTest {
private Map.Entry<Integer, String> getFirstPairUsingIterator(Map<Integer, String> map) {
if (map == null || map.size() == 0)
return null;
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet()
.iterator();
if (iterator.hasNext())
return iterator.next();
return null;
}
private Map.Entry<Integer, String> getFirstPairUsingStream(Map<Integer, String> map) {
if (map == null || map.size() == 0)
return null;
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
return entrySet.stream()
.findFirst()
.get();
}
private Map<Integer, String> populateMapValues(Map<Integer, String> map) {
if (map != null) {
map.put(5, "A");
map.put(1, "B");
map.put(2, "C");
}
return map;
}
@Test
public void whenUsingIteratorForHashMap_thenFirstPairWhichWasNotInsertedFirst() {
Map<Integer, String> hashMap = new HashMap<>();
hashMap = populateMapValues(hashMap);
Map.Entry<Integer, String> actualValue = getFirstPairUsingIterator(hashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(1, "B");
Map.Entry<Integer, String> pairInsertedFirst = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
assertEquals(expectedValue, actualValue);
assertNotEquals(pairInsertedFirst, actualValue);
}
@Test
public void whenUsingStreamForHashMap_thenFirstPairWhichWasNotInsertedFirst() {
Map<Integer, String> hashMap = new HashMap<>();
hashMap = populateMapValues(hashMap);
Map.Entry<Integer, String> actualValue = getFirstPairUsingStream(hashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(1, "B");
Map.Entry<Integer, String> pairInsertedFirst = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
assertEquals(expectedValue, actualValue);
assertNotEquals(pairInsertedFirst, actualValue);
}
@Test
public void whenUsingIteratorForLinkedHashMap_thenFirstPairWhichWasInsertedFirst() {
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap = populateMapValues(linkedHashMap);
Map.Entry<Integer, String> actualValue = getFirstPairUsingIterator(linkedHashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
assertEquals(expectedValue, actualValue);
}
@Test
public void whenUsingStreamForLinkedHashMap_thenFirstPairWhichWasInsertedFirst() {
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap = populateMapValues(linkedHashMap);
Map.Entry<Integer, String> actualValue = getFirstPairUsingStream(linkedHashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
assertEquals(expectedValue, actualValue);
}
@Test
public void whenAddedAnElementInHashMap_thenFirstPairChangedUsingIterator() {
Map<Integer, String> hashMap = new HashMap<>();
hashMap = populateMapValues(hashMap);
hashMap.put(0, "D");
Map.Entry<Integer, String> actualValue = getFirstPairUsingIterator(hashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(0, "D");
assertEquals(expectedValue, actualValue);
}
@Test
public void whenAddedAnElementInHashMap_thenFirstPairChangedUsingStream() {
Map<Integer, String> hashMap = new HashMap<>();
hashMap = populateMapValues(hashMap);
hashMap.put(0, "D");
Map.Entry<Integer, String> actualValue = getFirstPairUsingStream(hashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(0, "D");
assertEquals(expectedValue, actualValue);
}
@Test
public void whenAddedAnElementInLinkedHashMap_thenFirstPairRemainUnchangedUsingIterator() {
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap = populateMapValues(linkedHashMap);
linkedHashMap.put(0, "D");
Map.Entry<Integer, String> actualValue = getFirstPairUsingIterator(linkedHashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
assertEquals(expectedValue, actualValue);
}
@Test
public void whenAddedAnElementInLinkedHashMap_thenFirstPairRemainUnchangedUsingStream() {
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap = populateMapValues(linkedHashMap);
linkedHashMap.put(0, "D");
Map.Entry<Integer, String> actualValue = getFirstPairUsingStream(linkedHashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
assertEquals(expectedValue, actualValue);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.checkclassexistence;
import org.junit.Test;
public class CheckClassExistenceUnitTest {
public static class InitializingClass {
static {
if (true) { //enable throwing of an exception in a static initialization block
throw new RuntimeException();
}
}
}
@Test(expected = ClassNotFoundException.class) //thrown when class does not exist
public void givenNonExistingClass_whenUsingForName_thenClassNotFound() throws ClassNotFoundException {
Class.forName("class.that.does.not.exist");
}
@Test
public void givenExistingClass_whenUsingForName_thenNoException() throws ClassNotFoundException {
Class.forName("java.lang.String");
}
@Test(expected = ExceptionInInitializerError.class) //thrown when exception occurs inside of a static initialization block
public void givenInitializingClass_whenUsingForName_thenInitializationError() throws ClassNotFoundException {
Class.forName("com.baeldung.checkclassexistence.CheckClassExistenceUnitTest$InitializingClass");
}
@Test
public void givenInitializingClass_whenUsingForNameWithoutInitialization_thenNoException() throws ClassNotFoundException {
Class.forName("com.baeldung.checkclassexistence.CheckClassExistenceUnitTest$InitializingClass", false, getClass().getClassLoader());
}
}

View File

@ -35,6 +35,12 @@
<artifactId>async-http-client</artifactId> <artifactId>async-http-client</artifactId>
<version>${async-http-client.version}</version> <version>${async-http-client.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.icegreen</groupId>
<artifactId>greenmail</artifactId>
<version>1.5.8</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -0,0 +1,83 @@
package com.baeldung.mail.mailwithattachment;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class MailWithAttachmentService {
private String username = "";
private String password = "";
private String host = "";
private String port = "";
MailWithAttachmentService() {
}
MailWithAttachmentService(String username, String password, String host, String port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}
public Session getSession() {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", this.host);
props.put("mail.smtp.port", this.port);
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
return session;
}
public Message createMail(Session session) throws AddressException, MessagingException, IOException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("mail@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("mail@gmail.com"));
message.setSubject("Testing Subject");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is message body");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
MimeBodyPart attachmentPart = new MimeBodyPart();
MimeBodyPart attachmentPart2 = new MimeBodyPart();
attachmentPart.attachFile(new File("C:\\Document1.txt"));
attachmentPart2.attachFile(new File("C:\\Document2.txt"));
multipart.addBodyPart(attachmentPart);
multipart.addBodyPart(attachmentPart2);
message.setContent(multipart);
return message;
}
public void sendMail(Session session) throws MessagingException, IOException {
Message message = createMail(session);
Transport.send(message);
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.mail.mailwithattachment;
import static org.junit.Assert.*;
import javax.annotation.Resource;
import javax.mail.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.mail.mailwithattachment.MailWithAttachmentService;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetupTest;
public class MailWithAttachmentServiceLiveTest {
@Resource
private MailWithAttachmentService emailService;
private GreenMail greenMail;
@Before
public void startMailServer() {
emailService = new MailWithAttachmentService();
greenMail = new GreenMail(ServerSetupTest.SMTP);
greenMail.start();
}
@After
public void stopMailServer() {
greenMail.stop();
emailService = null;
}
@Test
public void canSendMail() {
try {
Session testSession = greenMail.getSmtp()
.createSession();
emailService.sendMail(testSession);
assertEquals(1, greenMail.getReceivedMessages().length);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -3,7 +3,6 @@
- [Void Type in Java](https://www.baeldung.com/java-void-type) - [Void Type in Java](https://www.baeldung.com/java-void-type)
- [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields) - [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields)
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection) - [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection) - [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params) - [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params)
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies) - [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)

View File

@ -6,7 +6,6 @@ This module contains articles about the Stream API in Java.
- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap) - [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap)
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic) - [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach) - [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
- [Guide to Java 8s Collectors](https://www.baeldung.com/java-8-collectors)
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams) - [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
- [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams) - [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams)
- [Add BigDecimals using the Stream API](https://www.baeldung.com/java-stream-add-bigdecimals) - [Add BigDecimals using the Stream API](https://www.baeldung.com/java-stream-add-bigdecimals)

View File

@ -78,6 +78,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>

View File

@ -0,0 +1,38 @@
apply plugin: "java"
apply plugin: "application"
description = "Gradle Command Line Arguments examples"
ext.javaMainClass = "com.baeldung.cmd.MainClass"
application {
mainClassName = javaMainClass
}
task propertyTypes(){
doLast{
if (project.hasProperty("args")) {
println "Our input argument with project property ["+project.getProperty("args")+"]"
}
println "Our input argument with system property ["+System.getProperty("args")+"]"
}
}
if (project.hasProperty("args")) {
ext.cmdargs = project.getProperty("args")
} else {
ext.cmdargs = "ls"
}
task cmdLineJavaExec(type: JavaExec) {
group = "Execution"
description = "Run the main class with JavaExecTask"
classpath = sourceSets.main.runtimeClasspath
main = javaMainClass
args cmdargs.split()
}
task cmdLineExec(type: Exec) {
group = "Execution"
description = "Run an external program with ExecTask"
commandLine cmdargs.split()
}

View File

@ -0,0 +1,10 @@
package com.baeldung.cmd;
public class MainClass {
public static void main(String[] args) {
System.out.println("Gradle command line arguments example");
for (String arg : args) {
System.out.println("Got argument [" + arg + "]");
}
}
}

View File

@ -2,3 +2,4 @@ rootProject.name='gradle-5-articles'
include 'java-exec' include 'java-exec'
include 'unused-dependencies' include 'unused-dependencies'
include 'source-sets' include 'source-sets'
include 'cmd-line-args'

View File

@ -15,6 +15,12 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.17.2</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>

View File

@ -1,5 +1,6 @@
package com.baeldung.arrayconversion; package com.baeldung.arrayconversion;
import org.assertj.core.api.ListAssert;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import org.junit.Test; import org.junit.Test;
@ -7,8 +8,7 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertArrayEquals;
public class ArrayToListConversionUnitTest { public class ArrayToListConversionUnitTest {
@ -17,8 +17,8 @@ public class ArrayToListConversionUnitTest {
String[] stringArray = new String[] { "A", "B", "C", "D" }; String[] stringArray = new String[] { "A", "B", "C", "D" };
List<String> stringList = Arrays.asList(stringArray); List<String> stringList = Arrays.asList(stringArray);
stringList.set(0, "E"); stringList.set(0, "E");
assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D")); assertThat(stringList).containsExactly("E", "B", "C", "D");
assertArrayEquals(stringArray, new String[] { "E", "B", "C", "D" }); assertThat(stringArray).containsExactly("E", "B", "C", "D");
stringList.add("F"); stringList.add("F");
} }
@ -27,9 +27,9 @@ public class ArrayToListConversionUnitTest {
String[] stringArray = new String[] { "A", "B", "C", "D" }; String[] stringArray = new String[] { "A", "B", "C", "D" };
List<String> stringList = new ArrayList<>(Arrays.asList(stringArray)); List<String> stringList = new ArrayList<>(Arrays.asList(stringArray));
stringList.set(0, "E"); stringList.set(0, "E");
assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D")); assertThat(stringList).containsExactly("E", "B", "C", "D");
assertArrayEquals(stringArray, new String[] { "A", "B", "C", "D" }); assertThat(stringArray).containsExactly("A", "B", "C", "D");
stringList.add("F"); stringList.add("F");
assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D", "F")); assertThat(stringList).containsExactly("E", "B", "C", "D", "F");
} }
} }

View File

@ -23,6 +23,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId> <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>

View File

@ -9,6 +9,7 @@
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>logging-modules</artifactId> <artifactId>logging-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent> </parent>
<dependencies> <dependencies>

View File

@ -79,6 +79,8 @@
</dependencies> </dependencies>
<build> <build>
<finalName>logging-service</finalName>
<pluginManagement> <pluginManagement>
<plugins> <plugins>
<plugin> <plugin>
@ -93,13 +95,21 @@
</plugin> </plugin>
</plugins> </plugins>
</pluginManagement> </pluginManagement>
<finalName>logging-service</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build> </build>
<properties> <properties>
<log4j2.version>2.7</log4j2.version> <log4j2.version>2.7</log4j2.version>
<disruptor.version>3.3.6</disruptor.version> <disruptor.version>3.3.6</disruptor.version>
<jbosslogging.version>3.3.0.Final</jbosslogging.version> <jbosslogging.version>3.3.0.Final</jbosslogging.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties> </properties>
</project> </project>

View File

@ -9,9 +9,9 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>logging-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<dependencies> <dependencies>

View File

@ -7,9 +7,9 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>logging-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<dependencies> <dependencies>

View File

@ -9,9 +9,9 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>logging-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<dependencies> <dependencies>

View File

@ -10,7 +10,7 @@
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modules> <modules>
@ -21,4 +21,17 @@
<module>flogger</module> <module>flogger</module>
</modules> </modules>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<properties>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
</project> </project>

View File

@ -82,7 +82,7 @@
<rest-assured.version>3.3.0</rest-assured.version> <rest-assured.version>3.3.0</rest-assured.version>
<!-- plugins --> <!-- plugins -->
<thin.version>1.0.22.RELEASE</thin.version> <thin.version>1.0.22.RELEASE</thin.version>
<spring-boot.version>2.2.6.RELEASE</spring-boot.version> <spring-boot.version>2.3.3.RELEASE</spring-boot.version>
<aspectjweaver.version>1.9.1</aspectjweaver.version> <aspectjweaver.version>1.9.1</aspectjweaver.version>
</properties> </properties>

View File

@ -21,6 +21,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId> <artifactId>spring-boot-starter-webflux</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>

View File

@ -1,18 +1,8 @@
package com.baeldung.mongodb; package com.baeldung.mongodb;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.util.SocketUtils;
import com.mongodb.BasicDBObjectBuilder; import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.MongoClient; import com.mongodb.client.MongoClients;
import de.flapdoodle.embed.mongo.MongodExecutable; import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodStarter; import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.IMongodConfig; import de.flapdoodle.embed.mongo.config.IMongodConfig;
@ -20,8 +10,19 @@ import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
import de.flapdoodle.embed.mongo.config.Net; import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.distribution.Version; import de.flapdoodle.embed.mongo.distribution.Version;
import de.flapdoodle.embed.process.runtime.Network; import de.flapdoodle.embed.process.runtime.Network;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.util.SocketUtils;
import static org.assertj.core.api.Assertions.assertThat;
class ManualEmbeddedMongoDbIntegrationTest { class ManualEmbeddedMongoDbIntegrationTest {
private static final String CONNECTION_STRING = "mongodb://%s:%d";
private MongodExecutable mongodExecutable; private MongodExecutable mongodExecutable;
private MongoTemplate mongoTemplate; private MongoTemplate mongoTemplate;
@ -42,7 +43,7 @@ class ManualEmbeddedMongoDbIntegrationTest {
MongodStarter starter = MongodStarter.getDefaultInstance(); MongodStarter starter = MongodStarter.getDefaultInstance();
mongodExecutable = starter.prepare(mongodConfig); mongodExecutable = starter.prepare(mongodConfig);
mongodExecutable.start(); mongodExecutable.start();
mongoTemplate = new MongoTemplate(new MongoClient(ip, randomPort), "test"); mongoTemplate = new MongoTemplate(MongoClients.create(String.format(CONNECTION_STRING, ip, randomPort)),"test");
} }
@DisplayName("Given object When save object using MongoDB template Then object can be found") @DisplayName("Given object When save object using MongoDB template Then object can be found")

View File

@ -51,6 +51,7 @@
</dependencies> </dependencies>
<properties> <properties>
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
<cassandra-unit-spring.version>3.11.2.0</cassandra-unit-spring.version> <cassandra-unit-spring.version>3.11.2.0</cassandra-unit-spring.version>
</properties> </properties>

View File

@ -2,8 +2,8 @@ package com.baeldung.multipledb.dao.user;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.multipledb.model.user.PossessionMultipleDB; import com.baeldung.multipledb.model.user.Possession;
public interface PossessionRepository extends JpaRepository<PossessionMultipleDB, Long> { public interface PossessionRepository extends JpaRepository<Possession, Long> {
} }

View File

@ -2,7 +2,7 @@ package com.baeldung.multipledb.dao.user;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.multipledb.model.user.UserMultipleDB; import com.baeldung.multipledb.model.user.User;
public interface UserRepository extends JpaRepository<UserMultipleDB, Integer> { public interface UserRepository extends JpaRepository<User, Integer> {
} }

View File

@ -4,7 +4,7 @@ import javax.persistence.*;
@Entity @Entity
@Table @Table
public class PossessionMultipleDB { public class Possession {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@ -12,11 +12,11 @@ public class PossessionMultipleDB {
private String name; private String name;
public PossessionMultipleDB() { public Possession() {
super(); super();
} }
public PossessionMultipleDB(final String name) { public Possession(final String name) {
super(); super();
this.name = name; this.name = name;
@ -58,7 +58,7 @@ public class PossessionMultipleDB {
if (getClass() != obj.getClass()) { if (getClass() != obj.getClass()) {
return false; return false;
} }
final PossessionMultipleDB other = (PossessionMultipleDB) obj; final Possession other = (Possession) obj;
if (id != other.id) { if (id != other.id) {
return false; return false;
} }

View File

@ -6,7 +6,7 @@ import java.util.List;
@Entity @Entity
@Table(name = "users") @Table(name = "users")
public class UserMultipleDB { public class User {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@ -18,13 +18,13 @@ public class UserMultipleDB {
private Integer status; private Integer status;
@OneToMany @OneToMany
List<PossessionMultipleDB> possessionList; List<Possession> possessionList;
public UserMultipleDB() { public User() {
super(); super();
} }
public UserMultipleDB(String name, String email, Integer status) { public User(String name, String email, Integer status) {
this.name = name; this.name = name;
this.email = email; this.email = email;
this.status = status; this.status = status;
@ -70,11 +70,11 @@ public class UserMultipleDB {
this.age = age; this.age = age;
} }
public List<PossessionMultipleDB> getPossessionList() { public List<Possession> getPossessionList() {
return possessionList; return possessionList;
} }
public void setPossessionList(List<PossessionMultipleDB> possessionList) { public void setPossessionList(List<Possession> possessionList) {
this.possessionList = possessionList; this.possessionList = possessionList;
} }

View File

@ -20,8 +20,8 @@ import com.baeldung.multipledb.dao.product.ProductRepository;
import com.baeldung.multipledb.dao.user.PossessionRepository; import com.baeldung.multipledb.dao.user.PossessionRepository;
import com.baeldung.multipledb.dao.user.UserRepository; import com.baeldung.multipledb.dao.user.UserRepository;
import com.baeldung.multipledb.model.product.Product; import com.baeldung.multipledb.model.product.Product;
import com.baeldung.multipledb.model.user.PossessionMultipleDB; import com.baeldung.multipledb.model.user.Possession;
import com.baeldung.multipledb.model.user.UserMultipleDB; import com.baeldung.multipledb.model.user.User;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes=MultipleDbApplication.class) @SpringBootTest(classes=MultipleDbApplication.class)
@ -42,15 +42,15 @@ public class JpaMultipleDBIntegrationTest {
@Test @Test
@Transactional("userTransactionManager") @Transactional("userTransactionManager")
public void whenCreatingUser_thenCreated() { public void whenCreatingUser_thenCreated() {
UserMultipleDB user = new UserMultipleDB(); User user = new User();
user.setName("John"); user.setName("John");
user.setEmail("john@test.com"); user.setEmail("john@test.com");
user.setAge(20); user.setAge(20);
PossessionMultipleDB p = new PossessionMultipleDB("sample"); Possession p = new Possession("sample");
p = possessionRepository.save(p); p = possessionRepository.save(p);
user.setPossessionList(Collections.singletonList(p)); user.setPossessionList(Collections.singletonList(p));
user = userRepository.save(user); user = userRepository.save(user);
final Optional<UserMultipleDB> result = userRepository.findById(user.getId()); final Optional<User> result = userRepository.findById(user.getId());
assertTrue(result.isPresent()); assertTrue(result.isPresent());
System.out.println(result.get().getPossessionList()); System.out.println(result.get().getPossessionList());
assertEquals(1, result.get().getPossessionList().size()); assertEquals(1, result.get().getPossessionList().size());
@ -59,14 +59,14 @@ public class JpaMultipleDBIntegrationTest {
@Test @Test
@Transactional("userTransactionManager") @Transactional("userTransactionManager")
public void whenCreatingUsersWithSameEmail_thenRollback() { public void whenCreatingUsersWithSameEmail_thenRollback() {
UserMultipleDB user1 = new UserMultipleDB(); User user1 = new User();
user1.setName("John"); user1.setName("John");
user1.setEmail("john@test.com"); user1.setEmail("john@test.com");
user1.setAge(20); user1.setAge(20);
user1 = userRepository.save(user1); user1 = userRepository.save(user1);
assertTrue(userRepository.findById(user1.getId()).isPresent()); assertTrue(userRepository.findById(user1.getId()).isPresent());
UserMultipleDB user2 = new UserMultipleDB(); User user2 = new User();
user2.setName("Tom"); user2.setName("Tom");
user2.setEmail("john@test.com"); user2.setEmail("john@test.com");
user2.setAge(10); user2.setAge(10);

View File

@ -1 +1 @@
spring.data.jpa.repositories.bootstrap-mode=default

View File

@ -224,6 +224,7 @@
<h2.version>1.4.200</h2.version> <h2.version>1.4.200</h2.version>
<couchbaseMock.version>1.5.23</couchbaseMock.version> <couchbaseMock.version>1.5.23</couchbaseMock.version>
<reactor-core.version>3.3.1.RELEASE</reactor-core.version> <reactor-core.version>3.3.1.RELEASE</reactor-core.version>
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
</properties> </properties>
</project> </project>

View File

@ -20,6 +20,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId> <artifactId>spring-boot-starter-webflux</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId> <artifactId>spring-boot-starter-security</artifactId>

View File

@ -2,7 +2,6 @@ package com.baeldung.reactive.authresolver;
import java.util.Collections; import java.util.Collections;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.ReactiveAuthenticationManagerResolver; import org.springframework.security.authentication.ReactiveAuthenticationManagerResolver;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -15,6 +14,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter; import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
@EnableWebFluxSecurity @EnableWebFluxSecurity
@ -38,9 +38,10 @@ public class CustomWebSecurityConfig {
return new AuthenticationWebFilter(resolver()); return new AuthenticationWebFilter(resolver());
} }
public ReactiveAuthenticationManagerResolver<ServerHttpRequest> resolver() { public ReactiveAuthenticationManagerResolver<ServerWebExchange> resolver() {
return request -> { return exchange -> {
if (request if (exchange
.getRequest()
.getPath() .getPath()
.subPath(0) .subPath(0)
.value() .value()

View File

@ -2,6 +2,8 @@
package com.baeldung.reactive.errorhandling; package com.baeldung.reactive.errorhandling;
import java.util.Map; import java.util.Map;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes; import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -13,13 +15,9 @@ public class GlobalErrorAttributes extends DefaultErrorAttributes{
private HttpStatus status = HttpStatus.BAD_REQUEST; private HttpStatus status = HttpStatus.BAD_REQUEST;
private String message = "please provide a name"; private String message = "please provide a name";
public GlobalErrorAttributes() {
super(false);
}
@Override @Override
public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) { public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
Map<String, Object> map = super.getErrorAttributes(request, includeStackTrace); Map<String, Object> map = super.getErrorAttributes(request, options);
map.put("status", getStatus()); map.put("status", getStatus());
map.put("message", getMessage()); map.put("message", getMessage());
return map; return map;

View File

@ -4,6 +4,7 @@ package com.baeldung.reactive.errorhandling;
import java.util.Map; import java.util.Map;
import org.springframework.boot.autoconfigure.web.ResourceProperties; import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler; import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.ErrorAttributes; import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
@ -37,7 +38,7 @@ public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHan
private Mono<ServerResponse> renderErrorResponse(final ServerRequest request) { private Mono<ServerResponse> renderErrorResponse(final ServerRequest request) {
final Map<String, Object> errorPropertiesMap = getErrorAttributes(request, false); final Map<String, Object> errorPropertiesMap = getErrorAttributes(request, ErrorAttributeOptions.defaults());
return ServerResponse.status(HttpStatus.BAD_REQUEST) return ServerResponse.status(HttpStatus.BAD_REQUEST)
.contentType(MediaType.APPLICATION_JSON_UTF8) .contentType(MediaType.APPLICATION_JSON_UTF8)

View File

@ -26,6 +26,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.h2database</groupId> <groupId>com.h2database</groupId>
<artifactId>h2</artifactId> <artifactId>h2</artifactId>

View File

@ -26,6 +26,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <artifactId>spring-boot-starter-data-jpa</artifactId>

View File

@ -20,6 +20,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId> <artifactId>spring-boot-starter-thymeleaf</artifactId>

View File

@ -23,6 +23,11 @@
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId> <artifactId>spring-boot-devtools</artifactId>

View File

@ -10,6 +10,7 @@ import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import springfox.bean.validators.plugins.Validators; import springfox.bean.validators.plugins.Validators;
import springfox.documentation.builders.StringElementFacetBuilder;
import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin; import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext; import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
@ -30,8 +31,9 @@ public class EmailAnnotationPlugin implements ModelPropertyBuilderPlugin {
public void apply(ModelPropertyContext context) { public void apply(ModelPropertyContext context) {
Optional<Email> email = annotationFromBean(context, Email.class); Optional<Email> email = annotationFromBean(context, Email.class);
if (email.isPresent()) { if (email.isPresent()) {
context.getBuilder().pattern(email.get().regexp()); context.getSpecificationBuilder().facetBuilder(StringElementFacetBuilder.class)
context.getBuilder().example("email@email.com"); .pattern(email.get().regexp());
context.getSpecificationBuilder().example("email@email.com");
} }
} }

View File

@ -27,6 +27,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId> <artifactId>spring-boot-starter-actuator</artifactId>

View File

@ -29,6 +29,11 @@
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId> <artifactId>spring-boot-starter-thymeleaf</artifactId>

View File

@ -24,6 +24,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <artifactId>spring-boot-starter-data-jpa</artifactId>

View File

@ -26,6 +26,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId> <artifactId>spring-boot-starter-tomcat</artifactId>

View File

@ -8,7 +8,7 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.rule.OutputCapture; import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext;
@ -29,7 +29,7 @@ public class LogbackMultiProfileTestLogLevelIntegrationTest {
private TestRestTemplate restTemplate; private TestRestTemplate restTemplate;
@Rule @Rule
public OutputCapture outputCapture = new OutputCapture(); public OutputCaptureRule outputCapture = new OutputCaptureRule();
private String baseUrl = "/testLogLevel"; private String baseUrl = "/testLogLevel";

View File

@ -8,7 +8,7 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.rule.OutputCapture; import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext;
@ -29,7 +29,7 @@ public class LogbackTestLogLevelIntegrationTest {
private TestRestTemplate restTemplate; private TestRestTemplate restTemplate;
@Rule @Rule
public OutputCapture outputCapture = new OutputCapture(); public OutputCaptureRule outputCapture = new OutputCaptureRule();
private String baseUrl = "/testLogLevel"; private String baseUrl = "/testLogLevel";

View File

@ -8,7 +8,7 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.rule.OutputCapture; import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext;
@ -29,7 +29,7 @@ public class TestLogLevelWithProfileIntegrationTest {
private TestRestTemplate restTemplate; private TestRestTemplate restTemplate;
@Rule @Rule
public OutputCapture outputCapture = new OutputCapture(); public OutputCaptureRule outputCapture = new OutputCaptureRule();
private String baseUrl = "/testLogLevel"; private String baseUrl = "/testLogLevel";

View File

@ -27,6 +27,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <artifactId>spring-boot-starter-data-jpa</artifactId>
@ -98,11 +102,6 @@
<artifactId>rome</artifactId> <artifactId>rome</artifactId>
<version>${rome.version}</version> <version>${rome.version}</version>
</dependency> </dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -60,6 +60,7 @@
</dependencyManagement> </dependencyManagement>
<properties> <properties>
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
<spring-cloud-dependencies.version>Hoxton.SR4</spring-cloud-dependencies.version> <spring-cloud-dependencies.version>Hoxton.SR4</spring-cloud-dependencies.version>
<postgresql.version>42.2.10</postgresql.version> <postgresql.version>42.2.10</postgresql.version>
<bytebuddy.version>1.10.10</bytebuddy.version> <bytebuddy.version>1.10.10</bytebuddy.version>

View File

@ -62,6 +62,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <artifactId>spring-boot-starter-data-jpa</artifactId>

View File

@ -24,6 +24,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId> <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>

View File

@ -69,7 +69,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.thymeleaf</groupId> <groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId> <artifactId>thymeleaf-spring5</artifactId>
<version>${org.thymeleaf-version}</version> <version>${org.thymeleaf-version}</version>
</dependency> </dependency>
@ -164,7 +164,7 @@
<hibernate-validator.version>6.0.10.Final</hibernate-validator.version> <hibernate-validator.version>6.0.10.Final</hibernate-validator.version>
<deploy-path>enter-location-of-server</deploy-path> <deploy-path>enter-location-of-server</deploy-path>
<commons-fileupload.version>1.3.2</commons-fileupload.version> <commons-fileupload.version>1.3.2</commons-fileupload.version>
<org.thymeleaf-version>3.0.7.RELEASE</org.thymeleaf-version> <org.thymeleaf-version>3.0.11.RELEASE</org.thymeleaf-version>
<groovy.version>2.4.12</groovy.version> <groovy.version>2.4.12</groovy.version>
<freemarker.version>2.3.27-incubating</freemarker.version> <freemarker.version>2.3.27-incubating</freemarker.version>
<jade.version>1.2.5</jade.version> <jade.version>1.2.5</jade.version>

View File

@ -11,8 +11,8 @@ import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
@Configuration @Configuration
@ComponentScan(basePackages = { "com.baeldung.spring.mail" }) @ComponentScan(basePackages = { "com.baeldung.spring.mail" })

View File

@ -4,9 +4,9 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.spring5.view.ThymeleafViewResolver;
@Configuration @Configuration
@EnableWebMvc @EnableWebMvc

View File

@ -19,7 +19,7 @@ import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.thymeleaf.context.Context; import org.thymeleaf.context.Context;
import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring5.SpringTemplateEngine;
import freemarker.template.Template; import freemarker.template.Template;
import freemarker.template.TemplateException; import freemarker.template.TemplateException;

View File

@ -21,6 +21,11 @@
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>

View File

@ -1,4 +1,4 @@
package com.baeldung.controller.optionalpathvars; package com.baeldung.optionalpathvars;
public class Article { public class Article {

View File

@ -1,6 +1,6 @@
package com.baeldung.controller.optionalpathvars; package com.baeldung.optionalpathvars;
import static com.baeldung.controller.optionalpathvars.Article.DEFAULT_ARTICLE; import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;

View File

@ -1,6 +1,6 @@
package com.baeldung.controller.optionalpathvars; package com.baeldung.optionalpathvars;
import static com.baeldung.controller.optionalpathvars.Article.DEFAULT_ARTICLE; import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE;
import java.util.Map; import java.util.Map;

View File

@ -1,6 +1,6 @@
package com.baeldung.controller.optionalpathvars; package com.baeldung.optionalpathvars;
import static com.baeldung.controller.optionalpathvars.Article.DEFAULT_ARTICLE; import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE;
import java.util.Optional; import java.util.Optional;

View File

@ -1,6 +1,6 @@
package com.baeldung.controller.optionalpathvars; package com.baeldung.optionalpathvars;
import static com.baeldung.controller.optionalpathvars.Article.DEFAULT_ARTICLE; import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;

View File

@ -1,6 +1,6 @@
package com.baeldung.controller.optionalpathvars; package com.baeldung.optionalpathvars;
import static com.baeldung.controller.optionalpathvars.Article.DEFAULT_ARTICLE; import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;

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