Java Code Examples for com.amazonaws.services.lambda.runtime.Context#getLogger()

The following examples show how to use com.amazonaws.services.lambda.runtime.Context#getLogger() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HelloCouchbaseLambda.java    From serverless with Apache License 2.0 6 votes vote down vote up
@Override
public String handleRequest(Request request, Context context) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    String timestamp = dateFormat.format(Calendar.getInstance().getTime());

    logger = context.getLogger();
    logger.log("Request received: %s" + timestamp);
    ButtonDocument buttonDocument = new ButtonDocument();
    buttonDocument.setId(context.getAwsRequestId());
    buttonDocument.setRequestId(context.getAwsRequestId());
    buttonDocument.setTimestamp(timestamp);

    getBucket().upsert(buttonDocument.toJson());

    return buttonDocument.toString();
}
 
Example 2
Source File: ProxyStreamHandlerLambda.java    From Serverless-Programming-Cookbook with MIT License 6 votes vote down vote up
/**
 * handleRequest implementation.
 * @param inputStream - Input stream from API Gateway.
 * @param outputStream - Output stream to API Gateway.
 * @param context - Context.
 * @throws IOException - If something goes wrong.
 */
public final void handleRequest(final InputStream inputStream,
                                final OutputStream outputStream,
                                final Context context) throws IOException {

    LambdaLogger logger = context.getLogger();
    context.getLogger().log("Inside Proxy Stream Handler.");

    final String greeting = generateGreetingFromInputStream(inputStream);
    final JSONObject responseJson = generateResponseJson(greeting);

    logger.log(responseJson.toJSONString());

    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
    writer.write(responseJson.toJSONString());
    writer.close();
}
 
Example 3
Source File: LambdaKinesisEventHandler.java    From Serverless-Programming-Cookbook with MIT License 6 votes vote down vote up
/**
 * Handle request.
 *
 * @param kinesisEvent  - Kinesis Event passed as input to lambda handler
 * @param context - context object
 * @return true if success, else false.
 */
public Boolean handleRequest(final KinesisEvent kinesisEvent, final Context context) {

    LambdaLogger logger = context.getLogger();
    logger.log("Received Kinesis event: " + kinesisEvent);
    logger.log("Number of records: " + kinesisEvent.getRecords().size());

    try {
        kinesisEvent.getRecords().forEach(r -> {
            final KinesisEvent.Record kr = r.getKinesis();
            logger.log("Record: " + kr.toString());
            logger.log("Data: " + StandardCharsets.UTF_8.decode(kr.getData()).toString());
        });
    } catch (final Exception e) {
        logger.log("There was an exception: " + e.getMessage());
        return false;
    }

    return true;
}
 
Example 4
Source File: Handler3.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
@Override
public String handleRequest(String event, Context context) {
    LambdaLogger logger = context.getLogger();
    String email = event ;

    // log execution details
    logger.log("Email value " + email);

    SendMessage msg = new SendMessage();
    try {
       msg.sendMessage(email);

   } catch (IOException e) {
       e.getStackTrace();
   }

    return "";

}
 
Example 5
Source File: EchoHandler.java    From kinesis-aggregation with Apache License 2.0 6 votes vote down vote up
@Override
public Void handleRequest(KinesisEvent event, Context context) {
	LambdaLogger logger = context.getLogger();

	// extract the records from the event
	List<KinesisEventRecord> records = event.getRecords();

	logger.log(String.format("Recieved %s Raw Records", records.size()));

	try {
		// now deaggregate the message contents
		List<KinesisClientRecord> deaggregated = new RecordDeaggregator<KinesisEventRecord>().deaggregate(records);
		logger.log(String.format("Received %s Deaggregated User Records", deaggregated.size()));

		deaggregated.stream().forEachOrdered(rec -> {
			logger.log(rec.partitionKey());
		});
	} catch (Exception e) {
		logger.log(e.getMessage());
	}

	return null;
}
 
