Example usage for com.amazonaws.regions Region getRegion

List of usage examples for com.amazonaws.regions Region getRegion

Introduction

In this page you can find the example usage for com.amazonaws.regions Region getRegion.

Prototype

public static Region getRegion(Regions region) 

Source Link

Document

Returns the region with the id given, or null if it cannot be found in the current regions.xml file.

Usage

From source file:com.pinterest.secor.uploader.S3UploadManager.java

License:Apache License

public S3UploadManager(SecorConfig config) {
    super(config);

    final String accessKey = mConfig.getAwsAccessKey();
    final String secretKey = mConfig.getAwsSecretKey();
    final String endpoint = mConfig.getAwsEndpoint();
    final String region = mConfig.getAwsRegion();
    final String awsRole = mConfig.getAwsRole();

    s3Path = mConfig.getS3Path();

    AmazonS3 client;//from w  w  w . j a va2  s. c o  m
    AWSCredentialsProvider provider;

    ClientConfiguration clientConfiguration = new ClientConfiguration();
    boolean isHttpProxyEnabled = mConfig.getAwsProxyEnabled();

    //proxy settings
    if (isHttpProxyEnabled) {
        LOG.info("Http Proxy Enabled for S3UploadManager");
        String httpProxyHost = mConfig.getAwsProxyHttpHost();
        int httpProxyPort = mConfig.getAwsProxyHttpPort();
        clientConfiguration.setProxyHost(httpProxyHost);
        clientConfiguration.setProxyPort(httpProxyPort);
    }

    if (accessKey.isEmpty() || secretKey.isEmpty()) {
        provider = new DefaultAWSCredentialsProviderChain();
    } else {
        provider = new AWSCredentialsProvider() {
            public AWSCredentials getCredentials() {
                return new BasicAWSCredentials(accessKey, secretKey);
            }

            public void refresh() {
            }
        };
    }

    if (!awsRole.isEmpty()) {
        provider = new STSAssumeRoleSessionCredentialsProvider(provider, awsRole, "secor");
    }

    client = new AmazonS3Client(provider, clientConfiguration);

    if (!endpoint.isEmpty()) {
        client.setEndpoint(endpoint);
    } else if (!region.isEmpty()) {
        client.setRegion(Region.getRegion(Regions.fromName(region)));
    }

    mManager = new TransferManager(client);
}

From source file:com.pocketdealhunter.HotDealsMessagesUtil.java

License:Open Source License

public HotDealsMessagesUtil() {
    AWSCredentials credentials = new BasicAWSCredentials(Constants.ACCESS_KEY_ID, Constants.SECRET_KEY);
    Region region = Region.getRegion(Regions.US_WEST_2);

    this.snsClient = new AmazonSNSClient(credentials);
    this.snsClient.setRegion(region);

    this.sqsClient = new AmazonSQSClient(credentials);
    this.sqsClient.setRegion(region);

    // Find the Topic for this App or create one.
    this.topicARN = this.findTopicArn();
    if (topicARN == null) {
        this.topicARN = this.createTopic();
    }//  www . j  a  v a  2s. c o m

    // Find the Queue for this App or create one.
    this.queueUrl = this.findQueueUrl();
    if (this.queueUrl == null) {
        this.queueUrl = this.createQueue();

        // Allow time for the queue to be created.
        try {
            Thread.sleep(4 * 1000);
        } catch (Exception exception) {
        }

        this.subscribeQueue();
    }
}

From source file:com.prd.AmazonSESSample.java

