com.amazonaws.services.lambda.runtime.events.SNSEvent Java Examples

The following examples show how to use com.amazonaws.services.lambda.runtime.events.SNSEvent. 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: SnsServiceImpl.java    From Serverless-Programming-Cookbook with MIT License 6 votes vote down vote up
@Override
public final Boolean processEvent(final SNSEvent event, final String outputQueueURL, final LambdaLogger logger) {

    try {

        logger.log("Number of records in event: " + event.getRecords().size());

        Collection<SendMessageBatchRequestEntry> entries = new ArrayList<>();

        int idVal = 1;
        for (SNSRecord r : event.getRecords()) {
            logger.log("Adding message: " + r.getSNS().getMessage());
            entries.add(new SendMessageBatchRequestEntry("id_" + idVal, r.getSNS().getMessage()));
            idVal++;
        }

        final SendMessageBatchRequest sendBatchRequest = new SendMessageBatchRequest()
                .withQueueUrl(outputQueueURL)
                .withEntries(entries);
        this.sqsClient.sendMessageBatch(sendBatchRequest);

    } catch (Exception e) {
        final String errorMessage = "Error occurred: " + e.getMessage();
        logger.log(errorMessage);
        return false;
    }

    return true;

}
 
Example #2
Source File: LambdaTest.java    From github-bucket with ISC License 6 votes vote down vote up
private SNSEvent createSnsEvent(final String githubEvent) {
    SNSEvent.SNS sns = new SNSEvent.SNS();
    sns.setMessageAttributes(new HashMap<String, SNSEvent.MessageAttribute>(1, 1) {
        {
            SNSEvent.MessageAttribute attr = new SNSEvent.MessageAttribute();
            attr.setValue(githubEvent);
            put("X-Github-Event", attr);
        }
    });
    try (InputStream is = getClass().getResourceAsStream("/github-push-payload.json")) {
        sns.setMessage(IOUtils.toString(is));
    }
    catch (IOException e) {
        throw new IllegalArgumentException(e);
    }

    SNSEvent.SNSRecord record = new SNSEvent.SNSRecord();
    record.setSns(sns);

    SNSEvent snsEvent = new SNSEvent();
    snsEvent.setRecords(Collections.singletonList(record));
    return snsEvent;
}
 
Example #3
Source File: LambdaTest.java    From github-bucket with ISC License 6 votes vote down vote up
@Test
public void shouldFailOnOtherError() throws Exception {
    // Given
    Context context = mock(Context.class);
    SNSEvent snsEvent = createSnsEvent("push");

    doThrow(new IllegalArgumentException("Expected test exception")).when(config).isWatchedBranch(any());

    // When
    Integer response = uut.handleRequest(snsEvent, context);

    // Then
    assertThat(response, is(HttpStatus.SC_INTERNAL_SERVER_ERROR));
    verify(config, times(1)).isWatchedBranch(any());
    verify(worker, times(0)).call();
}
 
Example #4
Source File: LambdaTest.java    From github-bucket with ISC License 6 votes vote down vote up
@Test
public void shouldFailOnOtherBranch() throws Exception {
    // Given
    Context context = mock(Context.class);
    SNSEvent snsEvent = createSnsEvent("push");

    when(config.isWatchedBranch(new Branch("changes"))).thenReturn(false);

    // When
    Integer response = uut.handleRequest(snsEvent, context);

    // Then
    assertThat(response, is(HttpStatus.SC_BAD_REQUEST));
    verify(config, times(1)).isWatchedBranch(any());
    verify(worker, times(0)).call();
}
 
Example #5
Source File: LambdaTest.java    From github-bucket with ISC License 6 votes vote down vote up
@Test
public void shouldFailOnWrongWorkerCall() throws Exception {
    // Given
    Context context = mock(Context.class);
    SNSEvent snsEvent = createSnsEvent("push");

    when(config.isWatchedBranch(new Branch("changes"))).thenReturn(true);
    when(worker.call()).thenReturn(Status.FAILED);

    // When
    Integer response = uut.handleRequest(snsEvent, context);

    // Then
    assertThat(response, is(HttpStatus.SC_BAD_REQUEST));
    verify(config, times(1)).isWatchedBranch(new Branch("changes"));
    verify(worker, times(1)).call();
}
 
