com.amazonaws.services.sns.model.PublishResult Java Examples

The following examples show how to use com.amazonaws.services.sns.model.PublishResult. 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: SnsDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
public PublishResult publish(AwsParamsDto awsParamsDto, String topicArn, String messageText, List<MessageHeader> messageHeaders)
{
    Map<String, MessageAttributeValue> messageAttributes = null;

    if (CollectionUtils.isNotEmpty(messageHeaders))
    {
        messageAttributes = new HashMap<>();

        for (MessageHeader messageHeader : messageHeaders)
        {
            messageAttributes.put(messageHeader.getKey(), new MessageAttributeValue().withDataType("String").withStringValue(messageHeader.getValue()));
        }
    }

    return snsOperations.publish(topicArn, messageText, messageAttributes, awsClientFactory.getAmazonSNSClient(awsParamsDto));
}
 
Example #2
Source File: PublishResultCodersTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testFullPublishResultWithoutHeadersDecodeEncodeEquals() throws Exception {
  CoderProperties.coderDecodeEncodeEqual(
      PublishResultCoders.fullPublishResultWithoutHeaders(),
      new PublishResult().withMessageId(UUID.randomUUID().toString()));

  PublishResult value = buildFullPublishResult();
  PublishResult clone =
      CoderUtils.clone(PublishResultCoders.fullPublishResultWithoutHeaders(), value);
  assertThat(
      clone.getSdkResponseMetadata().getRequestId(),
      equalTo(value.getSdkResponseMetadata().getRequestId()));
  assertThat(
      clone.getSdkHttpMetadata().getHttpStatusCode(),
      equalTo(value.getSdkHttpMetadata().getHttpStatusCode()));
  assertThat(clone.getSdkHttpMetadata().getHttpHeaders().isEmpty(), equalTo(true));
}
 
Example #3
Source File: SNSPublisher.java    From kork with Apache License 2.0 6 votes vote down vote up
public Optional<PublishResult> publishMessage(String message) {
  if (!isEnabled.get()) {
    log.warn("Publishing is disabled for topic {}, dropping message {}", topicARN, message);
    return Optional.empty();
  }

  try {
    PublishRequest publishRequest = new PublishRequest(topicARN.getArn(), message);
    PublishResult publishResponse =
        retrySupport.retry(
            () -> amazonSNS.publish(publishRequest), 5, Duration.ofMillis(200), false);

    log.debug(
        "Published message {} with id {} to topic {}",
        message,
        publishResponse.getMessageId(),
        topicARN);
    getSuccessCounter().increment();
    return Optional.of(publishResponse);
  } catch (Exception e) {
    log.error("failed to publish message {} to topic {}", message, topicARN, e);
    getErrorCounter(e).increment();
    return Optional.empty();
  }
}
 
Example #4
Source File: PushSnsService.java    From oxAuth with MIT License 6 votes vote down vote up
public PublishResult sendPushMessage(AmazonSNS snsClient, PushPlatform platform, String targetArn, Map<String, Object> customAppMessageMap, Map<String, MessageAttributeValue> messageAttributes) throws IOException {
	Map<String, Object> appMessageMap = new HashMap<String, Object>();

	if (platform == PushPlatform.GCM) {
		appMessageMap.put("collapse_key", "single");
		appMessageMap.put("delay_while_idle", true);
		appMessageMap.put("time_to_live", 30);
		appMessageMap.put("dry_run", false);
	}

	if (customAppMessageMap != null) {
		appMessageMap.putAll(customAppMessageMap);
	}

	String message = ServerUtil.asJson(appMessageMap);

	return sendPushMessage(snsClient, platform, targetArn, message, messageAttributes);
}
 