Example 6
Source File: EchoHandler.java    From kinesis-aggregation with Apache License 2.0 6 votes vote down vote up
@Override
public Void handleRequest(KinesisEvent event, Context context) {
	LambdaLogger logger = context.getLogger();

	// extract the records from the event
	List<KinesisEventRecord> records = event.getRecords();

	logger.log(String.format("Recieved %s Raw Records", records.size()));

	// now deaggregate the message contents
	List<UserRecord> deaggregated = new RecordDeaggregator<KinesisEventRecord>().deaggregate(records);
	logger.log(String.format("Received %s Deaggregated User Records", deaggregated.size()));
	
	deaggregated.stream().forEachOrdered(rec -> {
		logger.log(rec.getPartitionKey());
	});

	return null;
}
 
Example 7
Source File: KinesisLambdaReceiver.java    From kinesis-aggregation with Apache License 2.0 6 votes vote down vote up
/**
    * @see com.amazonaws.services.lambda.runtime.RequestHandler#handleRequest(java.lang.Object, com.amazonaws.services.lambda.runtime.Context)
    */
   public Void handleRequestBulkList(KinesisEvent event, Context context) {
	LambdaLogger logger = context.getLogger();
	logger.log("Received " + event.getRecords().size() + " raw Event Records.");

	try {
		List<UserRecord> userRecords = RecordDeaggregator.deaggregate(event.getRecords());
		for (UserRecord userRecord : userRecords) {
			// Your User Record Processing Code Here!
			logger.log(new String(userRecord.getData().array()));
		}
	} catch (Exception e) {
		logger.log(e.getMessage());
	}

	return null;
}
 
Example 8
Source File: KinesisToFirehose.java    From aws-big-data-blog with Apache License 2.0 6 votes vote down vote up
public void kinesisHandler(KinesisEvent event, Context context){
    logger = context.getLogger();
    setup();
    for(KinesisEvent.KinesisEventRecord rec : event.getRecords()) {
        logger.log("Got message ");
        String msg = new String(rec.getKinesis().getData().array())+"\n";
        Record deliveryStreamRecord = new Record().withData(ByteBuffer.wrap(msg.getBytes()));

        PutRecordRequest putRecordRequest = new PutRecordRequest()
                .withDeliveryStreamName(deliveryStreamName)
                .withRecord(deliveryStreamRecord);

        logger.log("Putting message");
        firehoseClient.putRecord(putRecordRequest);
        logger.log("Successful Put");
    }
}
 
Example 9
Source File: KinesisLambdaReceiver.java    From kinesis-aggregation with Apache License 2.0 5 votes vote down vote up
/**
 * @see com.amazonaws.services.lambda.runtime.RequestHandler#handleRequest(java.lang.Object, com.amazonaws.services.lambda.runtime.Context)
 */
   public Void handleRequest(KinesisEvent event, Context context) {
	LambdaLogger logger = context.getLogger();
	logger.log("Received " + event.getRecords().size() + " raw Event Records.");

	// Stream the User Records from the Lambda Event
	RecordDeaggregator.stream(event.getRecords().stream(), userRecord -> {
		// Your User Record Processing Code Here!
		logger.log(new String(userRecord.getData().array()));
	});

	return null;
}
 
Example 10
Source File: Handler2.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
@Override
public String handleRequest(String event, Context context) {

    PersistCase perCase = new PersistCase();

    LambdaLogger logger = context.getLogger();
    String val = event ;
   logger.log("CASE is about to be assigned " +val);

   // Create very simple logic to assign case to an employee
    int tmp = (Math.random() <= 0.5) ? 1 : 2;

    logger.log("TMP IS " +tmp);

    String emailEmp= "";

    if (tmp == 1) {
        // assign to tblue
        emailEmp = "[email protected]";
        perCase.putRecord(val, "Tom Blue", emailEmp );
    } else {
        // assign to swhite
        emailEmp = "[email protected]";
        perCase.putRecord(val, "Sarah White", emailEmp);
    }

    logger.log("emailEmp IS " +emailEmp);
    //return email - used in the next step
    return emailEmp;
    }
 