Example #6
Source File: LambdaTest.java    From github-bucket with ISC License 6 votes vote down vote up
@Test
public void shouldWorkCompletely() throws Exception {
    // Given
    Context context = mock(Context.class);
    SNSEvent snsEvent = createSnsEvent("push");

    when(config.isWatchedBranch(new Branch("changes"))).thenReturn(true);
    when(worker.call()).thenReturn(Status.SUCCESS);

    // When
    Integer response = uut.handleRequest(snsEvent, context);

    // Then
    assertThat(response, is(HttpStatus.SC_OK));
    verify(config, times(1)).isWatchedBranch(new Branch("changes"));
    verify(worker, times(1)).call();
}
 
Example #7
Source File: LambdaTest.java    From github-bucket with ISC License 6 votes vote down vote up
@Test
public void shouldFailOnWrongWorkerCall() throws Exception {
    // Given
    Context context = mock(Context.class);
    SNSEvent snsEvent = createSnsEvent("push");

    when(config.isWatchedBranch(new Branch("changes"))).thenReturn(true);
    when(worker.call()).thenReturn(Status.FAILED);

    // When
    Integer response = uut.handleRequest(snsEvent, context);

    // Then
    assertThat(response, is(HttpStatus.SC_BAD_REQUEST));
    verify(config, times(1)).isWatchedBranch(new Branch("changes"));
    verify(worker, times(1)).call();
}
 
Example #8
Source File: LambdaTest.java    From github-bucket with ISC License 6 votes vote down vote up
@Test
public void shouldFailOnOtherBranch() throws Exception {
    // Given
    Context context = mock(Context.class);
    SNSEvent snsEvent = createSnsEvent("push");

    when(config.isWatchedBranch(new Branch("changes"))).thenReturn(false);

    // When
    Integer response = uut.handleRequest(snsEvent, context);

    // Then
    assertThat(response, is(HttpStatus.SC_BAD_REQUEST));
    verify(config, times(1)).isWatchedBranch(any());
    verify(worker, times(0)).call();
}
 
Example #9
Source File: LambdaTest.java    From github-bucket with ISC License 6 votes vote down vote up
@Test
public void shouldWorkCompletely() throws Exception {
    // Given
    Context context = mock(Context.class);
    SNSEvent snsEvent = createSnsEvent("push");

    when(config.isWatchedBranch(new Branch("changes"))).thenReturn(true);
    when(worker.call()).thenReturn(Status.SUCCESS);

    // When
    Integer response = uut.handleRequest(snsEvent, context);

    // Then
    assertThat(response, is(HttpStatus.SC_OK));
    verify(config, times(1)).isWatchedBranch(new Branch("changes"));
    verify(worker, times(1)).call();
}
 
Example #10
Source File: LambdaTest.java    From github-bucket with ISC License 6 votes vote down vote up
@Test
public void shouldFailOnOtherError() throws Exception {
    // Given
    Context context = mock(Context.class);
    SNSEvent snsEvent = createSnsEvent("push");

    doThrow(new IllegalArgumentException("Expected test exception")).when(config).isWatchedBranch(any());

    // When
    Integer response = uut.handleRequest(snsEvent, context);

    // Then
    assertThat(response, is(HttpStatus.SC_INTERNAL_SERVER_ERROR));
    verify(config, times(1)).isWatchedBranch(any());
    verify(worker, times(0)).call();
}
 
Example #11
Source File: LambdaTest.java    From github-bucket with ISC License 6 votes vote down vote up
private SNSEvent createSnsEvent(final String githubEvent) {
    SNSEvent.SNS sns = new SNSEvent.SNS();
    sns.setMessageAttributes(new HashMap<String, SNSEvent.MessageAttribute>(1, 1) {
        {
            SNSEvent.MessageAttribute attr = new SNSEvent.MessageAttribute();
            attr.setValue(githubEvent);
            put("X-Github-Event", attr);
        }
    });
    try (InputStream is = getClass().getResourceAsStream("/github-push-payload.json")) {
        sns.setMessage(IOUtils.toString(is));
    }
    catch (IOException e) {
        throw new IllegalArgumentException(e);
    }

    SNSEvent.SNSRecord record = new SNSEvent.SNSRecord();
    record.setSns(sns);

    SNSEvent snsEvent = new SNSEvent();
    snsEvent.setRecords(Collections.singletonList(record));
    return snsEvent;
}
 