License:Open Source License

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

    // Construct an object to contain the recipient address.
    Destination destination = new Destination().withToAddresses(new String[] { TO });

    // Create the subject and body of the message.
    Content subject = new Content().withData(SUBJECT);
    Content textBody = new Content().withData(BODY);
    Body body = new Body().withText(textBody);

    // Create a message with the specified subject and body.
    Message message = new Message().withSubject(subject).withBody(body);

    // Assemble the email.
    SendEmailRequest request = new SendEmailRequest().withSource(FROM).withDestination(destination)
            .withMessage(message);/*from  w  w w  . ja v  a2s. com*/

    try {
        System.out.println("Attempting to send an email through Amazon SES by using the AWS SDK for Java...");

        /*
         * The ProfileCredentialsProvider will return your [default]
         * credential profile by reading from the credentials file located at
         * (/Users/prabhjitsingh/.aws/credentials).
         *
         * TransferManager manages a pool of threads, so we create a
         * single instance and share it throughout our application.
         */
        AWSCredentials credentials = null;
        try {
            credentials = new ProfileCredentialsProvider("default").getCredentials();
        } 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/prabhjitsingh/.aws/credentials), and is in valid format.", e);
        }

        // Instantiate an Amazon SES client, which will make the service call with the supplied AWS credentials.
        AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(credentials);

        // Choose the AWS region of the Amazon SES endpoint you want to connect to. Note that your production
        // access status, sending limits, and Amazon SES identity-related settings are specific to a given
        // AWS region, so be sure to select an AWS region in which you set up Amazon SES. Here, we are using
        // the US East (N. Virginia) region. Examples of other regions that Amazon SES supports are US_WEST_2
        // and EU_WEST_1. For a complete list, see http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html
        Region REGION = Region.getRegion(Regions.US_EAST_1);
        client.setRegion(REGION);

        // Send the email.
        client.sendEmail(request);
        System.out.println("Email sent!");

    } catch (Exception ex) {
        System.out.println("The email was not sent.");
        System.out.println("Error message: " + ex.getMessage());
    }
}

From source file:com.raoul.walkfoframe.web.DynamoDBManager.java

License:Open Source License

public static ArrayList<WOFPushNotification> getWofPushNotifications(int lastNotificationId)
        throws UnknownHostException {
    BasicAWSCredentials c = new BasicAWSCredentials("AKIAJRYXOB72QJQU3MQQ",
            "FOQ6TDEhxTqvZb6hb+5db1OQFd4nikDRh2tuGqy1");
    AmazonDynamoDB clientManager = new AmazonDynamoDBClient(c);
    clientManager.setRegion(Region.getRegion(Regions.US_WEST_2));

    AmazonDynamoDB ddb = clientManager;/*from   www.  j  ava  2 s .  com*/
    DynamoDBMapper mapper = new DynamoDBMapper(ddb);
    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();

    scanExpression.addFilterCondition("ID",
            new Condition().withComparisonOperator(ComparisonOperator.GT.toString())
                    .withAttributeValueList(new AttributeValue().withN(lastNotificationId + "")));
    try {
        PaginatedScanList<WOFPushNotification> result = mapper.scan(WOFPushNotification.class, scanExpression);

        ArrayList<WOFPushNotification> resultList = new ArrayList<WOFPushNotification>();
        for (WOFPushNotification up : result) {
            resultList.add(up);
        }

        Log.e("Push notification result list", resultList.size() + "");

        return resultList;

    } catch (AmazonServiceException ex) {
        //HWOFameApplication.clientManager.wipeCredentialsOnAuthError(ex);
    }

    return null;
}

From source file:com.remediatetheflag.global.actions.auth.user.LaunchExerciseInstanceAction.java

