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:com.amediamanager.metrics.MetricBatcher.java

License:Apache License

protected void sendBatch(Map<String, Collection<MetricDatum>> datums) {
    for (final Map.Entry<String, Collection<MetricDatum>> e : datums.entrySet()) {
        for (final List<MetricDatum> batch : Lists.partition(Lists.newLinkedList(e.getValue()), BATCH_SIZE)) {
            cloudWatch.putMetricDataAsync(
                    new PutMetricDataRequest().withNamespace(e.getKey()).withMetricData(batch),
                    new AsyncHandler<PutMetricDataRequest, Void>() {

                        @Override
                        public void onError(Exception exception) {
                            LOG.error("PutMetricData failed", exception);
                            LOG.info("Requeueing metric data.");
                            queuedDatums.putAll(e.getKey(), batch);
                        }//from  w  w  w .  ja v a2  s. c  o m

                        @Override
                        public void onSuccess(PutMetricDataRequest request, Void result) {
                            LOG.info("Successfully put " + request.getMetricData().size()
                                    + " datums for namespace " + request.getNamespace());
                            LOG.debug("Request", request);
                        }

                    });
        }
    }
}

From source file:com.kurtraschke.nyctrtproxy.services.CloudwatchProxyDataListener.java

License:Apache License

@PostConstruct
public void init() {
    if (_secretKey == null || _accessKey == null || _namespace == null) {
        _log.info("No AWS credentials supplied, disabling cloudwatch");
        _disabled = true;//  w w  w  . jav a  2  s.  c  om
        return;
    }
    BasicAWSCredentials cred = new BasicAWSCredentials(_accessKey, _secretKey);
    _client = AmazonCloudWatchAsyncClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(cred)).build();
    _handler = new AsyncHandler<PutMetricDataRequest, PutMetricDataResult>() {
        @Override
        public void onError(Exception e) {
            _log.error("Error sending to cloudwatch: " + e);
        }

        @Override
        public void onSuccess(PutMetricDataRequest request, PutMetricDataResult putMetricDataResult) {
            // do nothing
        }
    };
}

From source file:com.vmware.photon.controller.model.adapters.awsadapter.AWSEndpointAdapterService.java

License:Open Source License

private BiConsumer<AuthCredentialsServiceState, BiConsumer<ServiceErrorResponse, Throwable>> validate(
        EndpointConfigRequest body) {//from   w w  w. ja va 2s. c om

    return (credentials, callback) -> {
        String regionId = body.endpointProperties.get(REGION_KEY);
        AmazonEC2AsyncClient client = AWSUtils.getAsyncClient(credentials, regionId,
                this.clientManager.getExecutor(getHost()));

        // make a call to validate credentials
        client.describeAvailabilityZonesAsync(new DescribeAvailabilityZonesRequest(),
                new AsyncHandler<DescribeAvailabilityZonesRequest, DescribeAvailabilityZonesResult>() {
                    @Override
                    public void onError(Exception e) {
                        if (e instanceof AmazonServiceException) {
                            AmazonServiceException ase = (AmazonServiceException) e;
                            if (ase.getStatusCode() == STATUS_CODE_UNAUTHORIZED) {
                                ServiceErrorResponse r = Utils.toServiceErrorResponse(e);
                                r.statusCode = STATUS_CODE_UNAUTHORIZED;
                                callback.accept(r, e);
                            }
                            return;
                        }

                        callback.accept(null, e);
                    }

                    @Override
                    public void onSuccess(DescribeAvailabilityZonesRequest request,
                            DescribeAvailabilityZonesResult describeAvailabilityZonesResult) {
                        callback.accept(null, null);
                    }
                });
    };
}

From source file:com.vmware.photon.controller.model.adapters.awsadapter.AWSInstanceService.java

License:Open Source License

private void validateAWSCredentials(final AWSAllocation aws) {
    if (aws.computeRequest.isMockRequest) {
        aws.awsOperation.complete();//from ww  w .  j  a v a  2 s  .co m
        return;
    }

    aws.amazonEC2Client = this.clientManager.getOrCreateEC2Client(aws.parentAuth, getRequestRegionId(aws), this,
            aws.computeRequest.taskReference, false);

    // make a call to validate credentials
    aws.amazonEC2Client.describeAvailabilityZonesAsync(new DescribeAvailabilityZonesRequest(),
            new AsyncHandler<DescribeAvailabilityZonesRequest, DescribeAvailabilityZonesResult>() {
                @Override
                public void onError(Exception e) {
                    if (e instanceof AmazonServiceException) {
                        AmazonServiceException ase = (AmazonServiceException) e;
                        if (ase.getStatusCode() == STATUS_CODE_UNAUTHORIZED) {
                            ServiceErrorResponse r = Utils.toServiceErrorResponse(e);
                            r.statusCode = STATUS_CODE_UNAUTHORIZED;
                            aws.awsOperation.fail(e, r);
                        }
                        return;
                    }

                    aws.awsOperation.fail(e);
                }

                @Override
                public void onSuccess(DescribeAvailabilityZonesRequest request,
                        DescribeAvailabilityZonesResult describeAvailabilityZonesResult) {
                    aws.awsOperation.complete();
                }
            });
}

