Skip to content
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

fix: sonar issues #1313

Closed
wants to merge 22 commits into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@
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;
Expand All @@ -22,6 +26,8 @@

public class App extends AbstractCustomResourceHandler {
private final static Logger log = LogManager.getLogger(App.class);
private static final String CFN_CUSTOM_RESOURCE_EVENT_CANNOT_BE_NULL = "cloudFormationCustomResourceEvent cannot be null.";
private static final String BUCKET_NAME = "BucketName";
private final S3Client s3Client;

public App() {
Expand All @@ -40,11 +46,11 @@ public App() {
@Override
protected Response create(CloudFormationCustomResourceEvent cloudFormationCustomResourceEvent, Context context) {
// Validate the CloudFormation Custom Resource event
Objects.requireNonNull(cloudFormationCustomResourceEvent, "cloudFormationCustomResourceEvent cannot be null.");
Objects.requireNonNull(cloudFormationCustomResourceEvent.getResourceProperties().get("BucketName"), "BucketName cannot be null.");
Objects.requireNonNull(cloudFormationCustomResourceEvent, CFN_CUSTOM_RESOURCE_EVENT_CANNOT_BE_NULL);
Objects.requireNonNull(cloudFormationCustomResourceEvent.getResourceProperties().get(BUCKET_NAME), "BucketName cannot be null.");

log.info(cloudFormationCustomResourceEvent);
String bucketName = (String) cloudFormationCustomResourceEvent.getResourceProperties().get("BucketName");
String bucketName = (String) cloudFormationCustomResourceEvent.getResourceProperties().get(BUCKET_NAME);
log.info("Bucket Name {}", bucketName);
try {
// Create the S3 bucket with the given bucketName
Expand All @@ -69,16 +75,16 @@ protected Response create(CloudFormationCustomResourceEvent cloudFormationCustom
@Override
protected Response update(CloudFormationCustomResourceEvent cloudFormationCustomResourceEvent, Context context) {
// Validate the CloudFormation Custom Resource event
Objects.requireNonNull(cloudFormationCustomResourceEvent, "cloudFormationCustomResourceEvent cannot be null.");
Objects.requireNonNull(cloudFormationCustomResourceEvent.getResourceProperties().get("BucketName"), "BucketName cannot be null.");
Objects.requireNonNull(cloudFormationCustomResourceEvent, CFN_CUSTOM_RESOURCE_EVENT_CANNOT_BE_NULL);
Objects.requireNonNull(cloudFormationCustomResourceEvent.getResourceProperties().get(BUCKET_NAME), "BucketName cannot be null.");

log.info(cloudFormationCustomResourceEvent);
// Get the physicalResourceId. physicalResourceId is the value returned to CloudFormation in the Create request, and passed in on subsequent requests (e.g. UPDATE or DELETE)
String physicalResourceId = cloudFormationCustomResourceEvent.getPhysicalResourceId();
log.info("Physical Resource ID {}", physicalResourceId);

// Get the BucketName from the CloudFormation Event
String newBucketName = (String) cloudFormationCustomResourceEvent.getResourceProperties().get("BucketName");
String newBucketName = (String) cloudFormationCustomResourceEvent.getResourceProperties().get(BUCKET_NAME);

// Check if the physicalResourceId equals the new BucketName
if (!physicalResourceId.equals(newBucketName)) {
Expand Down Expand Up @@ -111,7 +117,7 @@ protected Response update(CloudFormationCustomResourceEvent cloudFormationCustom
@Override
protected Response delete(CloudFormationCustomResourceEvent cloudFormationCustomResourceEvent, Context context) {
// Validate the CloudFormation Custom Resource event
Objects.requireNonNull(cloudFormationCustomResourceEvent, "cloudFormationCustomResourceEvent cannot be null.");
Objects.requireNonNull(cloudFormationCustomResourceEvent, CFN_CUSTOM_RESOURCE_EVENT_CANNOT_BE_NULL);
Objects.requireNonNull(cloudFormationCustomResourceEvent.getPhysicalResourceId(), "PhysicalResourceId cannot be null.");

log.info(cloudFormationCustomResourceEvent);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ public class MyObject {
private String code;

public MyObject() {
// for deserialization
}

public long getId() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@ public final Response handleRequest(CloudFormationCustomResourceEvent event, Con
String responseUrl = Objects.requireNonNull(event.getResponseUrl(),
"Event must have a non-null responseUrl to be able to send the response.");

CloudFormationResponse client = buildResponseClient();
CloudFormationResponse cloudFormationResponse = buildResponseClient();

Response response = null;
try {
response = getResponse(event, context);
LOG.debug("Preparing to send response {} to {}.", response, responseUrl);
client.send(event, context, response);
cloudFormationResponse.send(event, context, response);
} catch (IOException ioe) {
LOG.error("Unable to send response {} to {}.", response, responseUrl, ioe);
onSendFailure(event, context, response, ioe);
Expand All @@ -70,7 +70,7 @@ public final Response handleRequest(CloudFormationCustomResourceEvent event, Con
// In the case of a Update or Delete, a failure is sent with the existing PhysicalResourceId
// indicating no change.
// In the case of a Create, null will be set and changed to the Lambda LogStreamName before sending.
client.send(event, context, Response.failed(event.getPhysicalResourceId()));
cloudFormationResponse.send(event, context, Response.failed(event.getPhysicalResourceId()));
} catch (Exception e) {
// unable to generate response AND send the failure
LOG.error("Unable to send failure response to {}.", responseUrl, e);
Expand All @@ -91,7 +91,7 @@ private Response getResponse(CloudFormationCustomResourceEvent event, Context co
case "Delete":
return delete(event, context);
default:
LOG.warn("Unexpected request type \"" + event.getRequestType() + "\" for event " + event);
LOG.warn("Unexpected request type \"{}\" for event {}", event.getRequestType(), event);
return null;
}
} catch (RuntimeException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,16 +118,14 @@ ObjectNode toObjectNode(JsonNode dataNode) {

@Override
public String toString() {
final StringBuffer sb = new StringBuffer("ResponseBody{");
sb.append("status='").append(status).append('\'');
sb.append(", reason='").append(reason).append('\'');
sb.append(", physicalResourceId='").append(physicalResourceId).append('\'');
sb.append(", stackId='").append(stackId).append('\'');
sb.append(", requestId='").append(requestId).append('\'');
sb.append(", logicalResourceId='").append(logicalResourceId).append('\'');
sb.append(", noEcho=").append(noEcho);
sb.append('}');
return sb.toString();
return "ResponseBody{" + "status='" + status + '\'' +
", reason='" + reason + '\'' +
", physicalResourceId='" + physicalResourceId + '\'' +
", stackId='" + stackId + '\'' +
", requestId='" + requestId + '\'' +
", logicalResourceId='" + logicalResourceId + '\'' +
", noEcho=" + noEcho +
'}';
}
}

Expand Down Expand Up @@ -232,15 +230,14 @@ StringInputStream responseBodyStream(CloudFormationCustomResourceEvent event,
} else {

String physicalResourceId = resp.getPhysicalResourceId() != null ? resp.getPhysicalResourceId() :
event.getPhysicalResourceId() != null? event.getPhysicalResourceId() : context.getLogStreamName();
(event.getPhysicalResourceId() != null ? event.getPhysicalResourceId() : context.getLogStreamName());

ResponseBody body = new ResponseBody(event, resp.getStatus(), physicalResourceId, resp.isNoEcho(), reason);
LOG.debug("ResponseBody: {}", body);
ObjectNode node = body.toObjectNode(resp.getJsonNode());
return new StringInputStream(node.toString());
}
} catch (RuntimeException e) {
LOG.error(e.getMessage());
throw new CustomResourceResponseException("Unable to generate response body.", e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,23 @@
package software.amazon.lambda.powertools.core.internal;

public class LambdaConstants {

private LambdaConstants() {
// avoid instantiation, static fields
}

public static final String LAMBDA_FUNCTION_NAME_ENV = "AWS_LAMBDA_FUNCTION_NAME";
public static final String AWS_REGION_ENV = "AWS_REGION";
// Also you can use AWS_LAMBDA_INITIALIZATION_TYPE to distinguish between on-demand and SnapStart initialization
// it's not recommended to use this env variable to initialize SDK clients or other resources.
/**
* @deprecated
* Also you can use AWS_LAMBDA_INITIALIZATION_TYPE to distinguish between on-demand and SnapStart initialization
* it's not recommended to use this env variable to initialize SDK clients or other resources.
*/
@Deprecated
public static final String AWS_LAMBDA_INITIALIZATION_TYPE = "AWS_LAMBDA_INITIALIZATION_TYPE";
/**
* @deprecated see AWS_LAMBDA_INITIALIZATION_TYPE
*/
@Deprecated
public static final String ON_DEMAND = "on-demand";
public static final String X_AMZN_TRACE_ID = "_X_AMZN_TRACE_ID";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

public class SystemWrapper {
private SystemWrapper() {
// avoid instantiation, static methods
}

public static String getenv(String name) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public Input(String message) {
}

public Input() {
// for deserialization
}

public String getMessage() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ public class Input {
private Map<String, String> keys;

public Input() {
// for deserialization
}

public String getMessage() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public void setMetrics(Map<String, Double> metrics) {
}

public Input() {
// for deserialization
}


Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package software.amazon.lambda.powertools.e2e;

import java.util.Map;

public class Input {

private String app;
private String environment;
private String key;

public Input() {
// for deserialization
}

public void setApp(String app) {
this.app = app;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ public class Input {
private String message;

public Input() {
// for deserialization
}

public String getMessage() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,10 @@
package software.amazon.lambda.powertools.idempotency;

public class Constants {

private Constants() {
// avoid instantiation, static fields
}

public static final String IDEMPOTENCY_DISABLED_ENV = "POWERTOOLS_IDEMPOTENCY_DISABLED";
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@
* </pre>
*/
public class Idempotency {
private IdempotencyConfig config;
private IdempotencyConfig idempotencyConfig;
private BasePersistenceStore persistenceStore;

private Idempotency() {
}

public IdempotencyConfig getConfig() {
return config;
return idempotencyConfig;
}

public BasePersistenceStore getPersistenceStore() {
Expand All @@ -49,8 +49,8 @@ public BasePersistenceStore getPersistenceStore() {
return persistenceStore;
}

private void setConfig(IdempotencyConfig config) {
this.config = config;
private void setConfig(IdempotencyConfig idempotencyConfig) {
this.idempotencyConfig = idempotencyConfig;
}

private void setPersistenceStore(BasePersistenceStore persistenceStore) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.lambda.powertools.idempotency.Idempotency;
import software.amazon.lambda.powertools.idempotency.exceptions.*;
import software.amazon.lambda.powertools.idempotency.exceptions.IdempotencyAlreadyInProgressException;
import software.amazon.lambda.powertools.idempotency.exceptions.IdempotencyInconsistentStateException;
import software.amazon.lambda.powertools.idempotency.exceptions.IdempotencyItemAlreadyExistsException;
import software.amazon.lambda.powertools.idempotency.exceptions.IdempotencyItemNotFoundException;
import software.amazon.lambda.powertools.idempotency.exceptions.IdempotencyKeyException;
import software.amazon.lambda.powertools.idempotency.exceptions.IdempotencyPersistenceLayerException;
import software.amazon.lambda.powertools.idempotency.exceptions.IdempotencyValidationException;
import software.amazon.lambda.powertools.idempotency.persistence.BasePersistenceStore;
import software.amazon.lambda.powertools.idempotency.persistence.DataRecord;
import software.amazon.lambda.powertools.utilities.JsonConfig;
Expand Down Expand Up @@ -83,9 +89,9 @@ private Object processIdempotency() throws Throwable {
// already exists. If it succeeds, there's no need to call getRecord.
persistenceStore.saveInProgress(data, Instant.now(), getRemainingTimeInMillis());
} catch (IdempotencyItemAlreadyExistsException iaee) {
DataRecord record = getIdempotencyRecord();
if (record != null) {
return handleForStatus(record);
DataRecord idempotencyRecord = getIdempotencyRecord();
if (idempotencyRecord != null) {
return handleForStatus(idempotencyRecord);
}
} catch (IdempotencyKeyException ike) {
throw ike;
Expand Down Expand Up @@ -132,29 +138,29 @@ private DataRecord getIdempotencyRecord() {
/**
* Take appropriate action based on data_record's status
*
* @param record DataRecord
* @param dataRecord DataRecord
* @return Function's response previously used for this idempotency key, if it has successfully executed already.
*/
private Object handleForStatus(DataRecord record) {
private Object handleForStatus(DataRecord dataRecord) {
// This code path will only be triggered if the record becomes expired between the saveInProgress call and here
if (EXPIRED.equals(record.getStatus())) {
if (EXPIRED.equals(dataRecord.getStatus())) {
throw new IdempotencyInconsistentStateException("saveInProgress and getRecord return inconsistent results");
}

if (INPROGRESS.equals(record.getStatus())) {
if (record.getInProgressExpiryTimestamp().isPresent()
&& record.getInProgressExpiryTimestamp().getAsLong() < Instant.now().toEpochMilli()) {
if (INPROGRESS.equals(dataRecord.getStatus())) {
if (dataRecord.getInProgressExpiryTimestamp().isPresent()
&& dataRecord.getInProgressExpiryTimestamp().getAsLong() < Instant.now().toEpochMilli()) {
throw new IdempotencyInconsistentStateException("Item should have been expired in-progress because it already time-outed.");
}
throw new IdempotencyAlreadyInProgressException("Execution already in progress with idempotency key: " + record.getIdempotencyKey());
throw new IdempotencyAlreadyInProgressException("Execution already in progress with idempotency key: " + dataRecord.getIdempotencyKey());
}

Class<?> returnType = ((MethodSignature) pjp.getSignature()).getReturnType();
try {
LOG.debug("Response for key '{}' retrieved from idempotency store, skipping the function", record.getIdempotencyKey());
LOG.debug("Response for key '{}' retrieved from idempotency store, skipping the function", dataRecord.getIdempotencyKey());
if (returnType.equals(String.class))
return record.getResponseData();
return JsonConfig.get().getObjectMapper().reader().readValue(record.getResponseData(), returnType);
return dataRecord.getResponseData();
return JsonConfig.get().getObjectMapper().reader().readValue(dataRecord.getResponseData(), returnType);
} catch (Exception e) {
throw new IdempotencyPersistenceLayerException("Unable to get function response as " + returnType.getSimpleName(), e);
}
Expand Down
Loading