Merge branch 'eugenp:master' into master
This commit is contained in:
@@ -0,0 +1 @@
|
||||
.aws-sam/
|
||||
@@ -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
|
||||
@@ -22,6 +22,16 @@
|
||||
<version>${spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.reflections</groupId>
|
||||
<artifactId>reflections</artifactId>
|
||||
<version>0.9.12</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>30.1.1-jre</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.reflection.access.packages;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.reflections.Reflections;
|
||||
import org.reflections.scanners.SubTypesScanner;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.reflect.ClassPath;
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public class AccessingAllClassesInPackage {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(AccessingAllClassesInPackage.class);
|
||||
|
||||
public Set<Class> findAllClassesUsingClassLoader(String packageName) {
|
||||
InputStream stream = ClassLoader.getSystemClassLoader()
|
||||
.getResourceAsStream(packageName.replaceAll("[.]", "/"));
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
|
||||
return reader.lines()
|
||||
.filter(line -> line.endsWith(".class"))
|
||||
.map(line -> getClass(line, packageName))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private Class getClass(String className, String packageName) {
|
||||
try {
|
||||
return Class.forName(packageName + "." + className.substring(0, className.lastIndexOf('.')));
|
||||
} catch (ClassNotFoundException e) {
|
||||
LOG.error("<<Class not found>>");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Set<Class> findAllClassesUsingReflectionsLibrary(String packageName) {
|
||||
Reflections reflections = new Reflections(packageName, new SubTypesScanner(false));
|
||||
return reflections.getSubTypesOf(Object.class)
|
||||
.stream()
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public Set<Class> findAllClassesUsingGoogleGuice(String packageName) throws IOException {
|
||||
return ClassPath.from(ClassLoader.getSystemClassLoader())
|
||||
.getAllClasses()
|
||||
.stream()
|
||||
.filter(clazz -> clazz.getPackageName()
|
||||
.equalsIgnoreCase(packageName))
|
||||
.map(clazz -> clazz.load())
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.reflection.access.packages.search;
|
||||
|
||||
public class ClassExample {
|
||||
class NestedClassExample {
|
||||
}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.reflection.access.packages.search;
|
||||
|
||||
public interface InterfaceExample {
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.reflection.access.packages.search;
|
||||
|
||||
public @interface Searchable {
|
||||
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
@Searchable
|
||||
package com.baeldung.reflection.access.packages.search;
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.reflection.access.packages;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public class AccessingAllClassesInPackageUnitTest {
|
||||
@Rule
|
||||
public final ExpectedException exception = ExpectedException.none();
|
||||
|
||||
private static final String PACKAGE_NAME = "com.baeldung.reflection.access.packages.search";
|
||||
|
||||
@Test
|
||||
public void when_findAllClassesUsingClassLoader_thenSuccess() {
|
||||
AccessingAllClassesInPackage instance = new AccessingAllClassesInPackage();
|
||||
Set<Class> classes = instance.findAllClassesUsingClassLoader(PACKAGE_NAME);
|
||||
Assertions.assertEquals(5, classes.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_findAllClassesUsingReflectionsLibrary_thenSuccess() {
|
||||
AccessingAllClassesInPackage instance = new AccessingAllClassesInPackage();
|
||||
Set<Class> classes = instance.findAllClassesUsingReflectionsLibrary(PACKAGE_NAME);
|
||||
Assertions.assertEquals(5, classes.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_findAllClassesUsingGoogleGuice_thenSuccess() throws IOException {
|
||||
AccessingAllClassesInPackage instance = new AccessingAllClassesInPackage();
|
||||
Set<Class> classes = instance.findAllClassesUsingGoogleGuice(PACKAGE_NAME);
|
||||
Assertions.assertEquals(5, classes.size());
|
||||
}
|
||||
|
||||
}
|
||||
+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");
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
<artifactId>client-java</artifactId>
|
||||
<version>11.0.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.kubernetes.intro;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import io.kubernetes.client.custom.V1Patch;
|
||||
import io.kubernetes.client.custom.V1Patch.V1PatchAdapter;
|
||||
import io.kubernetes.client.openapi.ApiClient;
|
||||
import io.kubernetes.client.openapi.apis.BatchV1Api;
|
||||
import io.kubernetes.client.openapi.apis.CoreV1Api;
|
||||
import io.kubernetes.client.openapi.models.V1DeleteOptions;
|
||||
import io.kubernetes.client.openapi.models.V1DeleteOptionsBuilder;
|
||||
import io.kubernetes.client.openapi.models.V1Job;
|
||||
import io.kubernetes.client.openapi.models.V1JobBuilder;
|
||||
import io.kubernetes.client.openapi.models.V1JobSpec;
|
||||
import io.kubernetes.client.openapi.models.V1JobSpecBuilder;
|
||||
import io.kubernetes.client.openapi.models.V1ObjectMeta;
|
||||
import io.kubernetes.client.openapi.models.V1ObjectMetaBuilder;
|
||||
import io.kubernetes.client.openapi.models.V1Status;
|
||||
import io.kubernetes.client.util.Config;
|
||||
import io.kubernetes.client.util.PatchUtils;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.logging.HttpLoggingInterceptor;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
public class RunJob {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(RunJob.class);
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
// Create client with logginginterceptor
|
||||
ApiClient client = Config.defaultClient();
|
||||
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> log.info(message));
|
||||
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
|
||||
OkHttpClient newClient = client.getHttpClient()
|
||||
.newBuilder()
|
||||
.addInterceptor(interceptor)
|
||||
.readTimeout(0, TimeUnit.SECONDS)
|
||||
.build();
|
||||
client.setHttpClient(newClient);
|
||||
|
||||
// Create Job Spec
|
||||
BatchV1Api api = new BatchV1Api(client);
|
||||
String ns = "report-jobs";
|
||||
V1Job body = new V1JobBuilder()
|
||||
.withNewMetadata()
|
||||
.withNamespace(ns)
|
||||
.withName("payroll-report-job")
|
||||
.endMetadata()
|
||||
.withNewSpec()
|
||||
.withCompletions(2)
|
||||
.withParallelism(1)
|
||||
.withNewTemplate()
|
||||
.withNewMetadata()
|
||||
.addToLabels("name", "payroll-report")
|
||||
.endMetadata()
|
||||
.editOrNewSpec()
|
||||
.addNewContainer()
|
||||
.withName("main")
|
||||
.withImage("alpine")
|
||||
.addNewCommand("/bin/sh")
|
||||
.addNewArg("-c")
|
||||
.addNewArg("sleep 10")
|
||||
.endContainer()
|
||||
.withRestartPolicy("Never")
|
||||
.endSpec()
|
||||
.endTemplate()
|
||||
.endSpec()
|
||||
.build();
|
||||
|
||||
// Send to K8S
|
||||
V1Job createdJob = api.createNamespacedJob(ns, body, null, null, null);
|
||||
log.info("job: uid={}", createdJob.getMetadata().getUid());
|
||||
|
||||
// Let's change its parallelism value
|
||||
V1Job patchedJob = new V1JobBuilder(createdJob)
|
||||
.withNewMetadata()
|
||||
.withName(createdJob.getMetadata().getName())
|
||||
.withNamespace(createdJob.getMetadata().getNamespace())
|
||||
.endMetadata()
|
||||
.editSpec()
|
||||
.withParallelism(2)
|
||||
.endSpec()
|
||||
.build();
|
||||
|
||||
String patchedJobJSON = client.getJSON().serialize(patchedJob);
|
||||
V1Patch patch = new V1Patch(patchedJobJSON);
|
||||
|
||||
PatchUtils.patch(
|
||||
V1Job.class,
|
||||
() -> api.patchNamespacedJobCall(
|
||||
createdJob.getMetadata().getName(),
|
||||
createdJob.getMetadata().getNamespace(),
|
||||
patch,
|
||||
null,
|
||||
null,
|
||||
"acme",
|
||||
true,
|
||||
null),
|
||||
V1Patch.PATCH_FORMAT_APPLY_YAML,
|
||||
api.getApiClient());
|
||||
|
||||
while(!jobCompleted(api,createdJob)) {
|
||||
log.info("[I75] still running...");
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
|
||||
V1Status response = api.deleteNamespacedJob(
|
||||
createdJob.getMetadata().getName(),
|
||||
createdJob.getMetadata().getNamespace(),
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null ) ;
|
||||
|
||||
log.info("[I122] response={}", response);
|
||||
}
|
||||
|
||||
private static boolean jobCompleted(BatchV1Api api, V1Job createdJob) throws Exception {
|
||||
|
||||
V1Job job = api.readNamespacedJob(
|
||||
createdJob.getMetadata().getName(),
|
||||
createdJob.getMetadata().getNamespace(),
|
||||
null,null,null);
|
||||
|
||||
if ( job.getStatus() == null ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
log.info("[I88] Status: active={}, succeeded={}, failed={}",
|
||||
job.getStatus().getActive(),
|
||||
job.getStatus().getSucceeded(),
|
||||
job.getStatus().getFailed()
|
||||
);
|
||||
Integer active = job.getStatus().getActive();
|
||||
|
||||
return active == null || active == 0 ;
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user