License:Apache License

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {

    User user = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);
    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_ATTRIBUTE_JSON);

    if (user.getCredits() == 0) {
        MessageGenerator.sendErrorMessage("CreditsLimit", response);
        logger.warn("No credits left for user " + user.getIdUser());
        return;//from w w w. j  av a  2  s  . co  m
    }
    List<ExerciseInstance> activeInstances = hpc.getActiveExerciseInstanceForUser(user.getIdUser());
    if (activeInstances.size() > 0 && activeInstances.size() >= user.getInstanceLimit()) {
        MessageGenerator.sendErrorMessage("InstanceLimit", response);
        logger.warn("Instance limit reached for user " + user.getIdUser() + " current: "
                + activeInstances.size() + " limit:" + user.getInstanceLimit());
        return;
    }

    Integer exerciseId = json.get(Constants.ACTION_PARAM_ID).getAsInt();
    JsonElement challengeElement = json.get(Constants.ACTION_PARAM_CHALLENGE_ID);

    AvailableExercise exercise = hpc.getAvailableExercise(exerciseId, user.getDefaultOrganization());
    if (null == exercise || exercise.getStatus().equals(AvailableExerciseStatus.INACTIVE)
            || exercise.getStatus().equals(AvailableExerciseStatus.COMING_SOON)) {
        MessageGenerator.sendErrorMessage("ExerciseUnavailable", response);
        logger.error("User " + user.getIdUser() + " requested an unavailable exercise: " + exerciseId);
        return;
    }

    Integer validatedChallengeId = null;

    List<Challenge> userChallengesWithExercise = hpc.getChallengesForUserExercise(exercise.getId(),
            user.getIdUser());

    if (!userChallengesWithExercise.isEmpty()) {
        Boolean inChallenge = false;
        if (null != challengeElement && (challengeElement.getAsInt() != -1)) {
            Integer challengeId = challengeElement.getAsInt();
            Challenge c = hpc.getChallengeWithDetailsForUser(challengeId, user.getIdUser());
            if (null != c) {
                for (AvailableExercise avE : c.getExercises()) {
                    if (avE.getId().equals(exerciseId)) {
                        validatedChallengeId = c.getIdChallenge();
                        inChallenge = true;
                        break;
                    }
                }
            }
            if (!inChallenge) {
                logger.error("Exercise " + exerciseId + " is NOT in Challenge: " + challengeId
                        + ", but a challenge id was provided by user: " + user.getIdUser());
                validatedChallengeId = null;
            }
            for (ExerciseInstance e : c.getRunExercises()) {
                if (e.getUser().getIdUser().equals(user.getIdUser())
                        && e.getAvailableExercise().getId().equals(exerciseId)) {
                    logger.warn("Exercise " + exerciseId + " is in Challenge: " + challengeId + ", but user: "
                            + user.getIdUser() + " already run it");
                    validatedChallengeId = null;
                    break;
                }
            }
        } else {
            logger.warn("Exercise " + exerciseId
                    + " is in Challenge, but no challenge id was provided by user: " + user.getIdUser());
            Boolean run = false;
            for (Challenge dbChallenges : userChallengesWithExercise) {
                for (ExerciseInstance dbChallengeExercise : dbChallenges.getRunExercises()) {
                    if (dbChallengeExercise.getUser().getIdUser().equals(user.getIdUser())
                            && dbChallengeExercise.getAvailableExercise().getId().equals(exerciseId)) {
                        run = true;
                    }
                }
                if (!run) {
                    validatedChallengeId = userChallengesWithExercise.get(0).getIdChallenge();
                    break;
                }
            }
        }
    }

    JsonElement exerciseRegionsElement = json.getAsJsonArray(Constants.ACTION_PARAM_REGION);
    Type listType = new TypeToken<ArrayList<ExerciseRegion>>() {
    }.getType();
    List<ExerciseRegion> regList = null;
    try {
        regList = new Gson().fromJson(exerciseRegionsElement, listType);

    } catch (Exception e) {
        MessageGenerator.sendErrorMessage("NoRegionsPing", response);
        logger.error("User " + user.getIdUser() + " requested an exercise: " + exerciseId
                + " without supplying regions pings");
        return;
    }
    Collections.sort(regList, new Comparator<ExerciseRegion>() {
        public int compare(ExerciseRegion p1, ExerciseRegion p2) {
            return Integer.valueOf(p1.getPing()).compareTo(p2.getPing());
        }
    });
    AWSHelper awsHelper = new AWSHelper();
    RTFECSTaskDefinition taskDefinition = null;
    Regions awsRegion = null;

    Boolean satisfied = false;
    for (ExerciseRegion r : regList) {
        if (satisfied)
            break;
        try {
            awsRegion = Regions.valueOf(r.getName());
        } catch (Exception e) {
            logger.warn("Region " + r.getName() + " not found for user " + user.getIdUser()
                    + " for launching exercise: " + exerciseId);
            continue;
        }

        RTFGateway gw = hpc.getGatewayForRegion(awsRegion);
        if (null == gw || !gw.isActive()) {
            logger.warn("User " + user.getIdUser() + " requested an unavailable gateway for region: "
                    + awsRegion + " for launching exercise: " + exerciseId);
            continue;
        }
        GuacamoleHelper guacHelper = new GuacamoleHelper();
        if (!guacHelper.isGuacOnline(gw)) {
            logger.warn("User " + user.getIdUser()
                    + " could not launch instance as Guac is not available in region: " + awsRegion
                    + " for launching exercise: " + exerciseId);
            continue;
        }
        taskDefinition = hpc.getTaskDefinitionForExerciseInRegion(exerciseId, awsRegion);
        if (null == taskDefinition) {
            taskDefinition = hpc.getTaskDefinitionFromUUID(exercise.getUuid(), awsRegion);
        }
        if (null == taskDefinition || !resourcesAvailable(Region.getRegion(awsRegion))) {
            logger.warn("No resources for user " + user.getIdUser() + " launching exercise: " + exerciseId
                    + " in region " + awsRegion);
            continue;
        }
        satisfied = true;
    }

    if (!satisfied) {
        MessageGenerator.sendErrorMessage("Unavailable", response);
        logger.error("User " + user.getIdUser()
                + " could not launch instance as there is no available region/gateway/guac/task def for exercise id "
                + exerciseId);
        return;
    }

    String otp = UUID.randomUUID().toString().replaceAll("-", "");
    LaunchStrategy strategy = new AWSECSLaunchStrategy(user, exercise.getDuration(),
            RTFConfig.getExercisesCluster(), otp, taskDefinition, exercise, validatedChallengeId);
    RTFInstanceReservation reservation = awsHelper.createRTFInstance(strategy);
    if (!reservation.getError()) {
        logger.info("Reservation " + reservation.getId() + " for user " + user.getIdUser()
                + "  launching exercise: " + exerciseId + " in region " + awsRegion);
        if (user.getCredits() != -1) {
            user.setCredits(user.getCredits() - 1);
            hpc.updateUserInfo(user);
            request.getSession().setAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT, user);
            logger.info("Reducing 1 credit for user " + user.getIdUser() + " to: " + user.getCredits());
        }
        MessageGenerator.sendReservationMessage(reservation, response);
        return;
    } else {
        MessageGenerator.sendErrorMessage("InstanceUnavailable", response);
    }

}

