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

The following examples show how to use com.amazonaws.services.lambda.runtime.events.SNSEvent.SNSRecord. 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: SnsRequestHandler.java    From jrestless with Apache License 2.0 6 votes vote down vote up
@Override
protected void extendActualJerseyContainerRequest(ContainerRequest actualContainerRequest,
		JRestlessContainerRequest containerRequest, SnsRecordAndLambdaContext snsRecordAndContext) {
	SNSRecord snsRecord = snsRecordAndContext.getSnsRecord();
	Context lambdaContext = snsRecordAndContext.getLambdaContext();
	actualContainerRequest.setRequestScopedInitializer(locator -> {
		Ref<SNSRecord> snsRecordRef = locator.<Ref<SNSRecord>>getInstance(SNS_RECORD_TYPE);
		if (snsRecordRef != null) {
			snsRecordRef.set(snsRecord);
		} else {
			LOG.error("SnsFeature has not been registered. SNSRecord injection won't work.");
		}
		Ref<Context> contextRef = locator
				.<Ref<Context>>getInstance(AbstractLambdaContextReferencingBinder.LAMBDA_CONTEXT_TYPE);
		if (contextRef != null) {
			contextRef.set(lambdaContext);
		} else {
			LOG.error("AwsFeature has not been registered. Context injection won't work.");
		}
	});
}
 
Example #3
Source File: SnsRequestHandlerTest.java    From jrestless with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void createResponseWriter_writeResponse_Always_ShouldDelegateResponseToHandler() throws IOException {
	SnsRecordAndLambdaContext reqAndContext = mock(SnsRecordAndLambdaContext.class);
	SNS sns = new SNS();
	sns.setTopicArn(":t");
	SNSRecord snsRecord = new SNSRecord();
	snsRecord.setSns(sns);
	when(reqAndContext.getSnsRecord()).thenReturn(snsRecord);

	StatusType statusType = mock(StatusType.class);
	Map<String, List<String>> headers = mock(Map.class);
	ByteArrayOutputStream entityOutputStream = mock(ByteArrayOutputStream.class);
	snsHandler.createResponseWriter(reqAndContext).writeResponse(statusType, headers, entityOutputStream);
	verify(snsHandler).handleReponse(reqAndContext, statusType, headers, entityOutputStream);
}
 
Example #4
Source File: SnsRequestHandlerTest.java    From jrestless with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void delegateRequest_ValidRequestAndReferencesGiven_ShouldSetReferencesOnRequestInitialization() {

	Context context = mock(Context.class);
	SNS sns = new SNS();
	sns.setTopicArn(":t");
	SNSRecord snsRecord = new SNSRecord();
	snsRecord.setSns(sns);

	RequestScopedInitializer requestScopedInitializer = getSetRequestScopedInitializer(context, snsRecord);

	Ref<SNSRecord> snsRef = mock(Ref.class);
	Ref<Context> contextRef = mock(Ref.class);

	InjectionManager injectionManager = mock(InjectionManager.class);
	when(injectionManager.getInstance(SNS_RECORD_TYPE)).thenReturn(snsRef);
	when(injectionManager.getInstance(AbstractLambdaContextReferencingBinder.LAMBDA_CONTEXT_TYPE)).thenReturn(contextRef);

	requestScopedInitializer.initialize(injectionManager);

	verify(snsRef).set(snsRecord);
	verify(contextRef).set(context);
}
 
Example #5
Source File: SnsRequestHandlerTest.java    From jrestless with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private RequestScopedInitializer getSetRequestScopedInitializer(Context context, SNSRecord snsRecord) {
	SnsRecordAndLambdaContext reqAndContext = new SnsRecordAndLambdaContext(snsRecord, context);
	ArgumentCaptor<Consumer> containerEnhancerCaptor = ArgumentCaptor.forClass(Consumer.class);
	snsHandler.delegateRequest(reqAndContext);
	verify(container).handleRequest(any(), any(), any(), containerEnhancerCaptor.capture());

	ContainerRequest containerRequest = mock(ContainerRequest.class);
	containerEnhancerCaptor.getValue().accept(containerRequest);

	ArgumentCaptor<RequestScopedInitializer> requestScopedInitializerCaptor = ArgumentCaptor.forClass(RequestScopedInitializer.class);

	verify(containerRequest).setRequestScopedInitializer(requestScopedInitializerCaptor.capture());

	return requestScopedInitializerCaptor.getValue();
}
 
