Example usage for com.amazonaws.handlers AsyncHandler AsyncHandler

List of usage examples for com.amazonaws.handlers AsyncHandler AsyncHandler

Introduction

In this page you can find the example usage for com.amazonaws.handlers AsyncHandler AsyncHandler.

Prototype

AsyncHandler

Source Link

Usage

From source file:lumbermill.internal.aws.SimpleRetryableKinesisClient.java

License:Apache License

/**
 * Recursively retry until there are no more failed records in response or to many retries
 *//*from w  w  w  .  j a  v  a 2s.c o m*/
private void putRecordsAsync(final RequestContext request) {
    amazonKinesisClient.putRecordsAsync(request.putRecordsRequest,
            new AsyncHandler<PutRecordsRequest, PutRecordsResult>() {

                @Override
                public void onError(Exception exception) {
                    try {
                        Observable<Optional<RequestContext>> observable = request.nextAttempt();
                        observable
                                .doOnNext(requestContext -> LOGGER.warn(
                                        "About to retry request from exception: {}", exception.getMessage()))
                                .doOnNext(context -> {
                                    if (context.isPresent()) {
                                        putRecordsAsync(context.get());
                                    } else {
                                        request.error(new FatalAWSException(
                                                "Too many kinesis retries, root cause:", exception));
                                    }
                                }).doOnError(throwable -> request.error(throwable)).subscribe();
                    } catch (Throwable t) {
                        LOGGER.error("Unexpected exception in onError()", t);
                        request.error(t);
                    }
                }

                @Override
                public void onSuccess(PutRecordsRequest putRecordsRequest, PutRecordsResult putRecordsResult) {
                    // Surround with try/catch to prevent any unexpected exceptions from beeing swallowed
                    try {
                        if (putRecordsResult.getFailedRecordCount() > 0) {
                            LOGGER.debug("Got {} failed records, retrying (attempts = {})",
                                    putRecordsResult.getFailedRecordCount(), request.attempt);
                            // Try again with failing records,
                            //Optional<RequestContext> nextAttempt = request.nextAttempt(putRecordsResult);
                            Observable<Optional<RequestContext>> observable = request
                                    .nextAttempt(putRecordsResult);
                            observable.doOnNext(context -> {
                                if (context.isPresent()) {
                                    putRecordsAsync(context.get());
                                } else {
                                    request.error(new FatalAWSException("Too many kinesis retries"));
                                }
                            }).doOnError(throwable -> request.error(throwable)).subscribe();
                        } else {
                            request.done();
                        }
                    } catch (Throwable t) {
                        LOGGER.error("Unexpected exception in onSuccess()", t);
                        request.error(t);
                    }
                }
            });
}

From source file:org.apache.usergrid.persistence.queue.impl.SNSQueueManagerImpl.java

License:Apache License

@Override
public <T extends Serializable> void sendMessageToAllRegions(final T body) throws IOException {
    if (snsAsync == null) {
        logger.error("SNS client is null, perhaps it failed to initialize successfully");
        return;/*from w  w  w .  ja v  a2s .c o  m*/
    }

    final String stringBody = toString(body);

    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);
        }

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

From source file:org.apache.usergrid.persistence.queue.impl.SNSQueueManagerImpl.java

License:Apache License

@Override
public <T extends Serializable> void sendMessageToLocalRegion(final T body) throws IOException {

    if (sqsAsync == null) {
        logger.error("SQS client is null, perhaps it failed to initialize successfully");
        return;/*from   w  w w .  j a v a 2  s .  com*/
    }
    final String stringBody = toString(body);

    String url = getReadQueue().getUrl();

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

    SendMessageRequest request = new SendMessageRequest(url, stringBody);

    sqsAsync.sendMessageAsync(request, new AsyncHandler<SendMessageRequest, SendMessageResult>() {

        @Override
        public void onError(final Exception e) {

            logger.error("Error sending message... {}", e);
        }

        @Override
        public void onSuccess(final SendMessageRequest request, final SendMessageResult sendMessageResult) {
            if (logger.isTraceEnabled()) {
                logger.trace("Successfully send... messageBody=[{}],  url=[{}]", request.getMessageBody(),
                        request.getQueueUrl());
            }
        }
    });
}

