Example usage for com.amazonaws.auth PropertiesCredentials PropertiesCredentials

List of usage examples for com.amazonaws.auth PropertiesCredentials PropertiesCredentials

Introduction

In this page you can find the example usage for com.amazonaws.auth PropertiesCredentials PropertiesCredentials.

Prototype

public PropertiesCredentials(InputStream inputStream) throws IOException 

Source Link

Document

Reads the specified input stream as a stream of Java properties file content and extracts the AWS access key ID and secret access key from the properties.

Usage

From source file:org.roqmessaging.management.GlobalConfigurationManager.java

License:Apache License

/**
 * This method processes the string we got.
 * @param request the string request we received.
 *//*  www .j av a2 s.co m*/
private void processStandardRequest(String request) {
    String info[] = request.split(",");
    int infoCode = Integer.parseInt(info[0]);
    logger.debug("Start analysing info code = " + infoCode);
    switch (infoCode) {

    // launch a new host to Amazon EC2
    case 1234503:
        logger.info("cvoicu: test for 1234503");
        RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
        runInstancesRequest.withImageId("ami-dfe090ef").withInstanceType("m3.large").withMinCount(1)
                .withMaxCount(1).withKeyName("cvoicu").withSubnetId("subnet-2ca6b844")
                .withSecurityGroupIds("sg-6dbd5202");

        AWSCredentials credentials = null;
        try {
            credentials = new PropertiesCredentials(new File("/home/ubuntu/rootkey.cvs"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.info("cvoicu: ioexcepion" + e);
            e.printStackTrace();
        }

        amazonEC2Client = new AmazonEC2Client(credentials);
        amazonEC2Client.setEndpoint("ec2.us-west-2.amazonaws.com");

        runInstancesResult.add(amazonEC2Client.runInstances(runInstancesRequest));

        logger.info("cvoicu: A new host is beeing launched on a vm of amazon ec2.");

        this.clientReqSocket.send("1234504", 0);
        break;

    case 1234505:

        ArrayList<String> hostsAddr = stateDAO.getHostManagerAddresses();

        if (hostsAddr.size() == 2) {
            this.clientReqSocket.send("1234505", 0);
        } else
            this.clientReqSocket.send("1234506", 0);

        break;

    //init request from client that want to receive a local cache of configuration
    case RoQConstant.INIT_REQ:
        // A client is asking for the topology of all local host
        // manager
        logger.debug("Recieveing init request from a client ");
        this.clientReqSocket.send(
                this.serializationUtils.serialiseObject(this.stateDAO.getHostManagerAddresses()), ZMQ.SNDMORE);
        this.clientReqSocket.send(this.serializationUtils.serialiseObject(this.stateDAO.getQueueMonitorMap()),
                ZMQ.SNDMORE);
        this.clientReqSocket.send(this.serializationUtils.serialiseObject(this.stateDAO.getQueueHostLocation()),
                ZMQ.SNDMORE);
        this.clientReqSocket
                .send(this.serializationUtils.serialiseObject(this.stateDAO.getQueueMonitorStatMap()), 0);
        logger.debug("Sending back the topology - list of local host");
        break;

    //A create queue request
    case RoQConstant.CONFIG_REMOVE_QUEUE:
        logger.debug("Recieveing remove Q request from a client ");
        if (info.length == 2) {
            logger.debug("The request format is valid we 2 part:  " + info[1]);
            // register the queue
            removeQueue(info[1]);
            this.clientReqSocket.send(Integer.toString(RoQConstant.OK).getBytes(), 0);
        } else {
            logger.error("The remove queue request sent does not contain 2 part: ID, quName");
            this.clientReqSocket.send(Integer.toString(RoQConstant.FAIL).getBytes(), 0);
        }
        break;

    //A remove  queue request
    case RoQConstant.CONFIG_CREATE_QUEUE:
        logger.debug("Recieveing create Q request from a client ");
        if (info.length > 3) {
            logger.debug("The request format is valid we 4 part:  " + info[1] + " " + info[2] + " " + info[3]
                    + " " + info[4]);
            // The logical queue config is sent int the part 2
            String qName = info[1];
            String monitorHost = info[2];
            String statMonitorHost = info[3];
            String targetAddress = info[4];
            // register the queue
            addQueueName(qName, monitorHost);
            addQueueStatMonitor(qName, statMonitorHost);
            addQueueLocation(qName, targetAddress);
            this.clientReqSocket.send(Integer.toString(RoQConstant.CONFIG_CREATE_QUEUE_OK).getBytes(), 0);
        } else {
            logger.error("The create queue request sent does not contain 3 part: ID, quName, Monitor host");
            this.clientReqSocket.send(Integer.toString(RoQConstant.CONFIG_CREATE_QUEUE_FAIL).getBytes(), 0);
        }
        break;

    //A add host request
    case RoQConstant.CONFIG_ADD_HOST:
        logger.debug("Recieveing ADD HOST request from a client ");
        if (info.length == 2) {
            logger.debug("The request format is valid adding as host : " + info[1]);
            // The logical queue config is sent int the part 2
            addHostManager(info[1]);
            this.clientReqSocket.send(Integer.toString(RoQConstant.OK).getBytes(), 0);
        } else {
            this.clientReqSocket.send(Integer.toString(RoQConstant.FAIL).getBytes(), 0);
        }
        break;

    //A remove host request
    case RoQConstant.CONFIG_REMOVE_HOST:
        logger.debug("Recieveing REMOVE HOST request from a client ");
        if (info.length == 2) {
            logger.debug("The request format is valid ");
            // The logical queue config is sent int the part 2
            removeHostManager(info[1]);
            this.clientReqSocket.send(Integer.toString(RoQConstant.OK).getBytes(), 0);
        }
        break;

    //Get the monitor and the statistic monitor forwarder  by the QName
    case RoQConstant.CONFIG_GET_HOST_BY_QNAME:
        logger.debug("Recieveing GET HOST request from a client ");
        if (info.length == 2) {
            logger.debug("The request format is valid - Asking for translating  " + info[1]);
            if (this.stateDAO.getQueueMonitorMap().containsKey(info[1])) {
                logger.debug("Answering back:" + this.stateDAO.getQueueMonitorMap().get(info[1]) + ","
                        + this.stateDAO.getQueueMonitorStatMap().get(info[1]));
                this.clientReqSocket.send((this.stateDAO.getQueueMonitorMap().get(info[1]) + ","
                        + this.stateDAO.getQueueMonitorStatMap().get(info[1])).getBytes(), 0);
            } else {
                logger.warn(" No logical queue as:" + info[1]);
                this.clientReqSocket.send(("").getBytes(), 0);
            }
        }
        break;

    //Get the monitor and the statistic monitor forwarder  by the QName BUT In BSON for non java processes
    case RoQConstant.BSON_CONFIG_GET_HOST_BY_QNAME:
        logger.debug("Recieveing GET HOST by QNAME in BSON request from a client ");
        if (info.length == 2) {
            logger.debug("The request format is valid - Asking for translating  " + info[1]);
            if (this.stateDAO.getQueueMonitorMap().containsKey(info[1])
                    && this.stateDAO.getQueueMonitorStatMap().containsKey(info[1])) {
                //Replace the stat monitor port to the subscription port
                String subscribingKPIMonitor = this.stateDAO.getQueueMonitorStatMap().get(info[1]);
                int basePort = this.serializationUtils.extractBasePort(subscribingKPIMonitor);
                String portOff = subscribingKPIMonitor.substring(0,
                        subscribingKPIMonitor.length() - "xxxx".length());
                subscribingKPIMonitor = portOff + (basePort + 1);
                logger.debug("Answering back:" + this.stateDAO.getQueueMonitorMap().get(info[1]) + ","
                        + subscribingKPIMonitor);
                this.clientReqSocket.send(this.serialiazer.serialiazeMonitorInfo(
                        this.stateDAO.getQueueMonitorMap().get(info[1]), subscribingKPIMonitor), 0);
            } else {
                logger.warn(" No logical queue as:" + info[1]);
                this.clientReqSocket.send(serialiazer.serialiazeConfigAnswer(RoQConstant.FAIL,
                        "The Queue " + info[1] + "  is not registred."), 0);
            }
        }
        break;

    case RoQConstant.ADD_SEED:
        if (info.length == 2) {
            seeds = seeds + info[1] + "#";
            this.clientReqSocket.send(("").getBytes(), 0);
        }
        break;

    case RoQConstant.GET_SEEDS:
        if (info.length == 2) {
            this.clientReqSocket.send(seeds.getBytes(), 0);
        }
        break;

    case RoQConstant.GET_HOSTS:
        if (info.length == 2) {
            ArrayList<String> hostList = stateDAO.getHostManagerAddresses();
            String hosts = "";
            int i = 0;
            while (i < hostList.size()) {
                if (i == 0)
                    hosts = hostList.get(i);
                else {
                    hosts = hosts + "#" + hostList.get(i);
                }
                i++;
            }
            this.clientReqSocket.send(hosts);
        }

        break;
    }
}

From source file:org.swiftshire.nifi.processors.kinesis.consumer.AbstractKinesisConsumerProcessor.java

License:Apache License

/**
 * Returns the AWS access keys we're configured to use. If none are configured, we use the standard
 * anonymous credentials by default. We currently support properties defined in Nifi or we can load
 * them from a separate properties file.
 * <p/>/*from  w  w w.  j a  va 2s  .  c  o m*/
 * We may want to consider other types of {@link AWSCredentials credentials} in the future.
 *
 * @param context
 * @return The AWS credentials to use when accessing the cloud
 */
protected AWSCredentials getCredentials(final ProcessContext context) {
    final String accessKey = context.getProperty(ACCESS_KEY).evaluateAttributeExpressions().getValue();
    final String secretKey = context.getProperty(SECRET_KEY).evaluateAttributeExpressions().getValue();

    final String credentialsFile = context.getProperty(CREDENTIALS_FILE).getValue();

    if (credentialsFile != null) {
        try {
            return new PropertiesCredentials(new File(credentialsFile));
        } catch (final IOException ex) {
            throw new ProcessException("Could not read Credentials File", ex);
        }
    }

    if (accessKey != null && secretKey != null) {
        return new BasicAWSCredentials(accessKey, secretKey);
    }

    return new AnonymousAWSCredentials();
}

From source file:org.terracotta.TerracottaCloudFormationSample.java

License:Open Source License

@org.junit.BeforeClass
public static void createStack() throws Exception {

    /*//from  w w w.  j  a  va 2 s  . c  o  m
    * Important: Be sure to fill in your AWS access credentials in the
    *            AwsCredentials.properties file before you try to run this
    *            sample.
    * http://aws.amazon.com/security-credentials
    */
    amazonCloudFormationClient = new AmazonCloudFormationClient(new PropertiesCredentials(
            TerracottaCloudFormationSample.class.getResourceAsStream("/AwsCredentials.properties")));

    System.out.println("================================");
    System.out.println("Terracotta CloudFormation Sample");
    System.out.println("================================\n");

    try {
        // Create a stack
        CreateStackRequest createRequest = new CreateStackRequest();
        createRequest.setStackName(stackName);
        createRequest.setTemplateBody(convertStreamToString(
                TerracottaCloudFormationSample.class.getResourceAsStream("/TerracottaServerArray.template")));

        Parameter parameter = new Parameter();
        parameter.setParameterKey("KeyName");
        parameter.setParameterValue(keyChainName);
        List parameters = new ArrayList();
        parameters.add(parameter);
        createRequest.setParameters(parameters);
        System.out.println("Creating a stack called " + createRequest.getStackName() + ".");
        amazonCloudFormationClient.createStack(createRequest);

        // Wait for stack to be created
        // Note that you could use SNS notifications on the CreateStack call to track the progress of the stack creation
        System.out.println("Stack creation completed, the stack " + stackName + " completed with "
                + waitForCompletion(amazonCloudFormationClient, stackName));

        // Show all the stacks for this account along with the resources for each stack
        for (Stack stack : amazonCloudFormationClient.describeStacks(new DescribeStacksRequest()).getStacks()) {
            System.out.println(
                    "Stack : " + stack.getStackName() + " [" + stack.getStackStatus().toString() + "]");

            DescribeStackResourcesRequest stackResourceRequest = new DescribeStackResourcesRequest();
            stackResourceRequest.setStackName(stack.getStackName());
            for (StackResource resource : amazonCloudFormationClient
                    .describeStackResources(stackResourceRequest).getStackResources()) {
                System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                        resource.getLogicalResourceId(), resource.getPhysicalResourceId());
            }
        }

        // Lookup a resource by its logical name
        DescribeStackResourcesRequest logicalNameResourceRequest = new DescribeStackResourcesRequest();
        logicalNameResourceRequest.setStackName(stackName);
        logicalNameResourceRequest.setLogicalResourceId(logicalResourceName);
        System.out.format("Looking up resource name %1$s from stack %2$s\n",
                logicalNameResourceRequest.getLogicalResourceId(), logicalNameResourceRequest.getStackName());
        for (StackResource resource : amazonCloudFormationClient
                .describeStackResources(logicalNameResourceRequest).getStackResources()) {
            System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                    resource.getLogicalResourceId(), resource.getPhysicalResourceId());
        }

        //deleteStack

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS CloudFormation, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS CloudFormation, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:ro.cosu.vampires.server.resources.ec2.EC2ResourceModule.java

License:Open Source License

protected static AmazonEC2Client getAmazonEC2Client(String credentialsFile) {
    AmazonEC2Client amazonEC2Client = null;

    LOG.debug("reading credentials  AWS from {}", credentialsFile);
    try {/*from  w ww. j a  v a  2  s  .c o m*/
        PropertiesCredentials credentials = new PropertiesCredentials(new FileInputStream(credentialsFile));
        amazonEC2Client = new AmazonEC2Client(credentials);

    } catch (IllegalArgumentException e) {
        LOG.error("Invalid EC2 file format", e);
    } catch (FileNotFoundException e) {
        LOG.error("could not find ec2 credentials file: " + credentialsFile);
    } catch (IOException e) {
        LOG.error("failed to create amazon client", e);
    }

    return amazonEC2Client;
}

From source file:servlet.FileUploadServlet.java

private void putInBucket(String fileName, String id) throws IOException {

    AWSCredentials awsCreds = new PropertiesCredentials(
            new File("/Users/paulamontojo/Desktop/AwsCredentials.properties"));
    AmazonS3 s3client = new AmazonS3Client(awsCreds);

    try {/*from  w  w  w.j ava2 s.  c  om*/
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFileName);
        s3client.putObject(new PutObjectRequest(bucketName, fileName, file));

        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName,
                fileName);
        generatePresignedUrlRequest.setMethod(HttpMethod.GET); // Default.

        URL s = s3client.generatePresignedUrl(generatePresignedUrlRequest);
        insertUrl(s.toString(), id);
        System.out.println(s);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which " + "means your request made it "
                + "to Amazon S3, but was rejected with an error response" + " for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                + "an internal error while trying to " + "communicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }

}