From source file:com.remediatetheflag.global.utils.RTFInstancesAutoShutdown.java

License:Apache License

@Override
public void run() {
    logger.debug("Running shutdown task");

    //get running exercise instances from db, returns ExerciseInstance
    List<ExerciseInstance> exerciseInstances = hpc.getAllRunningExerciseInstancesWithAwsGWFlag();
    logger.debug("Returned " + exerciseInstances.size() + " running exercise instances from db");

    // get active regions
    List<Region> activeRegions = new LinkedList<Region>();
    for (RTFGateway gw : hpc.getAllActiveGateways()) {
        activeRegions.add(Region.getRegion(gw.getRegion()));
    }//from   ww  w  .j a  va2  s . c o m
    logger.debug("Returned " + activeRegions.size() + " active regions from db");

    // get running ecs instances from AWS for active regions
    List<String> runningTasks = awsHelper.getRunningECSTasks(activeRegions);
    logger.debug("Returned " + runningTasks.size() + " running tasks for aws active regions");

    Date now = new Date();
    for (String taskArn : runningTasks) {
        boolean found = false;
        for (ExerciseInstance ei : exerciseInstances) {
            if (ei.getEcsInstance().getTaskArn().equals(taskArn)) {
                found = true;
                if (ei.getEndTime().getTime() < now.getTime()) {
                    logger.debug("Exercise " + ei.getIdExerciseInstance() + " needs to be shutdown");
                    Thread stopExerciseThread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if (!ei.getStatus().equals(ExerciseStatus.REVIEWED)
                                    && !ei.getStatus().equals(ExerciseStatus.AUTOREVIEWED)
                                    && !ei.getStatus().equals(ExerciseStatus.REVIEWED_MODIFIED)) {
                                logger.debug("Pulling exercise result file for exercise instance "
                                        + ei.getIdExerciseInstance());
                                ExerciseResultFile fr = gwHelper.getResultFile(ei);
                                ei.setResultFile(fr);

                                logger.debug("Pulling exercise results for exercise instance "
                                        + ei.getIdExerciseInstance());
                                Challenge exerciseChallenge = null;
                                if (null != ei.getChallengeId()) {
                                    exerciseChallenge = hpc.getChallengeFromId(ei.getChallengeId());
                                    exerciseChallenge.setLastActivity(new Date());
                                    hpc.updateChallenge(exerciseChallenge);
                                }

                                List<ExerciseResult> results = gwHelper.getResultStatus(ei, exerciseChallenge);
                                if (!ei.getResults().isEmpty()) {
                                    for (ExerciseResult origRes : ei.getResults()) {
                                        for (ExerciseResult newRes : results) {
                                            if (newRes.getName().equals(origRes.getName())) {
                                                if (origRes.getStatus().equals(ExerciseResultStatus.VULNERABLE)
                                                        && newRes.getStatus()
                                                                .equals(ExerciseResultStatus.NOT_VULNERABLE)) {
                                                    origRes.setStatus(ExerciseResultStatus.NOT_VULNERABLE);
                                                    origRes.setScore(newRes.getScore());
                                                    origRes.setLastChange(new Date());
                                                    origRes.setFirstForFlag(newRes.getFirstForFlag());
                                                    origRes.setSecondForFlag(newRes.getSecondForFlag());
                                                    origRes.setThirdForFlag(newRes.getThirdForFlag());
                                                }
                                                break;
                                            }
                                        }
                                    }
                                    hpc.updateExerciseInstance(ei);
                                } else {
                                    ei.setResults(results);
                                }

                                Integer totalScore = 0;
                                for (ExerciseResult r : ei.getResults()) {
                                    totalScore += r.getScore();
                                }
                                ei.getScore().setResult(totalScore);

                                if (ei.getScoring().equals(ExerciseScoringMode.MANUAL_REVIEW)) {
                                    ei.setStatus(ExerciseStatus.STOPPED);
                                } else {
                                    ei.setStatus(ExerciseStatus.AUTOREVIEWED);
                                    List<ExerciseInstance> userRunExercises = hpc
                                            .getCompletedExerciseInstancesForUser(ei.getUser().getIdUser());
                                    ei.setResultsAvailable(true);
                                    notificationsHelper.addCompletedReviewNotification(ei.getUser(), ei);

                                    boolean alreadyRun = false;
                                    for (ExerciseInstance runEx : userRunExercises) {
                                        if (runEx.getAvailableExercise().getId()
                                                .equals(ei.getAvailableExercise().getId())
                                                || runEx.getAvailableExercise().getUuid()
                                                        .equals(ei.getAvailableExercise().getUuid())) {
                                            alreadyRun = true;
                                            break;
                                        }
                                    }
                                    if (!alreadyRun) {
                                        User dbUser = hpc.getUserFromUserId(ei.getUser().getIdUser());
                                        dbUser.setExercisesRun(dbUser.getExercisesRun() + 1);
                                        dbUser.setScore(dbUser.getScore() + ei.getScore().getResult());
                                        hpc.updateUserInfo(dbUser);

                                        if (ei.getScore().getResult() >= ei.getScore().getTotal()) {
                                            List<AchievedTrophy> userAchievedTrophy = hpc
                                                    .getAllAchievedTropiesForUser(ei.getUser().getIdUser());
                                            boolean alreadyAchieved = false;
                                            for (AchievedTrophy trophy : userAchievedTrophy) {
                                                if (trophy.getTrophy().getName().equals(
                                                        ei.getAvailableExercise().getTrophy().getName())) {
                                                    alreadyAchieved = true;
                                                    break;
                                                }
                                            }
                                            if (!alreadyAchieved) {
                                                AchievedTrophy t = new AchievedTrophy();
                                                t.setDate(new Date());
                                                t.setUser(ei.getUser());
                                                t.setTrophy(ei.getAvailableExercise().getTrophy());
                                                hpc.managementAddAchievedTrophy(t);
                                            }
                                        }

                                    }

                                }

                                ei.getEcsInstance().setStatus(Constants.STATUS_STOPPED);

                                Calendar cal = Calendar.getInstance();
                                ei.setEndTime(cal.getTime());
                                ei.getEcsInstance().setShutdownTime(cal.getTime());
                                GuacamoleHelper guacHelper = new GuacamoleHelper();
                                try {
                                    Integer duration = guacHelper.getUserExerciseDuration(ei.getGuac());
                                    ei.setDuration(duration);
                                } catch (Exception e) {
                                    logger.error("Could not get duration for instance "
                                            + ei.getIdExerciseInstance() + e.getMessage());
                                    ei.setDuration(-1);
                                }
                                hpc.updateExerciseInstance(ei);
                            }
                            awsHelper.terminateTask(ei.getEcsInstance());
                        }
                    });
                    stopExerciseThread.start();
                    ei.setStatus(ExerciseStatus.STOPPING);
                    hpc.updateExerciseInstance(ei);
                }
            }
        }

        if (!found && RTFConfig.getEnvironment().equals(Constants.PROD_ENVIRONMENT)) { //orphans
            Date createdTime = awsHelper.getRunningECSTaskStartTime(taskArn);
            long time = System.currentTimeMillis();
            if (time - createdTime.getTime() >= 1200000) {
                logger.warn("Exercise " + taskArn + " is orphan and needs to be shutdown");
                awsHelper.terminateTask(taskArn);
            } else {
                logger.debug("Fullfilled Reservation " + (time - createdTime.getTime()) + " ms old");
            }
        }
    }
    logger.debug("End of shutdown task");
}

