Search in sources :

Example 46 with LambdaLogger

use of com.amazonaws.services.lambda.runtime.LambdaLogger in project formkiq-core by formkiq.

the class DocumentsS3Update method handleRequest.

@Override
public Void handleRequest(final Map<String, Object> map, final Context context) {
    LambdaLogger logger = context.getLogger();
    try {
        boolean debug = "true".equals(System.getenv("DEBUG"));
        if (debug) {
            String json = this.gson.toJson(map);
            logger.log(json);
        }
        List<Map<String, Object>> list = processRecords(logger, map);
        for (Map<String, Object> e : list) {
            Object eventName = e.getOrDefault("eventName", null);
            Object bucket = e.getOrDefault("s3bucket", null);
            Object key = e.getOrDefault("s3key", null);
            if (bucket != null && key != null) {
                boolean create = eventName != null && eventName.toString().toLowerCase().contains("objectcreated");
                boolean remove = eventName != null && eventName.toString().toLowerCase().contains("objectremove");
                if (debug) {
                    logger.log(String.format("processing event %s for file %s in bucket %s", eventName, bucket, key));
                }
                if (remove) {
                    processS3Delete(logger, bucket.toString(), key.toString());
                } else {
                    processS3File(logger, create, bucket.toString(), key.toString(), debug);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        sendToDlq(map);
    }
    return null;
}
Also used : LambdaLogger(com.amazonaws.services.lambda.runtime.LambdaLogger) HashMap(java.util.HashMap) Map(java.util.Map) FileNotFoundException(java.io.FileNotFoundException)

Example 47 with LambdaLogger

use of com.amazonaws.services.lambda.runtime.LambdaLogger in project formkiq-core by formkiq.

the class StagingS3Create method copyFile.

/**
 * Copies Documentid to a new file that is a {@link UUID}.
 *
 * @param s3Client {@link S3Client}
 * @param logger {@link LambdaLogger}
 * @param bucket {@link String}
 * @param originalkey {@link String}
 * @param date {@link Date}
 */
private void copyFile(final S3Client s3Client, final LambdaLogger logger, final String bucket, final String originalkey, final Date date) {
    String siteId = getSiteId(originalkey);
    String key = resetDatabaseKey(siteId, originalkey);
    boolean uuid = isUuid(key);
    String documentId = uuid ? key : UUID.randomUUID().toString();
    String destKey = createDatabaseKey(siteId, documentId);
    logger.log(String.format("Copying %s from bucket %s to %s in bucket %s.", originalkey, bucket, destKey, this.documentsBucket));
    S3ObjectMetadata metadata = this.s3.getObjectMetadata(s3Client, bucket, originalkey);
    String username = metadata.getMetadata().entrySet().stream().filter(s -> s.getKey().equalsIgnoreCase("userid")).findFirst().map(s -> s.getValue()).orElse("System");
    DynamicDocumentItem doc = new DynamicDocumentItem(Collections.emptyMap());
    doc.setDocumentId(documentId);
    doc.setContentLength(metadata.getContentLength());
    doc.setContentType(metadata.getContentType());
    doc.setUserId(username);
    doc.setChecksum(metadata.getEtag());
    doc.setInsertedDate(date);
    if (!uuid) {
        doc.setPath(key);
    }
    this.service.saveDocumentItemWithTag(siteId, doc);
    this.s3.copyObject(s3Client, bucket, originalkey, this.documentsBucket, destKey, metadata.getContentType());
}
Also used : SdkHttpUtils(software.amazon.awssdk.utils.http.SdkHttpUtils) DocumentService(com.formkiq.stacks.dynamodb.DocumentService) Date(java.util.Date) SimpleDateFormat(java.text.SimpleDateFormat) Context(com.amazonaws.services.lambda.runtime.Context) HashMap(java.util.HashMap) RequestHandler(com.amazonaws.services.lambda.runtime.RequestHandler) DynamicDocumentItem(com.formkiq.stacks.dynamodb.DynamicDocumentItem) SiteIdKeyGenerator.createDatabaseKey(com.formkiq.stacks.dynamodb.SiteIdKeyGenerator.createDatabaseKey) GsonBuilder(com.google.gson.GsonBuilder) DocumentServiceImpl(com.formkiq.stacks.dynamodb.DocumentServiceImpl) SiteIdKeyGenerator.resetDatabaseKey(com.formkiq.stacks.dynamodb.SiteIdKeyGenerator.resetDatabaseKey) LambdaLogger(com.amazonaws.services.lambda.runtime.LambdaLogger) Gson(com.google.gson.Gson) Map(java.util.Map) DocumentTag(com.formkiq.stacks.dynamodb.DocumentTag) S3ConnectionBuilder(com.formkiq.aws.s3.S3ConnectionBuilder) ParseException(java.text.ParseException) S3ObjectMetadata(com.formkiq.aws.s3.S3ObjectMetadata) Region(software.amazon.awssdk.regions.Region) S3Service(com.formkiq.aws.s3.S3Service) PutObjectResponse(software.amazon.awssdk.services.s3.model.PutObjectResponse) SqsConnectionBuilder(com.formkiq.aws.sqs.SqsConnectionBuilder) DynamicObject(com.formkiq.stacks.common.objects.DynamicObject) DATE_FORMAT(com.formkiq.stacks.dynamodb.DocumentService.DATE_FORMAT) S3Client(software.amazon.awssdk.services.s3.S3Client) UUID(java.util.UUID) StandardCharsets(java.nio.charset.StandardCharsets) SqsService(com.formkiq.aws.sqs.SqsService) Reflectable(com.formkiq.graalvm.annotations.Reflectable) ReflectableImport(com.formkiq.graalvm.annotations.ReflectableImport) Base64(java.util.Base64) List(java.util.List) DocumentItemDynamoDb(com.formkiq.stacks.dynamodb.DocumentItemDynamoDb) SiteIdKeyGenerator.getSiteId(com.formkiq.stacks.dynamodb.SiteIdKeyGenerator.getSiteId) DynamoDbConnectionBuilder(com.formkiq.stacks.dynamodb.DynamoDbConnectionBuilder) Collections(java.util.Collections) DocumentTagType(com.formkiq.stacks.dynamodb.DocumentTagType) DynamicDocumentItem(com.formkiq.stacks.dynamodb.DynamicDocumentItem) S3ObjectMetadata(com.formkiq.aws.s3.S3ObjectMetadata)

Example 48 with LambdaLogger

use of com.amazonaws.services.lambda.runtime.LambdaLogger in project formkiq-core by formkiq.

the class WebhooksTagsRequestHandler method get.

@Override
public ApiRequestHandlerResponse get(final LambdaLogger logger, final ApiGatewayRequestEvent event, final ApiAuthorizer authorizer, final AwsServiceCache awsServices) throws Exception {
    String siteId = authorizer.getSiteId();
    String id = getPathParameter(event, "webhookId");
    PaginationResults<DynamicObject> list = awsServices.webhookService().findTags(siteId, id, null);
    List<Map<String, Object>> tags = list.getResults().stream().map(m -> {
        Map<String, Object> map = new HashMap<>();
        map.put("insertedDate", m.getString("inserteddate"));
        map.put("webhookId", id);
        map.put("type", m.getString("type"));
        map.put("userId", m.getString("userId"));
        map.put("value", m.getString("tagValue"));
        map.put("key", m.getString("tagKey"));
        return map;
    }).collect(Collectors.toList());
    return new ApiRequestHandlerResponse(SC_OK, new ApiMapResponse(Map.of("tags", tags)));
}
Also used : SC_CREATED(com.formkiq.lambda.apigateway.ApiResponseStatus.SC_CREATED) Arrays(java.util.Arrays) DynamicObject(com.formkiq.stacks.common.objects.DynamicObject) Date(java.util.Date) ApiGatewayRequestHandler(com.formkiq.lambda.apigateway.ApiGatewayRequestHandler) ApiMapResponse(com.formkiq.lambda.apigateway.ApiMapResponse) HashMap(java.util.HashMap) AwsServiceCache(com.formkiq.lambda.apigateway.AwsServiceCache) ApiAuthorizer(com.formkiq.lambda.apigateway.ApiAuthorizer) NotFoundException(com.formkiq.lambda.apigateway.exception.NotFoundException) Collectors(java.util.stream.Collectors) BadException(com.formkiq.lambda.apigateway.exception.BadException) ApiResponse(com.formkiq.lambda.apigateway.ApiResponse) List(java.util.List) ApiGatewayRequestEventUtil(com.formkiq.lambda.apigateway.ApiGatewayRequestEventUtil) LambdaLogger(com.amazonaws.services.lambda.runtime.LambdaLogger) Map(java.util.Map) ApiGatewayRequestEvent(com.formkiq.lambda.apigateway.ApiGatewayRequestEvent) DocumentTag(com.formkiq.stacks.dynamodb.DocumentTag) ApiRequestHandlerResponse(com.formkiq.lambda.apigateway.ApiRequestHandlerResponse) ApiMessageResponse(com.formkiq.lambda.apigateway.ApiMessageResponse) SC_OK(com.formkiq.lambda.apigateway.ApiResponseStatus.SC_OK) DocumentTagType(com.formkiq.stacks.dynamodb.DocumentTagType) PaginationResults(com.formkiq.stacks.dynamodb.PaginationResults) DynamicObject(com.formkiq.stacks.common.objects.DynamicObject) ApiRequestHandlerResponse(com.formkiq.lambda.apigateway.ApiRequestHandlerResponse) ApiMapResponse(com.formkiq.lambda.apigateway.ApiMapResponse) HashMap(java.util.HashMap) Map(java.util.Map)

Example 49 with LambdaLogger

use of com.amazonaws.services.lambda.runtime.LambdaLogger in project formkiq-core by formkiq.

the class AbstractApiRequestHandler method handleRequest.

@Override
public void handleRequest(final InputStream input, final OutputStream output, final Context context) throws IOException {
    LambdaLogger logger = context.getLogger();
    ApiGatewayRequestEvent event = getApiGatewayEvent(input, logger, getAwsServices());
    ApiAuthorizer authorizer = new ApiAuthorizer(event);
    try {
        ApiRequestHandlerResponse object = processRequest(logger, event, authorizer);
        processResponse(authorizer, event, object);
        buildResponse(logger, output, object.getStatus(), object.getHeaders(), object.getResponse());
    } catch (NotFoundException e) {
        buildResponse(logger, output, SC_NOT_FOUND, Collections.emptyMap(), new ApiResponseError(e.getMessage()));
    } catch (TooManyRequestsException e) {
        buildResponse(logger, output, SC_TOO_MANY_REQUESTS, Collections.emptyMap(), new ApiResponseError(e.getMessage()));
    } catch (BadException | InvalidConditionsException | DateTimeException e) {
        buildResponse(logger, output, SC_BAD_REQUEST, Collections.emptyMap(), new ApiResponseError(e.getMessage()));
    } catch (ForbiddenException e) {
        buildResponse(logger, output, SC_FORBIDDEN, Collections.emptyMap(), new ApiResponseError(e.getMessage()));
    } catch (UnauthorizedException e) {
        buildResponse(logger, output, SC_UNAUTHORIZED, Collections.emptyMap(), new ApiResponseError(e.getMessage()));
    } catch (NotImplementedException e) {
        buildResponse(logger, output, SC_NOT_IMPLEMENTED, Collections.emptyMap(), new ApiResponseError(e.getMessage()));
    } catch (Exception e) {
        logError(logger, e);
        buildResponse(logger, output, SC_ERROR, Collections.emptyMap(), new ApiResponseError("Internal Server Error"));
    }
}
Also used : ForbiddenException(com.formkiq.lambda.apigateway.exception.ForbiddenException) NotImplementedException(com.formkiq.lambda.apigateway.exception.NotImplementedException) NotFoundException(com.formkiq.lambda.apigateway.exception.NotFoundException) BadException(com.formkiq.lambda.apigateway.exception.BadException) ForbiddenException(com.formkiq.lambda.apigateway.exception.ForbiddenException) NotImplementedException(com.formkiq.lambda.apigateway.exception.NotImplementedException) DateTimeException(java.time.DateTimeException) UnauthorizedException(com.formkiq.lambda.apigateway.exception.UnauthorizedException) IOException(java.io.IOException) NotFoundException(com.formkiq.lambda.apigateway.exception.NotFoundException) BadException(com.formkiq.lambda.apigateway.exception.BadException) TooManyRequestsException(com.formkiq.lambda.apigateway.exception.TooManyRequestsException) InvalidConditionsException(com.formkiq.stacks.dynamodb.InvalidConditionsException) TooManyRequestsException(com.formkiq.lambda.apigateway.exception.TooManyRequestsException) InvalidConditionsException(com.formkiq.stacks.dynamodb.InvalidConditionsException) DateTimeException(java.time.DateTimeException) UnauthorizedException(com.formkiq.lambda.apigateway.exception.UnauthorizedException) LambdaLogger(com.amazonaws.services.lambda.runtime.LambdaLogger)

Example 50 with LambdaLogger

use of com.amazonaws.services.lambda.runtime.LambdaLogger in project aws-lambda-developer-guide by awsdocs.

the class HandlerApiGateway method handleRequest.

@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {
    LambdaLogger logger = context.getLogger();
    APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();
    response.setIsBase64Encoded(false);
    response.setStatusCode(200);
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "text/html");
    response.setHeaders(headers);
    response.setBody("<!DOCTYPE html><html><head><title>AWS Lambda sample</title></head><body>" + "<h1>Welcome</h1><p>Page generated by a Lambda function.</p>" + "</body></html>");
    // log execution details
    Util.logEnvironment(event, context, gson);
    return response;
}
Also used : HashMap(java.util.HashMap) LambdaLogger(com.amazonaws.services.lambda.runtime.LambdaLogger) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)

Aggregations

LambdaLogger (com.amazonaws.services.lambda.runtime.LambdaLogger)59 HashMap (java.util.HashMap)10 Date (java.util.Date)9 List (java.util.List)8 Map (java.util.Map)8 Context (com.amazonaws.services.lambda.runtime.Context)6 ApiAuthorizer (com.formkiq.lambda.apigateway.ApiAuthorizer)6 ApiGatewayRequestEvent (com.formkiq.lambda.apigateway.ApiGatewayRequestEvent)6 ApiGatewayRequestEventUtil (com.formkiq.lambda.apigateway.ApiGatewayRequestEventUtil)6 ApiGatewayRequestHandler (com.formkiq.lambda.apigateway.ApiGatewayRequestHandler)6 ApiRequestHandlerResponse (com.formkiq.lambda.apigateway.ApiRequestHandlerResponse)6 IOException (java.io.IOException)6 SC_OK (com.formkiq.lambda.apigateway.ApiResponseStatus.SC_OK)5 AwsServiceCache (com.formkiq.lambda.apigateway.AwsServiceCache)5 BadException (com.formkiq.lambda.apigateway.exception.BadException)5 DynamicObject (com.formkiq.stacks.common.objects.DynamicObject)5 Collectors (java.util.stream.Collectors)5 ClientContext (com.amazonaws.services.lambda.runtime.ClientContext)4 CognitoIdentity (com.amazonaws.services.lambda.runtime.CognitoIdentity)4 ApiMapResponse (com.formkiq.lambda.apigateway.ApiMapResponse)4