Example 11
Source File: Handler.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
@Override
public String handleRequest(Map<String,String> event, Context context) {
    LambdaLogger logger = context.getLogger();
    Gson gson = new GsonBuilder().create();

    // log execution details
    logger.log("ENVIRONMENT VARIABLES: " + gson.toJson(System.getenv()));
    logger.log("CONTEXT: " + gson.toJson(context));
    // process event
    logger.log("EVENT Data: " + gson.toJson(event));

    String myCaseID = event.get("inputCaseID");
    logger.log("CaseId44: " + myCaseID);
    return myCaseID;
}
 
Example 12
Source File: rekognition-video-java-detect-labels-lambda.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
@Override
public String handleRequest(SNSEvent event, Context context) {

   String message = event.getRecords().get(0).getSNS().getMessage();
   LambdaLogger logger = context.getLogger(); 

   // Parse SNS event for analysis results. Log results
   try {
      ObjectMapper operationResultMapper = new ObjectMapper();
      JsonNode jsonResultTree = operationResultMapper.readTree(message);
      logger.log("Rekognition Video Operation:=========================");
      logger.log("Job id: " + jsonResultTree.get("JobId"));
      logger.log("Status : " + jsonResultTree.get("Status"));
      logger.log("Job tag : " + jsonResultTree.get("JobTag"));
      logger.log("Operation : " + jsonResultTree.get("API"));

      if (jsonResultTree.get("API").asText().equals("StartLabelDetection")) {

         if (jsonResultTree.get("Status").asText().equals("SUCCEEDED")){
            GetResultsLabels(jsonResultTree.get("JobId").asText(), context);
         }
         else{
            String errorMessage = "Video analysis failed for job " 
                  + jsonResultTree.get("JobId") 
                  + "State " + jsonResultTree.get("Status");
            throw new Exception(errorMessage); 
         }

      } else
         logger.log("Operation not StartLabelDetection");

   } catch (Exception e) {
      logger.log("Error: " + e.getMessage());
      throw new RuntimeException (e);


   }

   return message;
}
 
Example 13
Source File: ActionsAWSHandler.java    From dialogflow-webhook-boilerplate-java with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(InputStream inputStream,
                          OutputStream outputStream,
                          Context context) throws IOException {
  BufferedReader reader = new BufferedReader(
          new InputStreamReader(inputStream));
  JSONObject awsResponse = new JSONObject();
  LambdaLogger logger = context.getLogger();
  try {
    JSONObject awsRequest = (JSONObject) parser.parse(reader);
    JSONObject headers = (JSONObject) awsRequest.get("headers");
    String body = (String) awsRequest.get("body");
    logger.log("AWS request body = " + body);

    actionsApp.handleRequest(body, headers)
            .thenAccept((webhookResponseJson) -> {
              logger.log("Generated json = " + webhookResponseJson);

              JSONObject responseHeaders = new JSONObject();
              responseHeaders.put("Content-Type", "application/json");

              awsResponse.put("statusCode", "200");
              awsResponse.put("headers", responseHeaders);
              awsResponse.put("body", webhookResponseJson);
              writeResponse(outputStream, awsResponse);
            }).exceptionally((throwable -> {
      awsResponse.put("statusCode", "500");
      awsResponse.put("exception", throwable);
      writeResponse(outputStream, awsResponse);
      return null;
    }));

  } catch (ParseException e) {
    e.printStackTrace();
  }
}
 