From source file:com.rodosaenz.samples.aws.sqs.AwsSqsSimpleExample.java

License:Open Source License

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

    /*/*  w  w w.  j ava  2  s .c  o m*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider().getCredentials();
    } 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 (~/.aws/credentials), and is in valid format.", e);
    }

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

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

    String queue_name = "com-rodosaenz-examples-aws-sqs";

    try {
        // Create a queue
        System.out.println("Creating a new SQS queue called " + queue_name + ".\n");
        CreateQueueRequest createQueueRequest = new CreateQueueRequest(queue_name);
        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 " + queue_name + ".\n");
        sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my message text."));
        // Receive messages
        System.out.println("Receiving messages from MyQueue.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        receiveMessageRequest.setMaxNumberOfMessages(1);
        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 messageReceiptHandle = messages.get(0).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageReceiptHandle));

        //Get attributes
        GetQueueAttributesRequest request = new GetQueueAttributesRequest(myQueueUrl).withAttributeNames("All");
        final Map<String, String> attributes = sqs.getQueueAttributes(request).getAttributes();

        System.out.println("  Policy: " + attributes.get("Policy"));
        System.out.println("  MessageRetentionPeriod: " + attributes.get("MessageRetentionPeriod"));
        System.out.println("  MaximumMessageSize: " + attributes.get("MaximumMessageSize"));
        System.out.println("  CreatedTimestamp: " + attributes.get("CreatedTimestamp"));
        System.out.println("  VisibilityTimeout: " + attributes.get("VisibilityTimeout"));
        System.out.println("  QueueArn: " + attributes.get("QueueArn"));
        System.out.println("  ApproximateNumberOfMessages: " + attributes.get("ApproximateNumberOfMessages"));
        System.out.println("  ApproximateNumberOfMessagesNotVisible: "
                + attributes.get("ApproximateNumberOfMessagesNotVisible"));
        System.out.println("  DelaySeconds: " + attributes.get("DelaySeconds"));

        // 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:com.saife.sample.S3Sample.java

License:Apache License

/**
 * //from  www . jav a2s . co  m
 */