Example #5
Source File: PushSnsService.java    From oxAuth with MIT License 6 votes vote down vote up
public PublishResult sendPushMessage(AmazonSNS snsClient, PushPlatform platform, String targetArn, String message,
		Map<String, MessageAttributeValue> messageAttributes) throws IOException {
	Map<String, String> messageMap = new HashMap<String, String>();
	messageMap.put(platform.name(), message);
	message = ServerUtil.asJson(messageMap);

    PublishRequest publishRequest = new PublishRequest();
	publishRequest.setMessageStructure("json");
	
	if (messageAttributes != null) {
		publishRequest.setMessageAttributes(messageAttributes);
	}

	publishRequest.setTargetArn(targetArn);
	publishRequest.setMessage(message);

	PublishResult publishResult = snsClient.publish(publishRequest);

	return publishResult;
}
 
Example #6
Source File: PublishResultCodersTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testFullPublishResultIncludingHeadersDecodeEncodeEquals() throws Exception {
  CoderProperties.coderDecodeEncodeEqual(
      PublishResultCoders.fullPublishResult(),
      new PublishResult().withMessageId(UUID.randomUUID().toString()));

  PublishResult value = buildFullPublishResult();
  PublishResult clone = CoderUtils.clone(PublishResultCoders.fullPublishResult(), value);
  assertThat(
      clone.getSdkResponseMetadata().getRequestId(),
      equalTo(value.getSdkResponseMetadata().getRequestId()));
  assertThat(
      clone.getSdkHttpMetadata().getHttpStatusCode(),
      equalTo(value.getSdkHttpMetadata().getHttpStatusCode()));
  assertThat(
      clone.getSdkHttpMetadata().getHttpHeaders(),
      equalTo(value.getSdkHttpMetadata().getHttpHeaders()));
}
 
Example #7
Source File: SnsDaoTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testPublish()
{
    // Publish an SNS message without proxy.
    assertEquals(new PublishResult().withMessageId(MESSAGE_ID), snsDao.publish(
        new AwsParamsDto(NO_AWS_ACCESS_KEY, NO_AWS_SECRET_KEY, NO_SESSION_TOKEN, NO_HTTP_PROXY_HOST, NO_HTTP_PROXY_PORT, AWS_REGION_NAME_US_EAST_1),
        AWS_SNS_TOPIC_ARN, MESSAGE_TEXT, NO_MESSAGE_HEADERS));

    // Publish an SNS message using proxy settings.
    assertEquals(new PublishResult().withMessageId(MESSAGE_ID), snsDao
        .publish(new AwsParamsDto(NO_AWS_ACCESS_KEY, NO_AWS_SECRET_KEY, NO_SESSION_TOKEN, HTTP_PROXY_HOST, HTTP_PROXY_PORT, AWS_REGION_NAME_US_EAST_1),
            AWS_SNS_TOPIC_ARN, MESSAGE_TEXT, NO_MESSAGE_HEADERS));

    // Publish an SNS message with message headers.
    assertEquals(new PublishResult().withMessageId(MESSAGE_ID), snsDao
        .publish(new AwsParamsDto(NO_AWS_ACCESS_KEY, NO_AWS_SECRET_KEY, NO_SESSION_TOKEN, HTTP_PROXY_HOST, HTTP_PROXY_PORT, AWS_REGION_NAME_US_EAST_1),
            AWS_SNS_TOPIC_ARN, MESSAGE_TEXT, Collections.singletonList(new MessageHeader(KEY, VALUE))));
}
 
Example #8
Source File: TopicMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void sendMessage_withUuidAsId_shouldConvertUuidToString() throws Exception {
	// Arrange
	AmazonSNS amazonSns = mock(AmazonSNS.class);
	TopicMessageChannel messageChannel = new TopicMessageChannel(amazonSns,
			"http://testQueue");
	Message<String> message = MessageBuilder.withPayload("Hello").build();
	UUID uuid = (UUID) message.getHeaders().get(MessageHeaders.ID);

	ArgumentCaptor<PublishRequest> sendMessageRequestArgumentCaptor = ArgumentCaptor
			.forClass(PublishRequest.class);
	when(amazonSns.publish(sendMessageRequestArgumentCaptor.capture()))
			.thenReturn(new PublishResult());

	// Act
	boolean sent = messageChannel.send(message);

	// Assert
	assertThat(sent).isTrue();
	assertThat(sendMessageRequestArgumentCaptor.getValue().getMessageAttributes()
			.get(MessageHeaders.ID).getStringValue()).isEqualTo(uuid.toString());
}
 