Example #6
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 #7
Source File: SnsRequestHandlerIntTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
private SNSRecord createSnsRecord(String topicArn, String subject) {
	SNS sns = new SNS();
	sns.setTopicArn(topicArn);
	sns.setSubject(subject);
	SNSRecord snsRecord = new SNSRecord();
	snsRecord.setSns(sns);
	return snsRecord;
}
 
Example #8
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 #9
Source File: SnsRequestHandlerTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
private SnsRecordAndLambdaContext createMinimalRequest() {
	SNS sns = new SNS();
	sns.setTopicArn(":t");
	SNSRecord snsRecord = new SNSRecord();
	snsRecord.setSns(sns);
	return new SnsRecordAndLambdaContext(snsRecord, null);
}
 
Example #10
Source File: SnsRequestHandlerTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void delegateRequest_ValidRequestAndNoReferencesGiven_ShouldNotFailOnRequestInitialization() {

	Context context = mock(Context.class);
	SNS sns = new SNS();
	sns.setTopicArn(":t");
	SNSRecord snsRecord = new SNSRecord();
	snsRecord.setSns(sns);

	RequestScopedInitializer requestScopedInitializer = getSetRequestScopedInitializer(context, snsRecord);

	InjectionManager injectionManager = mock(InjectionManager.class);
	requestScopedInitializer.initialize(injectionManager);
}
 
Example #11
Source File: SNSS3HandlerTest.java    From bender with Apache License 2.0 4 votes vote down vote up
@Override
public SNSEvent getTestEvent() throws Exception {
  /*
   * Upload a test resoruce to the mock S3
   */
  String payload = IOUtils.toString(
      new InputStreamReader(this.getClass().getResourceAsStream("basic_input.log"), "UTF-8"));
  this.client.putObject(S3_BUCKET, "basic_input.log", payload);

  /*
   * Create a S3EventNotification event
   */
  S3ObjectEntity objEntity = new S3ObjectEntity("basic_input.log", 1L, null, null);
  S3BucketEntity bucketEntity = new S3BucketEntity(S3_BUCKET, null, null);
  S3Entity entity = new S3Entity(null, bucketEntity, objEntity, null);

  S3EventNotificationRecord rec = new S3EventNotificationRecord(null, null, null,
      "1970-01-01T00:00:00.000Z", null, null, null, entity, null);

  List<S3EventNotificationRecord> notifications = new ArrayList<S3EventNotificationRecord>(2);
  notifications.add(rec);

  /*
   * Wrap as an SNS Event
   */
  S3EventNotification event = new S3EventNotification(notifications);
  SNSEvent.SNS sns = new SNSEvent.SNS();
  sns.setMessage(event.toJson());

  SNSEvent snsEvent = new SNSEvent();

  ArrayList<SNSRecord> snsRecords = new ArrayList<SNSRecord>(1);
  SNSRecord snsRecord = new SNSRecord();
  snsRecord.setEventSource("aws:sns");
  snsRecord.setEventVersion("1.0");
  snsRecord.setEventSubscriptionArn("arn");

  snsRecord.setSns(sns);
  snsRecords.add(snsRecord);
  snsEvent.setRecords(snsRecords);

  return snsEvent;
}
 
Example #12
Source File: SnsRequestHandlerIntTest.java    From jrestless with Apache License 2.0 4 votes vote down vote up
@Path("/inject-sns-record-mock")
@POST
public void injectSnsRecordMock(@javax.ws.rs.core.Context SNSRecord snsRecord) {
	service.injectedSnsRecord(snsRecord);
}
 
Example #13
Source File: SnsRequestHandlerIntTest.java    From jrestless with Apache License 2.0 4 votes vote down vote up
@Path("/inject-sns-record")
@POST
public void injectSnsRecord(@javax.ws.rs.core.Context SNSRecord snsRecord) {
	service.injectedSns(snsRecord.getSNS());
}
 
Example #14
Source File: SnsRecordAndLambdaContext.java    From jrestless with Apache License 2.0 4 votes vote down vote up
public SNSRecord getSnsRecord() {
	return snsRecord;
}
 
Example #15
Source File: SnsRecordAndLambdaContext.java    From jrestless with Apache License 2.0 4 votes vote down vote up
public SnsRecordAndLambdaContext(SNSRecord snsRecord, Context lambdaContext) {
	this.snsRecord = snsRecord;
	this.lambdaContext = lambdaContext;
}
 
