Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
4c0469fd61
|
@ -5,3 +5,4 @@ This module contains articles about AWS Lambda
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Using AWS Lambda with API Gateway](https://www.baeldung.com/aws-lambda-api-gateway)
|
- [Using AWS Lambda with API Gateway](https://www.baeldung.com/aws-lambda-api-gateway)
|
||||||
- [Introduction to AWS Serverless Application Model](https://www.baeldung.com/aws-serverless)
|
- [Introduction to AWS Serverless Application Model](https://www.baeldung.com/aws-serverless)
|
||||||
|
- [How to Implement Hibernate in an AWS Lambda Function in Java](https://www.baeldung.com/java-aws-lambda-hibernate)
|
||||||
|
|
|
@ -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>
|
|
@ -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>
|
</project>
|
||||||
<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>
|
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
.aws-sam/
|
|
@ -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>
|
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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
|
||||||
|
|
|
@ -0,0 +1,122 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project
|
||||||
|
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>core-groovy-strings</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<name>core-groovy-strings</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy</artifactId>
|
||||||
|
<version>${groovy.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy-all</artifactId>
|
||||||
|
<version>${groovy-all.version}</version>
|
||||||
|
<type>pom</type>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy-dateutil</artifactId>
|
||||||
|
<version>${groovy.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy-sql</artifactId>
|
||||||
|
<version>${groovy-sql.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-runner</artifactId>
|
||||||
|
<version>${junit.platform.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hsqldb</groupId>
|
||||||
|
<artifactId>hsqldb</artifactId>
|
||||||
|
<version>${hsqldb.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.spockframework</groupId>
|
||||||
|
<artifactId>spock-core</artifactId>
|
||||||
|
<version>${spock-core.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.gmavenplus</groupId>
|
||||||
|
<artifactId>gmavenplus-plugin</artifactId>
|
||||||
|
<version>${gmavenplus-plugin.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>addSources</goal>
|
||||||
|
<goal>addTestSources</goal>
|
||||||
|
<goal>compile</goal>
|
||||||
|
<goal>compileTests</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-failsafe-plugin</artifactId>
|
||||||
|
<version>${maven-failsafe-plugin.version}</version>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||||
|
<version>${junit.platform.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>junit5</id>
|
||||||
|
<goals>
|
||||||
|
<goal>integration-test</goal>
|
||||||
|
<goal>verify</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<includes>
|
||||||
|
<include>**/*Test5.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<repositories>
|
||||||
|
<repository>
|
||||||
|
<id>central</id>
|
||||||
|
<url>https://jcenter.bintray.com</url>
|
||||||
|
</repository>
|
||||||
|
</repositories>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<junit.platform.version>1.0.0</junit.platform.version>
|
||||||
|
<groovy.version>2.5.6</groovy.version>
|
||||||
|
<groovy-all.version>2.5.6</groovy-all.version>
|
||||||
|
<groovy-sql.version>2.5.6</groovy-sql.version>
|
||||||
|
<hsqldb.version>2.4.0</hsqldb.version>
|
||||||
|
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||||
|
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,70 @@
|
||||||
|
package com.baeldung.removeprefix
|
||||||
|
|
||||||
|
import org.junit.Assert
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class RemovePrefixTest {
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCasePrefixIsRemoved_thenReturnTrue() {
|
||||||
|
def trimPrefix = {
|
||||||
|
it.startsWith('Groovy-') ? it.minus('Groovy-') : it
|
||||||
|
}
|
||||||
|
|
||||||
|
def actual = trimPrefix("Groovy-Tutorials at Baeldung")
|
||||||
|
def expected = "Tutorials at Baeldung"
|
||||||
|
|
||||||
|
Assert.assertEquals(expected, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPrefixIsRemoved_thenReturnTrue() {
|
||||||
|
|
||||||
|
String prefix = "groovy-"
|
||||||
|
String trimPrefix = "Groovy-Tutorials at Baeldung"
|
||||||
|
def actual;
|
||||||
|
if(trimPrefix.startsWithIgnoreCase(prefix)) {
|
||||||
|
actual = trimPrefix.substring(prefix.length())
|
||||||
|
}
|
||||||
|
|
||||||
|
def expected = "Tutorials at Baeldung"
|
||||||
|
|
||||||
|
Assert.assertEquals(expected, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPrefixIsRemovedUsingRegex_thenReturnTrue() {
|
||||||
|
|
||||||
|
def regex = ~"^([Gg])roovy-"
|
||||||
|
String trimPrefix = "Groovy-Tutorials at Baeldung"
|
||||||
|
String actual = trimPrefix - regex
|
||||||
|
|
||||||
|
def expected = "Tutorials at Baeldung"
|
||||||
|
|
||||||
|
Assert.assertEquals(expected, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPrefixIsRemovedUsingReplaceFirst_thenReturnTrue() {
|
||||||
|
def regex = ~"^groovy"
|
||||||
|
String trimPrefix = "groovyTutorials at Baeldung's groovy page"
|
||||||
|
String actual = trimPrefix.replaceFirst(regex, "")
|
||||||
|
|
||||||
|
def expected = "Tutorials at Baeldung's groovy page"
|
||||||
|
|
||||||
|
Assert.assertEquals(expected, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPrefixIsRemovedUsingReplaceAll_thenReturnTrue() {
|
||||||
|
|
||||||
|
String trimPrefix = "groovyTutorials at Baeldung groovy"
|
||||||
|
String actual = trimPrefix.replaceAll(/^groovy/, "")
|
||||||
|
|
||||||
|
def expected = "Tutorials at Baeldung groovy"
|
||||||
|
|
||||||
|
Assert.assertEquals(expected, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -7,7 +7,7 @@ import junit.framework.TestSuite;
|
||||||
/**
|
/**
|
||||||
* Unit test for simple App.
|
* Unit test for simple App.
|
||||||
*/
|
*/
|
||||||
public class AppTest
|
public class AppUnitTest
|
||||||
extends TestCase
|
extends TestCase
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
|
@ -15,7 +15,7 @@ public class AppTest
|
||||||
*
|
*
|
||||||
* @param testName name of the test case
|
* @param testName name of the test case
|
||||||
*/
|
*/
|
||||||
public AppTest( String testName )
|
public AppUnitTest(String testName )
|
||||||
{
|
{
|
||||||
super( testName );
|
super( testName );
|
||||||
}
|
}
|
||||||
|
@ -25,7 +25,7 @@ public class AppTest
|
||||||
*/
|
*/
|
||||||
public static Test suite()
|
public static Test suite()
|
||||||
{
|
{
|
||||||
return new TestSuite( AppTest.class );
|
return new TestSuite( AppUnitTest.class );
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
|
@ -0,0 +1,8 @@
|
||||||
|
## Core Java 11
|
||||||
|
|
||||||
|
This module contains articles about Java 11 core features
|
||||||
|
|
||||||
|
### Relevant articles
|
||||||
|
- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional)
|
||||||
|
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
||||||
|
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
|
@ -0,0 +1,54 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project
|
||||||
|
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>core-java-11-2</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<name>core-java-11-2</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.google.guava</groupId>
|
||||||
|
<artifactId>guava</artifactId>
|
||||||
|
<version>${guava.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>${maven.compiler.source.version}</source>
|
||||||
|
<target>${maven.compiler.target.version}</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||||
|
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||||
|
<guava.version>29.0-jre</guava.version>
|
||||||
|
<assertj.version>3.17.2</assertj.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -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 {
|
||||||
|
|
|
@ -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;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
import java.lang.annotation.Annotation;
|
import java.lang.annotation.Annotation;
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
public interface Eating {
|
public interface Eating {
|
||||||
String eats();
|
String eats();
|
|
@ -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 {
|
||||||
|
|
|
@ -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;
|
|
@ -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;
|
|
@ -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 {
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
public interface Locomotion {
|
public interface Locomotion {
|
||||||
String getLocomotion();
|
String getLocomotion();
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.reflection;
|
package com.baeldung.reflection;
|
||||||
|
|
||||||
public class Operations {
|
public class Operations {
|
||||||
|
|
|
@ -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;
|
|
@ -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(
|
|
@ -7,7 +7,9 @@ import java.util.Optional;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class OptionalChainingUnitTest {
|
public class OptionalChainingUnitTest {
|
||||||
|
|
|
@ -9,7 +9,9 @@ import java.util.List;
|
||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class OptionalUnitTest {
|
public class OptionalUnitTest {
|
||||||
|
|
||||||
|
@ -262,6 +264,12 @@ public class OptionalUnitTest {
|
||||||
.orElseThrow(IllegalArgumentException::new);
|
.orElseThrow(IllegalArgumentException::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test(expected = NoSuchElementException.class)
|
||||||
|
public void whenNoArgOrElseThrowWorks_thenCorrect() {
|
||||||
|
String nullName = null;
|
||||||
|
String name = Optional.ofNullable(nullName).orElseThrow();
|
||||||
|
}
|
||||||
|
|
||||||
public String getMyDefault() {
|
public String getMyDefault() {
|
||||||
LOG.debug("Getting default value...");
|
LOG.debug("Getting default value...");
|
||||||
return "Default Value";
|
return "Default Value";
|
|
@ -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;
|
|
@ -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");
|
|
@ -107,7 +107,7 @@
|
||||||
<uberjar.name>benchmarks</uberjar.name>
|
<uberjar.name>benchmarks</uberjar.name>
|
||||||
<jmh.version>1.22</jmh.version>
|
<jmh.version>1.22</jmh.version>
|
||||||
<eclipse.collections.version>10.0.0</eclipse.collections.version>
|
<eclipse.collections.version>10.0.0</eclipse.collections.version>
|
||||||
<shade.plugin.version>10.0.0</shade.plugin.version>
|
<shade.plugin.version>3.2.4</shade.plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -5,7 +5,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class StringAPITest {
|
public class StringAPIUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPositiveArgument_thenReturnIndentedString() {
|
public void whenPositiveArgument_thenReturnIndentedString() {
|
|
@ -7,7 +7,7 @@ import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class PersonTest {
|
public class PersonUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSameNameAndAddress_whenEquals_thenPersonsEqual() {
|
public void givenSameNameAndAddress_whenEquals_thenPersonsEqual() {
|
|
@ -44,6 +44,16 @@
|
||||||
<artifactId>commons-collections4</artifactId>
|
<artifactId>commons-collections4</artifactId>
|
||||||
<version>${commons-collections4.version}</version>
|
<version>${commons-collections4.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>3.11</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-io</groupId>
|
||||||
|
<artifactId>commons-io</artifactId>
|
||||||
|
<version>2.7</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -77,6 +87,7 @@
|
||||||
<maven.compiler.target>1.9</maven.compiler.target>
|
<maven.compiler.target>1.9</maven.compiler.target>
|
||||||
<guava.version>25.1-jre</guava.version>
|
<guava.version>25.1-jre</guava.version>
|
||||||
<commons-collections4.version>4.1</commons-collections4.version>
|
<commons-collections4.version>4.1</commons-collections4.version>
|
||||||
|
<commons-collections3.version>3.2.2</commons-collections3.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -17,7 +17,7 @@ import org.junit.Test;
|
||||||
/**
|
/**
|
||||||
* Test case for the {@link MethodHandles} API
|
* Test case for the {@link MethodHandles} API
|
||||||
*/
|
*/
|
||||||
public class MethodHandlesTest {
|
public class MethodHandlesUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenConcatMethodHandle_whenInvoked_thenCorrectlyConcatenated() throws Throwable {
|
public void givenConcatMethodHandle_whenInvoked_thenCorrectlyConcatenated() throws Throwable {
|
|
@ -6,3 +6,4 @@ This module contains complete guides about arrays in Java
|
||||||
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
|
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
|
||||||
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
|
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
|
||||||
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
|
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
|
||||||
|
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
|
||||||
|
|
|
@ -0,0 +1,86 @@
|
||||||
|
package com.baeldung.collections.removeallperformance;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.RandomStringUtils;
|
||||||
|
import org.openjdk.jmh.annotations.Benchmark;
|
||||||
|
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||||
|
import org.openjdk.jmh.annotations.Level;
|
||||||
|
import org.openjdk.jmh.annotations.Mode;
|
||||||
|
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||||
|
import org.openjdk.jmh.annotations.Scope;
|
||||||
|
import org.openjdk.jmh.annotations.Setup;
|
||||||
|
import org.openjdk.jmh.annotations.State;
|
||||||
|
import org.openjdk.jmh.annotations.Warmup;
|
||||||
|
import org.openjdk.jmh.runner.Runner;
|
||||||
|
import org.openjdk.jmh.runner.options.Options;
|
||||||
|
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||||
|
|
||||||
|
import com.baeldung.collections.containsperformance.Employee;
|
||||||
|
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||||
|
@Warmup(iterations = 5)
|
||||||
|
public class HashSetBenchmark {
|
||||||
|
|
||||||
|
@State(Scope.Thread)
|
||||||
|
public static class MyState {
|
||||||
|
private Set<Employee> employeeSet1 = new HashSet<>();
|
||||||
|
private List<Employee> employeeList1 = new ArrayList<>();
|
||||||
|
private Set<Employee> employeeSet2 = new HashSet<>();
|
||||||
|
private List<Employee> employeeList2 = new ArrayList<>();
|
||||||
|
|
||||||
|
private long set1Size = 60000;
|
||||||
|
private long list1Size = 50000;
|
||||||
|
private long set2Size = 50000;
|
||||||
|
private long list2Size = 60000;
|
||||||
|
|
||||||
|
@Setup(Level.Trial)
|
||||||
|
public void setUp() {
|
||||||
|
|
||||||
|
for (long i = 0; i < set1Size; i++) {
|
||||||
|
employeeSet1.add(new Employee(i, RandomStringUtils.random(7, true, false)));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (long i = 0; i < list1Size; i++) {
|
||||||
|
employeeList1.add(new Employee(i, RandomStringUtils.random(7, true, false)));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (long i = 0; i < set2Size; i++) {
|
||||||
|
employeeSet2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (long i = 0; i < list2Size; i++) {
|
||||||
|
employeeList2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean given_SizeOfHashsetGreaterThanSizeOfCollection_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) {
|
||||||
|
return state.employeeSet1.removeAll(state.employeeList1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public boolean given_SizeOfHashsetSmallerThanSizeOfCollection_When_RemoveAllFromHashSet_Then_BadPerformance(MyState state) {
|
||||||
|
return state.employeeSet2.removeAll(state.employeeList2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Options options = new OptionsBuilder().include(HashSetBenchmark.class.getSimpleName())
|
||||||
|
.threads(1)
|
||||||
|
.forks(1)
|
||||||
|
.shouldFailOnError(true)
|
||||||
|
.shouldDoGC(true)
|
||||||
|
.jvmArgs("-server")
|
||||||
|
.build();
|
||||||
|
new Runner(options).run();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,33 @@
|
||||||
|
package com.baeldung.collections.hashset;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class HashSetUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenRemoveAllFromHashset_thenRemovesAllElementsFromHashsetThatArePresentInCollection() {
|
||||||
|
Set<Integer> set = new HashSet<>();
|
||||||
|
Collection<Integer> collection = new ArrayList<>();
|
||||||
|
set.add(1);
|
||||||
|
set.add(2);
|
||||||
|
set.add(3);
|
||||||
|
set.add(4);
|
||||||
|
collection.add(1);
|
||||||
|
collection.add(3);
|
||||||
|
|
||||||
|
set.removeAll(collection);
|
||||||
|
|
||||||
|
assertEquals(2, set.size());
|
||||||
|
Integer[] actualElements = new Integer[set.size()];
|
||||||
|
Integer[] expectedElements = new Integer[] { 2, 4 };
|
||||||
|
assertArrayEquals(expectedElements, set.toArray(actualElements));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,146 @@
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,6 +1,8 @@
|
||||||
package com.baeldung.date;
|
package com.baeldung.date;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import org.joda.time.Days;
|
||||||
|
import org.joda.time.Minutes;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.text.ParseException;
|
import java.text.ParseException;
|
||||||
import java.text.SimpleDateFormat;
|
import java.text.SimpleDateFormat;
|
||||||
|
@ -16,7 +18,7 @@ import java.util.Locale;
|
||||||
import java.util.TimeZone;
|
import java.util.TimeZone;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import org.junit.Test;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class DateDiffUnitTest {
|
public class DateDiffUnitTest {
|
||||||
|
|
||||||
|
@ -29,18 +31,39 @@ public class DateDiffUnitTest {
|
||||||
long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
|
long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
|
||||||
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
|
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() {
|
public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenWorks() {
|
||||||
LocalDate now = LocalDate.now();
|
LocalDate aDate = LocalDate.of(2020, 9, 11);
|
||||||
LocalDate sixDaysBehind = now.minusDays(6);
|
LocalDate sixDaysBehind = aDate.minusDays(6);
|
||||||
|
|
||||||
Period period = Period.between(now, sixDaysBehind);
|
Period period = Period.between(aDate, sixDaysBehind);
|
||||||
int diff = Math.abs(period.getDays());
|
int diff = Math.abs(period.getDays());
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenDoesNotWork() {
|
||||||
|
LocalDate aDate = LocalDate.of(2020, 9, 11);
|
||||||
|
LocalDate sixtyDaysBehind = aDate.minusDays(60);
|
||||||
|
Period period = Period.between(aDate, sixtyDaysBehind);
|
||||||
|
int diff = Math.abs(period.getDays());
|
||||||
|
//not equals
|
||||||
|
assertNotEquals(60, diff);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoDatesInJava8_whenUsingPeriod_thenWeGet0Year1Month29Days() {
|
||||||
|
LocalDate aDate = LocalDate.of(2020, 9, 11);
|
||||||
|
LocalDate sixtyDaysBehind = aDate.minusDays(60);
|
||||||
|
Period period = Period.between(aDate, sixtyDaysBehind);
|
||||||
|
int years = Math.abs(period.getYears());
|
||||||
|
int months = Math.abs(period.getMonths());
|
||||||
|
int days = Math.abs(period.getDays());
|
||||||
|
assertArrayEquals(new int[] { 0, 1, 29 }, new int[] { years, months, days });
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -51,7 +74,7 @@ public class DateDiffUnitTest {
|
||||||
Duration duration = Duration.between(now, sixMinutesBehind);
|
Duration duration = Duration.between(now, sixMinutesBehind);
|
||||||
long diff = Math.abs(duration.toMinutes());
|
long diff = Math.abs(duration.toMinutes());
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -61,7 +84,7 @@ public class DateDiffUnitTest {
|
||||||
|
|
||||||
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
|
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
|
||||||
|
|
||||||
assertEquals(diff, 10);
|
assertEquals(10, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -69,9 +92,9 @@ public class DateDiffUnitTest {
|
||||||
LocalDateTime ldt = LocalDateTime.now();
|
LocalDateTime ldt = LocalDateTime.now();
|
||||||
ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal"));
|
ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal"));
|
||||||
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore"))
|
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore"))
|
||||||
.minusDays(6);
|
.minusDays(6);
|
||||||
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
|
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -81,7 +104,7 @@ public class DateDiffUnitTest {
|
||||||
|
|
||||||
long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS);
|
long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS);
|
||||||
|
|
||||||
assertEquals(diff, 10);
|
assertEquals(10, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -89,10 +112,9 @@ public class DateDiffUnitTest {
|
||||||
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
|
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
|
||||||
org.joda.time.LocalDate sixDaysBehind = now.minusDays(6);
|
org.joda.time.LocalDate sixDaysBehind = now.minusDays(6);
|
||||||
|
|
||||||
org.joda.time.Period period = new org.joda.time.Period(now, sixDaysBehind);
|
long diff = Math.abs(Days.daysBetween(now, sixDaysBehind).getDays());
|
||||||
long diff = Math.abs(period.getDays());
|
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -100,8 +122,9 @@ public class DateDiffUnitTest {
|
||||||
org.joda.time.LocalDateTime now = org.joda.time.LocalDateTime.now();
|
org.joda.time.LocalDateTime now = org.joda.time.LocalDateTime.now();
|
||||||
org.joda.time.LocalDateTime sixMinutesBehind = now.minusMinutes(6);
|
org.joda.time.LocalDateTime sixMinutesBehind = now.minusMinutes(6);
|
||||||
|
|
||||||
org.joda.time.Period period = new org.joda.time.Period(now, sixMinutesBehind);
|
long diff = Math.abs(Minutes.minutesBetween(now, sixMinutesBehind).getMinutes());
|
||||||
long diff = Math.abs(period.getDays());
|
assertEquals(6, diff);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -111,6 +134,6 @@ public class DateDiffUnitTest {
|
||||||
|
|
||||||
long diff = Math.abs(now.numDaysFrom(sixDaysBehind));
|
long diff = Math.abs(now.numDaysFrom(sixDaysBehind));
|
||||||
|
|
||||||
assertEquals(diff, 6);
|
assertEquals(6, diff);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,7 +6,7 @@ import org.junit.jupiter.api.Test;
|
||||||
import java.sql.Timestamp;
|
import java.sql.Timestamp;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
|
|
||||||
public class TimestampToStringConverterTest {
|
public class TimestampToStringConverterUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDatePattern_whenFormatting_thenResultingStringIsCorrect() {
|
public void givenDatePattern_whenFormatting_thenResultingStringIsCorrect() {
|
|
@ -1,3 +1,5 @@
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
|
|
||||||
- [NoSuchMethodError in Java](https://www.baeldung.com/java-nosuchmethod-error)
|
- [NoSuchMethodError in Java](https://www.baeldung.com/java-nosuchmethod-error)
|
||||||
|
- [IllegalArgumentException or NullPointerException for a Null Parameter?](https://www.baeldung.com/java-illegalargumentexception-or-nullpointerexception)
|
||||||
|
- [IllegalMonitorStateException in Java](https://www.baeldung.com/java-illegalmonitorstateexception)
|
||||||
|
|
|
@ -9,4 +9,6 @@ This module contains articles about core Java input and output (IO)
|
||||||
- [Check If a File or Directory Exists in Java](https://www.baeldung.com/java-file-directory-exists)
|
- [Check If a File or Directory Exists in Java](https://www.baeldung.com/java-file-directory-exists)
|
||||||
- [Copy a Directory in Java](https://www.baeldung.com/java-copy-directory)
|
- [Copy a Directory in Java](https://www.baeldung.com/java-copy-directory)
|
||||||
- [Java Files Open Options](https://www.baeldung.com/java-file-options)
|
- [Java Files Open Options](https://www.baeldung.com/java-file-options)
|
||||||
|
- [Creating Temporary Directories in Java](https://www.baeldung.com/java-temp-directories)
|
||||||
|
- [Reading a Line at a Given Line Number From a File in Java](https://www.baeldung.com/java-read-line-at-number)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-io-2)
|
- [[<-- Prev]](/core-java-modules/core-java-io-2)
|
||||||
|
|
|
@ -4,6 +4,7 @@ import org.junit.Test;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
import java.nio.file.DirectoryStream;
|
import java.nio.file.DirectoryStream;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
@ -20,8 +21,8 @@ public class DirectoryEmptinessUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException {
|
public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException, URISyntaxException {
|
||||||
Path aFile = Paths.get(getClass().getResource("/notDir.txt").getPath());
|
Path aFile = Paths.get(getClass().getResource("/notDir.txt").toURI());
|
||||||
assertThat(isEmpty(aFile)).isFalse();
|
assertThat(isEmpty(aFile)).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -4,10 +4,7 @@ import org.junit.Test;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.*;
|
||||||
import java.nio.file.LinkOption;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.util.concurrent.ThreadLocalRandom;
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
||||||
|
@ -47,8 +44,18 @@ public class ExistenceUnitTest {
|
||||||
public void givenSymbolicLink_whenTargetDoesNotExists_thenFollowOrNotBasedOnTheOptions() throws IOException {
|
public void givenSymbolicLink_whenTargetDoesNotExists_thenFollowOrNotBasedOnTheOptions() throws IOException {
|
||||||
Path target = Files.createTempFile("baeldung", "target");
|
Path target = Files.createTempFile("baeldung", "target");
|
||||||
Path symbol = Paths.get("test-link-" + ThreadLocalRandom.current().nextInt());
|
Path symbol = Paths.get("test-link-" + ThreadLocalRandom.current().nextInt());
|
||||||
|
Path symbolicLink = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
symbolicLink = Files.createSymbolicLink(symbol, target);
|
||||||
|
} catch (FileSystemException ex) {
|
||||||
|
System.out.println("Your OS security policy prevents the current user from creating symbolic links.\n" +
|
||||||
|
"Most probably you're running Windows with UAC.\n" +
|
||||||
|
"If this is the case, please see - https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/create-symbolic-links\n" +
|
||||||
|
"You must change your security settings to run this test under Windows.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
Path symbolicLink = Files.createSymbolicLink(symbol, target);
|
|
||||||
assertTrue(Files.exists(symbolicLink));
|
assertTrue(Files.exists(symbolicLink));
|
||||||
assertTrue(Files.isSymbolicLink(symbolicLink));
|
assertTrue(Files.isSymbolicLink(symbolicLink));
|
||||||
assertFalse(Files.isSymbolicLink(target));
|
assertFalse(Files.isSymbolicLink(target));
|
||||||
|
|
|
@ -4,6 +4,7 @@ import org.apache.commons.io.FileUtils;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.nio.file.FileSystems;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
|
@ -66,10 +67,16 @@ public class TemporaryDirectoriesUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTempDirWithPrefixWithFileAttrs_whenCreatePlainJava_thenAttributesAreSet() throws IOException {
|
public void givenTempDirWithPrefixWithFileAttrs_whenCreatePlainJava_thenAttributesAreSet() throws IOException {
|
||||||
final FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r--------"));
|
boolean isPosix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
|
||||||
|
|
||||||
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix", attrs);
|
if(!isPosix){
|
||||||
assertThat(tmpdir.toFile().getPath()).startsWith("target");
|
System.out.println("You must be under a Posix Compliant Filesystem to run this test.");
|
||||||
assertThat(tmpdir.toFile().canWrite()).isFalse();
|
} else {
|
||||||
|
final FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r--------"));
|
||||||
|
|
||||||
|
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix", attrs);
|
||||||
|
assertThat(tmpdir.toFile().getPath()).startsWith("target");
|
||||||
|
assertThat(tmpdir.toFile().canWrite()).isFalse();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,7 +17,7 @@
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.baeldung.servicemodule</groupId>
|
<groupId>com.baeldung.servicemodule</groupId>
|
||||||
<artifactId>servicemodule</artifactId>
|
<artifactId>servicemodule1</artifactId>
|
||||||
<version>${servicemodule.version}</version>
|
<version>${servicemodule.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
|
@ -4,7 +4,8 @@
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
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>servicemodule</artifactId>
|
<groupId>com.baeldung.servicemodule</groupId>
|
||||||
|
<artifactId>servicemodule1</artifactId>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
|
|
|
@ -17,7 +17,7 @@
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.baeldung.servicemodule</groupId>
|
<groupId>com.baeldung.servicemodule</groupId>
|
||||||
<artifactId>servicemodule</artifactId>
|
<artifactId>servicemodule2</artifactId>
|
||||||
<version>${servicemodule.version}</version>
|
<version>${servicemodule.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
|
@ -4,7 +4,8 @@
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
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>servicemodule</artifactId>
|
<groupId>com.baeldung.servicemodule</groupId>
|
||||||
|
<artifactId>servicemodule2</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0</version>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
|
|
|
@ -5,4 +5,5 @@ This module contains articles about core features in the Java language
|
||||||
- [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom)
|
- [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom)
|
||||||
- [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean)
|
- [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean)
|
||||||
- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
|
- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
|
||||||
|
- [Checking if a Class Exists in Java](https://www.baeldung.com/java-check-class-exists)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-lang-2)
|
- [[<-- Prev]](/core-java-modules/core-java-lang-2)
|
||||||
|
|
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
|
@ -13,4 +13,5 @@
|
||||||
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
|
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
|
||||||
- [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging)
|
- [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging)
|
||||||
- [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication)
|
- [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication)
|
||||||
|
- [Largest Power of 2 That Is Less Than the Given Number](https://www.baeldung.com/java-largest-power-of-2-less-than-number)
|
||||||
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math)
|
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math)
|
||||||
|
|
|
@ -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>
|
||||||
|
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -4,7 +4,6 @@ This module contains articles about Java Optional.
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Java Optional as Return Type](https://www.baeldung.com/java-optional-return)
|
- [Java Optional as Return Type](https://www.baeldung.com/java-optional-return)
|
||||||
- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional)
|
|
||||||
- [Java Optional – orElse() vs orElseGet()](https://www.baeldung.com/java-optional-or-else-vs-or-else-get)
|
- [Java Optional – orElse() vs orElseGet()](https://www.baeldung.com/java-optional-or-else-vs-or-else-get)
|
||||||
- [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional)
|
- [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional)
|
||||||
- [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)
|
- [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)
|
||||||
|
|
|
@ -4,7 +4,7 @@ import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class CurrentDirectoryFetcherTest {
|
public class CurrentDirectoryFetcherUnitTest {
|
||||||
|
|
||||||
private static final String CURRENT_DIR = "core-java-os";
|
private static final String CURRENT_DIR = "core-java-os";
|
||||||
|
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.reflection.check.staticmethods;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalTime;
|
||||||
|
|
||||||
|
public class StaticUtility {
|
||||||
|
|
||||||
|
public static String getAuthorName() {
|
||||||
|
return "Umang Budhwar";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalDate getLocalDate() {
|
||||||
|
return LocalDate.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalTime getLocalTime() {
|
||||||
|
return LocalTime.now();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.reflection.check.staticmethods;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.lang.reflect.Modifier;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Assertions;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class StaticUtilityUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCheckStaticMethod_ThenSuccess() throws Exception {
|
||||||
|
Method method = StaticUtility.class.getMethod("getAuthorName", null);
|
||||||
|
Assertions.assertTrue(Modifier.isStatic(method.getModifiers()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCheckAllStaticMethods_thenSuccess() {
|
||||||
|
List<Method> methodList = Arrays.asList(StaticUtility.class.getMethods())
|
||||||
|
.stream()
|
||||||
|
.filter(method -> Modifier.isStatic(method.getModifiers()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
Assertions.assertEquals(3, methodList.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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)
|
|
@ -0,0 +1,35 @@
|
||||||
|
package com.baeldung.cipher;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.security.Provider;
|
||||||
|
import java.security.Security;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
public class AvailableCiphersUnitTest {
|
||||||
|
private final Logger logger = LoggerFactory.getLogger(AvailableCiphersUnitTest.class);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetServices_thenGetAllCipherAlgorithms() {
|
||||||
|
for (Provider provider : Security.getProviders()) {
|
||||||
|
for (Provider.Service service : provider.getServices()) {
|
||||||
|
logger.info(service.getAlgorithm());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGetServicesWithFilter_thenGetAllCompatibleCipherAlgorithms() {
|
||||||
|
List<String> algorithms = Arrays.stream(Security.getProviders())
|
||||||
|
.flatMap(provider -> provider.getServices().stream())
|
||||||
|
.filter(service -> "Cipher".equals(service.getType()))
|
||||||
|
.map(Provider.Service::getAlgorithm)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
algorithms.forEach(logger::info);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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 8’s 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)
|
||||||
|
|
|
@ -20,6 +20,10 @@
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<source>${maven.compiler.source}</source>
|
||||||
|
<target>${maven.compiler.target}</target>
|
||||||
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
|
@ -20,6 +20,10 @@
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<source>${maven.compiler.source}</source>
|
||||||
|
<target>${maven.compiler.target}</target>
|
||||||
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
|
@ -38,6 +38,10 @@
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<source>${maven.compiler.source}</source>
|
||||||
|
<target>${maven.compiler.target}</target>
|
||||||
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
|
@ -33,6 +33,10 @@
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<source>${maven.compiler.source}</source>
|
||||||
|
<target>${maven.compiler.target}</target>
|
||||||
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
|
@ -18,20 +18,9 @@
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
<module>core-java</module>
|
<module>core-java</module>
|
||||||
<!-- <module>core-java-10</module> --> <!-- We haven't upgraded to java 10. Fixing in BAEL-10841 -->
|
|
||||||
<!-- <module>core-java-11</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
|
|
||||||
<!-- <module>core-java-12</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
|
|
||||||
<!-- <module>core-java-13</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
|
|
||||||
<!-- <module>core-java-14</module> --> <!-- We haven't upgraded to java 14.-->
|
|
||||||
<module>core-java-8</module>
|
<module>core-java-8</module>
|
||||||
<module>core-java-8-2</module>
|
<module>core-java-8-2</module>
|
||||||
|
|
||||||
<!-- <module>core-java-9</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
|
||||||
<!-- <module>core-java-9-improvements</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
|
||||||
<!-- <module>core-java-9-jigsaw</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
|
||||||
<!-- <module>core-java-9-new-features</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
|
||||||
<!-- <module>core-java-9-streams</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
|
||||||
|
|
||||||
<module>core-java-annotations</module>
|
<module>core-java-annotations</module>
|
||||||
|
|
||||||
<module>core-java-arrays-sorting</module>
|
<module>core-java-arrays-sorting</module>
|
||||||
|
@ -51,7 +40,6 @@
|
||||||
<module>core-java-collections-maps</module>
|
<module>core-java-collections-maps</module>
|
||||||
<module>core-java-collections-maps-2</module>
|
<module>core-java-collections-maps-2</module>
|
||||||
<module>core-java-collections-maps-3</module>
|
<module>core-java-collections-maps-3</module>
|
||||||
<!-- <module>core-java-collections-set</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
|
|
||||||
|
|
||||||
<module>core-java-concurrency-2</module>
|
<module>core-java-concurrency-2</module>
|
||||||
<module>core-java-concurrency-advanced</module>
|
<module>core-java-concurrency-advanced</module>
|
||||||
|
@ -65,10 +53,7 @@
|
||||||
|
|
||||||
<!--<module>core-java-8-datetime</module>--> <!-- unit test case failure -->
|
<!--<module>core-java-8-datetime</module>--> <!-- unit test case failure -->
|
||||||
<module>core-java-8-datetime-2</module>
|
<module>core-java-8-datetime-2</module>
|
||||||
<!-- <module>core-java-date-operations-1</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
|
||||||
<module>core-java-date-operations-2</module>
|
<module>core-java-date-operations-2</module>
|
||||||
<!-- We haven't upgraded to java 9. -->
|
|
||||||
<!-- <module>core-java-datetime-computations</module> <module>core-java-datetime-conversion</module> <module>core-java-datetime-java8</module> <module>core-java-datetime-string</module> -->
|
|
||||||
<module>core-java-8-datetime</module>
|
<module>core-java-8-datetime</module>
|
||||||
|
|
||||||
<module>core-java-exceptions</module>
|
<module>core-java-exceptions</module>
|
||||||
|
@ -85,7 +70,6 @@
|
||||||
|
|
||||||
<module>core-java-jar</module>
|
<module>core-java-jar</module>
|
||||||
<module>core-java-jndi</module>
|
<module>core-java-jndi</module>
|
||||||
<!-- <module>core-java-jpms</module> --> <!-- We haven't upgraded to java 10. Fixing in BAEL-10841 -->
|
|
||||||
<module>core-java-jvm</module>
|
<module>core-java-jvm</module>
|
||||||
<module>core-java-jvm-2</module>
|
<module>core-java-jvm-2</module>
|
||||||
|
|
||||||
|
@ -113,7 +97,6 @@
|
||||||
<module>core-java-nio-2</module>
|
<module>core-java-nio-2</module>
|
||||||
|
|
||||||
<module>core-java-optional</module>
|
<module>core-java-optional</module>
|
||||||
<!--<module>core-java-os</module> --> <!-- We haven't upgraded to java 9. -->
|
|
||||||
|
|
||||||
<module>core-java-perf</module>
|
<module>core-java-perf</module>
|
||||||
|
|
||||||
|
@ -138,9 +121,6 @@
|
||||||
<module>core-java-sun</module>
|
<module>core-java-sun</module>
|
||||||
|
|
||||||
<module>core-java-regex</module>
|
<module>core-java-regex</module>
|
||||||
<!-- <module>core-java-time-measurements</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
|
||||||
|
|
||||||
<!-- <module>multimodulemavenproject</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
|
||||||
<module>pre-jpms</module>
|
<module>pre-jpms</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
|
|
|
@ -2,6 +2,6 @@
|
||||||
|
|
||||||
This module contains articles about core Kotlin collections.
|
This module contains articles about core Kotlin collections.
|
||||||
|
|
||||||
### Relevant articles:
|
## Relevant articles:
|
||||||
|
|
||||||
|
|
||||||
|
- [Aggregate Operations in Kotlin](https://www.baeldung.com/kotlin/aggregate-operations)
|
||||||
|
|
|
@ -22,6 +22,30 @@ fun main() {
|
||||||
numbers.each { println(random * it) } // capturing the random variable
|
numbers.each { println(random * it) } // capturing the random variable
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun namedFunction(): Int {
|
||||||
|
return 42
|
||||||
|
}
|
||||||
|
|
||||||
|
fun anonymous(): () -> Int {
|
||||||
|
return fun(): Int {
|
||||||
|
return 42
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline fun <T> List<T>.eachIndexed(f: (Int, T) -> Unit) {
|
||||||
|
for (i in indices) {
|
||||||
|
f(i, this[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun <T> List<T>.indexOf(x: T): Int {
|
||||||
|
eachIndexed { index, value ->
|
||||||
|
if (value == x) return index
|
||||||
|
}
|
||||||
|
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generates a random number.
|
* Generates a random number.
|
||||||
*/
|
*/
|
||||||
|
|
|
@ -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>
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
## Relevant Articles:
|
||||||
|
|
||||||
|
- [Passing Command Line Arguments in Gradle](https://www.baeldung.com/gradle-command-line-arguments)
|
|
@ -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()
|
||||||
|
}
|
|
@ -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 + "]");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,4 +1,5 @@
|
||||||
rootProject.name='gradle-5-articles'
|
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'
|
|
@ -0,0 +1,3 @@
|
||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [Gradle Source Sets](https://www.baeldung.com/gradle-source-sets)
|
|
@ -1,8 +1,8 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project
|
<project
|
||||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
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>hazelcast</artifactId>
|
<artifactId>hazelcast</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
@ -15,7 +15,6 @@
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<!-- Hazelcast Jet -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.hazelcast.jet</groupId>
|
<groupId>com.hazelcast.jet</groupId>
|
||||||
<artifactId>hazelcast-jet</artifactId>
|
<artifactId>hazelcast-jet</artifactId>
|
||||||
|
@ -34,8 +33,7 @@
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- hazelcast jet -->
|
<hazelcast.jet.version>4.2</hazelcast.jet.version>
|
||||||
<hazelcast.jet.version>0.6</hazelcast.jet.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -1,24 +1,20 @@
|
||||||
package com.baeldung.hazelcast.cluster;
|
package com.baeldung.hazelcast.cluster;
|
||||||
|
|
||||||
import java.util.Map.Entry;
|
|
||||||
|
|
||||||
import com.hazelcast.client.HazelcastClient;
|
import com.hazelcast.client.HazelcastClient;
|
||||||
import com.hazelcast.client.config.ClientConfig;
|
import com.hazelcast.client.config.ClientConfig;
|
||||||
import com.hazelcast.config.GroupConfig;
|
|
||||||
import com.hazelcast.core.HazelcastInstance;
|
import com.hazelcast.core.HazelcastInstance;
|
||||||
import com.hazelcast.core.IMap;
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
public class NativeClient {
|
public class NativeClient {
|
||||||
|
|
||||||
public static void main(String[] args) throws InterruptedException {
|
public static void main(String[] args) {
|
||||||
ClientConfig config = new ClientConfig();
|
ClientConfig config = new ClientConfig();
|
||||||
GroupConfig groupConfig = config.getGroupConfig();
|
config.setClusterName("dev");
|
||||||
groupConfig.setName("dev");
|
|
||||||
groupConfig.setPassword("dev-pass");
|
|
||||||
HazelcastInstance hazelcastInstanceClient = HazelcastClient.newHazelcastClient(config);
|
HazelcastInstance hazelcastInstanceClient = HazelcastClient.newHazelcastClient(config);
|
||||||
IMap<Long, String> map = hazelcastInstanceClient.getMap("data");
|
Map<Long, String> map = hazelcastInstanceClient.getMap("data");
|
||||||
for (Entry<Long, String> entry : map.entrySet()) {
|
for (Map.Entry<Long, String> entry : map.entrySet()) {
|
||||||
System.out.println(String.format("Key: %d, Value: %s", entry.getKey(), entry.getValue()));
|
System.out.printf("Key: %d, Value: %s%n", entry.getKey(), entry.getValue());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,19 +1,19 @@
|
||||||
package com.baeldung.hazelcast.cluster;
|
package com.baeldung.hazelcast.cluster;
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import com.hazelcast.core.Hazelcast;
|
import com.hazelcast.core.Hazelcast;
|
||||||
import com.hazelcast.core.HazelcastInstance;
|
import com.hazelcast.core.HazelcastInstance;
|
||||||
import com.hazelcast.core.IdGenerator;
|
import com.hazelcast.flakeidgen.FlakeIdGenerator;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
public class ServerNode {
|
public class ServerNode {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
|
HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
|
||||||
Map<Long, String> map = hazelcastInstance.getMap("data");
|
Map<Long, String> map = hazelcastInstance.getMap("data");
|
||||||
IdGenerator idGenerator = hazelcastInstance.getIdGenerator("newid");
|
FlakeIdGenerator idGenerator = hazelcastInstance.getFlakeIdGenerator("newid");
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
map.put(idGenerator.newId(), "message" + 1);
|
map.put(idGenerator.newId(), "message" + i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,33 +1,31 @@
|
||||||
package com.baeldung.hazelcast.jet;
|
package com.baeldung.hazelcast.jet;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import static com.hazelcast.jet.Traversers.traverseArray;
|
|
||||||
import static com.hazelcast.jet.aggregate.AggregateOperations.counting;
|
|
||||||
import static com.hazelcast.jet.function.DistributedFunctions.wholeItem;
|
|
||||||
|
|
||||||
import com.hazelcast.jet.Jet;
|
import com.hazelcast.jet.Jet;
|
||||||
import com.hazelcast.jet.JetInstance;
|
import com.hazelcast.jet.JetInstance;
|
||||||
import com.hazelcast.jet.pipeline.Pipeline;
|
import com.hazelcast.jet.pipeline.Pipeline;
|
||||||
import com.hazelcast.jet.pipeline.Sinks;
|
import com.hazelcast.jet.pipeline.Sinks;
|
||||||
import com.hazelcast.jet.pipeline.Sources;
|
import com.hazelcast.jet.pipeline.Sources;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static com.hazelcast.function.Functions.wholeItem;
|
||||||
|
import static com.hazelcast.jet.Traversers.traverseArray;
|
||||||
|
import static com.hazelcast.jet.aggregate.AggregateOperations.counting;
|
||||||
|
|
||||||
public class WordCounter {
|
public class WordCounter {
|
||||||
|
|
||||||
private static final String LIST_NAME = "textList";
|
private static final String LIST_NAME = "textList";
|
||||||
|
|
||||||
private static final String MAP_NAME = "countMap";
|
private static final String MAP_NAME = "countMap";
|
||||||
|
|
||||||
private Pipeline createPipeLine() {
|
private Pipeline createPipeLine() {
|
||||||
Pipeline p = Pipeline.create();
|
Pipeline p = Pipeline.create();
|
||||||
p.drawFrom(Sources.<String> list(LIST_NAME))
|
p.readFrom(Sources.<String>list(LIST_NAME))
|
||||||
.flatMap(word -> traverseArray(word.toLowerCase()
|
.flatMap(word -> traverseArray(word.toLowerCase().split("\\W+")))
|
||||||
.split("\\W+")))
|
|
||||||
.filter(word -> !word.isEmpty())
|
.filter(word -> !word.isEmpty())
|
||||||
.groupingKey(wholeItem())
|
.groupingKey(wholeItem())
|
||||||
.aggregate(counting())
|
.aggregate(counting())
|
||||||
.drainTo(Sinks.map(MAP_NAME));
|
.writeTo(Sinks.map(MAP_NAME));
|
||||||
return p;
|
return p;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -38,8 +36,7 @@ public class WordCounter {
|
||||||
List<String> textList = jet.getList(LIST_NAME);
|
List<String> textList = jet.getList(LIST_NAME);
|
||||||
textList.addAll(sentences);
|
textList.addAll(sentences);
|
||||||
Pipeline p = createPipeLine();
|
Pipeline p = createPipeLine();
|
||||||
jet.newJob(p)
|
jet.newJob(p).join();
|
||||||
.join();
|
|
||||||
Map<String, Long> counts = jet.getMap(MAP_NAME);
|
Map<String, Long> counts = jet.getMap(MAP_NAME);
|
||||||
count = counts.get(word);
|
count = counts.get(word);
|
||||||
} finally {
|
} finally {
|
||||||
|
|
|
@ -1,16 +1,16 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<hazelcast xsi:schemaLocation="http://www.hazelcast.com/schema/config hazelcast-config-3.7.xsd"
|
<hazelcast xmlns="http://www.hazelcast.com/schema/config"
|
||||||
xmlns="http://www.hazelcast.com/schema/config"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
xsi:schemaLocation="http://www.hazelcast.com/schema/config
|
||||||
|
http://www.hazelcast.com/schema/config/hazelcast-config-4.0.xsd">
|
||||||
<network>
|
<network>
|
||||||
<port auto-increment="true" port-count="20">5701</port>
|
<port auto-increment="true" port-count="20">5701</port>
|
||||||
<join>
|
<join>
|
||||||
<multicast enabled="false">
|
<multicast enabled="false"/>
|
||||||
</multicast>
|
<tcp-ip enabled="true">
|
||||||
<tcp-ip enabled="true">
|
<member>machine1</member>
|
||||||
<member>machine1</member>
|
<member>localhost</member>
|
||||||
<member>localhost</member>
|
</tcp-ip>
|
||||||
</tcp-ip>
|
|
||||||
</join>
|
</join>
|
||||||
</network>
|
</network>
|
||||||
</hazelcast>
|
</hazelcast>
|
|
@ -1,11 +1,11 @@
|
||||||
package com.baeldung.hazelcast.jet;
|
package com.baeldung.hazelcast.jet;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.Test;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
public class WordCounterUnitTest {
|
public class WordCounterUnitTest {
|
||||||
|
|
||||||
|
@ -15,7 +15,7 @@ public class WordCounterUnitTest {
|
||||||
sentences.add("The first second was alright, but the second second was tough.");
|
sentences.add("The first second was alright, but the second second was tough.");
|
||||||
WordCounter wordCounter = new WordCounter();
|
WordCounter wordCounter = new WordCounter();
|
||||||
long countSecond = wordCounter.countWord(sentences, "second");
|
long countSecond = wordCounter.countWord(sentences, "second");
|
||||||
assertTrue(countSecond == 3);
|
assertEquals(3, countSecond);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue