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:SimpleDBSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*/*from   w w w .ja va2 s  .c  om*/
     * 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
     */
    AmazonSimpleDB sdb = new AmazonSimpleDBClient(
            new PropertiesCredentials(SimpleDBSample.class.getResourceAsStream("AwsCredentials.properties")));

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

    try {
        // Create a domain
        String myDomain = "MyStore";
        System.out.println("Creating domain called " + myDomain + ".\n");
        sdb.createDomain(new CreateDomainRequest(myDomain));

        // List domains
        System.out.println("Listing all domains in your account:\n");
        for (String domainName : sdb.listDomains().getDomainNames()) {
            System.out.println("  " + domainName);
        }
        System.out.println();

        // Put data into a domain
        System.out.println("Putting data into " + myDomain + " domain.\n");
        sdb.batchPutAttributes(new BatchPutAttributesRequest(myDomain, createSampleData()));

        // Select data from a domain
        // Notice the use of backticks around the domain name in our select expression.
        String selectExpression = "select * from `" + myDomain + "` where Category = 'Clothes'";
        System.out.println("Selecting: " + selectExpression + "\n");
        SelectRequest selectRequest = new SelectRequest(selectExpression);
        for (Item item : sdb.select(selectRequest).getItems()) {
            System.out.println("  Item");
            System.out.println("    Name: " + item.getName());
            for (Attribute attribute : item.getAttributes()) {
                System.out.println("      Attribute");
                System.out.println("        Name:  " + attribute.getName());
                System.out.println("        Value: " + attribute.getValue());
            }
        }
        System.out.println();

        // Delete values from an attribute
        System.out.println("Deleting Blue attributes in Item_O3.\n");
        Attribute deleteValueAttribute = new Attribute("Color", "Blue");
        sdb.deleteAttributes(
                new DeleteAttributesRequest(myDomain, "Item_03").withAttributes(deleteValueAttribute));

        // Delete an attribute and all of its values
        System.out.println("Deleting attribute Year in Item_O3.\n");
        sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "Item_03")
                .withAttributes(new Attribute().withName("Year")));

        // Replace an attribute
        System.out.println("Replacing Size of Item_03 with Medium.\n");
        List<ReplaceableAttribute> replaceableAttributes = new ArrayList<ReplaceableAttribute>();
        replaceableAttributes.add(new ReplaceableAttribute("Size", "Medium", true));
        sdb.putAttributes(new PutAttributesRequest(myDomain, "Item_03", replaceableAttributes));

        // Delete an item and all of its attributes
        System.out.println("Deleting Item_03.\n");
        sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "Item_03"));

        // Delete a domain
        System.out.println("Deleting " + myDomain + " domain.\n");
        sdb.deleteDomain(new DeleteDomainRequest(myDomain));
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SimpleDB, 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 SimpleDB, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:AwsConsoleApp.java

License:Open Source License

/**
 * The only information needed to create a client are security credentials
 * consisting of the AWS Access Key ID and Secret Access Key. All other
 * configuration, such as the service endpoints, are performed
 * automatically. Client parameters, such as proxies, can be specified in an
 * optional ClientConfiguration object when constructing a client.
 *
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.PropertiesCredentials
 * @see com.amazonaws.ClientConfiguration
 *///from w  w w  .ja  v a  2  s .c  om
private static void init() throws Exception {
    AWSCredentials credentials = new PropertiesCredentials(
            AwsConsoleApp.class.getResourceAsStream("AwsCredentials.properties"));

    ec2 = new AmazonEC2Client(credentials);
    s3 = new AmazonS3Client(credentials);
    sdb = new AmazonSimpleDBClient(credentials);
}