Example #9
Source File: SnsIOTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testDataWritesToSNS() {
  final PublishRequest request1 = createSampleMessage("my_first_message");
  final PublishRequest request2 = createSampleMessage("my_second_message");

  final TupleTag<PublishResult> results = new TupleTag<>();
  final AmazonSNS amazonSnsSuccess = getAmazonSnsMockSuccess();

  final PCollectionTuple snsWrites =
      p.apply(Create.of(request1, request2))
          .apply(
              SnsIO.write()
                  .withTopicName(topicName)
                  .withRetryConfiguration(
                      SnsIO.RetryConfiguration.create(
                          5, org.joda.time.Duration.standardMinutes(1)))
                  .withAWSClientsProvider(new Provider(amazonSnsSuccess))
                  .withResultOutputTag(results));

  final PCollection<Long> publishedResultsSize = snsWrites.get(results).apply(Count.globally());
  PAssert.that(publishedResultsSize).containsInAnyOrder(ImmutableList.of(2L));
  p.run().waitUntilFinish();
}
 
Example #10
Source File: SnsIOTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetries() throws Throwable {
  thrown.expectMessage("Error writing to SNS");
  final PublishRequest request1 = createSampleMessage("my message that will not be published");
  final TupleTag<PublishResult> results = new TupleTag<>();
  final AmazonSNS amazonSnsErrors = getAmazonSnsMockErrors();
  p.apply(Create.of(request1))
      .apply(
          SnsIO.write()
              .withTopicName(topicName)
              .withRetryConfiguration(
                  SnsIO.RetryConfiguration.create(4, org.joda.time.Duration.standardSeconds(10)))
              .withAWSClientsProvider(new Provider(amazonSnsErrors))
              .withResultOutputTag(results));

  try {
    p.run();
  } catch (final Pipeline.PipelineExecutionException e) {
    // check 3 retries were initiated by inspecting the log before passing on the exception
    expectedLogs.verifyWarn(String.format(SnsIO.Write.SnsWriterFn.RETRY_ATTEMPT_LOG, 1));
    expectedLogs.verifyWarn(String.format(SnsIO.Write.SnsWriterFn.RETRY_ATTEMPT_LOG, 2));
    expectedLogs.verifyWarn(String.format(SnsIO.Write.SnsWriterFn.RETRY_ATTEMPT_LOG, 3));
    throw e.getCause();
  }
  fail("Pipeline is expected to fail because we were unable to write to SNS.");
}
 
Example #11
Source File: SnsIOTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomCoder() throws Exception {
  final PublishRequest request1 = createSampleMessage("my_first_message");

  final TupleTag<PublishResult> results = new TupleTag<>();
  final AmazonSNS amazonSnsSuccess = getAmazonSnsMockSuccess();
  final MockCoder mockCoder = new MockCoder();

  final PCollectionTuple snsWrites =
      p.apply(Create.of(request1))
          .apply(
              SnsIO.write()
                  .withTopicName(topicName)
                  .withAWSClientsProvider(new Provider(amazonSnsSuccess))
                  .withResultOutputTag(results)
                  .withCoder(mockCoder));

  final PCollection<Long> publishedResultsSize =
      snsWrites
          .get(results)
          .apply(MapElements.into(TypeDescriptors.strings()).via(result -> result.getMessageId()))
          .apply(Count.globally());
  PAssert.that(publishedResultsSize).containsInAnyOrder(ImmutableList.of(1L));
  p.run().waitUntilFinish();
  assertThat(mockCoder.captured).isNotNull();
}
 
