Skip to content

chore: apply checkstyle again #1339

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion .sonarcloud.properties
Original file line number Diff line number Diff line change
@@ -1,2 +1,17 @@
#
# Copyright 2023 Amazon.com, Inc. or its affiliates.
# Licensed under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
sonar.exclusions=examples/**/*,powertools-e2e-tests/handlers/**/*

# Ignore code duplicates in the examples
sonar.cpd.exclusions=examples/**/*,powertools-e2e-tests/**/*
sonar.cpd.exclusions=examples/**/*,powertools-e2e-tests/**/*
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,23 @@

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.events.CloudFormationCustomResourceEvent;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.HeadBucketResponse;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import software.amazon.awssdk.services.s3.waiters.S3Waiter;
import software.amazon.lambda.powertools.cloudformation.AbstractCustomResourceHandler;
import software.amazon.lambda.powertools.cloudformation.Response;

import java.util.Objects;

/**
* Handler for requests to Lambda function.
*/
Expand Down
26 changes: 13 additions & 13 deletions examples/powertools-examples-core/src/main/java/helloworld/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,10 @@ public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEv
metricsLogger().putMetric("CustomMetric1", 1, Unit.COUNT);

withSingleMetric("CustomMetrics2", 1, Unit.COUNT, "Another", (metric) ->
{
metric.setDimensions(DimensionSet.of("AnotherService", "CustomService"));
metric.setDimensions(DimensionSet.of("AnotherService1", "CustomService1"));
});
{
metric.setDimensions(DimensionSet.of("AnotherService", "CustomService"));
metric.setDimensions(DimensionSet.of("AnotherService1", "CustomService1"));
});

LoggingUtils.appendKey("test", "willBeLogged");

Expand All @@ -77,11 +77,11 @@ public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEv
String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents);

TracingUtils.withSubsegment("loggingResponse", subsegment ->
{
String sampled = "log something out";
log.info(sampled);
log.info(output);
});
{
String sampled = "log something out";
log.info(sampled);
log.info(output);
});

threadOption1();

Expand All @@ -107,10 +107,10 @@ private void threadOption1() throws InterruptedException {
private void threadOption2() throws InterruptedException {
Entity traceEntity = AWSXRay.getTraceEntity();
Thread anotherThread = new Thread(() -> withEntitySubsegment("inlineLog", traceEntity, subsegment ->
{
String var = "somethingToProcess";
log.info("inside threaded logging inline {}", var);
}));
{
String var = "somethingToProcess";
log.info("inside threaded logging inline {}", var);
}));
anotherThread.start();
anotherThread.join();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,22 +63,22 @@ public String handleRequest(final ScheduledEvent input, final Context context) {
// Push 5 messages on each invoke.
List<SendMessageBatchRequestEntry> batchRequestEntries = IntStream.range(0, 5)
.mapToObj(value ->
{
Map<String, MessageAttributeValue> attributeValueHashMap = new HashMap<>();
attributeValueHashMap.put("Key" + value, MessageAttributeValue.builder()
.dataType("String")
.stringValue("Value" + value)
.build());

byte[] array = new byte[7];
random.nextBytes(array);

return SendMessageBatchRequestEntry.builder()
.messageAttributes(attributeValueHashMap)
.id(input.getId() + value)
.messageBody("Sample Message " + value)
.build();
}).collect(toList());
{
Map<String, MessageAttributeValue> attributeValueHashMap = new HashMap<>();
attributeValueHashMap.put("Key" + value, MessageAttributeValue.builder()
.dataType("String")
.stringValue("Value" + value)
.build());

byte[] array = new byte[7];
random.nextBytes(array);

return SendMessageBatchRequestEntry.builder()
.messageAttributes(attributeValueHashMap)
.id(input.getId() + value)
.messageBody("Sample Message " + value)
.build();
}).collect(toList());

