Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2012-2015 Amazon Technologies, Inc.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at:
   *
   *    http://aws.amazon.com/apache2.0
   *
  * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
  * OR CONDITIONS OF ANY KIND, either express or implied. See the
  * License for the specific language governing permissions and
  * limitations under the License.
  */
 package com.amazonaws.services.glacier.transfer;
 
 import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 
 
Utility for monitoring the status of an Amazon Glacier job, through Amazon SNS/SQS.
 
 public class JobStatusMonitor {
     private AmazonSQSClient sqs;
     private AmazonSNSClient sns;
     private String queueUrl;
     private String topicArn;
 
     private static final Log log = LogFactory.getLog(JobStatusMonitor.class);
 
     public JobStatusMonitor(AWSCredentialsProvider credentialsProviderClientConfiguration clientConfiguration) {
          = new AmazonSQSClient(credentialsProviderclientConfiguration);
          = new AmazonSNSClient(credentialsProviderclientConfiguration);
         setupQueueAndTopic();
     }

    
Constructs a JobStatusMonitor that will use the specified clients for polling archive download job status.

Parameters:
sqs The client for working with Amazon SQS when polling archive retrieval job status.
sns The client for working with Amazon SNS when polling archive retrieval job status.
 
     public JobStatusMonitor(AmazonSQSClient sqsAmazonSNSClient sns) {
         this. = sqs;
         this. = sns;
         setupQueueAndTopic();
     }
 
     public String getTopicArn() {
         return ;
     }
 
     public void shutdown() {
         try {
             .deleteQueue(new DeleteQueueRequest());
         } catch (Exception e) {
             .warn("Unable to delete queue: " + e);
         }
 
         try {
             .deleteTopic(new DeleteTopicRequest());
        } catch (Exception e) {
            .warn("Unable to delete topic: " + e);
        }
    }

    
Poll the SQS queue to see if we've received a message about the job completion yet.
    public void waitForJobToComplete(String jobId) {
        while (true) {
            List<Messagemessages = .receiveMessage(new ReceiveMessageRequest()).getMessages();
            for (Message message : messages) {
                String messageBody = message.getBody();
                if (!messageBody.startsWith("{")) {
                    messageBody = new String(BinaryUtils.fromBase64(messageBody));
                }
                try {
                    JSONObject json = new JSONObject(messageBody);
                    String jsonMessage = json.getString("Message").replace("\\\"""\"");
                    json = new JSONObject(jsonMessage);
                    String messageJobId = json.getString("JobId");
                    String messageStatus = json.getString("StatusMessage");
                    // Don't process this message if it wasn't the job we were looking for
                    if (!jobId.equals(messageJobId)) continue;
                    try {
                        if (..toString().equals(messageStatus)) return;
                        if (..toString().equals(messageStatus)) {
                            throw new AmazonClientException("Archive retrieval failed");
                        }
                    } finally {
                        deleteMessage(message);
                    }
                } catch (JSONException e) {
                    throw new AmazonClientException("Unable to parse status message: " + messageBodye);
                }
            }
            sleep(1000 * 30);
        }
    }
    private void sleep(long milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException ie) {
            throw new AmazonClientException("Archive download interrupted"ie);
        }
    }
    private void deleteMessage(Message message) {
        try {
            .deleteMessage(new DeleteMessageRequest(message.getReceiptHandle()));
        } catch (Exception e) {}
    }
    private void setupQueueAndTopic() {
        String randomSeed = UUID.randomUUID().toString();
        String queueName = "glacier-archive-transfer-" + randomSeed;
        String topicName = "glacier-archive-transfer-" + randomSeed;
         = .createQueue(new CreateQueueRequest(queueName)).getQueueUrl();
         = .createTopic(new CreateTopicRequest(topicName)).getTopicArn();
        String queueARN = .getQueueAttributes(new GetQueueAttributesRequest().withAttributeNames("QueueArn")).getAttributes().get("QueueArn");
        Policy sqsPolicy =
            new Policy().withStatements(
                    new Statement(.)
                    .withPrincipals(.)
                    .withActions(.)
                    .withResources(new Resource(queueARN))
                    .withConditions(ConditionFactory.newSourceArnCondition()));
        .setQueueAttributes(new SetQueueAttributesRequest(newAttributes("Policy"sqsPolicy.toJson())));
        .subscribe(new SubscribeRequest("sqs"queueARN));
    }
    private Map<StringStringnewAttributes(String... keyValuePairs) {
        if (keyValuePairs.length % 2 != 0)
            throw new IllegalArgumentException("Incorrect number of arguments passed.  Input must be specified as: key, value, key, value, ...");
        Map<StringStringmap = new HashMap<StringString>();
        for (int i = 0; i < keyValuePairs.lengthi += 2) {
            String key   = keyValuePairs[i];
            String value = keyValuePairs[i+1];
            map.put(keyvalue);
        }
        return map;
    }
New to GrepCode? Check out our FAQ X