Example #12
Source File: SNSNotifyAction.java    From davos with MIT License 6 votes vote down vote up
@Override
public void execute(PostDownloadExecution execution) {

    AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretAccessKey);

    AmazonSNS sns = snsClientBuilder.withRegion(region)
            .withCredentials(new AWSStaticCredentialsProvider(credentials)).build();

    LOGGER.debug("SNS: Topic Arn               : {}", arn);
    LOGGER.debug("SNS: Topic Region            : {}", region);
    LOGGER.debug("SNS: Topic Access Key        : {}", accessKey);
    LOGGER.debug("SNS: Topic Secret Access Key : {}", secretAccessKey);

    PublishRequest request = new PublishRequest();
    request.setTopicArn(arn);
    request.setMessageStructure("json");
    request.setMessage(formatJsonMessage(execution.fileName));
    request.setSubject("A new file has been downloaded");

    LOGGER.info("Publishing message to SNS");
    PublishResult result = sns.publish(request);
    LOGGER.info("Publish successful!");
    LOGGER.debug("{}", result.getMessageId());
}
 
Example #13
Source File: SnsWebhookManager.java    From Singularity with Apache License 2.0 6 votes vote down vote up
<T> CompletableFuture<Void> publish(WebhookType type, T content) {
  try {
    return CompletableFuture.runAsync(
      () -> {
        try {
          PublishRequest publishRequest = new PublishRequest(
            getOrCreateSnsTopic(type),
            objectMapper.writeValueAsString(content)
          );
          PublishResult result = snsClient.publish(publishRequest);
          LOG.trace("Sent update {} with messageId {}", content, result.getMessageId());
        } catch (IOException ioe) {
          throw new RuntimeException(ioe);
        }
      },
      publishExecutor
    );
  } catch (Throwable t) {
    CompletableFuture<Void> f = new CompletableFuture<>();
    f.completeExceptionally(t);
    return f;
  }
}
 
Example #14
Source File: SnsExecutor.java    From spring-integration-aws with MIT License 6 votes vote down vote up
/**
 * Executes the outbound Sns Operation.
 * 
 */
public Object executeOutboundOperation(final Message<?> message) {

	try {
		String serializedMessage = messageMarshaller.serialize(message);

		if (snsTestProxy == null) {
			PublishRequest request = new PublishRequest();
			PublishResult result = client.publish(request.withTopicArn(
					topicArn).withMessage(serializedMessage));
			log.debug("Published message to topic: "
					+ result.getMessageId());
		} else {
			snsTestProxy.dispatchMessage(serializedMessage);
		}

	} catch (MessageMarshallerException e) {
		log.error(e.getMessage(), e);
		throw new MessagingException(e.getMessage(), e.getCause());
	}

	return message.getPayload();
}
 
Example #15
Source File: SNSNotificationServiceImpl.java    From metacat with Apache License 2.0 6 votes vote down vote up
private void publishNotification(
    final String arn,
    final SNSMessage<?> message,
    final String counterKey
) throws Exception {
    PublishResult result = null;
    try {
        result = this.client.publish(arn, this.mapper.writeValueAsString(message));
    } catch (Exception exception) {
        log.error("SNS Publish message failed.", exception);
        notificationMetric.counterIncrement(
            Metrics.CounterSNSNotificationPublishMessageSizeExceeded.getMetricName());
        final SNSMessage<Void> voidMessage = new SNSMessage<>(message.getId(),
            message.getTimestamp(), message.getRequestId(), message.getType(), message.getName(),
            null);
        result = this.client.publish(arn, this.mapper.writeValueAsString(voidMessage));
    }
    log.info("Successfully published message to topic {} with id {}", arn, result.getMessageId());
    log.debug("Successfully published message {} to topic {} with id {}", message, arn, result.getMessageId());
    notificationMetric.counterIncrement(counterKey);
    notificationMetric.recordTime(message, Metrics.TimerNotificationsPublishDelay.getMetricName());
}
 
Example #16
Source File: SNSManager.java    From AWS-MIMIC-IIItoOMOP with Apache License 2.0 6 votes vote down vote up
public PublishResult publishFailure(String topicName, String table, String stack) 
{
    PublishResult result = null;
    
    for(Topic topic : sns.listTopics().getTopics())
    {
        if(sns.getTopicAttributes(topic.getTopicArn()).getAttributes().get("DisplayName").equals(topicName))
        {
            PublishRequest publishRequest = new PublishRequest(topic.getTopicArn(), "[ERROR]: " + table + " table was not able to be staged in S3. \n\n" + stack);
    
            result = sns.publish(publishRequest);
        }
        
    }
    return result;
}
 