Example #12
Source File: Driver.java    From AWS-MIMIC-IIItoOMOP with Apache License 2.0 6 votes vote down vote up
public String lambda(SNSEvent event, Context context)
{
    try
    {   
        List<String> list = new ArrayList<String>();
        
        for(SNSEvent.SNSRecord record : event.getRecords())
        {
            String table = record.getSNS().getMessage().split(" ")[0];
            
            processor = new FileProcessor(table);
            processor.readFiles();
       
            processor.closeConnection();
            
            list.add(table);
        }
        
        return list.toString() + " successfully loaded";
    }
    catch(IOException | ClassNotFoundException | SQLException ex){ return ex.toString(); }
}
 
Example #13
Source File: SnsRequestHandlerIntTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleRecordsCreateMultipleRequest() {
	SNSEvent snsEvent = new SNSEvent();
	SNSRecord snsRecord0 = createSnsRecord("a:b:mytopic", "inject-sns-record-member0");
	SNSRecord snsRecord1 = createSnsRecord("a:b:mytopic", "inject-sns-record-member1");
	snsEvent.setRecords(ImmutableList.of(snsRecord0, snsRecord1));
	handler.handleRequest(snsEvent, context);
	InOrder inOrder = Mockito.inOrder(testService);
	inOrder.verify(testService).injectedSns(snsRecord0.getSNS());
	inOrder.verify(testService).injectedSns(snsRecord1.getSNS());
}
 
Example #14
Source File: SnsRequestObjectHandler.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Override
public Void handleRequest(SNSEvent snsEvent, Context context) {
	for (SNSRecord snsRecord : snsEvent.getRecords()) {
		delegateRequest(new SnsRecordAndLambdaContext(snsRecord, context));
	}
	return null;
}
 
Example #15
Source File: SnsRequestHandlerIntTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void testSnsRecordInjectionAsMember() {
	SNSEvent snsEvent = createSnsEvent("inject-sns-record-member0");
	handler.handleRequest(snsEvent, context);
	verify(testService).injectedSns(snsEvent.getRecords().get(0).getSNS());
	snsEvent = createSnsEvent("inject-sns-record-member1");
	handler.handleRequest(snsEvent, context);
	verify(testService).injectedSns(snsEvent.getRecords().get(0).getSNS());
}
 
Example #16
Source File: SnsRequestHandlerIntTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void testLambdaContextMemberInjection() {
	when(context.getAwsRequestId()).thenReturn("0", "1");
	for (int i = 0; i <= 1; i++) {
		SNSEvent snsEvent = createSnsEvent("inject-lambda-context-member" + i);
		handler.handleRequest(snsEvent, context);
		verify(testService).injectedStringArg("" + i);
	}
}
 
Example #17
Source File: SNSS3HandlerTest.java    From bender with Apache License 2.0 5 votes vote down vote up
@Test
public void testExceptionHandlingd() throws Throwable {
  BaseHandler.CONFIG_FILE = "/com/nextdoor/bender/handler/config_test_sns.json";

  TestContext ctx = new TestContext();
  ctx.setFunctionName("unittest");
  ctx.setInvokedFunctionArn("arn:aws:lambda:us-east-1:123:function:test-function:staging");

  /*
   * Invoke handler
   */
  SNSS3Handler fhandler = (SNSS3Handler) getHandler();
  fhandler.init(ctx);

  IpcSenderService ipcSpy = spy(fhandler.getIpcService());
  doThrow(new TransportException("expected")).when(ipcSpy).flush();
  fhandler.setIpcService(ipcSpy);

  AmazonSNSClient mockClient = mock(AmazonSNSClient.class);
  AmazonSNSClientFactory mockClientFactory = mock(AmazonSNSClientFactory.class);
  doReturn(mockClient).when(mockClientFactory).newInstance();

  fhandler.snsClientFactory = mockClientFactory;

  SNSEvent event = getTestEvent();

  try {
    fhandler.handler(event, ctx);
  } catch (Exception e) {
  }
  verify(mockClient, times(1)).publish("foo", "basic_input.log", "SNSS3Handler Failed");
}
 