From source file:com.vmware.photon.controller.model.adapters.awsadapter.AWSPowerService.java

License:Open Source License

private void powerOn(AmazonEC2AsyncClient client, ComputePowerRequest pr, BaseAwsContext c) {
    AWSPowerService powerService = this;
    OperationContext opContext = OperationContext.getOperationContext();

    StartInstancesRequest request = new StartInstancesRequest();
    request.withInstanceIds(c.child.id);
    client.startInstancesAsync(request, new AsyncHandler<StartInstancesRequest, StartInstancesResult>() {
        @Override/*from w w  w.j a  va2 s .  c om*/
        public void onSuccess(StartInstancesRequest request, StartInstancesResult result) {
            OperationContext.restoreOperationContext(opContext);
            updateComputeState(pr);
        }

        @Override
        public void onError(Exception e) {
            OperationContext.restoreOperationContext(opContext);
            AdapterUtils.sendPatchToTask(powerService, pr.taskReference,
                    ResourceOperationResponse.fail(pr.resourceLink(), e));
        }
    });
}

From source file:com.vmware.photon.controller.model.adapters.awsadapter.AWSPowerService.java

License:Open Source License

private void powerOff(AmazonEC2AsyncClient client, ComputePowerRequest pr, BaseAwsContext c) {
    AWSPowerService powerService = this;
    OperationContext opContext = OperationContext.getOperationContext();

    StopInstancesRequest request = new StopInstancesRequest();
    request.withInstanceIds(c.child.id);
    client.stopInstancesAsync(request, new AsyncHandler<StopInstancesRequest, StopInstancesResult>() {
        @Override/*from   ww  w .  jav  a 2  s .  c om*/
        public void onSuccess(StopInstancesRequest request, StopInstancesResult result) {
            OperationContext.restoreOperationContext(opContext);
            updateComputeState(pr);
        }

        @Override
        public void onError(Exception e) {
            OperationContext.restoreOperationContext(opContext);
            AdapterUtils.sendPatchToTask(powerService, pr.taskReference,
                    ResourceOperationResponse.fail(pr.resourceLink(), e));
        }
    });
}

From source file:com.vmware.photon.controller.model.adapters.awsadapter.AWSTaskStatusChecker.java

License:Open Source License

public void start() {
    if (this.expirationTimeMicros > 0 && Utils.getNowMicrosUtc() > this.expirationTimeMicros) {
        String msg = String.format(
                "Compute with instance id %s did not reach desired %s state in the required time interval.",
                this.instanceId, this.desiredState);
        this.service.logSevere(msg);
        Throwable t = new RuntimeException(msg);
        AdapterUtils.sendFailurePatchToProvisioningTask(this.service, this.computeRequest.taskReference, t);
        return;/*from w ww  .j a v a2 s .c  om*/
    }
    DescribeInstancesRequest descRequest = new DescribeInstancesRequest();
    List<String> instanceIdList = new ArrayList<String>();
    instanceIdList.add(this.instanceId);
    descRequest.setInstanceIds(instanceIdList);
    AsyncHandler<DescribeInstancesRequest, DescribeInstancesResult> describeHandler = new AsyncHandler<DescribeInstancesRequest, DescribeInstancesResult>() {

        @Override
        public void onError(Exception exception) {
            // Sometimes AWS takes time to acknowledge the presence of newly provisioned
            // instances. Not failing the request immediately in case AWS cannot find the
            // particular instanceId.
            if (exception instanceof AmazonServiceException && ((AmazonServiceException) exception)
                    .getErrorCode().equalsIgnoreCase(AWS_INVALID_INSTANCE_ID_ERROR_CODE)) {
                AWSTaskStatusChecker.this.service.logWarning(
                        "Could not retrieve status for instance %s. Retrying... Exception on AWS is %s",
                        AWSTaskStatusChecker.this.instanceId, exception);
                AWSTaskStatusChecker.create(AWSTaskStatusChecker.this.amazonEC2Client,
                        AWSTaskStatusChecker.this.instanceId, AWSTaskStatusChecker.this.desiredState,
                        AWSTaskStatusChecker.this.consumer, AWSTaskStatusChecker.this.computeRequest,
                        AWSTaskStatusChecker.this.service, AWSTaskStatusChecker.this.expirationTimeMicros)
                        .start();
                return;
            }
            AdapterUtils.sendFailurePatchToProvisioningTask(AWSTaskStatusChecker.this.service,
                    AWSTaskStatusChecker.this.computeRequest.taskReference, exception);
            return;
        }

        @Override
        public void onSuccess(DescribeInstancesRequest request, DescribeInstancesResult result) {
            Instance instance = result.getReservations().get(0).getInstances().get(0);
            if (!instance.getState().getName().equals(AWSTaskStatusChecker.this.desiredState)) {
                // if the task is not in the running state, schedule thread
                // to run again in 5 seconds
                AWSTaskStatusChecker.this.service.getHost().schedule(() -> {
                    AWSTaskStatusChecker.create(AWSTaskStatusChecker.this.amazonEC2Client,
                            AWSTaskStatusChecker.this.instanceId, AWSTaskStatusChecker.this.desiredState,
                            AWSTaskStatusChecker.this.consumer, AWSTaskStatusChecker.this.computeRequest,
                            AWSTaskStatusChecker.this.service, AWSTaskStatusChecker.this.expirationTimeMicros)
                            .start();
                }, 5, TimeUnit.SECONDS);
                return;
            }
            AWSTaskStatusChecker.this.consumer.accept(instance);
            return;
        }
    };
    this.amazonEC2Client.describeInstancesAsync(descRequest, describeHandler);
}