From source file:org.springframework.cloud.aws.autoconfigure.metrics.BufferingCloudWatchMetricSender.java

License:Apache License

protected BufferingCloudWatchMetricSender(String namespace, int maxBuffer, long nextRunDelayMillis,
        final AmazonCloudWatchAsync amazonCloudWatchAsync,
        final ScheduledExecutorService scheduledExecutorService) {
    this.namespace = namespace.trim();
    this.maxBuffer = maxBuffer;
    this.nextRunDelayMillis = nextRunDelayMillis;
    this.amazonCloudWatchAsync = amazonCloudWatchAsync;
    this.scheduledExecutorService = scheduledExecutorService;

    // Create a single async handler which can be reused.
    this.asyncHandler = new AsyncHandler<PutMetricDataRequest, Void>() {
        @Override/* w  w w . ja v  a2s  .  co m*/
        public void onError(Exception exception) {
            logger.error("Error sending metric data.", exception);
        }

        @Override
        public void onSuccess(PutMetricDataRequest request, Void aVoid) {

        }
    };

    // The next collect/send run.
    nextRun = new Runnable() {
        @Override
        public void run() {
            collectAndSend();
        }
    };
}

From source file:org.springframework.integration.aws.metadata.DynamoDbMetaDataStore.java

License:Apache License

@Override
public void afterPropertiesSet() throws Exception {
    try {/*from   ww  w . j ava  2s.  c  o m*/
        this.table.describe();
        createTableLatch.countDown();
        return;
    } catch (ResourceNotFoundException e) {
        if (logger.isInfoEnabled()) {
            logger.info("No table '" + this.table.getTableName() + "'. Creating one...");
        }
    }

    CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(this.table.getTableName())
            .withKeySchema(new KeySchemaElement(KEY, KeyType.HASH))
            .withAttributeDefinitions(new AttributeDefinition(KEY, ScalarAttributeType.S))
            .withProvisionedThroughput(new ProvisionedThroughput(this.readCapacity, this.writeCapacity));

    this.dynamoDB.createTableAsync(createTableRequest,
            new AsyncHandler<CreateTableRequest, CreateTableResult>() {

                @Override
                public void onError(Exception e) {
                    logger.error(
                            "Cannot create DynamoDb table: " + DynamoDbMetaDataStore.this.table.getTableName(),
                            e);
                    DynamoDbMetaDataStore.this.createTableLatch.countDown();
                }

                @Override
                public void onSuccess(CreateTableRequest request, CreateTableResult createTableResult) {
                    Waiter<DescribeTableRequest> waiter = DynamoDbMetaDataStore.this.dynamoDB.waiters()
                            .tableExists();

                    WaiterParameters<DescribeTableRequest> waiterParameters = new WaiterParameters<>(
                            new DescribeTableRequest(DynamoDbMetaDataStore.this.table.getTableName()))
                                    .withPollingStrategy(new PollingStrategy(new MaxAttemptsRetryStrategy(25),
                                            new FixedDelayStrategy(1)));

                    waiter.runAsync(waiterParameters, new WaiterHandler<DescribeTableRequest>() {

                        @Override
                        public void onWaitSuccess(DescribeTableRequest request) {
                            DynamoDbMetaDataStore.this.createTableLatch.countDown();
                            DynamoDbMetaDataStore.this.table.describe();
                        }

                        @Override
                        public void onWaitFailure(Exception e) {
                            logger.error("Cannot describe DynamoDb table: "
                                    + DynamoDbMetaDataStore.this.table.getTableName(), e);
                            DynamoDbMetaDataStore.this.createTableLatch.countDown();
                        }

                    });
                }

            });
}