Search in sources :

Example 26 with LambdaLogger

use of com.amazonaws.services.lambda.runtime.LambdaLogger in project aws-ingesting-click-logs-using-terraform by aws-samples.

the class ClickLoggerStreamHandler method handleRequest.

@Override
public KinesisAnalyticsInputPreprocessingResponse handleRequest(final KinesisFirehoseEvent event, final Context context) {
    final LambdaLogger logger = context.getLogger();
    final String success_response = new String("200 OK");
    logger.log("EVENT: " + gson.toJson(event));
    String env_table = System.getenv("DB_TABLE");
    if (!StringUtils.isBlank(env_table)) {
        dynamo_table_name = env_table;
    }
    // System.getenv("REGION");
    String env_region = System.getenv("AWS_REGION");
    logger.log("Environment region name - " + env_region);
    if (!StringUtils.isBlank(env_region)) {
        region = env_region;
    }
    List<Record> records = new ArrayList<>();
    event.getRecords().forEach(kinesisRecord -> {
        String clickJson = new String(kinesisRecord.getData().array());
        logger.log("Individual record: " + kinesisRecord.getData());
        Gson gson = new Gson();
        try {
            ClickLogRequest clickLogRequest = gson.fromJson(clickJson, ClickLogRequest.class);
            String req = clickLogRequest.getRequestid() + " - " + clickLogRequest.getCallerid() + "  - " + clickLogRequest.getComponent() + " - " + clickLogRequest.getType() + " - " + clickLogRequest.getAction() + " - " + clickLogRequest.getUser() + " - " + clickLogRequest.getClientip() + " - " + clickLogRequest.getCreatedtime();
            Boolean valid_input = true;
            logger.log("Incoming request variables - " + req);
            if (clickLogRequest != null) {
                logger.log("Validating inputs");
                if (StringUtils.isBlank(clickLogRequest.getRequestid())) {
                    logger.log("error occurred - requestid missing");
                    valid_input = false;
                }
                if (StringUtils.isBlank(clickLogRequest.getContextid())) {
                    logger.log("error occurred - contextid missing");
                    valid_input = false;
                }
                if (StringUtils.isBlank(clickLogRequest.getCallerid())) {
                    logger.log("error occurred - caller missing");
                    valid_input = false;
                }
                if (StringUtils.isBlank(clickLogRequest.getType())) {
                    logger.log("error occurred - type missing");
                    valid_input = false;
                }
                if (StringUtils.isBlank(clickLogRequest.getAction())) {
                    logger.log("error occurred - action missing");
                    valid_input = false;
                }
                if (StringUtils.isBlank(clickLogRequest.getComponent())) {
                    logger.log("error occurred - component missing");
                    valid_input = false;
                }
                String user = "GUEST";
                if (StringUtils.isBlank(clickLogRequest.getUser())) {
                    logger.log("setting default user");
                    clickLogRequest.setUser(user);
                }
                String clientip = "APIGWY";
                if (StringUtils.isBlank(clickLogRequest.getClientip())) {
                    logger.log("setting default clientip");
                    clickLogRequest.setClientip(clientip);
                }
                String datetime = "";
                if (StringUtils.isBlank(clickLogRequest.getCreatedtime())) {
                    logger.log("setting default createdtime");
                    Format f = new SimpleDateFormat("mm-dd-yyyy hh:mm:ss");
                    datetime = f.format(new Date());
                    clickLogRequest.setCreatedtime(datetime);
                }
                logger.log("Validated inputs");
            }
            req = clickLogRequest.getRequestid() + " - " + clickLogRequest.getCallerid() + "  - " + clickLogRequest.getComponent() + " - " + clickLogRequest.getType() + " - " + clickLogRequest.getAction() + " - " + clickLogRequest.getUser() + " - " + clickLogRequest.getClientip() + " - " + clickLogRequest.getCreatedtime();
            logger.log("Modified request variables - " + req);
            logger.log("Valid Input - " + String.valueOf(valid_input));
            System.out.println("Calling updateclicklogs method for the received clicklogrequest");
            if (valid_input) {
                updateClickLogs(clickLogRequest);
            }
            Record record = new Record();
            record.setRecordId(kinesisRecord.getRecordId());
            record.setData(kinesisRecord.getData());
            Result result = KinesisAnalyticsInputPreprocessingResponse.Result.Ok;
            record.setResult(result);
            records.add(record);
        } catch (JsonSyntaxException jsEx) {
            System.out.println(jsEx);
        }
    });
    KinesisAnalyticsInputPreprocessingResponse response = new KinesisAnalyticsInputPreprocessingResponse(records);
    logger.log(success_response);
    return response;
}
Also used : ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) ClickLogRequest(com.clicklogs.model.ClickLogRequest) Date(java.util.Date) Result(com.amazonaws.services.lambda.runtime.events.KinesisAnalyticsInputPreprocessingResponse.Result) Format(java.text.Format) SimpleDateFormat(java.text.SimpleDateFormat) JsonSyntaxException(com.google.gson.JsonSyntaxException) Record(com.amazonaws.services.lambda.runtime.events.KinesisAnalyticsInputPreprocessingResponse.Record) LambdaLogger(com.amazonaws.services.lambda.runtime.LambdaLogger) SimpleDateFormat(java.text.SimpleDateFormat) KinesisAnalyticsInputPreprocessingResponse(com.amazonaws.services.lambda.runtime.events.KinesisAnalyticsInputPreprocessingResponse)

