software.amazon.awssdk.services.sns.model.PublishResponse Java Examples

The following examples show how to use software.amazon.awssdk.services.sns.model.PublishResponse. 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: PublishTopic.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void pubTopic(SnsClient snsClient, String message, String topicArn) {

        try {
            PublishRequest request = PublishRequest.builder()
                .message(message)
                .topicArn(topicArn)
                .build();

            PublishResponse result = snsClient.publish(request);
            System.out.println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode());

         } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
              System.exit(1);
         }
        //snippet-end:[sns.java2.PublishTopic.main]
    }
 
Example #2
Source File: PublishTextSMS.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) {
    try {
        PublishRequest request = PublishRequest.builder()
            .message(message)
            .phoneNumber(phoneNumber)
            .build();

        PublishResponse result = snsClient.publish(request);

        System.out.println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode());

    } catch (SnsException e) {

    System.err.println(e.awsErrorDetails().errorMessage());
    System.exit(1);
    }

    //snippet-end:[sns.java2.PublishTextSMS.main]
}
 
Example #3
Source File: PublishTextSMS.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public void sendMessage(String id) {

        Region region = Region.US_EAST_1;
        SnsClient snsClient = SnsClient.builder()
                .region(region)
                .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
                .build();
        String message = "A new item with ID value "+ id +" was added to the DynamoDB table";
        String phoneNumber="ENTER MOBILE NUMBER"; //Replace with a mobile phone number

        try {
            PublishRequest request = PublishRequest.builder()
                    .message(message)
                    .phoneNumber(phoneNumber)
                    .build();

            PublishResponse result = snsClient.publish(request);

        } catch (SnsException e) {

            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
 
Example #4
Source File: SnsIOTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testDataWritesToSNS() {
  ImmutableList<String> input = ImmutableList.of("message1", "message2");

  final PCollection<PublishResponse> results =
      p.apply(Create.of(input))
          .apply(
              SnsIO.<String>write()
                  .withPublishRequestFn(SnsIOTest::createSampleMessage)
                  .withTopicArn(topicArn)
                  .withRetryConfiguration(
                      SnsIO.RetryConfiguration.create(
                          5, org.joda.time.Duration.standardMinutes(1)))
                  .withSnsClientProvider(SnsClientMockSuccess::new));

  final PCollection<Long> publishedResultsSize = results.apply(Count.globally());
  PAssert.that(publishedResultsSize).containsInAnyOrder(ImmutableList.of(2L));
  p.run().waitUntilFinish();
}
 
Example #5
Source File: QuarksCannonSyncResource.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/shoot")
@Consumes(MediaType.APPLICATION_JSON)
public Response publish(Quark quark) throws Exception {
    String message = QUARK_WRITER.writeValueAsString(quark);
    PublishResponse response = sns.publish(p -> p.topicArn(topicArn).message(message));
    LOGGER.infov("Fired Quark[{0}, {1}}]", quark.getFlavor(), quark.getSpin());
    return Response.ok().entity(response.messageId()).build();
}
 
Example #6
Source File: QuarksCannonAsyncResource.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/shoot")
@Consumes(MediaType.APPLICATION_JSON)
public Uni<Response> publish(Quark quark) throws Exception {
    String message = QUARK_WRITER.writeValueAsString(quark);
    return Uni.createFrom()
        .completionStage(sns.publish(p -> p.topicArn(topicArn).message(message)))
        .onItem().invoke(item -> LOGGER.infov("Fired Quark[{0}, {1}}]", quark.getFlavor(), quark.getSpin()))
        .onItem().apply(PublishResponse::messageId)
        .onItem().apply(id -> Response.ok().entity(id).build());
}
 
Example #7
Source File: SnsIO.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public PCollection<PublishResponse> expand(PCollection<T> input) {
  checkArgument(getTopicArn() != null, "withTopicArn() is required");
  checkArgument(getPublishRequestFn() != null, "withPublishRequestFn() is required");
  checkArgument(getSnsClientProvider() != null, "withSnsClientProvider() is required");
  checkArgument(
      isTopicExists(getSnsClientProvider().getSnsClient(), getTopicArn()),
      "Topic arn %s does not exist",
      getTopicArn());

  return input.apply(ParDo.of(new SnsWriterFn<>(this)));
}
 
Example #8
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 =
      (PublishRequest) spec.getPublishRequestFn().apply(context.element());
  Sleeper sleeper = Sleeper.DEFAULT;
  BackOff backoff = retryBackoff.backoff();
  int attempt = 0;
  while (true) {
    attempt++;
    try {
      PublishResponse 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.message(), 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 #9
Source File: SnsIO.java    From beam with Apache License 2.0 5 votes vote down vote up
private BiConsumer<? super PublishResponse, ? super Throwable> getPublishResponse(
    DoFn<T, SnsResponse<T>>.ProcessContext context) {
  return (response, ex) -> {
    if (ex == null) {
      SnsResponse<T> snsResponse = SnsResponse.of(context.element(), response);
      context.output(snsResponse);
    } else {
      LOG.error("Error while publishing request to SNS", ex);
      throw new SnsWriteException("Error while publishing request to SNS", ex);
    }
  };
}
 
Example #10
Source File: SnsResponse.java    From beam with Apache License 2.0 5 votes vote down vote up
public static <T> SnsResponse<T> of(@NonNull T element, @Nullable PublishResponse response) {

    final Optional<PublishResponse> publishResponse = Optional.ofNullable(response);
    OptionalInt statusCode =
        publishResponse
            .map(r -> OptionalInt.of(r.sdkHttpResponse().statusCode()))
            .orElse(OptionalInt.empty());

    Optional<String> statusText = publishResponse.flatMap(r -> r.sdkHttpResponse().statusText());

    return create(element, statusCode, statusText);
  }
 
Example #11
Source File: SnsClientMockSuccess.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public PublishResponse publish(PublishRequest publishRequest) {
  PublishResponse response = Mockito.mock(PublishResponse.class);
  SdkHttpResponse metadata = Mockito.mock(SdkHttpResponse.class);

  Mockito.when(metadata.headers()).thenReturn(new HashMap<>());
  Mockito.when(metadata.statusCode()).thenReturn(200);
  Mockito.when(response.sdkHttpResponse()).thenReturn(metadata);
  Mockito.when(response.messageId()).thenReturn(UUID.randomUUID().toString());

  return response;
}
 
Example #12
Source File: MockSnsAsyncExceptionClient.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<PublishResponse> publish(PublishRequest publishRequest) {
  CompletableFuture<PublishResponse> completableFuture = new CompletableFuture<>();
  completableFuture.completeExceptionally(
      new RuntimeException("Error occurred during publish call"));
  return completableFuture;
}
 
Example #13
Source File: SnsCoderProviderRegistrar.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public List<CoderProvider> getCoderProviders() {
  return ImmutableList.of(
      CoderProviders.forCoder(
          TypeDescriptor.of(PublishResponse.class), PublishResponseCoder.of()));
}
 
Example #14
Source File: PublishResponseCoder.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public void encode(PublishResponse value, OutputStream outStream) throws IOException {
  StringUtf8Coder.of().encode(value.messageId(), outStream);
}
 
Example #15
Source File: PublishResponseCoder.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public PublishResponse decode(InputStream inStream) throws IOException {
  final String messageId = StringUtf8Coder.of().decode(inStream);
  return PublishResponse.builder().messageId(messageId).build();
}
 
Example #16
Source File: SnsClientMockErrors.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public PublishResponse publish(PublishRequest publishRequest) {
  throw InternalErrorException.builder().message("Service unavailable").build();
}