Example #17
Source File: SNSManager.java    From AWS-MIMIC-IIItoOMOP with Apache License 2.0 6 votes vote down vote up
public PublishResult publishSuccess(String topicName, String table) 
{
    PublishResult result = null;
    
    for(Topic topic : sns.listTopics().getTopics())
    {
        if(sns.getTopicAttributes(topic.getTopicArn()).getAttributes().get("DisplayName").equals(topicName))
        {
            PublishRequest publishRequest = new PublishRequest(topic.getTopicArn(), table + " table has been staged in S3");
    
            result = sns.publish(publishRequest);
        }
        
    }
    return result;
}
 
Example #18
Source File: SnsMessageBroker.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
@Override
public void sendRawMessage(String message) {
  if (SNS_CLIENT == null) {
    logger.warn("The AdminMessage can not be sent as the MessageBroker is not ready. Message was: {}", message);
    return;
  }
  if (message.length() > MAX_MESSAGE_SIZE) {
    throw new RuntimeException("AdminMessage is larger than the MAX_MESSAGE_SIZE. Can not send it.");
  }
  //Send using SNS client
  SNS_CLIENT.publishAsync(TOPIC_ARN, message, new AsyncHandler<PublishRequest, PublishResult>() {
    @Override
    public void onError(Exception exception) {
      logger.error("Error sending message: {}", message, exception);
    }

    @Override
    public void onSuccess(PublishRequest request, PublishResult publishResult) {
      logger.debug("Message has been sent with following content: {}", message);
    }
  });
}
 
Example #19
Source File: SnsIO.java    From beam with Apache License 2.0 5 votes vote down vote up
@ProcessElement
public void processElement(ProcessContext context) throws Exception {
  PublishRequest request = context.element();
  Sleeper sleeper = Sleeper.DEFAULT;
  BackOff backoff = retryBackoff.backoff();
  int attempt = 0;
  while (true) {
    attempt++;
    try {
      PublishResult pr = producer.publish(request);
      context.output(pr);
      break;
    } catch (Exception ex) {
      // Fail right away if there is no retry configuration
      if (spec.getRetryConfiguration() == null
          || !spec.getRetryConfiguration().getRetryPredicate().test(ex)) {
        SNS_WRITE_FAILURES.inc();
        LOG.info("Unable to publish message {} due to {} ", request.getMessage(), ex);
        throw new IOException("Error writing to SNS (no attempt made to retry)", ex);
      }

      if (!BackOffUtils.next(sleeper, backoff)) {
        throw new IOException(
            String.format(
                "Error writing to SNS after %d attempt(s). No more attempts allowed",
                attempt),
            ex);
      } else {
        // Note: this used in test cases to verify behavior
        LOG.warn(String.format(RETRY_ATTEMPT_LOG, attempt), ex);
      }
    }
  }
}
 
Example #20
Source File: PublishResultCoders.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public PublishResult decode(InputStream inStream) throws CoderException, IOException {
  String messageId = MESSAGE_ID_CODER.decode(inStream);
  PublishResult publishResult = new PublishResult().withMessageId(messageId);
  if (responseMetadataEncoder != null) {
    publishResult.setSdkResponseMetadata(responseMetadataEncoder.decode(inStream));
  }
  if (sdkHttpMetadataCoder != null) {
    publishResult.setSdkHttpMetadata(sdkHttpMetadataCoder.decode(inStream));
  }
  return publishResult;
}
 
Example #21
Source File: LambdaSnsPublishHandler.java    From Serverless-Programming-Cookbook with MIT License 5 votes vote down vote up
/**
 * Handle request.
 *
 * @param request  - input to lambda handler.
 * @param context - context object.
 * @return Message id of the published message.
 */