Example #18
Source File: SnsRequestHandlerIntTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostString() {
	SNSEvent snsEvent = createSnsEvent("plain-data");
	snsEvent.getRecords().get(0).getSNS().setMessage("123");
	handler.handleRequest(snsEvent, context);
	verify(testService).injectedStringArg("123");
}
 
Example #19
Source File: SnsRequestHandlerIntTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostJson() {
	SNSEvent snsEvent = createSnsEvent("entities");
	snsEvent.getRecords().get(0).getSNS().setMessage("{\"value\":\"some data\"}");
	handler.handleRequest(snsEvent, context);
	verify(testService).injectedStringArg("some data");
}
 
Example #20
Source File: Lambda.java    From github-bucket with ISC License 5 votes vote down vote up
public Integer handleRequest(SNSEvent event, Context context) {
    try {
        // SNS Events could be possible more than one even if this looks a bit unusual for the deploy case.
        for (SNSEvent.SNSRecord record : event.getRecords()) {
            SNSEvent.SNS sns = record.getSNS();
            // Check SNS header for event type.
            SNSEvent.MessageAttribute attr = sns.getMessageAttributes().get(X_GITHUB_EVENT);
            // Only watch pushes to master.
            if (EVENT_PUSH.equalsIgnoreCase(attr.getValue())) {
                PushPayload value = MAPPER.readValue(sns.getMessage(), PushPayload.class);
                if (config.isWatchedBranch(new Branch(value.getRef()))) {
                    LOG.info(format("Processing '%s' on '%s': '%s'", attr.getValue(), value.getRef(), value.getHeadCommit().getId()));
                    switch (worker.call()) {
                        case SUCCESS:
                            return HttpStatus.SC_OK;
                        case FAILED:
                            return HttpStatus.SC_BAD_REQUEST;
                    }
                }
                // Different branch was found.
                else {
                    LOG.info(format("Push received for: '%s'", value.getRef()));
                }
            }
            // Different event was found.
            else {
                LOG.info(format("Event was: '%s'", attr.getValue()));
            }
        }
    }
    catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return HttpStatus.SC_INTERNAL_SERVER_ERROR;
    }
    return HttpStatus.SC_BAD_REQUEST;
}
 
Example #21
Source File: LambdaTest.java    From github-bucket with ISC License 5 votes vote down vote up
@Test
public void shouldFailOnOtherEvent() throws Exception {
    // Given
    Context context = mock(Context.class);
    SNSEvent snsEvent = createSnsEvent("commit");

    // When
    Integer response = uut.handleRequest(snsEvent, context);

    // Then
    assertThat(response, is(HttpStatus.SC_BAD_REQUEST));
    verify(config, times(0)).isWatchedBranch(any());
    verify(worker, times(0)).call();
}
 
Example #22
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 #23
Source File: LambdaSnsEventHandler.java    From Serverless-Programming-Cookbook with MIT License 5 votes vote down vote up
/**
 * Handle request.
 *
 * @param snsEvent  - SQS Event passed as input to lambda handler
 * @param context - context object
 * @return true if success, else false.
 */
public Boolean handleRequest(final SNSEvent snsEvent, final Context context) {
    context.getLogger().log("Received SQS event: " + snsEvent);

    final SnsService snsService =  new SnsServiceImpl(this.sqsClient);
    // It is a good practice to prefix environment variables with a project specific prefix.
    // E.g. SPC is a prefix that denote Serverless Programming Cookbook.
    return snsService.processEvent(snsEvent, System.getenv("SPC_OUTPUT_QUEUE_URL"), context.getLogger());

}
 