From source file:S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*//from w  ww.j  ava 2s.c om
     * 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
     */
    AmazonS3 s3 = new AmazonS3Client(
            new PropertiesCredentials(S3Sample.class.getResourceAsStream("AwsCredentials.properties")));

    String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
    String key = "MyObjectKey";

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

    try {
        /*
         * Create a new S3 bucket - Amazon S3 bucket names are globally unique,
         * so once a bucket name has been taken by any user, you can't create
         * another bucket with that same name.
         *
         * You can optionally specify a location for your bucket if you want to
         * keep your data closer to your applications or users.
         */
        System.out.println("Creating bucket " + bucketName + "\n");
        s3.createBucket(bucketName);

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();

        /*
         * Upload an object to your bucket - You can easily upload a file to
         * S3, or upload directly an InputStream if you know the length of
         * the data in the stream. You can also specify your own metadata
         * when uploading to S3, which allows you set a variety of options
         * like content-type and content-encoding, plus additional metadata
         * specific to your applications.
         */
        System.out.println("Uploading a new object to S3 from a file\n");
        s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

        /*
         * Download an object - When you download an object, you get all of
         * the object's metadata and a stream from which to read the contents.
         * It's important to read the contents of the stream as quickly as
         * possibly since the data is streamed directly from Amazon S3 and your
         * network connection will remain open until you read all the data or
         * close the input stream.
         *
         * GetObjectRequest also supports several other options, including
         * conditional downloading of objects based on modification times,
         * ETags, and selectively downloading a range of an object.
         */
        System.out.println("Downloading an object");
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());

        /*
         * List objects in your bucket by prefix - There are many options for
         * listing the objects in your bucket.  Keep in mind that buckets with
         * many objects might truncate their results when listing their objects,
         * so be sure to check if the returned object listing is truncated, and
         * use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve
         * additional results.
         */
        System.out.println("Listing objects");
        ObjectListing objectListing = s3
                .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My"));
        for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(
                    " - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
        }
        System.out.println();

        /*
         * Delete an object - Unless versioning has been turned on for your bucket,
         * there is no way to undelete an object, so use caution when deleting objects.
         */
        System.out.println("Deleting an object\n");
        s3.deleteObject(bucketName, key);

        /*
         * Delete a bucket - A bucket must be completely empty before it can be
         * deleted, so remember to delete any objects from your buckets before
         * you try to delete them.
         */
        System.out.println("Deleting bucket " + bucketName + "\n");
        s3.deleteBucket(bucketName);
    } 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 "
                + "a serious internal problem 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:HW1.java

License:Open Source License

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

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

    /*********************************************
     * /*from  w  w  w . j  a va 2  s.  c o  m*/
     *  #1 Create Amazon Client object
     *  
     *********************************************/
    System.out.println("#1 Create Amazon Client object");
    ec2 = new AmazonEC2Client(credentials);
    ec2.setEndpoint("https://us-east-1.ec2.amazonaws.com");

    System.out.println("Please enter required group name and key name... (consider them to be the same)");
    Scanner scan = new Scanner(System.in);
    final String keyGroupName = scan.nextLine();

    /* create security group */
    CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest();
    createSecurityGroupRequest.withGroupName(keyGroupName).withDescription("My Java Security Group");
    CreateSecurityGroupResult createSecurityGroupResult = ec2.createSecurityGroup(createSecurityGroupRequest);

    /* set ip settings */
    IpPermission ipPermission = new IpPermission();
    /* authorize tcp, ssh 22 */
    ipPermission.withIpRanges("0.0.0.0/0").withIpProtocol("tcp").withFromPort(22)
            /* authorize http 80 */
            .withToPort(80);

    AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest();
    authorizeSecurityGroupIngressRequest.withGroupName(keyGroupName).withIpPermissions(ipPermission);
    ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

    /* create key pair */
    CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest();
    createKeyPairRequest.withKeyName(keyGroupName);
    CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest);
    KeyPair keyPair = new KeyPair();
    keyPair = createKeyPairResult.getKeyPair();
    String privateKey = keyPair.getKeyMaterial();
    PrintWriter file = new PrintWriter("/Users/will/.ssh/" + keyGroupName + ".pem");
    file.print(privateKey);
    file.close();
    Runtime.getRuntime().exec("chmod 400 /Users/will/.ssh/" + keyGroupName + ".pem");

    try {

        /*********************************************
         * 
         *  #2 Create two Instances
         *  
         *********************************************/
        System.out.println();
        System.out.println("#2 Create two new Instances");
        int ready_num = 0;
        String insDNS1 = new String();
        String insDNS2 = new String();
        String insId1 = new String();
        String insId2 = new String();
        String insZone1 = new String();
        String insZone2 = new String();

        String imageId = "ami-76f0061f"; //Basic 32-bit Amazon Linux AMI
        int minInstanceCount = 2; // create 2 instance
        int maxInstanceCount = 2;

        /* create instances */
        RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
        rir.withKeyName(keyGroupName).withSecurityGroups(keyGroupName);
        ec2.runInstances(rir);

        /* waiting for instance to start */
        System.out.println("Created instance, wait for pending...");

        DescribeInstancesResult describeInstancesRequest;
        List<Reservation> reservations;
        List<Instance> allInstances = new ArrayList<Instance>();

        while (ready_num < 2) {
            describeInstancesRequest = ec2.describeInstances();
            reservations = describeInstancesRequest.getReservations();
            for (Reservation reservation : reservations) {
                for (Instance ins : reservation.getInstances()) {
                    if (ins.getState().getName().compareTo("running") == 0
                            && ins.getPublicIpAddress() != null) {
                        if (allInstances.size() == 0 || (allInstances.size() > 0
                                && allInstances.get(0).getInstanceId().compareTo(ins.getInstanceId()) != 0)) {
                            ready_num++;
                            allInstances.add(ins);
                        }
                    }
                }
            }
        }

        System.out.println("You have " + allInstances.size() + " Amazon EC2 instance(s).");
        insId1 = allInstances.get(0).getInstanceId();
        insId2 = allInstances.get(1).getInstanceId();
        insDNS1 = allInstances.get(0).getPublicIpAddress();
        insDNS2 = allInstances.get(1).getPublicIpAddress();
        insZone1 = allInstances.get(0).getPlacement().getAvailabilityZone();
        insZone2 = allInstances.get(1).getPlacement().getAvailabilityZone();

        for (Instance ins : allInstances) {
            System.out.println("New instance has been created: " + ins.getInstanceId());
        }

        System.out.println("Both instances are running now:");
        System.out.println("Instance id1: " + insId1);
        System.out.println("IP: " + insDNS1);
        System.out.println("Zone: " + insZone1);
        System.out.println("Instance id1: " + insId2);
        System.out.println("IP: " + insDNS2);
        System.out.println("Zone: " + insZone2);
        System.out.println();

        /*********************************************
         *  #3 Check OR Create two volumes
         *********************************************/
        System.out.println();
        System.out.println("#3 Create volumes");
        String volume_name1 = createVolume(insZone1, null);
        String volume_name2 = createVolume(insZone2, null);

        /*********************************************
         *  #4 Attach the volume to the instance
         *********************************************/
        System.out.println();
        System.out.println("#4 Attach the volume to the instance");
        System.out.println("Wait for volumes to be available...");
        Thread.sleep(20000);

        /* attach instances to existing volume */
        attachVolume(insId1, volume_name1);
        attachVolume(insId2, volume_name2);

        /************************************************
        *  #5 S3 bucket and object
        ***************************************************/
        System.out.println();
        System.out.println("#5 S3 bucket and object");
        s3 = new AmazonS3Client(credentials);

        /* create bucket */
        String bucketName = "cloud-hw1-bucket";
        s3.createBucket(bucketName);

        /* set key */
        String key = "object-hw1.txt";

        /* set value */
        File new_file = File.createTempFile("temp", ".txt");
        new_file.deleteOnExit();
        Writer writer = new OutputStreamWriter(new FileOutputStream(new_file));
        writer.write("This is the file stored on the S3 storage on the first day!!!.");
        writer.close();

        /* put object - bucket, key, value(file) */
        s3.putObject(new PutObjectRequest(bucketName, key, new_file));
        System.out.println("Successfully put file temp.txt to S3, we will read it tomorrow...");
        System.out.println();

        /***********************************
        *   #3 Monitoring (CloudWatch)
        *********************************/
        System.out.println();
        System.out.println("#6 set up cloudwatch");
        try {
            /* create CloudWatch client */
            AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(credentials);
            /* create request message1 */
            GetMetricStatisticsRequest statRequest1 = new GetMetricStatisticsRequest();
            GetMetricStatisticsRequest statRequest2 = new GetMetricStatisticsRequest();
            /* set up request message */
            statRequest1.setNamespace("AWS/EC2"); //namespace
            statRequest2.setNamespace("AWS/EC2"); //namespace
            statRequest1.setPeriod(60); //period of data
            statRequest2.setPeriod(60); //period of data
            ArrayList<String> stats = new ArrayList<String>();
            /* Use one of these strings: Average, Maximum, Minimum, SampleCount, Sum */
            stats.add("Average");
            stats.add("Sum");
            statRequest1.setStatistics(stats);
            statRequest2.setStatistics(stats);
            /* Use one of these strings: CPUUtilization, NetworkIn, NetworkOut, DiskReadBytes, DiskWriteBytes, DiskReadOperations  */
            statRequest1.setMetricName("CPUUtilization");
            statRequest2.setMetricName("CPUUtilization");
            /* set time */
            GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            calendar.add(GregorianCalendar.SECOND, -1 * calendar.get(GregorianCalendar.SECOND)); // 1 second ago
            Date endTime = calendar.getTime();
            calendar.add(GregorianCalendar.MINUTE, -10); // 10 minutes ago
            Date startTime = calendar.getTime();
            statRequest1.setStartTime(startTime);
            statRequest1.setEndTime(endTime);
            statRequest2.setStartTime(startTime);
            statRequest2.setEndTime(endTime);
            /* specify an instance */
            ArrayList<Dimension> dimensions1 = new ArrayList<Dimension>();
            dimensions1.add(new Dimension().withName("InstanceId").withValue(insId1));
            ArrayList<Dimension> dimensions2 = new ArrayList<Dimension>();
            dimensions2.add(new Dimension().withName("InstanceId").withValue(insId2));
            statRequest1.setDimensions(dimensions1);
            statRequest2.setDimensions(dimensions2);
            System.out.println("Set up cloud watch for instance: " + insId1 + " and instance: " + insId2);

            /* !!!!!!!!!!!!here set for 10 loops for now */
            /* get statistics */
            for (int i = 0; i < 10; i++) {
                GetMetricStatisticsResult statResult1 = cloudWatch.getMetricStatistics(statRequest1);
                GetMetricStatisticsResult statResult2 = cloudWatch.getMetricStatistics(statRequest2);
                /* display */
                System.out.println("Instance 1: " + statResult1.toString());
                List<Datapoint> dataList = statResult1.getDatapoints();
                Double averageCPU = null;
                Date timeStamp = null;
                for (Datapoint d : dataList) {
                    averageCPU = d.getAverage();
                    timeStamp = d.getTimestamp();
                    System.out
                            .println("Instance 1 average CPU utlilization for last 10 minutes: " + averageCPU);
                    System.out.println("Instance 1 total CPU utlilization for last 10 minutes: " + d.getSum());
                }
                System.out.println();
                System.out.println("Instance 2: " + statResult1.toString());
                dataList = statResult2.getDatapoints();
                for (Datapoint d : dataList) {
                    averageCPU = d.getAverage();
                    timeStamp = d.getTimestamp();
                    System.out
                            .println("Instance 2 average CPU utlilization for last 10 minutes: " + averageCPU);
                    System.out.println("Instance 2 total CPU utlilization for last 10 minutes: " + d.getSum());
                }
            }

        } catch (AmazonServiceException ase) {
            System.out.println("Caught Exception: " + ase.getMessage());
            System.out.println("Reponse Status Code: " + ase.getStatusCode());
            System.out.println("Error Code: " + ase.getErrorCode());
            System.out.println("Request ID: " + ase.getRequestId());
        }

        /***********************************
        *   # Copy script to 
        *       instance and run
        *********************************/
        System.out.println();
        System.out.println("Waiting for init and automatically SSH...");
        /* call runtime exec to run scp */
        execCmdRuby(insDNS1, keyGroupName);

        /***********************************
        *   # Save instances to image
        *********************************/
        System.out.println();
        System.out.println("******* Approaching 5:00 pm, create ami for instances *********");
        String imageId1;
        String imageId2;
        String snapshot1;
        String snapshot2;

        imageId1 = createAmiFromInstance(insId1, "image1", true);
        imageId2 = createAmiFromInstance(insId2, "image2", true);
        System.out.println("Created first image id: " + imageId1);
        System.out.println("Created second image id: " + imageId2);

        snapshot1 = createSnapShotFromVolume(volume_name1);
        snapshot2 = createSnapShotFromVolume(volume_name2);
        System.out.println("Created first snapshot id: " + snapshot1);
        System.out.println("Created second snapshot id: " + snapshot2);

        /*********************************************
         * 
         *  # Stop Instances
         *  
         *********************************************/
        System.out.println();
        System.out.println("#7 Stop & terminate the Instance");
        List<String> instanceIds = new LinkedList<String>();
        instanceIds.add(insId1);
        instanceIds.add(insId2);
        /* stop instances */
        StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds);
        ec2.stopInstances(stopIR);
        TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(tir);

        /*********************************************
         * 
         *  # Detach volumes
         *  
         *********************************************/
        System.out.println();
        System.out.println("Detach the volumes from the instances...");
        deatchVolume(insId1, volume_name1);
        deatchVolume(insId2, volume_name2);

        /*********************************************
          * 
          *  # Delete Volumes
          *  
          *********************************************/
        System.out.println();

        while (true) {
            if (getVolumeState(volume_name1).compareTo("available") == 0
                    && getVolumeState(volume_name2).compareTo("available") == 0)
                break;
        }
        System.out.println("Delete volumes...");
        Thread.sleep(10000);
        deleteVolume(volume_name1);
        deleteVolume(volume_name2);

        /*********************************************
          * 
          *  # Second day restore instances and volumes
          *  
          *********************************************/
        System.out.println();
        System.out.println("#8 Second day start up instances from stored amis...");
        String newInsId1 = "";
        String newInsId2 = "";
        String newInsIP1 = "";
        String newInsIP2 = "";
        String newInsZone1 = "";
        String newInsZone2 = "";

        newInsId1 = createInstanceFromImageId(imageId1, keyGroupName);
        newInsId2 = createInstanceFromImageId(imageId2, keyGroupName);
        System.out.println("Second day first instance has been restored with id: " + newInsId1);
        System.out.println("Second day second instance has been restored with id: " + newInsId2);
        newInsZone1 = getInstanceZone(newInsId1);
        newInsZone2 = getInstanceZone(newInsId2);
        System.out.println("New instance 1 zone: " + newInsZone1);
        System.out.println("New instance 2 zone: " + newInsZone2);
        newInsIP1 = getInstanceIP(newInsId1);
        newInsIP2 = getInstanceIP(newInsId2);
        System.out.println("New instance 1 IP: " + newInsIP1);
        System.out.println("New instance 2 IP: " + newInsIP2);

        Thread.sleep(120000);
        /* exec read */
        System.out.println();
        System.out.println("Now start to read the file stored yesterday...");
        execCmdRead(newInsIP1, keyGroupName);

        /*********************************************
         *  
         *  #9 Read data from S3
         *  
         *********************************************/

        /* get the object from the first day */
        System.out.println();
        System.out.println("#9 Reading data from S3 stored on the first day");
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        BufferedReader reader = new BufferedReader(new InputStreamReader(object.getObjectContent()));
        String data = null;
        while ((data = reader.readLine()) != null) {
            System.out.println(data);
        }

        /*********************************************
         *  
         *  #10 shutdown client object
         *  
         *********************************************/
        System.out.println("#10 shutdown client objects");
        ec2.shutdown();
        s3.shutdown();

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

}