Example 14
Source File: Handler.java    From serverless-examples-cached-rds-ws with Apache License 2.0 5 votes vote down vote up
public Response handleRequest(Request input, Context context) {
    context.getLogger().log("Environment variables:");
    for (String env : System.getenv().keySet())
        context.getLogger().log(String.format("  %s = %s", env, System.getenv(env)));

    String response = "";

    try (
            CacheApi cache = new SyncMemcachedCache(
                    System.getenv("memcachedEndpoint"), 1, TimeUnit.SECONDS, context.getLogger()
            )
    ) {
        Object cached = cache.get("result");
        context.getLogger().log(String.format("Retrieved value from cache: %s", cached));
        response = (String) cache.getOrElse("result", 15 * 60, () -> {
            Long currentEpochTime = System.currentTimeMillis();
            try (
                    Connection conn = DriverManager.getConnection(
                            String.format("jdbc:postgresql://%s/%s", System.getenv("postgresEndpoint"), System.getenv("postgresDatabase")),
                            System.getenv("postgresUser"),
                            System.getenv("postgresPassword")
                    )
            ) {
                Statement stmt = conn.createStatement();
                ResultSet resultSet = stmt.executeQuery("SELECT EXTRACT(EPOCH FROM NOW())");
                if (resultSet.next()) {
                    context.getLogger().log(String.format("Successfully executed query.  Result: %s", resultSet.getLong(1)));
                    currentEpochTime = resultSet.getLong(1) * 1000L;
                }
            } catch (Exception e) {
                context.getLogger().log(String.format("Exception during access to RDS. %s", e.getMessage()));
            }
            return String.format("My message at %s", currentEpochTime);
        });
    } catch (Exception e) {
        context.getLogger().log(String.format("Exception during access to ElastiCache. %s", e.getMessage()));
    }

    return new Response("200", serialize(new ResponseBody(String.format("Message at %s is: %s", System.currentTimeMillis(), response), input)));
}
 
Example 15
Source File: LambdaTestHandler.java    From lambda-selenium with MIT License 5 votes vote down vote up
public TestResult handleRequest(TestRequest testRequest, Context context) {
    LoggerContainer.LOGGER = new Logger(context.getLogger());
    System.setProperty("target.test.uuid", testRequest.getTestRunUUID());

    Optional<Result> result = Optional.empty();
    try {
        BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(getTestClass(testRequest));
        runner.filter(new MethodFilter(testRequest.getFrameworkMethod()));

        result = ofNullable(new JUnitCore().run(runner));
    } catch (Exception e) {
        testResult.setThrowable(e);
        LOGGER.log(e);
    }

    if (result.isPresent()) {
        testResult.setRunCount(result.get().getRunCount());
        testResult.setRunTime(result.get().getRunTime());
        LOGGER.log("Run count: " + result.get().getRunCount());
        result.get().getFailures().forEach(failure -> {
            LOGGER.log(failure.getException());
            testResult.setThrowable(failure.getException());
        });
    }

    return testResult;
}
 
Example 16
Source File: Handler.java    From djl-demo with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(InputStream is, OutputStream os, Context context) throws IOException {
    LambdaLogger logger = context.getLogger();
    String input = Utils.toString(is);
    try {
        Request request = GSON.fromJson(input, Request.class);
        String url = request.getInputImageUrl();
        String artifactId = request.getArtifactId();
        Map<String, String> filters = request.getFilters();
        Criteria<Image, Classifications> criteria =
                Criteria.builder()
                        .setTypes(Image.class, Classifications.class)
                        .optArtifactId(artifactId)
                        .optFilters(filters)
                        .build();
        try (ZooModel<Image, Classifications> model = ModelZoo.loadModel(criteria);
                Predictor<Image, Classifications> predictor = model.newPredictor()) {
            Image image = ImageFactory.getInstance().fromUrl(url);
            List<Classifications.Classification> result = predictor.predict(image).topK(5);
            os.write(GSON.toJson(result).getBytes(StandardCharsets.UTF_8));
        }
    } catch (RuntimeException | ModelException | TranslateException e) {
        logger.log("Failed handle input: " + input);
        logger.log(e.toString());
        String msg = "{\"status\": \"invoke failed: " + e.toString() + "\"}";
        os.write(msg.getBytes(StandardCharsets.UTF_8));
    }
}
 