Example #24
Source File: SnsLambdaHandler.java    From Building-Serverless-Architectures with MIT License 5 votes vote down vote up
@Override
public Void handleRequest(SNSEvent input, Context context) {
    input.getRecords().forEach(snsMessage -> {
        try {
            I deserializedPayload = objectMapper.readValue(snsMessage.getSNS().getMessage(), getJsonType());
            handleSnsRequest(deserializedPayload, context);
        } catch (IOException anyException) {
            LOGGER.error("JSON could not be deserialized", anyException);
        }
    });
    return null;
}
 
Example #25
Source File: SnsLambdaHandler.java    From Building-Serverless-Architectures with MIT License 5 votes vote down vote up
@Override
public Void handleRequest(SNSEvent input, Context context) {
    input.getRecords().forEach(snsMessage -> {
        try {
            I deserializedPayload = objectMapper.readValue(snsMessage.getSNS().getMessage(), getJsonType());
            handleSnsRequest(deserializedPayload, context);
        } catch (IOException anyException) {
            LOGGER.error("JSON could not be deserialized", anyException);
        }
    });
    return null;
}
 
Example #26
Source File: SnsLambdaHandler.java    From Building-Serverless-Architectures with MIT License 5 votes vote down vote up
@Override
public Void handleRequest(SNSEvent input, Context context) {
    input.getRecords().forEach(snsMessage -> {
        try {
            I deserializedPayload = objectMapper.readValue(snsMessage.getSNS().getMessage(), getJsonType());
            handleSnsRequest(deserializedPayload, context);
        } catch (IOException anyException) {
            LOGGER.error("JSON could not be deserialized", anyException);
        }
    });
    return null;
}
 
Example #27
Source File: SNSS3HandlerTest.java    From bender with Apache License 2.0 5 votes vote down vote up
@Override
public Handler<SNSEvent> getHandler() {
  SNSS3Handler handler = new SNSS3Handler();
  handler.s3ClientFactory = this.clientFactory;

  return handler;
}
 
Example #28
Source File: Lambda.java    From github-bucket with ISC License 5 votes vote down vote up
public Integer handleRequest(SNSEvent event, Context context) {
    try {
        // SNS Events could be possible more than one even if this looks a bit unusual for the deploy case.
        for (SNSEvent.SNSRecord record : event.getRecords()) {
            SNSEvent.SNS sns = record.getSNS();
            // Check SNS header for event type.
            SNSEvent.MessageAttribute attr = sns.getMessageAttributes().get(X_GITHUB_EVENT);
            // Only watch pushes to master.
            if (EVENT_PUSH.equalsIgnoreCase(attr.getValue())) {
                PushPayload value = MAPPER.readValue(sns.getMessage(), PushPayload.class);
                if (config.isWatchedBranch(new Branch(value.getRef()))) {
                    LOG.info(format("Processing '%s' on '%s': '%s'", attr.getValue(), value.getRef(), value.getHeadCommit().getId()));
                    switch (worker.call()) {
                        case SUCCESS:
                            return HttpStatus.SC_OK;
                        case FAILED:
                            return HttpStatus.SC_BAD_REQUEST;
                    }
                }
                // Different branch was found.
                else {
                    LOG.info(format("Push received for: '%s'", value.getRef()));
                }
            }
            // Different event was found.
            else {
                LOG.info(format("Event was: '%s'", attr.getValue()));
            }
        }
    }
    catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return HttpStatus.SC_INTERNAL_SERVER_ERROR;
    }
    return HttpStatus.SC_BAD_REQUEST;
}
 
Example #29
Source File: LambdaTest.java    From github-bucket with ISC License 5 votes vote down vote up
@Test
public void shouldFailOnOtherEvent() throws Exception {
    // Given
    Context context = mock(Context.class);
    SNSEvent snsEvent = createSnsEvent("commit");

    // When
    Integer response = uut.handleRequest(snsEvent, context);

    // Then
    assertThat(response, is(HttpStatus.SC_BAD_REQUEST));
    verify(config, times(0)).isWatchedBranch(any());
    verify(worker, times(0)).call();
}
 
Example #30
Source File: SNSS3HandlerTest.java    From bender with Apache License 2.0 5 votes vote down vote up
@Override
public Handler<SNSEvent> getHandler() {
  SNSS3Handler handler = new SNSS3Handler();
  handler.s3ClientFactory = this.clientFactory;

  return handler;
}