SendMessageBatchResponse sendMessageBatchResponse = sqsClient.sendMessageBatch(SendMessageBatchRequest.builder()
.queueUrl(queueUrl)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,16 @@ static CloudFormationResponse testableCloudFormationResponse() {
ExecutableHttpRequest executableRequest = mock(ExecutableHttpRequest.class);

when(client.prepareRequest(any(HttpExecuteRequest.class))).thenAnswer(args ->
{
HttpExecuteRequest request = args.getArgument(0, HttpExecuteRequest.class);
assertThat(request.contentStreamProvider()).isPresent();

InputStream inputStream = request.contentStreamProvider().get().newStream();
HttpExecuteResponse response = mock(HttpExecuteResponse.class);
when(response.responseBody()).thenReturn(Optional.of(AbortableInputStream.create(inputStream)));
when(executableRequest.call()).thenReturn(response);
return executableRequest;
});
{
HttpExecuteRequest request = args.getArgument(0, HttpExecuteRequest.class);
assertThat(request.contentStreamProvider()).isPresent();

InputStream inputStream = request.contentStreamProvider().get().newStream();
HttpExecuteResponse response = mock(HttpExecuteResponse.class);
when(response.responseBody()).thenReturn(Optional.of(AbortableInputStream.create(inputStream)));
when(executableRequest.call()).thenReturn(response);
return executableRequest;
});

return new CloudFormationResponse(client);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@

class UserAgentConfiguratorTest {

private static final String SEM_VER_PATTERN = "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$";
private static final String SEM_VER_PATTERN =
"^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$";
private static final String VERSION = UserAgentConfigurator.getProjectVersion();


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
import com.amazonaws.services.lambda.runtime.events.SQSBatchResponse;
import com.amazonaws.services.lambda.runtime.events.SQSEvent;
import com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
Expand All @@ -29,10 +32,6 @@
import software.amazon.lambda.powertools.largemessages.LargeMessage;
import software.amazon.lambda.powertools.logging.Logging;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Function implements RequestHandler<SQSEvent, SQSBatchResponse> {

private static final String TABLE_FOR_ASYNC_TESTS = System.getenv("TABLE_FOR_ASYNC_TESTS");
Expand All @@ -49,7 +48,7 @@ public Function() {

@Logging(logEvent = true)
public SQSBatchResponse handleRequest(SQSEvent event, Context context) {
for (SQSMessage message: event.getRecords()) {
for (SQSMessage message : event.getRecords()) {
processRawMessage(message, context);
}
return SQSBatchResponse.builder().build();
Expand All @@ -59,14 +58,18 @@ public SQSBatchResponse handleRequest(SQSEvent event, Context context) {
private void processRawMessage(SQSMessage sqsMessage, Context context) {
String bodyMD5 = md5(sqsMessage.getBody());
if (!sqsMessage.getMd5OfBody().equals(bodyMD5)) {
throw new SecurityException(String.format("message digest does not match, expected %s, got %s", sqsMessage.getMd5OfBody(), bodyMD5));
throw new SecurityException(
String.format("message digest does not match, expected %s, got %s", sqsMessage.getMd5OfBody(),
bodyMD5));
}

Map<String, AttributeValue> item = new HashMap<>();
item.put("functionName", AttributeValue.builder().s(context.getFunctionName()).build());
item.put("id", AttributeValue.builder().s(sqsMessage.getMessageId()).build());
item.put("bodyMD5", AttributeValue.builder().s(bodyMD5).build());
item.put("bodySize", AttributeValue.builder().n(String.valueOf(sqsMessage.getBody().getBytes(StandardCharsets.UTF_8).length)).build());
item.put("bodySize",
AttributeValue.builder().n(String.valueOf(sqsMessage.getBody().getBytes(StandardCharsets.UTF_8).length))
.build());

client.putItem(PutItemRequest.builder().tableName(TABLE_FOR_ASYNC_TESTS).item(item).build());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public Function(DynamoDbClient client) {

@Logging(logEvent = true)
public SQSBatchResponse handleRequest(SQSEvent event, Context context) {
for (SQSEvent.SQSMessage message: event.getRecords()) {
for (SQSEvent.SQSMessage message : event.getRecords()) {
processRawMessage(message, context);
}
return SQSBatchResponse.builder().build();
Expand All @@ -82,7 +82,9 @@ public SQSBatchResponse handleRequest(SQSEvent event, Context context) {
private String processRawMessage(@IdempotencyKey SQSEvent.SQSMessage sqsMessage, Context context) {
String bodyMD5 = md5(sqsMessage.getBody());
if (!sqsMessage.getMd5OfBody().equals(bodyMD5)) {
throw new SecurityException(String.format("message digest does not match, expected %s, got %s", sqsMessage.getMd5OfBody(), bodyMD5));
throw new SecurityException(
String.format("message digest does not match, expected %s, got %s", sqsMessage.getMd5OfBody(),
bodyMD5));
}

Instant now = Instant.now();
Expand All @@ -91,7 +93,9 @@ private String processRawMessage(@IdempotencyKey SQSEvent.SQSMessage sqsMessage,
item.put("id", AttributeValue.builder().s(sqsMessage.getMessageId()).build());
item.put("bodyMD5", AttributeValue.builder().s(bodyMD5).build());
item.put("now", AttributeValue.builder().n(String.valueOf(now.getEpochSecond())).build());
item.put("bodySize", AttributeValue.builder().n(String.valueOf(sqsMessage.getBody().getBytes(StandardCharsets.UTF_8).length)).build());
item.put("bodySize",
AttributeValue.builder().n(String.valueOf(sqsMessage.getBody().getBytes(StandardCharsets.UTF_8).length))
.build());

client.putItem(PutItemRequest.builder().tableName(TABLE_FOR_ASYNC_TESTS).item(item).build());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ public String handleRequest(Input input, Context context) {
String message = buildMessage(input.getMessage(), context.getFunctionName());

TracingUtils.withSubsegment("internal_stuff", subsegment ->
{
try {
Thread.sleep(100); // simulate stuff
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
{
try {
Thread.sleep(100); // simulate stuff
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});

return message;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
package software.amazon.lambda.powertools;

import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.lambda.powertools.testutils.Infrastructure.FUNCTION_NAME_OUTPUT;

import com.amazon.sqs.javamessaging.AmazonSQSExtendedClient;
import com.amazon.sqs.javamessaging.ExtendedClientConfiguration;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
Expand All @@ -23,19 +35,6 @@
import software.amazon.awssdk.services.sqs.model.SendMessageRequest;
import software.amazon.lambda.powertools.testutils.Infrastructure;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.lambda.powertools.testutils.Infrastructure.FUNCTION_NAME_OUTPUT;

public class LargeMessageE2ET {

private static final Logger LOG = LoggerFactory.getLogger(LargeMessageE2ET.class);
Expand Down Expand Up @@ -81,6 +80,13 @@ public static void setup() {
LOG.info("Testing '" + LargeMessageE2ET.class.getSimpleName() + "'");
}

@AfterAll
public static void tearDown() {
if (infrastructure != null) {
infrastructure.destroy();
}
}

@AfterEach
public void reset() {
if (messageId != null) {
Expand All @@ -92,19 +98,14 @@ public void reset() {
}
}

@AfterAll
public static void tearDown() {
if (infrastructure != null)
infrastructure.destroy();
}

@Test
public void bigSQSMessageOffloadedToS3_shouldLoadFromS3() throws IOException, InterruptedException {
// given
final ExtendedClientConfiguration extendedClientConfig =
new ExtendedClientConfiguration()
.withPayloadSupportEnabled(s3Client, bucketName);
AmazonSQSExtendedClient client = new AmazonSQSExtendedClient(SqsClient.builder().httpClient(httpClient).build(), extendedClientConfig);
AmazonSQSExtendedClient client =
new AmazonSQSExtendedClient(SqsClient.builder().httpClient(httpClient).build(), extendedClientConfig);
InputStream inputStream = this.getClass().getResourceAsStream("/large_sqs_message.txt");
String bigMessage = IOUtils.toString(inputStream, StandardCharsets.UTF_8);

Expand All @@ -122,7 +123,8 @@ public void bigSQSMessageOffloadedToS3_shouldLoadFromS3() throws IOException, In
.builder()
.tableName(tableName)
.keyConditionExpression("functionName = :func")
.expressionAttributeValues(Collections.singletonMap(":func", AttributeValue.builder().s(functionName).build()))
.expressionAttributeValues(
Collections.singletonMap(":func", AttributeValue.builder().s(functionName).build()))
.build();
QueryResponse response = dynamoDbClient.query(request);
List<Map<String, AttributeValue>> items = response.items();
Expand All @@ -138,7 +140,8 @@ public void smallSQSMessage_shouldNotReadFromS3() throws IOException, Interrupte
final ExtendedClientConfiguration extendedClientConfig =
new ExtendedClientConfiguration()
.withPayloadSupportEnabled(s3Client, bucketName);
AmazonSQSExtendedClient client = new AmazonSQSExtendedClient(SqsClient.builder().httpClient(httpClient).build(), extendedClientConfig);
AmazonSQSExtendedClient client =
new AmazonSQSExtendedClient(SqsClient.builder().httpClient(httpClient).build(), extendedClientConfig);
String message = "Hello World";

// when
Expand All @@ -155,13 +158,15 @@ public void smallSQSMessage_shouldNotReadFromS3() throws IOException, Interrupte
.builder()
.tableName(tableName)
.keyConditionExpression("functionName = :func")
.expressionAttributeValues(Collections.singletonMap(":func", AttributeValue.builder().s(functionName).build()))
.expressionAttributeValues(
Collections.singletonMap(":func", AttributeValue.builder().s(functionName).build()))
.build();
QueryResponse response = dynamoDbClient.query(request);
List<Map<String, AttributeValue>> items = response.items();
assertThat(items).hasSize(1);
messageId = items.get(0).get("id").s();
assertThat(Integer.valueOf(items.get(0).get("bodySize").n())).isEqualTo(message.getBytes(StandardCharsets.UTF_8).length);
assertThat(Integer.valueOf(items.get(0).get("bodySize").n())).isEqualTo(
message.getBytes(StandardCharsets.UTF_8).length);
assertThat(items.get(0).get("bodyMD5").s()).isEqualTo("b10a8db164e0754105b7a99be72e3fe5");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,8 @@ public void test_ttlNotExpired_doesNotInsertInDDB_ttlExpired_insertInDDB() throw
.builder()
.tableName(tableName)
.keyConditionExpression("functionName = :func")
.expressionAttributeValues(Collections.singletonMap(":func", AttributeValue.builder().s(functionName).build()))
.expressionAttributeValues(
Collections.singletonMap(":func", AttributeValue.builder().s(functionName).build()))
.build();
QueryResponse response = dynamoDbClient.query(request);
List<Map<String, AttributeValue>> items = response.items();
Expand Down
Loading