private void initS3() {
    // S3 credential identity
    final String me = "john.curtis@saife-tiprnet";

    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider(me).getCredentials();
    } catch (final 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 (/home/builder/.aws/credentials), and is in valid format.", e);
    }

    s3 = new AmazonS3Client(credentials);
    final Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

    // define a bucket name
    bucketName = null;

    try {

        /*
         * List the buckets in your account
         */
        for (final Bucket bucket : s3.listBuckets()) {
            if (bucket.getName().startsWith("saife-test-bucket")) {
                bucketName = bucket.getName();
                System.out.println("Found Test Bucket:" + bucket.getName());
            }
        }

        /*
         * Create a globally unique bucket name if needed.
         */
        if (null == bucketName) {
            bucketName = "saife-test-bucket" + UUID.randomUUID();
            System.out.println("Creating bucket " + bucketName + "\n");
            s3.createBucket(bucketName);
        }
    } catch (final 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 (final 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());
    }

    System.out.println("S3 services are enabled.");
}

From source file:com.screensaver.util.Util.java

License:Open Source License

/**
 * Gets an instance of a S3 client which is constructed using the given
 * Context.//from ww  w  .ja  v a2 s  .  co  m
 *
 * @param context An Context instance.
 * @return A default S3 client.
 */
public static AmazonS3Client getS3Client(Context context) {
    if (sS3Client == null) {
        sS3Client = new AmazonS3Client(getCredProvider(context.getApplicationContext()));
        sS3Client.setRegion(Region.getRegion(Regions.fromName(Constants.BUCKET_REGION)));
    }
    return sS3Client;
}

From source file:com.serverless.manager.DynamoDBManager.java

License:Open Source License

private DynamoDBManager() {

    AmazonDynamoDBClient client = new AmazonDynamoDBClient();
    client.setRegion(Region.getRegion(Regions.US_WEST_1));
    mapper = new DynamoDBMapper(client);
}