From source file:VideoServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    String url = request.getParameter("action");

    System.out.println("url" + url);

    Connection conn = null;/* www .j av  a  2s  .  c o m*/
    Statement setupStatement;
    Statement readStatement = null;
    ResultSet resultSet = null;
    String results = "";
    int numresults = 0;
    String statement = null;
    List<Video> result = new ArrayList<>();

    try {

        // Create connection to RDS instance
        conn = DriverManager.getConnection(jdbcUrl);
        setupStatement = conn.createStatement();

        String retrieveVideoName = "select id from metadata where url like '" + url + "%';";

        ResultSet rs = setupStatement.executeQuery(retrieveVideoName);
        rs.next();
        String ids = rs.getString(1);
        String retrieveUrl = "select url from metadata where id =" + ids + ";";
        ResultSet ru = setupStatement.executeQuery(retrieveUrl);
        ru.next();
        String urls = ru.getString(1);
        System.out.println("este es el id:" + ids);
        System.out.println("esta es la url:" + urls);
        String[] urlIdeal = urls.split(".mp4");
        String finalUrl = urlIdeal[0] + ".mp4";
        System.out.println(finalUrl);

        AWSCredentials credentials = new PropertiesCredentials(
                new File("/Users/diana/Desktop/AwsCredentials.properties"));

        dynamoDBClient = new AmazonDynamoDBClient(new STSSessionCredentialsProvider(credentials));
        dynamoDBClient.setRegion(Region.getRegion(Regions.US_WEST_2));
        String s = getItem(String.valueOf(ids));
        System.out.println(s);
        String[] textArray = s.split("\\{");

        String textFinal = textArray[3];
        String[] newTextArray = textFinal.split(",}");
        String textFinalFinal = newTextArray[0];
        String[] last = textFinalFinal.split("S:");

        System.out.println(last[1].trim());

        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Mp4Servlet</title>");
            out.println(" <script src=\"jquery-1.11.3.min.js\"></script>\n"
                    + "           <script type=\"text/javascript\" src=\"../libs/base64.js\"></script>\n"
                    + "   <script type=\"text/javascript\" src=\"../libs/sprintf.js\"></script>\n"
                    + "   <script type=\"text/javascript\" src=\"../jspdf.js\"></script>");
            out.println(" <style type=\"text/css\">\n" + "      body {\n" + "        padding-top: 20px;\n"
                    + "        padding-bottom: 40px;\n" + "      }\n" + "\n" + "        table{\n"
                    + "        display: table;\n" + "        border:black 5px solid;\n"
                    + "        border-collapse: separate;\n" + "        border-spacing: 7px;\n"
                    + "        border-color: gray;\n" + "        padding:2px;\n" + "\n" + "      }\n"
                    + "      \n" + "      #logo{\n" + "          height: 130px;\n" + "          width: 728px;\n"
                    + "      }\n" + "      hr{\n" + "        /*border-color:#357EC7;*/\n"
                    + "        border-color:#B6B6B4;\n" + "      }\n" + "\n" + "      /* Custom container */\n"
                    + "      .container-narrow {\n" + "        margin: 0 auto;\n"
                    + "        max-width: 700px;\n" + "      }\n" + "      .container-narrow > hr {\n"
                    + "        margin: 30px 0;\n" + "      }\n" + "\n" + "      /* Main marketing messages */\n"
                    + "      .jumbotron {\n" + "        margin: 60px 0;\n" + "        text-align: center;\n"
                    + "        color: grey;\n" + "      }\n" + "      .jumbotron h1 {\n"
                    + "        font-size: 72px;\n" + "        line-height: 1;\n" + "\n" + "      }\n"
                    + "      .jumbotron .btn {\n" + "        font-size: 21px;\n"
                    + "        padding: 14px 24px;\n" + "      }\n" + "\n"
                    + "      /* Supporting marketing content */\n" + "      .marketing {\n"
                    + "        margin: 60px 0;\n" + "      }\n" + "      .marketing p + h4 {\n"
                    + "        margin-top: 28px;\n" + "      }\n" + "      \n" + "      \n" + "      </style>\n"
                    + "      \n" + "\n"
                    + "<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\">\n"
                    + "");
            out.println("</head>");
            out.println("<body>");
            out.println("<div class=\"container-narrow\">\n"
                    + "       <img id = \"logo\" src=\"http://opennebula.org/wp-content/uploads/2015/05/IIT_Logo_stack_186_blk.png\">\n"
                    + "       </div>");
            out.println("<div class='jumbotron'></div>");
            out.println(
                    "<div class='container-narrow'> <video id='idtry'  controls preload='auto' width='500' height='200'></div>\n"
                            + "\n" + "   \n" + "      </video>");
            out.println(
                    "<div class='container-narrow'><br><button id ='button' type='button' class='btn btn-primary btn-lg' onclick='getText()'>EDIT</button></div>\n"
                            + "      <div>\n"
                            + "            <div class='container-narrow'><form id='usrform'><textarea id='text' class = 'container-narrow' name='comment' style='width: 400px; height: 200px;' form='usrform'></textarea>\n"
                            + "           <br><button id ='button2' type='button' onclick='submitToDynamo()'>Submit changes</button>\n"
                            + "            </form></div>\n" + "       </div>");

            out.println("<script>    \n" + "    var textA = " + "\"" + last[1].trim() + "\"" + ";\n" + "\n"
                    + "    document.getElementById('usrform').style.visibility = 'hidden';\n" + "    \n"
                    + "    function getText() {\n" + "\n" + "       var t = document.createTextNode(textA);\n"
                    + "       document.getElementById('text').appendChild(t);\n"
                    + "       document.getElementById('button').style.visibility = 'hidden';\n"
                    + "       document.getElementById('usrform').style.visibility = 'visible';\n" + "\n"
                    + "    }");

            out.println("  var x;\n" + "    function submitToDynamo() {\n" + "        \n"
                    + "       document.getElementById('usrform').style.visibility = 'hidden';\n"
                    + "       document.getElementById('button').style.visibility = 'visible';\n"
                    + "        x = document.getElementById('text').value;\n" + "      download(f,x);\n"
                    + "    }\n" + "       ");

            out.println("  function download(filename, text) {\n"
                    + "    var pom = document.createElement('a');\n"
                    + "    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));\n"
                    + "    pom.setAttribute('download', filename);\n" + "\n"
                    + "    if (document.createEvent) {\n"
                    + "        var event = document.createEvent('MouseEvents');\n"
                    + "        event.initEvent('click', true, true);\n" + "        pom.dispatchEvent(event);\n"
                    + "    }\n" + "    else {\n" + "        pom.click();\n" + "    }\n" + "}\n" + "    \n"
                    + "    \n" + "var f = '/Users/diana/Desktop/texto.txt';");
            out.println("var code = '<source src=\"" + finalUrl + "\" type=\"video/mp4\" />';\n"
                    + "    document.getElementById(\"idtry\").innerHTML=code;");

            out.println("</script>");
            out.println("<div>");

            out.println("</div><br>");
            out.println("<a href='http://localhost:8080/studentUI/Uiservlet'>BACK TO LIST </a>");

            out.println("</body>");
            out.println("</html>");
        }

    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
    } finally {
        System.out.println("Closing the connection.");
        if (conn != null)
            try {
                conn.close();
            } catch (SQLException ignore) {
            }
    }

}

