Merge branch 'master' into BAEL-4406-jacoco-exclusions
This commit is contained in:
@@ -0,0 +1 @@
|
||||
.aws-sam/
|
||||
@@ -6,3 +6,4 @@ This module contains articles about AWS Lambda
|
||||
- [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)
|
||||
- [How to Implement Hibernate in an AWS Lambda Function in Java](https://www.baeldung.com/java-aws-lambda-hibernate)
|
||||
- [Writing an Enterprise-Grade AWS Lambda in Java](https://www.baeldung.com/java-enterprise-aws-lambda)
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
<modules>
|
||||
<module>lambda</module>
|
||||
<module>shipping-tracker/ShippingFunction</module>
|
||||
<module>todo-reminder/ToDoFunction</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
<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>helloworld</groupId>
|
||||
<artifactId>HelloWorld</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>To Do Application Example.</name>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-core</artifactId>
|
||||
<version>1.2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-events</artifactId>
|
||||
<version>3.6.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>uk.org.webcompere</groupId>
|
||||
<artifactId>lightweight-config</artifactId>
|
||||
<version>1.1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-log4j2</artifactId>
|
||||
<version>1.2.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-slf4j-impl</artifactId>
|
||||
<version>2.13.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-core</artifactId>
|
||||
<version>11.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-slf4j</artifactId>
|
||||
<version>11.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-gson</artifactId>
|
||||
<version>11.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.inject</groupId>
|
||||
<artifactId>guice</artifactId>
|
||||
<version>5.0.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>uk.org.webcompere</groupId>
|
||||
<artifactId>system-stubs-junit4</artifactId>
|
||||
<version>1.2.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.19.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.2.4</version>
|
||||
<configuration>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.lambda.todo;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URL;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.amazonaws.services.lambda.runtime.Context;
|
||||
import com.amazonaws.services.lambda.runtime.RequestHandler;
|
||||
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
|
||||
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
|
||||
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
|
||||
import com.baeldung.lambda.todo.config.ExecutionContext;
|
||||
import com.baeldung.lambda.todo.service.PostService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Handler for requests to Lambda function.
|
||||
*/
|
||||
public class App implements RequestStreamHandler {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
|
||||
|
||||
private String environmentName = System.getenv("ENV_NAME");
|
||||
private ExecutionContext executionContext = new ExecutionContext();
|
||||
|
||||
@Override
|
||||
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
|
||||
context.getLogger().log("App starting\n");
|
||||
context.getLogger().log("Environment: "
|
||||
+ environmentName + "\n");
|
||||
|
||||
try {
|
||||
PostService postService = executionContext.getPostService();
|
||||
executionContext.getToDoReaderService()
|
||||
.getOldestToDo()
|
||||
.ifPresent(postService::makePost);
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("Failed: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.lambda.todo.api;
|
||||
|
||||
import feign.RequestLine;
|
||||
|
||||
public interface PostApi {
|
||||
@RequestLine("POST /posts")
|
||||
void makePost(PostItem item);
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.lambda.todo.api;
|
||||
|
||||
public class PostItem {
|
||||
private String title;
|
||||
private String body;
|
||||
private int userId;
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public void setBody(String body) {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public int getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(int userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "PostItem{"
|
||||
+ "title='" + title + '\''
|
||||
+ ", body='" + body + '\''
|
||||
+ ", userId=" + userId +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.lambda.todo.api;
|
||||
|
||||
import feign.RequestLine;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ToDoApi {
|
||||
@RequestLine("GET /todos")
|
||||
List<ToDoItem> getAllTodos();
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.lambda.todo.api;
|
||||
|
||||
public class ToDoItem {
|
||||
private int userId;
|
||||
private int id;
|
||||
private String title;
|
||||
private boolean completed;
|
||||
|
||||
public int getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(int userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public boolean isCompleted() {
|
||||
return completed;
|
||||
}
|
||||
|
||||
public void setCompleted(boolean completed) {
|
||||
this.completed = completed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ToDoItem{"
|
||||
+ "userId=" + userId
|
||||
+ ", id=" + id
|
||||
+ ", title='" + title + '\''
|
||||
+ ", completed=" + completed +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.lambda.todo.config;
|
||||
|
||||
public class Config {
|
||||
private String toDoEndpoint;
|
||||
private String postEndpoint;
|
||||
private String environmentName;
|
||||
|
||||
private Credentials toDoCredentials;
|
||||
private Credentials postCredentials;
|
||||
|
||||
public String getToDoEndpoint() {
|
||||
return toDoEndpoint;
|
||||
}
|
||||
|
||||
public void setToDoEndpoint(String toDoEndpoint) {
|
||||
this.toDoEndpoint = toDoEndpoint;
|
||||
}
|
||||
|
||||
public String getPostEndpoint() {
|
||||
return postEndpoint;
|
||||
}
|
||||
|
||||
public void setPostEndpoint(String postEndpoint) {
|
||||
this.postEndpoint = postEndpoint;
|
||||
}
|
||||
|
||||
public String getEnvironmentName() {
|
||||
return environmentName;
|
||||
}
|
||||
|
||||
public void setEnvironmentName(String environmentName) {
|
||||
this.environmentName = environmentName;
|
||||
}
|
||||
|
||||
public Credentials getToDoCredentials() {
|
||||
return toDoCredentials;
|
||||
}
|
||||
|
||||
public void setToDoCredentials(Credentials toDoCredentials) {
|
||||
this.toDoCredentials = toDoCredentials;
|
||||
}
|
||||
|
||||
public Credentials getPostCredentials() {
|
||||
return postCredentials;
|
||||
}
|
||||
|
||||
public void setPostCredentials(Credentials postCredentials) {
|
||||
this.postCredentials = postCredentials;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.lambda.todo.config;
|
||||
|
||||
public class Credentials {
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.lambda.todo.config;
|
||||
|
||||
import com.baeldung.lambda.todo.service.PostService;
|
||||
import com.baeldung.lambda.todo.service.ToDoReaderService;
|
||||
import com.google.inject.Guice;
|
||||
import com.google.inject.Injector;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class ExecutionContext {
|
||||
private static final Logger LOGGER =
|
||||
LoggerFactory.getLogger(ExecutionContext.class);
|
||||
|
||||
private ToDoReaderService toDoReaderService;
|
||||
private PostService postService;
|
||||
|
||||
public ExecutionContext() {
|
||||
LOGGER.info("Loading configuration");
|
||||
|
||||
try {
|
||||
Injector injector = Guice.createInjector(new Services());
|
||||
this.toDoReaderService = injector.getInstance(ToDoReaderService.class);
|
||||
this.postService = injector.getInstance(PostService.class);
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("Could not start", e);
|
||||
}
|
||||
}
|
||||
|
||||
public ToDoReaderService getToDoReaderService() {
|
||||
return toDoReaderService;
|
||||
}
|
||||
|
||||
public PostService getPostService() {
|
||||
return postService;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.lambda.todo.config;
|
||||
|
||||
import com.baeldung.lambda.todo.api.PostApi;
|
||||
import com.baeldung.lambda.todo.api.ToDoApi;
|
||||
import com.google.inject.AbstractModule;
|
||||
import feign.Feign;
|
||||
import feign.auth.BasicAuthRequestInterceptor;
|
||||
import feign.gson.GsonDecoder;
|
||||
import feign.gson.GsonEncoder;
|
||||
import feign.slf4j.Slf4jLogger;
|
||||
import uk.org.webcompere.lightweightconfig.ConfigLoader;
|
||||
|
||||
import static feign.Logger.Level.FULL;
|
||||
|
||||
public class Services extends AbstractModule {
|
||||
@Override
|
||||
protected void configure() {
|
||||
Config config = ConfigLoader.loadYmlConfigFromResource("configuration.yml", Config.class);
|
||||
|
||||
ToDoApi toDoApi = Feign.builder()
|
||||
.decoder(new GsonDecoder())
|
||||
.logger(new Slf4jLogger())
|
||||
.logLevel(FULL)
|
||||
.requestInterceptor(new BasicAuthRequestInterceptor(config.getToDoCredentials().getUsername(), config.getToDoCredentials().getPassword()))
|
||||
.target(ToDoApi.class, config.getToDoEndpoint());
|
||||
|
||||
PostApi postApi = Feign.builder()
|
||||
.encoder(new GsonEncoder())
|
||||
.logger(new Slf4jLogger())
|
||||
.logLevel(FULL)
|
||||
.requestInterceptor(new BasicAuthRequestInterceptor(config.getPostCredentials().getUsername(), config.getPostCredentials().getPassword()))
|
||||
.target(PostApi.class, config.getPostEndpoint());
|
||||
|
||||
bind(Config.class).toInstance(config);
|
||||
bind(ToDoApi.class).toInstance(toDoApi);
|
||||
bind(PostApi.class).toInstance(postApi);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.lambda.todo.service;
|
||||
|
||||
import com.baeldung.lambda.todo.api.PostApi;
|
||||
import com.baeldung.lambda.todo.api.PostItem;
|
||||
import com.baeldung.lambda.todo.api.ToDoItem;
|
||||
import com.google.inject.Inject;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
|
||||
public class PostService {
|
||||
private static final Logger LOGGER = LogManager.getLogger(PostService.class);
|
||||
private PostApi postApi;
|
||||
|
||||
@Inject
|
||||
public PostService(PostApi postApi) {
|
||||
this.postApi = postApi;
|
||||
}
|
||||
|
||||
public void makePost(ToDoItem toDoItem) {
|
||||
LOGGER.info("Posting about: {}", toDoItem);
|
||||
PostItem item = new PostItem();
|
||||
item.setTitle("To Do is Out Of Date: " + toDoItem.getId());
|
||||
item.setUserId(toDoItem.getUserId());
|
||||
item.setBody("Not done: " + toDoItem.getTitle());
|
||||
|
||||
LOGGER.info("Post: {}", item);
|
||||
postApi.makePost(item);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.lambda.todo.service;
|
||||
|
||||
import com.baeldung.lambda.todo.api.ToDoApi;
|
||||
import com.baeldung.lambda.todo.api.ToDoItem;
|
||||
import com.baeldung.lambda.todo.config.Config;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import java.util.Optional;
|
||||
|
||||
public class ToDoReaderService {
|
||||
// Log4j logger
|
||||
private static final Logger LOGGER = LogManager.getLogger(ToDoReaderService.class);
|
||||
|
||||
private ToDoApi toDoApi;
|
||||
|
||||
@Inject
|
||||
public ToDoReaderService(Config configuration, ToDoApi toDoApi) {
|
||||
LOGGER.info("ToDo Endpoint on: {}", configuration.getToDoEndpoint());
|
||||
|
||||
this.toDoApi = toDoApi;
|
||||
}
|
||||
|
||||
public Optional<ToDoItem> getOldestToDo() {
|
||||
return toDoApi.getAllTodos().stream()
|
||||
.filter(item -> !item.isCompleted())
|
||||
.findFirst();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
toDoEndpoint: https://jsonplaceholder.typicode.com
|
||||
postEndpoint: https://jsonplaceholder.typicode.com
|
||||
environmentName: ${ENV_NAME}
|
||||
toDoCredentials:
|
||||
username: baeldung
|
||||
password: ${TODO_PASSWORD:-password}
|
||||
postCredentials:
|
||||
username: baeldung
|
||||
password: ${POST_PASSWORD:-password}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration packages="com.amazonaws.services.lambda.runtime.log4j2">
|
||||
<Appenders>
|
||||
<Lambda name="Lambda">
|
||||
<PatternLayout>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} %X{AWSRequestId} %-5p %c{1} - %m%n</pattern>
|
||||
</PatternLayout>
|
||||
</Lambda>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<Root level="info">
|
||||
<AppenderRef ref="Lambda" />
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.lambda.todo;
|
||||
|
||||
import com.amazonaws.services.lambda.runtime.Context;
|
||||
import com.baeldung.lambda.todo.config.Config;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Answers;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import uk.org.webcompere.lightweightconfig.ConfigLoader;
|
||||
import uk.org.webcompere.systemstubs.rules.EnvironmentVariablesRule;
|
||||
import uk.org.webcompere.systemstubs.stream.input.LinesAltStream;
|
||||
import uk.org.webcompere.systemstubs.stream.output.NoopStream;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class AppTest {
|
||||
|
||||
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
|
||||
private Context mockContext;
|
||||
|
||||
@Rule
|
||||
public EnvironmentVariablesRule environmentVariablesRule = new EnvironmentVariablesRule();
|
||||
|
||||
private InputStream fakeInputStream = new LinesAltStream();
|
||||
private OutputStream fakeOutputStream = new NoopStream();
|
||||
|
||||
@Test
|
||||
public void whenTheEnvironmentVariableIsSet_thenItIsLogged() throws Exception {
|
||||
environmentVariablesRule.set("ENV_NAME", "unitTest");
|
||||
new App().handleRequest(fakeInputStream, fakeOutputStream, mockContext);
|
||||
|
||||
verify(mockContext.getLogger())
|
||||
.log("Environment: unitTest\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEnvironmentVariableIsNotSet_thenUseDefault() {
|
||||
String setting = Optional.ofNullable(System.getenv("SETTING"))
|
||||
.orElse("default");
|
||||
|
||||
assertThat(setting).isEqualTo("default");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConfiguration_canLoadIntoPojo() {
|
||||
environmentVariablesRule.set("ENV_NAME", "unitTest");
|
||||
Config config = ConfigLoader.loadYmlConfigFromResource("configuration.yml", Config.class);
|
||||
assertThat(config.getEnvironmentName()).isEqualTo("unitTest");
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.lambda.todo.service;
|
||||
|
||||
import com.baeldung.lambda.todo.config.Config;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import uk.org.webcompere.systemstubs.rules.SystemOutRule;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
|
||||
|
||||
public class ToDoReaderServiceTest {
|
||||
|
||||
@Rule
|
||||
public SystemOutRule systemOutRule = new SystemOutRule();
|
||||
|
||||
@Test
|
||||
public void whenTheServiceStarts_thenItOutputsEndpoint() {
|
||||
Config config = new Config();
|
||||
config.setToDoEndpoint("https://todo-endpoint.com");
|
||||
ToDoReaderService service = new ToDoReaderService(config, null);
|
||||
|
||||
assertThat(systemOutRule.getLinesNormalized())
|
||||
.contains("ToDo Endpoint on: https://todo-endpoint.com");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
Transform: AWS::Serverless-2016-10-31
|
||||
Description: todo-reminder application
|
||||
|
||||
Parameters:
|
||||
EnvironmentName:
|
||||
Type: String
|
||||
Default: dev
|
||||
|
||||
Resources:
|
||||
ToDoFunction:
|
||||
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
|
||||
Properties:
|
||||
Timeout: 20
|
||||
CodeUri: ToDoFunction
|
||||
Handler: com.baeldung.lambda.todo.App::handleRequest
|
||||
Runtime: java8
|
||||
MemorySize: 512
|
||||
Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
|
||||
Variables:
|
||||
PARAM1: VALUE
|
||||
ENV_NAME: !Ref EnvironmentName
|
||||
@@ -8,3 +8,4 @@ This module contains complete guides about arrays in Java
|
||||
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
|
||||
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
|
||||
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
|
||||
- [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size)
|
||||
|
||||
@@ -8,3 +8,4 @@
|
||||
- [Localizing Exception Messages in Java](https://www.baeldung.com/java-localize-exception-messages)
|
||||
- [Explanation of ClassCastException in Java](https://www.baeldung.com/java-classcastexception)
|
||||
- [NoSuchFieldError in Java](https://www.baeldung.com/java-nosuchfielderror)
|
||||
- [IllegalAccessError in Java](https://www.baeldung.com/java-illegalaccesserror)
|
||||
|
||||
@@ -5,4 +5,5 @@ This module contains articles about networking in Java
|
||||
### Relevant Articles
|
||||
|
||||
- [Finding a Free Port in Java](https://www.baeldung.com/java-free-port)
|
||||
- [Downloading Email Attachments in Java](https://www.baeldung.com/java-download-email-attachments)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-networking-2)
|
||||
|
||||
@@ -5,3 +5,4 @@
|
||||
- [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static)
|
||||
- [Checking if a Java Class is ‘abstract’ Using Reflection](https://www.baeldung.com/java-reflection-is-class-abstract)
|
||||
- [Invoking a Private Method in Java](https://www.baeldung.com/java-call-private-method)
|
||||
- [Finding All Classes in a Java Package](https://www.baeldung.com/java-find-all-classes-in-package)
|
||||
|
||||
@@ -13,3 +13,4 @@
|
||||
- [Regular Expressions \s and \s+ in Java](https://www.baeldung.com/java-regex-s-splus)
|
||||
- [Validate Phone Numbers With Java Regex](https://www.baeldung.com/java-regex-validate-phone-numbers)
|
||||
- [How to Count the Number of Matches for a Regex?](https://www.baeldung.com/java-count-regex-matches)
|
||||
- [Find All Numbers in a String in Java](https://www.baeldung.com/java-find-numbers-in-string)
|
||||
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package com.baeldung.regex.countdigits;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
|
||||
/**
|
||||
* Unit Test to count the number of digits in a String
|
||||
*/
|
||||
class CountDigitsUnitTest {
|
||||
|
||||
// Guava CharMatcher to match digits
|
||||
private static final CharMatcher DIGIT_CHAR_MATCHER = CharMatcher.inRange('0', '9');
|
||||
|
||||
private static final String STR_WITH_ALL_DIGITS = "970987678607608";
|
||||
private static final String STR_WITH_SINGLE_DIGITS_SEP_BY_NON_DIGITS = "9kjl()4f*(&6~3dfd8&5dfd8a";
|
||||
private static final String STR_WITH_SEQUENCES_OF_1_OR_MORE_DIGITS_SEP_BY_NON_DIGITS
|
||||
= "64.6lk.l~453lkdsf9wg038.68*()(k;95786fsd7986";
|
||||
|
||||
private static int countDigits(String stringToSearch) {
|
||||
Matcher countEmailMatcher = Pattern.compile("\\d").matcher(stringToSearch);
|
||||
|
||||
int count = 0;
|
||||
while (countEmailMatcher.find()) {
|
||||
count++;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrOfAllDigits_whenRegexMatchByDigit_thenFifteenDigitsCounted() {
|
||||
int count = countDigits(STR_WITH_ALL_DIGITS);
|
||||
|
||||
assertThat(count).isEqualTo(15);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrWithSingleDigitsSepByNonDigits_whenRegexMatchByDigit_thenSevenDigitsCounted() {
|
||||
int count = countDigits(STR_WITH_SINGLE_DIGITS_SEP_BY_NON_DIGITS);
|
||||
|
||||
assertThat(count).isEqualTo(7);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrWithOneOrMoreDigitsSepByNonDigits_whenRegexMatchByDigit_thenTwentyOneDigitsCounted() {
|
||||
int count = countDigits(STR_WITH_SEQUENCES_OF_1_OR_MORE_DIGITS_SEP_BY_NON_DIGITS);
|
||||
|
||||
assertThat(count).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrOfAllDigits_whenGuavaCharMatchByDigit_thenFifteenDigitsCounted() {
|
||||
int count = DIGIT_CHAR_MATCHER.countIn(STR_WITH_ALL_DIGITS);
|
||||
|
||||
assertThat(count).isEqualTo(15);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrWithSingleDigitsSepByNonDigits_whenGuavaCharMatchByDigit_thenSevenDigitsCounted() {
|
||||
int count = DIGIT_CHAR_MATCHER.countIn(STR_WITH_SINGLE_DIGITS_SEP_BY_NON_DIGITS);
|
||||
|
||||
assertThat(count).isEqualTo(7);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrWithOneOrMoreDigitsSepByNonDigits_whenGuavaCharMatchByDigit_thenTwentyOneDigitsCounted() {
|
||||
int count = DIGIT_CHAR_MATCHER.countIn(STR_WITH_SEQUENCES_OF_1_OR_MORE_DIGITS_SEP_BY_NON_DIGITS);
|
||||
|
||||
assertThat(count).isEqualTo(21);
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package com.baeldung.regex.findnumbers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.LongStream;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Unit Test to find Integers, Decimal Numbers, and Scientific Notation and Hexadecimal Numbers in a String
|
||||
*/
|
||||
class FindNumbersUnitTest {
|
||||
|
||||
private static List<String> findIntegers(String stringToSearch) {
|
||||
Pattern integerPattern = Pattern.compile("-?\\d+");
|
||||
Matcher matcher = integerPattern.matcher(stringToSearch);
|
||||
|
||||
List<String> integerList = new ArrayList<>();
|
||||
while (matcher.find()) {
|
||||
integerList.add(matcher.group());
|
||||
}
|
||||
|
||||
return integerList;
|
||||
}
|
||||
|
||||
private static List<String> findDecimalNums(String stringToSearch) {
|
||||
Pattern decimalNumPattern = Pattern.compile("-?\\d+(\\.\\d+)?");
|
||||
Matcher matcher = decimalNumPattern.matcher(stringToSearch);
|
||||
|
||||
List<String> decimalNumList = new ArrayList<>();
|
||||
while (matcher.find()) {
|
||||
decimalNumList.add(matcher.group());
|
||||
}
|
||||
|
||||
return decimalNumList;
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrOfAllDigits_whenRegexMatchByInt_thenWholeStrMatchedAsOneInt() {
|
||||
List<String> integersFound = findIntegers("970987678607608");
|
||||
|
||||
assertThat(integersFound).containsExactly("970987678607608");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrWithIntegersSepByPeriods_whenRegexMatchByInt_thenExpectedIntsFound() {
|
||||
List<String> integersFound = findIntegers("3453..5.-23532...32432.-2363.3454......345.-34.");
|
||||
|
||||
assertThat(integersFound).containsExactly("3453", "5", "-23532", "32432", "-2363", "3454", "345", "-34");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrWithIntegersSepByNonDigits_whenRegexMatchByInt_thenExpectedIntsFound() {
|
||||
List<String> integersFound = findIntegers("646lkl~4-53l-k34.fdsf.-ds-35.45f9wg3868*()(k;-95786fsd79-86");
|
||||
|
||||
assertThat(integersFound).containsExactly("646", "4", "-53", "34", "-35", "45", "9", "3868", "-95786", "79", "-86");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrOfAllDigits_whenRegexMatchByDecNum_thenWholeStrMatchedAsOneDecimalNumber() {
|
||||
List<String> decimalNumsFound = findDecimalNums("970987678607608");
|
||||
|
||||
assertThat(decimalNumsFound).containsExactly("970987678607608");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrOfDecNumsSepByNonDigits_whenRegexMatchByDecNum_thenExpectedNumsFound() {
|
||||
List<String> decimalNumsFound = findDecimalNums(".7854.455wo.rdy(do.g)-3.-553.00.53;good^night%o3456sdcardR%3567.4%£cat");
|
||||
|
||||
assertThat(decimalNumsFound).containsExactly("7854.455", "-3", "-553.00", "53", "3456", "3567.4");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrWithRandomDigitsDashesAndPeriods_whenRegexMatchByDecNum_thenExpectedNumsFound() {
|
||||
List<String> decimalNumsFound = findDecimalNums(".-..90834.345.--493-..-85.-875.345-.-.-355.345...345.-.636-5.6-3.");
|
||||
|
||||
assertThat(decimalNumsFound).containsExactly("90834.345", "-493", "-85", "-875.345", "-355.345", "345", "636", "-5.6", "-3");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrOfIntsSepByNonDigits_whenRegexMatchByInt_thenExpectedValuesFound() {
|
||||
LongStream integerValuesFound = findIntegers(".7854.455wo.rdy(do.g)-3.ght%o34.56")
|
||||
.stream().mapToLong(Long::valueOf);
|
||||
|
||||
assertThat(integerValuesFound).containsExactly(7854L, 455L, -3L, 34L, 56L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrOfDecNumsSepByNonDigits_whenRegexMatchByDecNum_thenExpectedValuesFound() {
|
||||
DoubleStream decimalNumValuesFound = findDecimalNums(".7854.455wo.rdy(do.g)-3.ght%o34.56")
|
||||
.stream().mapToDouble(Double::valueOf);
|
||||
|
||||
assertThat(decimalNumValuesFound).containsExactly(7854.455, -3.0, 34.56);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrOfSciNotationNumsSepByNonDigits_whenRegexMatchBySciNotNum_thenExpectedNumsFound() {
|
||||
String strToSearch = "}s1.25E-3>,/@l2e109he-70.96E+105d£d_-8.7312E-102=#;,.d919.3822e+31e]";
|
||||
|
||||
Matcher matcher = Pattern.compile("-?\\d+(\\.\\d+)?[eE][+-]?\\d+")
|
||||
.matcher(strToSearch);
|
||||
List<String> sciNotationNums = new ArrayList<>();
|
||||
while (matcher.find()) {
|
||||
sciNotationNums.add(matcher.group());
|
||||
}
|
||||
|
||||
assertThat(sciNotationNums).containsExactly("1.25E-3", "2e109", "-70.96E+105", "-8.7312E-102", "919.3822e+31");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStrOfHexNumsSepByNonDigits_whenRegexMatchByHexNum_thenExpectedNumsFound() {
|
||||
String strToSearch = "}saF851Bq-3f6Cm>,/@j-2Ad9eE>70ae19.>";
|
||||
|
||||
Matcher matcher = Pattern.compile("-?[0-9a-fA-F]+")
|
||||
.matcher(strToSearch);
|
||||
List<String> hexNums = new ArrayList<>();
|
||||
while (matcher.find()) {
|
||||
hexNums.add(matcher.group());
|
||||
}
|
||||
|
||||
assertThat(hexNums).containsExactly("aF851B", "-3f6C", "-2Ad9eE", "70ae19");
|
||||
}
|
||||
}
|
||||
@@ -4,5 +4,5 @@ This module contains articles about core Java Security
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Secret Key and String Conversion in Java](https://www.baeldung.com/secret-key-and-string-conversion-in-java/)
|
||||
- [Secret Key and String Conversion in Java](https://www.baeldung.com/java-secret-key-to-string)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-security-2)
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Using Cucumber with Gradle](https://www.baeldung.com/java-cucumber-gradle)
|
||||
@@ -17,6 +17,7 @@
|
||||
<artifactId>client-java</artifactId>
|
||||
<version>11.0.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user