Example 17
Source File: rekognition-video-java-detect-labels-lambda.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
void GetResultsLabels(String startJobId, Context context) throws Exception {

      LambdaLogger logger = context.getLogger();

      AmazonRekognition rek = AmazonRekognitionClientBuilder.standard().withRegion(Regions.US_EAST_1).build();

      int maxResults = 1000;
      String paginationToken = null;
      GetLabelDetectionResult labelDetectionResult = null;
      String labels = "";
      Integer labelsCount = 0;
      String label = "";
      String currentLabel = "";
     
      //Get label detection results and log them. 
      do {

         GetLabelDetectionRequest labelDetectionRequest = new GetLabelDetectionRequest().withJobId(startJobId)
               .withSortBy(LabelDetectionSortBy.NAME).withMaxResults(maxResults).withNextToken(paginationToken);

         labelDetectionResult = rek.getLabelDetection(labelDetectionRequest);
         
         paginationToken = labelDetectionResult.getNextToken();
         VideoMetadata videoMetaData = labelDetectionResult.getVideoMetadata();

         // Add labels to log
         List<LabelDetection> detectedLabels = labelDetectionResult.getLabels();
         
         for (LabelDetection detectedLabel : detectedLabels) {
            label = detectedLabel.getLabel().getName();
            if (label.equals(currentLabel)) {
               continue;
            }
            labels = labels + label + " / ";
            currentLabel = label;
            labelsCount++;

         }
      } while (labelDetectionResult != null && labelDetectionResult.getNextToken() != null);

      logger.log("Total number of labels : " + labelsCount);
      logger.log("labels : " + labels);

   }
 
Example 18
Source File: LambdaWrapper.java    From cloudformation-cli-java-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * This function initialises dependencies which are depending on credentials
 * passed at function invoke and not available during construction
 */
private void initialiseRuntime(final String resourceType,
                               final Credentials providerCredentials,
                               final String providerLogGroupName,
                               final Context context,
                               final String awsAccountId) {

    this.loggerProxy = new LoggerProxy();
    this.metricsPublisherProxy = new MetricsPublisherProxy();

    this.platformLambdaLogger = new LambdaLogPublisher(context.getLogger());
    this.loggerProxy.addLogPublisher(this.platformLambdaLogger);

    // Initialisation skipped if dependencies were set during injection (in unit
    // tests).

    // NOTE: providerCredentials and providerLogGroupName are null/not null in
    // sync.
    // Both are required parameters when LoggingConfig (optional) is provided when
    // 'RegisterType'.
    if (providerCredentials != null) {
        if (this.providerCredentialsProvider != null) {
            this.providerCredentialsProvider.setCredentials(providerCredentials);
        }

        if (this.providerMetricsPublisher == null) {
            this.providerMetricsPublisher = new MetricsPublisherImpl(this.providerCloudWatchProvider, this.loggerProxy,
                                                                     awsAccountId, resourceType);
        }
        this.metricsPublisherProxy.addMetricsPublisher(this.providerMetricsPublisher);
        this.providerMetricsPublisher.refreshClient();

        if (this.providerEventsLogger == null) {
            this.cloudWatchLogHelper = new CloudWatchLogHelper(this.cloudWatchLogsProvider, providerLogGroupName,
                                                               context.getLogger(), this.metricsPublisherProxy);
            this.cloudWatchLogHelper.refreshClient();

            this.providerEventsLogger = new CloudWatchLogPublisher(this.cloudWatchLogsProvider, providerLogGroupName,
                                                                   this.cloudWatchLogHelper.prepareLogStream(),
                                                                   context.getLogger(), this.metricsPublisherProxy);
        }
        this.loggerProxy.addLogPublisher(this.providerEventsLogger);
        this.providerEventsLogger.refreshClient();
    }
}
 