From source file:TweetSQS.java

License:Open Source License

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

    /*//from w  ww  . ja va  2s . co m
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * ().
     */
    AWSCredentials credentials = null;
    try {
        credentials = new PropertiesCredentials(
                TweetSQS.class.getResourceAsStream("AwsCredentials.properties"));
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (/Users/aohong/.aws/credentials), and is in valid format.", e);
    }

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    sqs.setRegion(usEast1);

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

    try {
        // Create a queue
        System.out.println("Creating a new SQS queue called MyQueue.\n");
        CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue");
        String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

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

        // Send a message
        System.out.println("Sending a message to MyQueue.\n");
        sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my first message text."));

        // Receive messages
        System.out.println("Receiving messages from MyQueue.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        for (Message message : messages) {
            System.out.println("  Message");
            System.out.println("    MessageId:     " + message.getMessageId());
            System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
            System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
            System.out.println("    Body:          " + message.getBody());
            for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                System.out.println("  Attribute");
                System.out.println("    Name:  " + entry.getKey());
                System.out.println("    Value: " + entry.getValue());
            }
        }
        System.out.println();

        // Delete a message
        System.out.println("Deleting a message.\n");
        String messageRecieptHandle = messages.get(0).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle));

        // Delete a queue
        System.out.println("Deleting the test queue.\n");
        sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl));
    } 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:virtualIT.java