Example 27 with LambdaLogger

use of com.amazonaws.services.lambda.runtime.LambdaLogger in project saas-tenant-isolation-architecture by aws-samples.

the class WatchdogHandler method handleRequest.

@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
    LambdaLogger logger = context.getLogger();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.US_ASCII))) {
        Event event = gson.fromJson(reader, Event.class);
        String eventName = event.getDetail().getEventName();
        if (eventName.equals("AssumeRole")) {
            String policy = event.getDetail().getRequestParameters().getPolicy();
            String roleArn = event.getDetail().getRequestParameters().getRoleArn();
            logger.log("RoleArn: " + roleArn);
            logger.log("Policy: " + policy);
            if (policy == null || (!policy.contains(searchString))) {
                // Publish a message to an Amazon SNS topic.
                final String msg = "A call to AssumeRoll was made without an inline policy.";
                PublishRequest publishRequest = PublishRequest.builder().message(msg).topicArn(topicArn).build();
                snsClient.publish(publishRequest);
            }
        }
    } catch (IllegalStateException | JsonSyntaxException exception) {
        logger.log(exception.toString());
    }
}
Also used : IllegalStateException(java.lang.IllegalStateException) JsonSyntaxException(com.google.gson.JsonSyntaxException) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) Event(tenant.watchdog.models.Event) LambdaLogger(com.amazonaws.services.lambda.runtime.LambdaLogger) PublishRequest(software.amazon.awssdk.services.sns.model.PublishRequest)

Example 28 with LambdaLogger

use of com.amazonaws.services.lambda.runtime.LambdaLogger in project spring-teaching-demos by kennyk65.

the class ApplicationLambdaEntry method handleRequest.

public Object handleRequest(Object o, Context context) {
    LambdaLogger logger = context.getLogger();
    logger.log("Start of Lambda Function");
    // Get a reference to the Spring ApplicationMainEntry Context:
    ApplicationContext spring = SpringLauncherSingleton.getInstance();
    // Get the bean / entry point to your application:
    Map<String, Object> map = spring.getBeansWithAnnotation(Handler.class);
    if (map == null || map.size() < 1) {
        throw new ServerlessException("No @Handler bean was found in the application context.");
    } else if (map.size() > 1) {
        throw new ServerlessException("Only one @Handler bean is permitted in the application context, found " + map.size() + ".");
    }
    // Get the one and only one @Handler bean:
    Object handlerBean = map.values().iterator().next();
    // Get the AWS Lambda Adapter:
    LambdaAdapter adapter = spring.getBean(LambdaAdapter.class);
    // Call the @CloudFunction on the @Handler:
    Object result = adapter.handle(handlerBean, o, context);
    logger.log("End of Lambda Function, " + context.getRemainingTimeInMillis() + " millisecond of time remaining.\n" + Runtime.getRuntime().freeMemory() + " memory free\n");
    return result;
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) ServerlessException(org.springframework.cloud.serverless.ServerlessException) LambdaLogger(com.amazonaws.services.lambda.runtime.LambdaLogger)

Example 29 with LambdaLogger

use of com.amazonaws.services.lambda.runtime.LambdaLogger in project spring-teaching-demos by kennyk65.

the class LambdaBootSampleApplicationTests method basicTest.

private void basicTest() {
    // Mock up the AWS Context and Logger objects.  Needed as input.
    Context context = Mockito.mock(Context.class);
    LambdaLogger logger = Mockito.mock(LambdaLogger.class);
    when(context.getLogger()).thenReturn(logger);
    ApplicationLambdaEntry lambdaEntry = new ApplicationLambdaEntry();
    assertEquals("Invocation #" + testInvocationNumber++, lambdaEntry.handleRequest(null, context));
    assertEquals("Invocation #" + testInvocationNumber++, lambdaEntry.handleRequest(null, context));
    assertEquals("Invocation #" + testInvocationNumber++, lambdaEntry.handleRequest(null, context));
}
Also used : Context(com.amazonaws.services.lambda.runtime.Context) LambdaLogger(com.amazonaws.services.lambda.runtime.LambdaLogger) ApplicationLambdaEntry(org.springframework.cloud.serverless.aws.ApplicationLambdaEntry)

Example 30 with LambdaLogger

use of com.amazonaws.services.lambda.runtime.LambdaLogger in project aws-doc-sdk-examples by awsdocs.

the class ListMissingStudentsHandler method handleRequest.

@Override
public String handleRequest(Map<String, String> event, Context context) {
    LambdaLogger logger = context.getLogger();
    String date = event.get("date");
    logger.log("DATE: " + date);
    RDSGetStudents students = new RDSGetStudents();
    String xml = null;
    try {
        xml = students.getStudentsRDS(date);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    logger.log("XML: " + xml);
    return xml;
}
Also used : SQLException(java.sql.SQLException) LambdaLogger(com.amazonaws.services.lambda.runtime.LambdaLogger)

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