public String handleRequest(final Request request, final Context context) {
    context.getLogger().log("Received Request: " + request);

    final PublishResult result;
    try {
        PublishRequest publishRequest = new PublishRequest(request.getTopicArn(), request.getMessage());
        result = snsClient.publish(publishRequest);
    } catch (Exception e) {
        return "Exception occurred: " + e.getMessage();
    }

    return "Message Id: " + result.getMessageId();
}
 
Example #22
Source File: TopicMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void sendMessage_withStringMessageHeader_shouldBeSentAsTopicMessageAttribute()
		throws Exception {
	// Arrange
	AmazonSNS amazonSns = mock(AmazonSNS.class);
	ArgumentCaptor<PublishRequest> publishRequestArgumentCaptor = ArgumentCaptor
			.forClass(PublishRequest.class);
	when(amazonSns.publish(publishRequestArgumentCaptor.capture()))
			.thenReturn(new PublishResult());

	String headerValue = "Header value";
	String headerName = "MyHeader";
	Message<String> message = MessageBuilder.withPayload("Hello")
			.setHeader(headerName, headerValue).build();
	MessageChannel messageChannel = new TopicMessageChannel(amazonSns, "topicArn");

	// Act
	boolean sent = messageChannel.send(message);

	// Assert
	assertThat(sent).isTrue();
	assertThat(publishRequestArgumentCaptor.getValue().getMessageAttributes()
			.get(headerName).getStringValue()).isEqualTo(headerValue);
	assertThat(publishRequestArgumentCaptor.getValue().getMessageAttributes()
			.get(headerName).getDataType())
					.isEqualTo(MessageAttributeDataTypes.STRING);
}
 
Example #23
Source File: TopicMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void sendMessage_withBinaryMessageHeader_shouldBeSentAsBinaryMessageAttribute()
		throws Exception {
	// Arrange
	AmazonSNS amazonSns = mock(AmazonSNS.class);
	ArgumentCaptor<PublishRequest> publishRequestArgumentCaptor = ArgumentCaptor
			.forClass(PublishRequest.class);
	when(amazonSns.publish(publishRequestArgumentCaptor.capture()))
			.thenReturn(new PublishResult());

	ByteBuffer headerValue = ByteBuffer.wrap("My binary data!".getBytes());
	String headerName = "MyHeader";
	Message<String> message = MessageBuilder.withPayload("Hello")
			.setHeader(headerName, headerValue).build();
	MessageChannel messageChannel = new TopicMessageChannel(amazonSns, "topicArn");

	// Act
	boolean sent = messageChannel.send(message);

	// Assert
	assertThat(sent).isTrue();
	assertThat(publishRequestArgumentCaptor.getValue().getMessageAttributes()
			.get(headerName).getBinaryValue()).isEqualTo(headerValue);
	assertThat(publishRequestArgumentCaptor.getValue().getMessageAttributes()
			.get(headerName).getDataType())
					.isEqualTo(MessageAttributeDataTypes.BINARY);
}
 
Example #24
Source File: PlatformEndpointImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public PublishResult publish(PublishRequest request,
        ResultCapture<PublishResult> extractor) {

    ActionResult result = resource.performAction("Publish", request,
            extractor);

    if (result == null) return null;
    return (PublishResult) result.getData();
}
 
Example #25
Source File: TopicImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public PublishResult publish(PublishRequest request,
        ResultCapture<PublishResult> extractor) {

    ActionResult result = resource.performAction("Publish", request,
            extractor);

    if (result == null) return null;
    return (PublishResult) result.getData();
}
 
Example #26
Source File: TopicImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public PublishResult publish(String message, ResultCapture<PublishResult>
        extractor) {

    PublishRequest request = new PublishRequest()
        .withMessage(message);
    return publish(request, extractor);
}
 
Example #27
Source File: TopicImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public PublishResult publish(String subject, String message,
        ResultCapture<PublishResult> extractor) {

    PublishRequest request = new PublishRequest()
        .withSubject(subject)
        .withMessage(message);
    return publish(request, extractor);
}
 