License:Open Source License

public static void main(String[] args) throws Exception {
    AWSCredentials credentials = new PropertiesCredentials(
            virtualIT.class.getResourceAsStream("AwsCredentials.properties"));
    int intialCounter = 0;
    int s;//from   w  w w .  j  av  a2s . c om
    virtualIT vIT = new virtualIT();
    /*********************************************
     * 
     *  #1 Create Amazon Client object
     *  
     *********************************************/
    System.out.println("#1 Create Amazon Client object");
    ec2 = new AmazonEC2Client(credentials);
    db = new AmazonDynamoDBClient(credentials);
    cloudWatch = new AmazonCloudWatchClient(credentials);
    autoScaleClient = new AmazonAutoScalingClient(credentials);
    vIT.deleteAutoScalingGroup(12345);
    try {
        System.out.println("Starting Virtual System Admin \n");
        System.out.println("Enter no of users want to login\n");
        Scanner getInput = new Scanner(System.in);
        s = getInput.nextInt();
        if (s != 0) {
            for (int j = 0; j < s; j++) {
                System.out.println("Enter UserId:\n");
                int getUserId = getInput.nextInt();
                if (getUserId != 0) {
                    vIT.userIds.add(getUserId);
                    vIT.StartUpGroup(getUserId);
                    vIT.cloudWatchMonitor(getUserId);
                }
            }

            Calendar cal = Calendar.getInstance();
            Date time = cal.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

            vIT.currentHour = (sdf.format(Calendar.HOUR));
            System.out.println(sdf.format(Calendar.HOUR));
            /****
             * Entering Continuous Loop
             */
            for (int i = 0; i < vIT.userIds.size(); i++) {

                int userId = vIT.userIds.get(i);
                double cpu = vIT.mapUserCpu.get(userId);
                tempMin = cal.getTime();

                while (vIT.currentHour.equals(stopTime) || cpu < 5)
                    ;
                {

                    vIT.cloudWatchMonitor(userId);

                    /****************
                     * Entering Time end Group Keeps on looping 
                     */
                    vIT.TimeEndGroup();
                }
            }

        }
        /*********************************************
         * 
          *  #2 Describe Availability Zones.
          *  
          *********************************************/
        /*System.out.println("#2 Describe Availability Zones.");
         DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
         System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size() +
                 " Availability Zones.");*/

        /*********************************************
         * 
         *  #3 Describe Available Images
         *  
         *********************************************/
        /*System.out.println("#3 Describe Available Images");
        DescribeImagesResult dir = ec2.describeImages();
        List<Image> images = dir.getImages();
        System.out.println("You have " + images.size() + " Amazon images");*/

        /*********************************************
         *                 
         *  #4 Describe Key Pair
         *                 
         *********************************************/
        /* System.out.println("#9 Describe Key Pair");
         DescribeKeyPairsResult dkr = ec2.describeKeyPairs();
         System.out.println(dkr.toString());*/

        /*********************************************
         * 
         *  #5 Describe Current Instances
         *  
         *********************************************/
        /* System.out.println("#4 Describe Current Instances");
         DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
         List<Reservation> reservations = describeInstancesRequest.getReservations();
         Set<Instance> instances = new HashSet<Instance>();
         // add all instances to a Set.
         for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
         }
                 
         System.out.println("You have " + instances.size() + " Amazon EC2 instance(s).");
         for (Instance ins : instances){
                    
            // instance id
            String instanceId = ins.getInstanceId();
                    
            // instance state
            InstanceState is = ins.getState();
            System.out.println(instanceId+" "+is.getName());
        //    System.out.println("Key for the instance  "+keyName);
         }*/

        // Thread.currentThread().sleep(100000);

        //get instanceId from the result

        /*  List<Instance> resultInstance = result.getReservation().getInstances();
          String createdInstanceId = null;
          for (Instance ins : resultInstance){   
             createdInstanceId = ins.getInstanceId();
             System.out.println("New instance has been created: "+ins.getInstanceId());
          }
          describeInstancesRequest = ec2.describeInstances();
          reservations = describeInstancesRequest.getReservations();
          int k = reservations.size();
          Reservation totalReservations = reservations.get(k-1);
          Instance getFirstInstance = totalReservations.getInstances().get(0);
                 
          System.out.println("The private IP is: "+getFirstInstance.getPrivateIpAddress());
          System.out.println("The public IP is: "+getFirstInstance.getPublicIpAddress());*/

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

}

From source file:AmazonDynamoDBSample.java

License:Open Source License

/**
 * The only information needed to create a client are security credentials
 * consisting of the AWS Access Key ID and Secret Access Key. All other
 * configuration, such as the service endpoints, are performed
 * automatically. Client parameters, such as proxies, can be specified in an
 * optional ClientConfiguration object when constructing a client.
 *
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.PropertiesCredentials
 * @see com.amazonaws.ClientConfiguration
 *//* w  ww. j  a v  a 2  s.  co m*/
private static void init() throws Exception {
    AWSCredentials credentials = new PropertiesCredentials(
            AmazonDynamoDBSample.class.getResourceAsStream("AwsCredentials.properties"));

    dynamoDB = new AmazonDynamoDBClient(credentials);
}

From source file:PutFile.java

License:Apache License

public static void main(String[] args) throws IOException {
    /*//w ww.  jav a 2 s  . c om
     * 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
     */
    AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(

            PutFile.class.getResourceAsStream("AwsCredentials.properties")));
    String bucketName = "dtccTest";

    System.out.println("===========================================");
    System.out.println(" Amazon S3 Test");
    System.out.println("===========================================\n");

    try {

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();
        String fileName = "S3HWTest.zip";
        File file = new File(fileName);
        System.out.println("Uploading a new object to S3 from a file " + fileName + "\n");
        System.out.println("file.length() " + file.length() + "\n");

        long start = System.currentTimeMillis();
        PutObjectRequest request = new PutObjectRequest(bucketName, fileName, file);
        request.setCannedAcl(CannedAccessControlList.PublicRead);
        s3.putObject(request);
        System.out.println("Uploading done in " + (System.currentTimeMillis() - start) + " ms.\n");

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, whichmeans your request made it "
                + "to Amazon S3, but was rejected with an errorresponse 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, whichmeans the client encountered "
                + "a serious internal problem while trying tocommunicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:GetTestFile.java

License:Apache License

public static void main(String[] args) throws IOException {
    /*// ww  w  . jav  a2 s.  co 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
     */
    AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(

            GetTestFile.class.getResourceAsStream("AwsCredentials.properties")));

    String bucketName = "dtccTest";

    String key = "largerfile.txt";

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

    try {

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();

        System.out.println("Downloading an object");
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        System.out.println("ContentEncod: " + object.getObjectMetadata().getContentEncoding());
        System.out.println("ContentLengt: " + object.getObjectMetadata().getContentLength());
        System.out.println("ContentDisp: " + object.getObjectMetadata().getContentDisposition());

        displayTextInputStream(object.getObjectContent());

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, whichmeans your request made it "
                + "to Amazon S3, but was rejected with an errorresponse 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, whichmeans the client encountered "
                + "a serious internal problem while trying tocommunicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}