From source file:servlet.FileUploadServlet.java

public void sqs(String msg) throws Exception {
    AWSCredentials awsCreds = new PropertiesCredentials(
            new File("/Users/paulamontojo/Desktop/AwsCredentials.properties"));

    AmazonSQS sqs = new AmazonSQSClient(awsCreds);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    sqs.setRegion(usWest2);//  w w  w .  j  ava 2  s .  c o  m

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon SQS");
    System.out.println("===========================================\n");

    try {

        String myQueueUrl = "https://sqs.us-west-2.amazonaws.com/711690152696/MyQueue";

        // List queues
        System.out.println("Listing all queues in your account.\n");
        for (String queueUrl : sqs.listQueues().getQueueUrls()) {
            System.out.println("  QueueUrl: " + queueUrl);
        }

        // Send a message
        System.out.println("Sending a message to MyQueue.\n");
        sqs.sendMessage(new SendMessageRequest(myQueueUrl, msg));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SQS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with SQS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:spikes.email.AmazonSimpleEmailServiceSpike.java

License:Open Source License

public static void main(String[] args) throws IOException {

    PropertiesCredentials credentials = new PropertiesCredentials(
            AmazonSimpleEmailServiceSpike.class.getResourceAsStream("AwsCredentials.properties"));

    AmazonSimpleEmailService service = new AmazonSimpleEmailServiceClient(credentials);

    verifyAddressIfNecessary(service, FROM);

    Destination destination = new Destination(Arrays.asList(TO));
    Content subject = new Content(SUBJECT);
    Body body = new Body().withHtml(new Content(BODY));
    Message message = new Message(subject, body);
    service.sendEmail(new SendEmailRequest(from(), destination, message));

    System.exit(0);/*from w w w.  j av a 2s  .c  o m*/

}

From source file:thinkbig.util.Util.java

License:Open Source License

/**
 * get an Amazon s3 client//from   w  w  w.j  a  v a  2  s .  co  m
 * @param credentialFile AWS credential properties file
 * @return an s3 client, if credential is valid, otherwise return null
 */
public static AmazonS3 getAmazonS3Client(String credentialFile) {

    AmazonS3 s3 = null;

    try {
        s3 = new AmazonS3Client(new PropertiesCredentials(new File(credentialFile)));
    } catch (FileNotFoundException e) {
        System.out.println("File '" + credentialFile + "' not found!");
    } catch (IOException e) {
        System.out.println("Could not open File '" + credentialFile + "'!");
    } catch (Exception e) {
        System.out.println("Could not start Amazon Client!");
    }

    return s3;
}