Example #28
Source File: TestPutSNS.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublish() throws IOException {
    runner.setProperty(PutSNS.CREDENTIALS_FILE, "src/test/resources/mock-aws-credentials.properties");
    runner.setProperty(PutSNS.ARN, "arn:aws:sns:us-west-2:123456789012:test-topic-1");
    runner.setProperty(PutSNS.SUBJECT, "${eval.subject}");
    assertTrue(runner.setProperty("DynamicProperty", "hello!").isValid());
    final Map<String, String> ffAttributes = new HashMap<>();
    ffAttributes.put("filename", "1.txt");
    ffAttributes.put("eval.subject", "test-subject");
    runner.enqueue("Test Message Content", ffAttributes);

    PublishResult mockPublishResult = new PublishResult();
    Mockito.when(mockSNSClient.publish(Mockito.any(PublishRequest.class))).thenReturn(mockPublishResult);

    runner.run();

    ArgumentCaptor<PublishRequest> captureRequest = ArgumentCaptor.forClass(PublishRequest.class);
    Mockito.verify(mockSNSClient, Mockito.times(1)).publish(captureRequest.capture());
    PublishRequest request = captureRequest.getValue();
    assertEquals("arn:aws:sns:us-west-2:123456789012:test-topic-1", request.getTopicArn());
    assertEquals("Test Message Content", request.getMessage());
    assertEquals("test-subject", request.getSubject());
    assertEquals("hello!", request.getMessageAttributes().get("DynamicProperty").getStringValue());

    runner.assertAllFlowFilesTransferred(PutSNS.REL_SUCCESS, 1);
    List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(PutSNS.REL_SUCCESS);
    MockFlowFile ff0 = flowFiles.get(0);
    ff0.assertAttributeEquals(CoreAttributes.FILENAME.key(), "1.txt");
}
 
Example #29
Source File: SNSQueueManagerImpl.java    From usergrid with Apache License 2.0 5 votes vote down vote up
private <T extends Serializable> void sendMessageToAllRegionsSync(final T body) throws IOException {
    if ( sns == null ) {
        logger.error( "SNS client is null, perhaps it failed to initialize successfully" );
        return;
    }

    final String stringBody = toString( body );

    String topicArn = getWriteTopicArn();

    if ( logger.isTraceEnabled() ) {
        logger.trace( "Publishing Message...{} to arn: {}", stringBody, topicArn );
    }

    try {
        PublishResult publishResult = sns.publish(topicArn, toString(body));
        if ( logger.isTraceEnabled() ) {
            logger.trace( "Successfully published... messageID=[{}],  arn=[{}]", publishResult.getMessageId(),
                topicArn );
        }
    } catch (Exception e) {
        if (logger.isErrorEnabled()) {
            logger.error(FAILED_TO_SEND_MESSAGE,  stringBody, topicArn, e);
        }
        sendMessageToAllRegionsAsync(body);
    }



}
 
Example #30
Source File: SNSQueueManagerImpl.java    From usergrid with Apache License 2.0 5 votes vote down vote up
private <T extends Serializable> void sendMessageToAllRegionsAsync(final T body ) throws IOException {
    if ( snsAsync == null ) {
        logger.error( "SNS client is null, perhaps it failed to initialize successfully" );
        return;
    }

    final String stringBody = toString( body );

    final String topicArn = getWriteTopicArn();

    if ( logger.isTraceEnabled() ) {
        logger.trace( "Publishing Message...{} to arn: {}", stringBody, topicArn );
    }

    PublishRequest publishRequest = new PublishRequest( topicArn, stringBody );

    snsAsync.publishAsync( publishRequest, new AsyncHandler<PublishRequest, PublishResult>() {
        @Override
        public void onError( Exception e ) {
            logger.error( "Error publishing message... {}", e );
            logger.error(FAILED_TO_SEND_MESSAGE, stringBody, topicArn, e);
        }


        @Override
        public void onSuccess( PublishRequest request, PublishResult result ) {
            if ( logger.isTraceEnabled() ) {
                logger.trace( "Successfully published... messageID=[{}],  arn=[{}]", result.getMessageId(),
                    request.getTopicArn() );
            }
        }
    } );
}