Example 19
Source File: APIRequestHandler.java    From smartthings-ringalarm with MIT License 4 votes vote down vote up
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {

        LambdaLogger logger = context.getLogger();
        logger.log("Loading Java Lambda handler of ProxyWithStream");


        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        JSONObject responseJson = new JSONObject();
        String responseCode = "200";
        String action = "";

        try {
            JSONObject event = (JSONObject) parser.parse(reader);

            if (event.get("pathParameters") != null) {
                JSONObject pps = (JSONObject) event.get("pathParameters");
                if (pps.get("ring-action") != null) {
                    action = (String) pps.get("ring-action");
                }
            }

            RingInput input = new RingInput();
            if (event.get("body") != null) {
                JSONObject body = (JSONObject) parser.parse((String) event.get("body"));
                if (body.get("user") != null) {
                    input.setUser((String) body.get("user"));
                }

                if (body.get("password") != null) {
                    input.setPassword((String) body.get("password"));
                }

                if (body.get("locationId") != null) {
                    input.setLocationId((String) body.get("locationId"));
                }

                if (body.get("zid") != null) {
                    input.setZid((String) body.get("zid"));
                }

            }

            JSONObject responseBody = new JSONObject();

            switch (action) {
                case "home":
                    setHome(input, responseBody);
                    break;
                case "away":
                    setAway(input, responseBody);
                    break;
                case "off":
                    disArmMode(input, responseBody);
                    break;
                case "status":
                    getMode(input, responseBody);
                    break;
                default:
                    responseBody.put("message", "Unknown");
            }

            responseJson.put("isBase64Encoded", false);
            responseJson.put("statusCode", responseCode);
            responseJson.put("body", responseBody.toString());

        } catch (ParseException pex) {
            responseJson.put("statusCode", "400");
            responseJson.put("exception", pex);
        }

        logger.log(responseJson.toJSONString());
        OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
        writer.write(responseJson.toJSONString());
        writer.close();
    }
 
Example 20
Source File: TikaLambdaHandler.java    From tika-lambda with Apache License 2.0 4 votes vote down vote up
public String handleRequest(S3Event s3event, Context context) {
    _logger = context.getLogger();
    _logger.log("Received S3 Event: " + s3event.toJson());

    try {
        S3EventNotificationRecord record = s3event.getRecords().get(0);

        String bucket = record.getS3().getBucket().getName();
        String extractBucket = "extracts." + bucket;

        // Object key may have spaces or unicode non-ASCII characters.
        String key = URLDecoder.decode(record.getS3().getObject().getKey().replace('+', ' '), "UTF-8");

        // Short-circuit ignore .extract files because they have already been extracted, this prevents an endless loop
        if (key.toLowerCase().endsWith(".extract")) {
          _logger.log("Ignoring extract file " + key);
          return "Ignored";
        }

        AmazonS3 s3Client = new AmazonS3Client();
        S3Object s3Object = s3Client.getObject(new GetObjectRequest(bucket, key));

        try (InputStream objectData = s3Object.getObjectContent()) {
            String extractJson = doTikaStuff(bucket, key, objectData);

            byte[] extractBytes = extractJson.getBytes(Charset.forName("UTF-8"));
            int extractLength = extractBytes.length;

            ObjectMetadata metaData = new ObjectMetadata();
            metaData.setContentLength(extractLength);

            _logger.log("Saving extract file to S3");
            InputStream inputStream = new ByteArrayInputStream(extractBytes);
            s3Client.putObject(extractBucket, key + ".extract", inputStream, metaData);
        }
    } catch (IOException | TransformerConfigurationException | SAXException e) {
        _logger.log("Exception: " + e.getLocalizedMessage());
        throw new RuntimeException(e);
    }
    return "Success";
}