Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Tarun Jain 2020-09-12 20:36:48 +05:30
commit 72253d4f17
520 changed files with 5952 additions and 3780 deletions

5
.gitignore vendored
View File

@ -87,4 +87,7 @@ transaction.log
apache-cxf/cxf-aegis/baeldung.xml
testing-modules/report-*.json
libraries-2/*.db
libraries-2/*.db
# SDKMan
.sdkmanrc

View File

@ -74,6 +74,7 @@
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>package</phase>

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

@ -0,0 +1,100 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>aws-lambda-examples</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>aws-lambda-examples</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-dynamodb</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-core</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>${aws-lambda-java-core.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>${aws-lambda-java-events.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>${json-simple.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<json-simple.version>1.1.1</json-simple.version>
<commons-io.version>2.5</commons-io.version>
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
<gson.version>2.8.2</gson.version>
<aws-java-sdk.version>1.11.241</aws-java-sdk.version>
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
</properties>
</project>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,8 +1,8 @@
<?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">
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>cdi</artifactId>
<version>1.0-SNAPSHOT</version>
@ -10,9 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-spring-4</artifactId>
<artifactId>parent-spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring-4</relativePath>
<relativePath>../parent-spring-5</relativePath>
</parent>
<dependencies>
@ -26,28 +26,22 @@
<artifactId>weld-se-core</artifactId>
<version>${weld-se-core.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
@ -61,7 +55,6 @@
<weld-se-core.version>3.0.5.Final</weld-se-core.version>
<aspectjweaver.version>1.9.2</aspectjweaver.version>
<assertj-core.version>3.10.0</assertj-core.version>
<spring.version>5.1.2.RELEASE</spring.version>
</properties>
</project>

View File

@ -10,5 +10,6 @@ public class CopyListServiceUnitTest {
@Test(expected = UnsupportedOperationException.class)
public void whenModifyCopyOfList_thenThrowsException() {
List<Integer> copyList = List.copyOf(Arrays.asList(1, 2, 3, 4));
copyList.add(4);
}
}

View File

@ -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 8s Collectors](https://www.baeldung.com/java-8-collectors)

View File

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

View File

@ -1,18 +1,11 @@
package com.baeldung.streams.collectors;
package com.baeldung.collectors;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.junit.Test;
import java.util.Arrays;
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.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
@ -20,19 +13,7 @@ import java.util.function.Supplier;
import java.util.stream.Collector;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.stream.Collectors.averagingDouble;
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 java.util.stream.Collectors.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@ -48,6 +29,14 @@ public class Java8CollectorsUnitTest {
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
public void whenCollectingToSet_shouldCollectToSet() throws Exception {
final Set<String> result = givenList.stream().collect(toSet());
@ -55,6 +44,14 @@ public class Java8CollectorsUnitTest {
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
public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception {
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);
}
@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
public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception {
final Map<String, Integer> result = listWithDuplicates.stream().collect(

View File

@ -7,7 +7,9 @@ import java.util.Optional;
import java.util.function.Supplier;
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 {

View File

@ -9,7 +9,9 @@ import java.util.List;
import java.util.NoSuchElementException;
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 {
@ -262,6 +264,12 @@ public class OptionalUnitTest {
.orElseThrow(IllegalArgumentException::new);
}
@Test(expected = NoSuchElementException.class)
public void whenNoArgOrElseThrowWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElseThrow();
}
public String getMyDefault() {
LOG.debug("Getting default value...");
return "Default Value";

View File

@ -107,7 +107,7 @@
<uberjar.name>benchmarks</uberjar.name>
<jmh.version>1.22</jmh.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>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.array.arraystoreexception;
public class ArrayStoreExampleCE {
public static void main(String[] args) {
//String array[] = new String[5]; //This will lead to compile-time error at line-8 when uncommented
//array[0] = 2;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.array.arraystoreexception;
public class ArrayStoreExceptionExample {
public static void main(String[] args) {
try {
Object array[] = new String[5];
array[0] = 2;
} catch (ArrayStoreException e) {
// handle the exception
}
}
}

View File

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

View File

@ -30,5 +30,4 @@
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.exceptions.illegalmonitorstate;
public class Data {
private String message;
public void send(String message) {
this.message = message;
}
public String receive() {
return message;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.exceptions.illegalmonitorstate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SynchronizedReceiver implements Runnable {
private static Logger log = LoggerFactory.getLogger(SynchronizedReceiver.class);
private final Data data;
private String message;
private boolean illegalMonitorStateExceptionOccurred;
public SynchronizedReceiver(Data data) {
this.data = data;
}
@Override
public void run() {
synchronized (data) {
try {
data.wait();
this.message = data.receive();
} catch (InterruptedException e) {
log.error("thread was interrupted", e);
Thread.currentThread().interrupt();
} catch (IllegalMonitorStateException e) {
log.error("illegal monitor state exception occurred", e);
illegalMonitorStateExceptionOccurred = true;
}
}
}
public boolean hasIllegalMonitorStateExceptionOccurred() {
return illegalMonitorStateExceptionOccurred;
}
public String getMessage() {
return message;
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.exceptions.illegalmonitorstate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SynchronizedSender implements Runnable {
private static Logger log = LoggerFactory.getLogger(SynchronizedSender.class);
private final Data data;
private boolean illegalMonitorStateExceptionOccurred;
public SynchronizedSender(Data data) {
this.data = data;
}
@Override
public void run() {
synchronized (data) {
try {
Thread.sleep(1000);
data.send("test");
data.notifyAll();
} catch (InterruptedException e) {
log.error("thread was interrupted", e);
Thread.currentThread().interrupt();
} catch (IllegalMonitorStateException e) {
log.error("illegal monitor state exception occurred", e);
illegalMonitorStateExceptionOccurred = true;
}
}
}
public boolean hasIllegalMonitorStateExceptionOccurred() {
return illegalMonitorStateExceptionOccurred;
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.exceptions.illegalmonitorstate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UnsynchronizedReceiver implements Runnable {
private static Logger log = LoggerFactory.getLogger(UnsynchronizedReceiver.class);
private final Data data;
private String message;
private boolean illegalMonitorStateExceptionOccurred;
public UnsynchronizedReceiver(Data data) {
this.data = data;
}
@Override
public void run() {
try {
data.wait();
this.message = data.receive();
} catch (InterruptedException e) {
log.error("thread was interrupted", e);
Thread.currentThread().interrupt();
} catch (IllegalMonitorStateException e) {
log.error("illegal monitor state exception occurred", e);
illegalMonitorStateExceptionOccurred = true;
}
}
public boolean hasIllegalMonitorStateExceptionOccurred() {
return illegalMonitorStateExceptionOccurred;
}
public String getMessage() {
return message;
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.exceptions.illegalmonitorstate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UnsynchronizedSender implements Runnable {
private static Logger log = LoggerFactory.getLogger(UnsynchronizedSender.class);
private final Data data;
private boolean illegalMonitorStateExceptionOccurred;
public UnsynchronizedSender(Data data) {
this.data = data;
}
@Override
public void run() {
try {
Thread.sleep(1000);
data.send("test");
data.notifyAll();
} catch (InterruptedException e) {
log.error("thread was interrupted", e);
Thread.currentThread().interrupt();
} catch (IllegalMonitorStateException e) {
log.error("illegal monitor state exception occurred", e);
illegalMonitorStateExceptionOccurred = true;
}
}
public boolean hasIllegalMonitorStateExceptionOccurred() {
return illegalMonitorStateExceptionOccurred;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.nullmethodparameter;
public class NullParameterExample {
public void processSomethingNotNull(Object myParameter) {
if (myParameter == null) {
throw new IllegalArgumentException("Parameter 'myParameter' cannot be null");
}
//Do something with the parameter
}
public void processSomethingElseNotNull(Object myParameter) {
if (myParameter == null) {
throw new NullPointerException("Parameter 'myParameter' cannot be null");
}
//Do something with the parameter
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.exceptions.illegalmonitorstate;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class IllegalMonitorStateExceptionUnitTest {
@Test
void whenSyncSenderAndSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldNotBeThrown() throws InterruptedException {
Data data = new Data();
SynchronizedReceiver receiver = new SynchronizedReceiver(data);
Thread receiverThread = new Thread(receiver, "receiver-thread");
receiverThread.start();
SynchronizedSender sender = new SynchronizedSender(data);
Thread senderThread = new Thread(sender, "sender-thread");
senderThread.start();
senderThread.join(1000);
receiverThread.join(1000);
assertEquals("test", receiver.getMessage());
assertFalse(sender.hasIllegalMonitorStateExceptionOccurred());
assertFalse(receiver.hasIllegalMonitorStateExceptionOccurred());
}
@Test
void whenSyncSenderAndUnSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldNotBeThrown() throws InterruptedException {
Data data = new Data();
UnsynchronizedReceiver receiver = new UnsynchronizedReceiver(data);
Thread receiverThread = new Thread(receiver, "receiver-thread");
receiverThread.start();
SynchronizedSender sender = new SynchronizedSender(data);
Thread senderThread = new Thread(sender, "sender-thread");
senderThread.start();
receiverThread.join(1000);
senderThread.join(1000);
assertNull(receiver.getMessage());
assertFalse(sender.hasIllegalMonitorStateExceptionOccurred());
assertTrue(receiver.hasIllegalMonitorStateExceptionOccurred());
}
@Test
void whenUnSyncSenderAndSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldBeThrown() throws InterruptedException {
Data data = new Data();
SynchronizedReceiver receiver = new SynchronizedReceiver(data);
Thread receiverThread = new Thread(receiver, "receiver-thread");
receiverThread.start();
UnsynchronizedSender sender = new UnsynchronizedSender(data);
Thread senderThread = new Thread(sender, "sender-thread");
senderThread.start();
receiverThread.join(1000);
senderThread.join(1000);
assertNull(receiver.getMessage());
assertFalse(receiver.hasIllegalMonitorStateExceptionOccurred());
assertTrue(sender.hasIllegalMonitorStateExceptionOccurred());
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.nullmethodparameter;
import org.junit.Test;
public class NullParameterExampleUnitTest {
@Test(expected = IllegalArgumentException.class)
public void givenNullParameter_whenProcessSomethingNotNull_thenIllegalArgumentException() {
NullParameterExample example = new NullParameterExample();
example.processSomethingNotNull(null);
}
@Test(expected = NullPointerException.class)
public void givenNullParameter_whenProcessSomethingElseNotNull_thenNullPointerException() {
NullParameterExample example = new NullParameterExample();
example.processSomethingElseNotNull(null);
}
}

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="WARN">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,75 @@
package com.baeldung.tempdirectory;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests several possibilities on how to create
* temporary directories.
*
* @author Rui Vilao (rpvilao@gmail.com)
*/
public class TemporaryDirectoriesUnitTest {
@Test
public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithPlainJava_thenInsideOSTempDirStructure() throws IOException {
final String tmpdir = Files.createTempDirectory("tmpDirPrefix").toFile().getAbsolutePath();
final String tmpDirsLocation = System.getProperty("java.io.tmpdir");
assertThat(tmpdir).startsWith(tmpDirsLocation);
}
@Test
public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithGuava_thenInsideOSTempDirStructure() throws IOException {
final String tmpdir = com.google.common.io.Files.createTempDir().getAbsolutePath();
final String tmpDirsLocation = System.getProperty("java.io.tmpdir");
assertThat(tmpdir).startsWith(tmpDirsLocation);
}
@Test
public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithApacheCommonsIo_thenInsideOSTempDirStructure() throws IOException {
final String tmpDirsLocation = System.getProperty("java.io.tmpdir");
final Path path = Paths.get(FileUtils.getTempDirectory().getAbsolutePath(), UUID.randomUUID().toString());
final String tmpdir = Files.createDirectories(path).toFile().getAbsolutePath();
assertThat(tmpdir).startsWith(tmpDirsLocation);
}
@Test
public void givenTempDirWithPrefixWithTargetSpecified_whenCreatePlainJava_thenInsideTarget() throws IOException {
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix");
assertThat(tmpdir.toFile().getPath()).startsWith("target");
}
@Test
public void givenTempDirWithPrefixWithTargetSpecifiedWithDeleteOnExit_whenCreatePlainJava_thenInsideTarget() throws IOException {
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix");
assertThat(tmpdir.toFile().getPath()).startsWith("target");
tmpdir.toFile().deleteOnExit();
// we can really assert this test, just as an example.
}
@Test
public void givenTempDirWithPrefixWithFileAttrs_whenCreatePlainJava_thenAttributesAreSet() throws IOException {
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();
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.algorithms.largestpowerof2;
import org.nd4j.linalg.io.Assert;
public class LargestPowerOf2 {
public long findLargestPowerOf2LessThanTheGivenNumber(long input) {
Assert.isTrue(input > 1, "Invalid input");
long firstPowerOf2 = 1;
long nextPowerOf2 = 2;
while (nextPowerOf2 < input) {
firstPowerOf2 = nextPowerOf2;
nextPowerOf2 = nextPowerOf2 * 2;
}
return firstPowerOf2;
}
public long findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(long input) {
Assert.isTrue(input > 1, "Invalid input");
long temp = input;
if (input % 2 == 0) {
temp = input - 1;
}
// Find log base 2 of a given number
long power = (long) (Math.log(temp) / Math.log(2));
long result = (long) Math.pow(2, power);
return result;
}
public long findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(long input) {
Assert.isTrue(input > 1, "Invalid input");
long result = 1;
for (long i = input - 1; i > 1; i--) {
if ((i & (i - 1)) == 0) {
result = i;
break;
}
}
return result;
}
public long findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(long input) {
Assert.isTrue(input > 1, "Invalid input");
long result = 1;
long powerOf2;
for (long i = 0; i < Long.BYTES * 8; i++) {
powerOf2 = 1 << i;
if (powerOf2 >= input) {
break;
}
result = powerOf2;
}
return result;
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.algorithms.largestpowerof2;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class LargestPowerOf2UnitTest {
private long input;
private long expectedResult;
public LargestPowerOf2UnitTest(long input, long expectedResult) {
this.input = input;
this.expectedResult = expectedResult;
}
@Parameterized.Parameters(name = "{index}: verifyLargestPowerOf2LessThanTheGivenNumber({0}) = {1}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] { { 2, 1 }, { 4, 2 }, { 500, 256 }, { 512, 256 }, { 1050, 1024 } });
}
@Test
public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumber() {
LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2();
long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumber(input);
Assert.assertEquals(expectedResult, result);
}
@Test
public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberUsingLogBase2() {
LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2();
long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(input);
Assert.assertEquals(expectedResult, result);
}
@Test
public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberBitwiseAnd() {
LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2();
long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(input);
Assert.assertEquals(expectedResult, result);
}
@Test
public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberBitShiftApproach() {
LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2();
long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(input);
Assert.assertEquals(expectedResult, result);
}
@Test(expected = IllegalArgumentException.class)
public void givenInvalidInput_ShouldThrowException() {
LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2();
largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumber(1);
}
}

View File

@ -4,7 +4,6 @@ This module contains articles about Java Optional.
### Relevant Articles:
- [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)
- [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)

View File

@ -6,7 +6,6 @@ This module contains articles about the Stream API in Java.
- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap)
- [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)
- [Guide to Java 8s Collectors](https://www.baeldung.com/java-8-collectors)
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
- [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)

View File

@ -0,0 +1,7 @@
## Core Kotlin Collections
This module contains articles about core Kotlin collections.
### Relevant articles:

View File

@ -0,0 +1,47 @@
<?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-kotlin-collections-2</artifactId>
<name>core-kotlin-collections-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-kotlin-modules</groupId>
<artifactId>core-kotlin-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test</artifactId>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<kotlin.version>1.3.30</kotlin.version>
<commons-math3.version>3.6.1</commons-math3.version>
<assertj.version>3.10.0</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,107 @@
package com.baeldung.aggregate
class AggregateOperations {
private val numbers = listOf(1, 15, 3, 8)
fun countList(): Int {
return numbers.count()
}
fun sumList(): Int {
return numbers.sum()
}
fun averageList(): Double {
return numbers.average()
}
fun maximumInList(): Int? {
return numbers.max()
}
fun minimumInList(): Int? {
return numbers.min()
}
fun maximumByList(): Int? {
return numbers.maxBy { it % 5 }
}
fun minimumByList(): Int? {
return numbers.minBy { it % 5 }
}
fun maximumWithList(): String? {
val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona")
return strings.maxWith(compareBy { it.length % 4 })
}
fun minimumWithList(): String? {
val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona")
return strings.minWith(compareBy { it.length % 4 })
}
fun sumByList(): Int {
return numbers.sumBy { it * 5 }
}
fun sumByDoubleList(): Double {
return numbers.sumByDouble { it.toDouble() / 8 }
}
fun foldList(): Int {
return numbers.fold(100) { total, it ->
println("total = $total, it = $it")
total - it
} // ((((100 - 1)-15)-3)-8) = 73
}
fun foldRightList(): Int {
return numbers.foldRight(100) { it, total ->
println("total = $total, it = $it")
total - it
} // ((((100-8)-3)-15)-1) = 73
}
fun foldIndexedList(): Int {
return numbers.foldIndexed(100) { index, total, it ->
println("total = $total, it = $it, index = $index")
if (index.minus(2) >= 0) total - it else total
} // ((100 - 3)-8) = 89
}
fun foldRightIndexedList(): Int {
return numbers.foldRightIndexed(100) { index, it, total ->
println("total = $total, it = $it, index = $index")
if (index.minus(2) >= 0) total - it else total
} // ((100 - 8)-3) = 89
}
fun reduceList(): Int {
return numbers.reduce { total, it ->
println("total = $total, it = $it")
total - it
} // (((1 - 15)-3)-8) = -25
}
fun reduceRightList(): Int {
return numbers.reduceRight() { it, total ->
println("total = $total, it = $it")
total - it
} // ((8-3)-15)-1) = -11
}
fun reduceIndexedList(): Int {
return numbers.reduceIndexed { index, total, it ->
println("total = $total, it = $it, index = $index")
if (index.minus(2) >= 0) total - it else total
} // ((1-3)-8) = -10
}
fun reduceRightIndexedList(): Int {
return numbers.reduceRightIndexed { index, it, total ->
println("total = $total, it = $it, index = $index")
if (index.minus(2) >= 0) total - it else total
} // ((8-3) = 5
}
}

View File

@ -0,0 +1,104 @@
package com.baeldung.aggregate
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class AggregateOperationsUnitTest {
private val classUnderTest: AggregateOperations = AggregateOperations()
@Test
fun whenCountOfList_thenReturnsValue() {
assertEquals(4, classUnderTest.countList())
}
@Test
fun whenSumOfList_thenReturnsTotalValue() {
assertEquals(27, classUnderTest.sumList())
}
@Test
fun whenAverageOfList_thenReturnsValue() {
assertEquals(6.75, classUnderTest.averageList())
}
@Test
fun whenMaximumOfList_thenReturnsMaximumValue() {
assertEquals(15, classUnderTest.maximumInList())
}
@Test
fun whenMinimumOfList_thenReturnsMinimumValue() {
assertEquals(1, classUnderTest.minimumInList())
}
@Test
fun whenMaxByList_thenReturnsLargestValue() {
assertEquals(3, classUnderTest.maximumByList())
}
@Test
fun whenMinByList_thenReturnsSmallestValue() {
assertEquals(15, classUnderTest.minimumByList())
}
@Test
fun whenMaxWithList_thenReturnsLargestValue(){
assertEquals("Kolkata", classUnderTest.maximumWithList())
}
@Test
fun whenMinWithList_thenReturnsSmallestValue(){
assertEquals("Barcelona", classUnderTest.minimumWithList())
}
@Test
fun whenSumByList_thenReturnsIntegerValue(){
assertEquals(135, classUnderTest.sumByList())
}
@Test
fun whenSumByDoubleList_thenReturnsDoubleValue(){
assertEquals(3.375, classUnderTest.sumByDoubleList())
}
@Test
fun whenFoldList_thenReturnsValue(){
assertEquals(73, classUnderTest.foldList())
}
@Test
fun whenFoldRightList_thenReturnsValue(){
assertEquals(73, classUnderTest.foldRightList())
}
@Test
fun whenFoldIndexedList_thenReturnsValue(){
assertEquals(89, classUnderTest.foldIndexedList())
}
@Test
fun whenFoldRightIndexedList_thenReturnsValue(){
assertEquals(89, classUnderTest.foldRightIndexedList())
}
@Test
fun whenReduceList_thenReturnsValue(){
assertEquals(-25, classUnderTest.reduceList())
}
@Test
fun whenReduceRightList_thenReturnsValue(){
assertEquals(-11, classUnderTest.reduceRightList())
}
@Test
fun whenReduceIndexedList_thenReturnsValue(){
assertEquals(-10, classUnderTest.reduceIndexedList())
}
@Test
fun whenReduceRightIndexedList_thenReturnsValue(){
assertEquals(5, classUnderTest.reduceRightIndexedList())
}
}

View File

@ -22,6 +22,30 @@ fun main() {
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.
*/

View File

@ -21,6 +21,7 @@
<module>core-kotlin-advanced</module>
<module>core-kotlin-annotations</module>
<module>core-kotlin-collections</module>
<module>core-kotlin-collections-2</module>
<module>core-kotlin-concurrency</module>
<module>core-kotlin-date-time</module>
<module>core-kotlin-design-patterns</module>

View File

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

View File

@ -1,3 +0,0 @@
### Relevant Article:
- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images)

View File

@ -6,3 +6,4 @@ This module contains articles about Drools
- [Introduction to Drools](https://www.baeldung.com/drools)
- [An Example of Backward Chaining in Drools](https://www.baeldung.com/drools-backward-chaining)
- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel)

View File

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

1
gradle-5/source-sets/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build/

View File

@ -0,0 +1,67 @@
apply plugin: "eclipse"
apply plugin: "java"
description = "Source Sets example"
task printSourceSetInformation(){
description = "Print source set information"
doLast{
sourceSets.each { srcSet ->
println "["+srcSet.name+"]"
print "-->Source directories: "+srcSet.allJava.srcDirs+"\n"
print "-->Output directories: "+srcSet.output.classesDirs.files+"\n"
print "-->Compile classpath:\n"
srcSet.compileClasspath.files.each {
print " "+it.path+"\n"
}
println ""
}
}
}
sourceSets{
itest {
compileClasspath += sourceSets.main.output
runtimeClasspath += sourceSets.main.output
java {
}
}
}
test {
testLogging {
events "passed","skipped", "failed"
}
}
dependencies {
implementation('org.apache.httpcomponents:httpclient:4.5.12')
testImplementation('junit:junit:4.12')
itestImplementation('com.google.guava:guava:29.0-jre')
}
task itest(type: Test) {
description = "Run integration tests"
group = "verification"
testClassesDirs = sourceSets.itest.output.classesDirs
classpath = sourceSets.itest.runtimeClasspath
}
itest {
testLogging {
events "passed","skipped", "failed"
}
}
configurations {
itestImplementation.extendsFrom(testImplementation)
itestRuntimeOnly.extendsFrom(testRuntimeOnly)
}
eclipse {
classpath {
plusConfigurations+=[configurations.itestCompileClasspath]
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.itest;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.Test;
import com.baeldung.main.SourceSetsObject;
import com.google.common.collect.ImmutableList;
public class SourceSetsItest {
@Test
public void givenImmutableList_whenRun_ThenSuccess() {
SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum");
List<String> someStrings = ImmutableList.of("Baeldung", "is", "cool");
assertThat(underTest.getUser(), is("lorem"));
assertThat(underTest.getPassword(), is("ipsum"));
assertThat(someStrings.size(), is(3));
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.main;
public class SourceSetsMain {
public static void main(String[] args) {
System.out.println("Hell..oh...world!");
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.main;
public class SourceSetsObject {
private final String user;
private final String password;
public SourceSetsObject(String user, String password) {
this.user = user;
this.password = password;
}
public String getPassword() {
return password;
}
public String getUser() {
return user;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import com.baeldung.main.SourceSetsObject;
public class SourceSetsTest {
@Test
public void whenRun_ThenSuccess() {
SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum");
assertThat(underTest.getUser(), is("lorem"));
assertThat(underTest.getPassword(), is("ipsum"));
}
}

View File

@ -1,21 +1,24 @@
package com.baeldung.arrayconversion;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertArrayEquals;
public class ArrayToListConversionUnitTest {
@Test(expected = UnsupportedOperationException.class)
public void givenAnArray_whenConvertingToList_returnUnmodifiableListUnitTest() {
String[] stringArray = new String[] { "A", "B", "C", "D" };
List<String> stringList = Arrays.asList(stringArray);
System.out.println(stringList);
stringList.set(0, "E");
System.out.println(stringList);
System.out.println(Arrays.toString(stringArray));
assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D"));
assertArrayEquals(stringArray, new String[] { "E", "B", "C", "D" });
stringList.add("F");
}
@ -23,10 +26,10 @@ public class ArrayToListConversionUnitTest {
public void givenAnArray_whenConvertingToList_returnModifiableListUnitTest() {
String[] stringArray = new String[] { "A", "B", "C", "D" };
List<String> stringList = new ArrayList<>(Arrays.asList(stringArray));
System.out.println(stringList);
stringList.set(0, "E");
System.out.println(stringList);
System.out.println(Arrays.toString(stringArray));
assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D"));
assertArrayEquals(stringArray, new String[] { "A", "B", "C", "D" });
stringList.add("F");
assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D", "F"));
}
}

View File

@ -237,6 +237,26 @@
<build>
<defaultGoal>spring-boot:run</defaultGoal>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<goals>
<goal>set-system-properties</goal>
</goals>
<configuration>
<properties>
<property>
<name>org.slf4j.simpleLogger.log.com.github.eirslett</name>
<value>error</value>
</property>
</properties>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>

View File

@ -9,6 +9,8 @@
<packaging>pom</packaging>
<parent>
<!-- Jhipster project is autogenerated and upgrading it will need a newly generated project.
Also, we already have jhipster-5 which has new version of boot-2. So, this project should be left as a legacy version. -->
<artifactId>parent-boot-1</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>

View File

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

View File

@ -14,29 +14,24 @@
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>com.github.scribejava</groupId>
<artifactId>scribejava-apis</artifactId>
<version>${scribejava.version}</version>
</dependency>
<dependency>
<groupId>com.google.crypto.tink</groupId>
<artifactId>tink</artifactId>
@ -72,6 +67,16 @@
<artifactId>jasypt</artifactId>
<version>${jasypt.version}</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>${jsch.version}</version>
</dependency>
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId>
<version>${apache-mina.version}</version>
</dependency>
</dependencies>
<properties>
@ -81,6 +86,8 @@
<cryptacular.version>1.2.2</cryptacular.version>
<jasypt.version>1.9.2</jasypt.version>
<bouncycastle.version>1.58</bouncycastle.version>
<jsch.version>0.1.55</jsch.version>
<apache-mina.version>2.5.1</apache-mina.version>
</properties>
</project>

View File

@ -0,0 +1,64 @@
package com.baeldung.ssh.apachesshd;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.EnumSet;
import java.util.concurrent.TimeUnit;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.channel.Channel;
public class SshdDemo {
public static void main(String[] args) throws Exception {
String username = "demo";
String password = "password";
String host = "test.rebex.net";
int port = 22;
long defaultTimeoutSeconds = 10l;
String command = "ls\n";
listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command);
}
public static String listFolderStructure(String username, String password, String host, int port, long defaultTimeoutSeconds, String command) throws Exception {
SshClient client = SshClient.setUpDefaultClient();
client.start();
try (ClientSession session = client.connect(username, host, port)
.verify(defaultTimeoutSeconds, TimeUnit.SECONDS)
.getSession()) {
session.addPasswordIdentity(password);
session.auth()
.verify(defaultTimeoutSeconds, TimeUnit.SECONDS);
try (ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream();
ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
channel.setOut(responseStream);
channel.setErr(errorResponseStream);
try {
channel.open()
.verify(defaultTimeoutSeconds, TimeUnit.SECONDS);
try (OutputStream pipedIn = channel.getInvertedIn()) {
pipedIn.write(command.getBytes());
pipedIn.flush();
}
channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(defaultTimeoutSeconds));
String errorString = new String(errorResponseStream.toByteArray());
if(!errorString.isEmpty()) {
throw new Exception(errorString);
}
String responseString = new String(responseStream.toByteArray());
return responseString;
} finally {
channel.close(false);
}
}
} finally {
client.stop();
}
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.ssh.jsch;
import java.io.ByteArrayOutputStream;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class JschDemo {
public static void main(String args[]) throws Exception {
String username = "demo";
String password = "password";
String host = "test.rebex.net";
int port = 22;
String command = "ls";
listFolderStructure(username, password, host, port, command);
}
public static String listFolderStructure(String username, String password, String host, int port, String command) throws Exception {
Session session = null;
ChannelExec channel = null;
String response = null;
try {
session = new JSch().getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream();
channel.setOutputStream(responseStream);
channel.setErrStream(errorResponseStream);
channel.connect();
while (channel.isConnected()) {
Thread.sleep(100);
}
String errorResponse = new String(errorResponseStream.toByteArray());
response = new String(responseStream.toByteArray());
if(!errorResponse.isEmpty()) {
throw new Exception(errorResponse);
}
} finally {
if (session != null) {
session.disconnect();
}
if (channel != null) {
channel.disconnect();
}
}
return response;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.ssh;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import com.baeldung.ssh.apachesshd.SshdDemo;
public class ApacheMinaSshdLiveTest {
@Test
public void givenValidCredentials_whenConnectionIsEstablished_thenServerReturnsResponse() throws Exception {
String username = "demo";
String password = "password";
String host = "test.rebex.net";
int port = 22;
long defaultTimeoutSeconds = 10l;
String command = "ls\n";
String responseString = SshdDemo.listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command);
assertNotNull(responseString);
}
@Test(expected = Exception.class)
public void givenInvalidCredentials_whenConnectionAttemptIsMade_thenServerReturnsErrorResponse() throws Exception {
String username = "invalidUsername";
String password = "password";
String host = "test.rebex.net";
int port = 22;
long defaultTimeoutSeconds = 10l;
String command = "ls\n";
String responseString = SshdDemo.listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command);
assertNull(responseString);
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.ssh;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import com.baeldung.ssh.jsch.JschDemo;
public class JSchLiveTest {
@Test
public void givenValidCredentials_whenConnectionIsEstablished_thenServerReturnsResponse() throws Exception {
String username = "demo";
String password = "password";
String host = "test.rebex.net";
int port = 22;
String command = "ls";
String responseString = JschDemo.listFolderStructure(username, password, host, port, command);
assertNotNull(responseString);
}
@Test(expected = Exception.class)
public void givenInvalidCredentials_whenConnectionAttemptIsMade_thenServerReturnsErrorResponse() throws Exception {
String username = "invalidUsername";
String password = "password";
String host = "test.rebex.net";
int port = 22;
String command = "ls";
String responseString = JschDemo.listFolderStructure(username, password, host, port, command);
assertNull(responseString);
}
}

View File

@ -24,7 +24,6 @@ public class SmurfsRepository {
smurfs.put("Architect", new Smurf("Architect", true, true));
smurfs.put("Baby", new Smurf("Baby", true, true));
smurfs.put("Baker", new Smurf("Baker", true, true));
smurfs.put("Baker", new Smurf("Baker", true, true));
}
public List<Smurf> findAll() {

View File

@ -5,8 +5,6 @@ public class Smurf {
private boolean comic;
private boolean cartoon;
public Smurf() {}
public Smurf(String name, boolean comic, boolean cartoon) {
this.name = name;
this.comic = comic;

View File

View File

@ -1,8 +1,6 @@
### Relevant Articles:
- TBD
- [Improved Java Logging with Mapped Diagnostic Context (MDC)](https://www.baeldung.com/mdc-in-log4j-2-logback)
- [Java Logging with Nested Diagnostic Context (NDC)](https://www.baeldung.com/java-logging-ndc-log4j)
- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel)
### References

View File

@ -10,9 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-spring-4</artifactId>
<artifactId>parent-spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-spring-4</relativePath>
<relativePath>../../parent-spring-5</relativePath>
</parent>
<dependencies>

View File

@ -27,6 +27,7 @@
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>${version.derby}</version>
<scope>provided</scope>
</dependency>
<!-- For tests -->
@ -70,27 +71,16 @@
<groupId>io.openliberty.tools</groupId>
<artifactId>liberty-maven-plugin</artifactId>
<version>${version.liberty-maven-plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>${version.maven-dependency-plugin}</version>
<executions>
<execution>
<id>copy-derby-dependency</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<includeArtifactIds>derby</includeArtifactIds>
<outputDirectory>${project.build.directory}/liberty/wlp/usr/shared/resources/</outputDirectory>
<systemPropertyVariables>
<liberty.test.port>${testServerHttpPort}</liberty.test.port>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
<configuration>
<copyDependencies>
<location>${project.build.directory}/liberty/wlp/usr/shared/resources/</location>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>${version.derby}</version>
</dependency>
</copyDependencies>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@ -112,8 +102,7 @@
<version.jakarta.jakartaee-web-api>8.0.0</version.jakarta.jakartaee-web-api>
<version.microprofile>3.2</version.microprofile>
<version.derby>10.14.2.0</version.derby>
<version.liberty-maven-plugin>3.1</version.liberty-maven-plugin>
<version.maven-dependency-plugin>2.10</version.maven-dependency-plugin>
<version.liberty-maven-plugin>3.3-M3</version.liberty-maven-plugin>
<version.maven-war-plugin>3.2.3</version.maven-war-plugin>
<version.junit>4.12</version.junit>
<version.yasson>1.0.5</version.yasson>

View File

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

View File

@ -0,0 +1,37 @@
package com.baeldung.repositoryvsdaopattern;
import java.util.Date;
public class Tweet {
private String email;
private String tweetText;
private Date dateCreated;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTweetText() {
return tweetText;
}
public void setTweetText(String tweetText) {
this.tweetText = tweetText;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.repositoryvsdaopattern;
import java.util.List;
public interface TweetDao {
List<Tweet> fetchTweets(String email);
}

View File

@ -0,0 +1,17 @@
package com.baeldung.repositoryvsdaopattern;
import java.util.ArrayList;
import java.util.List;
public class TweetDaoImpl implements TweetDao {
@Override
public List<Tweet> fetchTweets(String email) {
List<Tweet> tweets = new ArrayList<Tweet>();
//call Twitter API and prepare Tweet object
return tweets;
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.repositoryvsdaopattern;
public class User {
private Long id;
private String userName;
private String firstName;
private String lastName;
private String email;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.repositoryvsdaopattern;
public interface UserDao {
void create(User user);
User read(Long id);
void update(User user);
void delete(String userName);
}

View File

@ -0,0 +1,33 @@
package com.baeldung.repositoryvsdaopattern;
import javax.persistence.EntityManager;
public class UserDaoImpl implements UserDao {
private final EntityManager entityManager;
public UserDaoImpl(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public void create(User user) {
entityManager.persist(user);
}
@Override
public User read(Long id) {
return entityManager.find(User.class, id);
}
@Override
public void update(User user) {
}
@Override
public void delete(String userName) {
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.repositoryvsdaopattern;
import java.util.List;
public interface UserRepository {
User get(Long id);
void add(User user);
void update(User user);
void remove(User user);
User findByUserName(String userName);
User findByEmail(String email);
List<Tweet> fetchTweets(User user);
}

View File

@ -0,0 +1,51 @@
package com.baeldung.repositoryvsdaopattern;
import java.util.List;
public class UserRepositoryImpl implements UserRepository {
private UserDaoImpl userDaoImpl;
private TweetDaoImpl tweetDaoImpl;
@Override
public User get(Long id) {
UserSocialMedia user = (UserSocialMedia) userDaoImpl.read(id);
List<Tweet> tweets = tweetDaoImpl.fetchTweets(user.getEmail());
user.setTweets(tweets);
return user;
}
@Override
public void add(User user) {
userDaoImpl.create(user);
}
@Override
public void remove(User user) {
}
@Override
public void update(User user) {
}
@Override
public List<Tweet> fetchTweets(User user) {
return tweetDaoImpl.fetchTweets(user.getEmail());
}
@Override
public User findByUserName(String userName) {
return null;
}
@Override
public User findByEmail(String email) {
return null;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.repositoryvsdaopattern;
import java.util.List;
public class UserSocialMedia extends User {
private List<Tweet> tweets;
public List<Tweet> getTweets() {
return tweets;
}
public void setTweets(List<Tweet> tweets) {
this.tweets = tweets;
}
}

View File

@ -19,27 +19,14 @@
<version>${orika.version}</version>
</dependency>
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<groupId>com.github.dozermapper</groupId>
<artifactId>dozer-core</artifactId>
<version>${dozer.version}</version>
</dependency>
<dependency>
<groupId>io.craftsman</groupId>
<artifactId>dozer-jdk8-support</artifactId>
<version>${dozer-jdk8-support.version}</version>
</dependency>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>${mapstruct-jdk8.version}</version>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct-jdk8.version}</version>
<scope>provided</scope>
<artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<dependency>
@ -77,10 +64,15 @@
<source>${javac.target}</source>
<target>${javac.target}</target>
<annotationProcessorPaths>
<path>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct-processor.version}</version>
<version>${mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
@ -120,28 +112,16 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
<mainClass>com.baeldung.performancetests.MappingFrameworksPerformance</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.5</version>
<version>${clean.plugin.version}</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.1</version>
<version>${deploy.plugin.version}</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
@ -179,19 +159,13 @@
<!--
JMH version to use with this project.
-->
<jmh.version>1.21</jmh.version>
<orika.version>1.5.2</orika.version>
<dozer.version>5.5.1</dozer.version>
<dozer-jdk8-support.version>1.0.2</dozer-jdk8-support.version>
<mapstruct-jdk8.version>1.2.0.Final</mapstruct-jdk8.version>
<modelmapper.version>1.1.0</modelmapper.version>
<jmapper.version>1.6.0.1</jmapper.version>
<mapstruct-processor.version>1.2.0.Final</mapstruct-processor.version>
<jmh-core.version>1.21</jmh-core.version>
<jmh-generator.version>1.21</jmh-generator.version>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<maven-jar-plugin.version>3.2.0</maven-jar-plugin.version>
<jmh.version>1.23</jmh.version>
<orika.version>1.5.4</orika.version>
<dozer.version>6.5.0</dozer.version>
<mapstruct.version>1.3.1.Final</mapstruct.version>
<modelmapper.version>2.3.8</modelmapper.version>
<jmapper.version>1.6.1.CR2</jmapper.version>
<!--
Java source/target to use for compilation.
-->
@ -201,14 +175,16 @@
Name of the benchmark Uber-JAR to generate.
-->
<uberjar.name>benchmarks</uberjar.name>
<compiler.plugin.version>3.1</compiler.plugin.version>
<shade.plugin.version>2.2</shade.plugin.version>
<install.version>2.5.1</install.version>
<jar.plugin.version>2.4</jar.plugin.version>
<javadoc.plugin.version>2.9.1</javadoc.plugin.version>
<resources.plugin.version>2.6</resources.plugin.version>
<site.plugin.version>3.3</site.plugin.version>
<source.plugin.version>2.2.1</source.plugin.version>
<clean.plugin.version>3.1.0</clean.plugin.version>
<deploy.plugin.version>3.0.0-M1</deploy.plugin.version>
<compiler.plugin.version>3.8.1</compiler.plugin.version>
<shade.plugin.version>3.2.4</shade.plugin.version>
<install.version>3.0.0-M1</install.version>
<jar.plugin.version>3.2.0</jar.plugin.version>
<javadoc.plugin.version>3.2.0</javadoc.plugin.version>
<resources.plugin.version>3.1.0</resources.plugin.version>
<site.plugin.version>3.9.1</site.plugin.version>
<source.plugin.version>3.2.1</source.plugin.version>
<surefire.plugin.version>2.17</surefire.plugin.version>
</properties>

View File

@ -2,28 +2,28 @@ package com.baeldung.performancetests.dozer;
import com.baeldung.performancetests.Converter;
import com.baeldung.performancetests.model.destination.DestinationCode;
import com.baeldung.performancetests.model.destination.Order;
import com.baeldung.performancetests.model.source.SourceCode;
import com.baeldung.performancetests.model.source.SourceOrder;
import com.baeldung.performancetests.model.destination.Order;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
public class DozerConverter implements Converter {
private final Mapper mapper;
public class DozerConverter implements Converter {
private final Mapper mapper;
public DozerConverter() {
DozerBeanMapper mapper = new DozerBeanMapper();
mapper.addMapping(DozerConverter.class.getResourceAsStream("/dozer-mapping.xml"));
this.mapper = mapper;
}
@Override
public Order convert(SourceOrder sourceOrder) {
return mapper.map(sourceOrder,Order.class);
}
@Override
public DestinationCode convert(SourceCode sourceCode) {
return mapper.map(sourceCode, DestinationCode.class);
}
public DozerConverter() {
this.mapper = DozerBeanMapperBuilder.create()
.withMappingFiles("dozer-mapping.xml")
.build();
}
@Override
public Order convert(SourceOrder sourceOrder) {
return mapper.map(sourceOrder, Order.class);
}
@Override
public DestinationCode convert(SourceCode sourceCode) {
return mapper.map(sourceCode, DestinationCode.class);
}
}

View File

@ -1,8 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozer.sourceforge.net
http://dozer.sourceforge.net/schema/beanmapping.xsd">
<mappings xmlns="http://dozermapper.github.io/schema/bean-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozermapper.github.io/schema/bean-mapping https://dozermapper.github.io/schema/bean-mapping.xsd">
<configuration>
<stop-on-errors>true</stop-on-errors>

View File

@ -1,8 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozer.sourceforge.net
http://dozer.sourceforge.net/schema/beanmapping.xsd">
<mappings xmlns="http://dozermapper.github.io/schema/bean-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozermapper.github.io/schema/bean-mapping https://dozermapper.github.io/schema/bean-mapping.xsd">
<configuration>
<stop-on-errors>true</stop-on-errors>

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