From source file:com.zanox.vertx.mods.KinesisMessageProcessor.java

License:Apache License

protected void sendMessageToKinesis(final Message<JsonObject> event) throws KinesisException {
    if (kinesisAsyncClient == null) {
        throw new KinesisException("AmazonKinesisAsyncClient is not initialized");
    }/*from   w  ww  . j  a v  a 2  s  . com*/

    if (!isValid(event.body().getString(PAYLOAD))) {
        logger.error("Invalid message provided.");
        return;
    }

    JsonObject object = event.body();
    logger.debug(" --- Got event " + event.toString());
    logger.debug(" --- Got body + " + object.toString());

    byte[] payload = object.getBinary(PAYLOAD);

    if (payload == null) {
        logger.debug(" --- Payload is null, trying to get the payload as String");
        payload = object.getString(PAYLOAD).getBytes();
    }
    logger.debug("Binary payload size: " + payload.length);

    String msgPartitionKey = object.getString(PARTITION_KEY);
    String requestPartitionKey = msgPartitionKey != null ? msgPartitionKey : partitionKey;

    PutRecordRequest putRecordRequest = new PutRecordRequest();
    putRecordRequest.setStreamName(streamName);
    putRecordRequest.setPartitionKey(requestPartitionKey);

    logger.info("Writing to streamName " + streamName + " using partitionkey " + requestPartitionKey);

    putRecordRequest.setData(ByteBuffer.wrap(payload));

    final Context ctx = vertx.currentContext();
    kinesisAsyncClient.putRecordAsync(putRecordRequest, new AsyncHandler<PutRecordRequest, PutRecordResult>() {
        public void onSuccess(PutRecordRequest request, final PutRecordResult recordResult) {
            ctx.runOnContext(v -> {
                logger.info("Sent message to Kinesis: " + recordResult.toString());
                sendOK(event);
            });
        }

        public void onError(final java.lang.Exception iexc) {
            ctx.runOnContext(v -> {
                logger.error(iexc);
                sendError(event, "Failed sending message to Kinesis", iexc);
            });
        }
    });
}

From source file:doug.iotdemo.server.web.WebServer.java

License:Open Source License

private void handleFetch(RoutingContext context) {
    ScanRequest scanRequest = new ScanRequest().withTableName(sensorTableName);
    db.scanAsync(scanRequest, new AsyncHandler<ScanRequest, ScanResult>() {
        @Override/*  w ww.jav  a 2 s .  c o  m*/
        public void onSuccess(ScanRequest request, ScanResult result) {
            JsonObject states = new JsonObject();
            for (Map<String, AttributeValue> item : result.getItems()) {
                AttributeValue stateValue = item.get("state");
                if (stateValue != null) {
                    JsonObject sensorObj = new JsonObject();
                    sensorObj.put("state", Integer.valueOf(stateValue.getN()));

                    if (item.get("time") != null) {
                        long time = Long.parseLong(item.get("time").getN());
                        long count = Long.parseLong(item.get("count").getN());
                        long thresh = time / count;
                        sensorObj.put("thresh", thresh);
                    }

                    states.put(item.get("sensor").getS(), sensorObj);
                }
            }
            context.response().end(states.encode());
        }

        @Override
        public void onError(Exception exception) {
            StringWriter msg = new StringWriter();
            exception.printStackTrace(new PrintWriter(msg));
            context.response().setStatusCode(500).end(msg.toString());
        }
    });
}

From source file:io.micrometer.cloudwatch.CloudWatchMeterRegistry.java

License:Apache License

private void sendMetricData(List<MetricDatum> metricData) {
    PutMetricDataRequest putMetricDataRequest = new PutMetricDataRequest().withNamespace(config.namespace())
            .withMetricData(metricData);
    amazonCloudWatchAsync.putMetricDataAsync(putMetricDataRequest,
            new AsyncHandler<PutMetricDataRequest, PutMetricDataResult>() {
                @Override/*from ww w .  jav a2  s. c o m*/
                public void onError(Exception exception) {
                    logger.error("Error sending metric data.", exception);
                }

                @Override
                public void onSuccess(PutMetricDataRequest request, PutMetricDataResult result) {
                    logger.debug("Published metric with namespace:{}", request.getNamespace());
                }
            });
}