Example #16
Source File: SnsRequestHandler.java    From jrestless with Apache License 2.0 4 votes vote down vote up
@Inject
ReferencingSnsRecordFactory(final Provider<Ref<SNSRecord>> referenceFactory) {
	super(referenceFactory);
}
 
Example #17
Source File: SnsRequestHandler.java    From jrestless with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure() {
	bindReferencingLambdaContextFactory();
	bindReferencingFactory(SNSRecord.class, ReferencingSnsRecordFactory.class,
			new GenericType<Ref<SNSRecord>>() { });
}
 
Example #18
Source File: SNSS3HandlerTest.java    From bender with Apache License 2.0 4 votes vote down vote up
private SNSEvent getTestEvent(String bucket, boolean doPut) throws Exception {
  /*
   * Upload a test resoruce to the mock S3
   */
  if (doPut) {
    String payload = IOUtils.toString(
        new InputStreamReader(this.getClass().getResourceAsStream("basic_input.log"), "UTF-8"));
    this.client.putObject(bucket, "basic_input.log", payload);
  }
  /*
   * Create a S3EventNotification event
   */
  S3ObjectEntity objEntity = new S3ObjectEntity("basic_input.log", 1L, null, null);
  S3BucketEntity bucketEntity = new S3BucketEntity(bucket, null, null);
  S3Entity entity = new S3Entity(null, bucketEntity, objEntity, null);

  S3EventNotificationRecord rec = new S3EventNotificationRecord(null, null, null,
      "1970-01-01T00:00:00.000Z", null, null, null, entity, null);

  List<S3EventNotificationRecord> notifications = new ArrayList<S3EventNotificationRecord>(2);
  notifications.add(rec);

  /*
   * Wrap as an SNS Event
   */
  S3EventNotification event = new S3EventNotification(notifications);
  SNSEvent.SNS sns = new SNSEvent.SNS();
  sns.setMessage(event.toJson());

  SNSEvent snsEvent = new SNSEvent();

  ArrayList<SNSRecord> snsRecords = new ArrayList<SNSRecord>(1);
  SNSRecord snsRecord = new SNSRecord();
  snsRecord.setEventSource("aws:sns");
  snsRecord.setEventVersion("1.0");
  snsRecord.setEventSubscriptionArn("arn");

  snsRecord.setSns(sns);
  snsRecords.add(snsRecord);
  snsEvent.setRecords(snsRecords);

  return snsEvent;
}
 
Example #19
Source File: SNSS3Handler.java    From bender with Apache License 2.0 4 votes vote down vote up
@Override
public void handler(SNSEvent event, Context context) throws HandlerException {
  if (!initialized) {
    init(context);
    SNSS3HandlerConfig handlerConfig = (SNSS3HandlerConfig) this.config.getHandlerConfig();
    this.logTrigger = handlerConfig.getLogSnsTrigger();
  }

  this.source = this.sources.get(0);
  this.inputFiles = new ArrayList<String>(0);

  if (this.logTrigger) {
    logger.info("trigger: " + gson.toJson(event));
  }

  for (SNSRecord record : event.getRecords()) {
    /*
     * Parse SNS as a S3 notification
     */
    String json = record.getSNS().getMessage();
    S3EventNotification s3Event = S3EventNotification.parseJson(json);

    /*
     * Validate the S3 file matches the regex
     */
    List<S3EventNotificationRecord> toProcess =
        new ArrayList<S3EventNotificationRecord>(s3Event.getRecords());
    for (S3EventNotificationRecord s3Record : s3Event.getRecords()) {
      String s3Path = String.format("s3://%s/%s", s3Record.getS3().getBucket().getName(),
          s3Record.getS3().getObject().getKey());
      try {
        this.source = SourceUtils.getSource(s3Path, this.sources);
      } catch (SourceNotFoundException e) {
        logger.warn("skipping processing " + s3Path);
        toProcess.remove(s3Record);
      }
    }

    if (toProcess.size() == 0) {
      logger.warn("Nothing to process");
      return;
    }

    this.inputFiles.addAll(toProcess.stream().map(m -> {
      return m.getS3().getObject().getKey();
    }).collect(Collectors.toList()));

    this.recordIterator =
        new S3EventIterator(new LambdaContext(context), toProcess, s3ClientFactory);

    super.process(context);
  }
}
 
Example #20
Source File: SnsRequestHandlerIntTest.java    From jrestless with Apache License 2.0 votes vote down vote up
void injectedSnsRecord(SNSRecord snsRecord);