當前位置: 首頁>>代碼示例>>Java>>正文


Java Message.getBody方法代碼示例

本文整理匯總了Java中com.amazonaws.services.sqs.model.Message.getBody方法的典型用法代碼示例。如果您正苦於以下問題:Java Message.getBody方法的具體用法?Java Message.getBody怎麽用?Java Message.getBody使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.amazonaws.services.sqs.model.Message的用法示例。


在下文中一共展示了Message.getBody方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: parse

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
public List<S3SNSNotification> parse(Message message) {
    List<S3SNSNotification> notifications = Lists.newArrayList();

    try {
        SQSMessage envelope = om.readValue(message.getBody(), SQSMessage.class);

        if (envelope.message == null) {
            return Collections.emptyList();
        }

        S3EventNotification s3EventNotification = S3EventNotification.parseJson(envelope.message);

        notifications.addAll(s3EventNotification.getRecords().stream().map(record -> new S3SNSNotification(
                message.getReceiptHandle(),
                record.getS3().getBucket().getName(),
                record.getS3().getObject().getUrlDecodedKey()
        )).collect(Collectors.toList()));
    } catch (Exception e) {
        LOG.error("Could not parse SNS notification: " + message.getBody(), e);
        throw new RuntimeException("Could not parse SNS notification: " + message.getBody(), e);
    }

    return notifications;
}
 
開發者ID:sherzberg,項目名稱:graylog-plugin-s3,代碼行數:25,代碼來源:S3SNSNotificationParser.java

示例2: getMessages

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
public List<QueueMessage> getMessages() {

        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(_queueDns);
        List<Message> messages = _sqs.receiveMessage(receiveMessageRequest).getMessages();

        List<QueueMessage> deserializedMessages = new ArrayList<>();

        for (Message message : messages) {
            String body = message.getBody();
            QueueMessage qm = _gson.fromJson(body, QueueMessage.class);
            deserializedMessages.add(qm);

            System.out.println("query time: " + qm.queryExecutionTime);
            System.out.println("exec time: " + qm.totalExecutionTime);
            System.out.println("Has ex: " + qm.hasException);
            System.out.println("ex message: " + qm.exceptionMessage + "\n");

            String receiptHandle = message.getReceiptHandle();
            _sqs.deleteMessage(new DeleteMessageRequest(_queueDns, receiptHandle));
        }

        return deserializedMessages;
    }
 
開發者ID:hunterSThompson,項目名稱:aws-ski-resort,代碼行數:24,代碼來源:QueueService.java

示例3: processTask

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
private void processTask(Message message) {
    String path = message.getBody();
    PathSplit pathComp = new PathSplit(path);
    String bucket = pathComp.bucket;
    String key = pathComp.key;
    Logger.Info("Processing %s %s", bucket, key);

    // Rekognition: Detect Labels from S3 object
    DetectLabelsRequest req = new DetectLabelsRequest()
        .withImage(new Image().withS3Object(new S3Object().withBucket(bucket).withName(key)))
        .withMinConfidence(minConfidence);
    DetectLabelsResult result;
    result = rek.detectLabels(req);
    List<Label> labels = result.getLabels();
    Logger.Debug("In %s, found: %s", key, labels);

    // Process downstream actions:
    for (LabelProcessor processor : processors) {
        processor.process(labels, path);
    }
}
 
開發者ID:jhy,項目名稱:RekognitionS3Batch,代碼行數:22,代碼來源:Processor.java

示例4: process

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
private void process(final List<Message> messages) {
  if (messages.size() == 0) return;

  final List<DeleteMessageBatchRequestEntry> toDelete = new ArrayList<>();
  int count = 0;
  for (Message message : messages) {
    final String deleteId = String.valueOf(count++);
    try {
      String stringBody = message.getBody();
      if (stringBody.isEmpty()) continue;
      // allow plain-text json, but permit base64 encoded thrift or json
      byte[] spans = stringBody.charAt(0) == '['
          ? stringBody.getBytes(UTF_8)
          : Base64.decode(stringBody);
      collector.acceptSpans(spans, DETECTING_DECODER, new Callback<Void>() {
        @Override public void onSuccess(Void value) {
          toDelete.add(new DeleteMessageBatchRequestEntry(deleteId, message.getReceiptHandle()));
        }

        @Override public void onError(Throwable t) {
          // don't delete messages. this will allow accept calls retry once the
          // messages are marked visible by sqs.
          logger.log(Level.WARNING, "collector accept failed", t);
        }
      });
    } catch (RuntimeException | Error e) {
      logger.log(Level.WARNING, "message decoding failed", e);
      toDelete.add(new DeleteMessageBatchRequestEntry(deleteId, message.getReceiptHandle()));
    }
  }

  delete(toDelete);
}
 
開發者ID:openzipkin,項目名稱:zipkin-aws,代碼行數:34,代碼來源:SQSSpanProcessor.java

示例5: run

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
public void run() {
    while (receiveMessages) {
        try {
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(getQueueUrl());
            List<Message> messages = amazonSQS.receiveMessage(receiveMessageRequest).getMessages();
            for (Message message : messages) {
                JSONObject obj = new JSONObject(message.getBody());
                String msg = obj.get("Message").toString();
                JSONObject jsonMessage = new JSONObject(msg);
                if (jsonMessage.has("Event")) {
                    AutoScalingEvents event = AutoScalingEvents.fromString((String) jsonMessage.get("Event"));
                    switch (event) {
                        case EC2_INSTANCE_TERMINATE: {
                            if (eventsRepository.findOne(message.getMessageId()) == null) {
                                clusterEventPublisher.nodeTerminated((String) jsonMessage.get("EC2InstanceId"), message.getMessageId());
                                amazonSQS.deleteMessage(new DeleteMessageRequest()
                                        .withQueueUrl(getQueueUrl()).withReceiptHandle(message.getReceiptHandle()));
                            }
                            break;
                        }
                        default: {
                            LOG.warn("New AutoScaling event: {}", message.toString());
                            amazonSQS.deleteMessage(new DeleteMessageRequest()
                                    .withQueueUrl(getQueueUrl()).withReceiptHandle(message.getReceiptHandle()));
                        }
                    }
                } else {
                    LOG.warn("Unknown event: {}", message.toString());
                    amazonSQS.deleteMessage(new DeleteMessageRequest()
                            .withQueueUrl(getQueueUrl()).withReceiptHandle(message.getReceiptHandle()));
                }
            }
        } catch (Exception e) {
            LOG.error("Unable to process AutoScaling event", e);
        }
        sleep();
    }
}
 
開發者ID:SungardAS,項目名稱:enhanced-snapshots,代碼行數:39,代碼來源:AutoScalingEventListener.java

示例6: poll

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
@Override
public void poll(long waitInterval ) {
	Properties properties = new Properties();
	
	String access_key_id = getProperty("AccessKeyId");
       String secret_access_key = getProperty("SecretAccessKey");
       BasicAWSCredentials credentials = new BasicAWSCredentials(access_key_id, secret_access_key);
	
       AmazonSQS sqs = new AmazonSQSClient(credentials);
       
       // Region selection
       Region region = Region.getRegion(Regions.fromName(getProperty("region")));
       sqs.setRegion(region);
       
       GetQueueUrlResult queueUrl = sqs.getQueueUrl(getProperty("Queue"));
       
       ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl.getQueueUrl());
       List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
       
       String outputMessage = "";
       // if there are messages then do the processing
       if(messages.size() > 0){
       	
       	//append the message properties to the localenv tree
       	for (Message message : messages) {
               properties.setProperty("MessageId", message.getMessageId());
               properties.setProperty("ReceiptHandle", message.getReceiptHandle());
               properties.setProperty("MD5OfBody", message.getMD5OfBody());
               // get the message body to a string
               outputMessage = message.getBody();
           }
       	properties.setProperty("queueUrl", queueUrl.getQueueUrl());
           // delete the message from the queue
           String messageReceiptHandle = messages.get(0).getReceiptHandle();
           sqs.deleteMessage(new DeleteMessageRequest(queueUrl.getQueueUrl(), messageReceiptHandle));
           ConnectorCallback callback = getCallback();
   		callback.processInboundData(outputMessage.getBytes(), properties);
       }
}
 
開發者ID:ot4i,項目名稱:amazon-sqs-connector,代碼行數:40,代碼來源:AmazonSQSInputConnector.java

示例7: setSqsAttributesOnRecord

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
private void setSqsAttributesOnRecord(Message message, Record record, String queueUrl, String queueNamePrefix) {
  final Record.Header header = record.getHeader();

  switch (sqsAttributesOption) {
    case ALL:
      header.setAttribute(SQS_QUEUE_URL_ATTRIBUTE, queueUrl);
      Optional.of(message.getMessageAttributes()).ifPresent(attrs -> {
        attrs.forEach((name, val) -> {
          final String stringValue = val.getStringValue();
          if (stringValue != null) {
            header.setAttribute(SQS_MESSAGE_ATTRIBUTE_PREFIX + name, stringValue);
          }
        });
      });
      final String body = message.getBody();
      if (body != null) {
        header.setAttribute(SQS_MESSAGE_BODY_ATTRIBUTE, body);
      }
      final String bodyMd5 = message.getMD5OfBody();
      if (bodyMd5 != null) {
        header.setAttribute(SQS_MESSAGE_BODY_MD5_ATTRIBUTE, bodyMd5);
      }
      final String attrsMd5 = message.getMD5OfMessageAttributes();
      if (attrsMd5 != null) {
        header.setAttribute(SQS_MESSAGE_ATTRIBUTE_MD5_ATTRIBUTE, attrsMd5);
      }
      // fall through
    case BASIC:
      header.setAttribute(SQS_MESSAGE_ID_ATTRIBUTE, message.getMessageId());
      header.setAttribute(SQS_QUEUE_NAME_PREFIX_ATTRIBUTE, queueNamePrefix);
      header.setAttribute(SQS_REGION_ATTRIBUTE, awsRegionLabel);
      break;
    case NONE:
      // empty block
      break;
  }
}
 
開發者ID:streamsets,項目名稱:datacollector,代碼行數:38,代碼來源:SqsConsumerWorkerCallable.java

示例8: peek

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
@Override
public JSONArray peek(int max) throws Exception {
    ReceiveMessageRequest request = new ReceiveMessageRequest()
        .withQueueUrl(this.queueUrl).withMaxNumberOfMessages(max);
    ReceiveMessageResult result = this.client.receiveMessage(request);
    JSONArray array = new JSONArray();
    for (Message message : result.getMessages()) {
        JSONObject obj = new JSONObject(message.getBody());
        this.receipts.add(message.getReceiptHandle());
        obj.put(ITEM_RECEIPT, message.getReceiptHandle());
        obj.put(ITEM_MESSAGE_ID, message.getMessageId());
        array.put(obj);
    }
    return array;
}
 
開發者ID:mychaelstyle,項目名稱:generic-queue,代碼行數:16,代碼來源:AwsSQS.java

示例9: remoteBatchReceive

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
	public void remoteBatchReceive(PrintWriter out) throws ParseException{
    	JSONArray responseList = new JSONArray();
    	JSONParser parser=new JSONParser();
    	    	
    	while(msg_cnt > 0){ 
	    	while(resQ.getQueueSize() > 0){
	    		//Get up to 10 messages
	    		 List<Message> messages = resQ.batchReceive();
			      		     
			     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());
		          
		            //Get task
		            String messageBody = message.getBody();		           
		            JSONObject resp = (JSONObject)parser.parse(messageBody);
		            responseList.add(resp);
		            		            	            
		            msg_cnt--;
		            // Delete the message
                    String messageRecieptHandle = message.getReceiptHandle();
                    resQ.deleteMessage(messageRecieptHandle);

		        }
			    if(!responseList.isEmpty()){
			    	 out.println(responseList.toString());
			    	 responseList.clear();
			    }
			    
	    	}
    	}  	 
    }
 
開發者ID:cs553-cloud-computing,項目名稱:amazon-cloudengine,代碼行數:37,代碼來源:ServerThread.java

示例10: handle

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
@Override
public void handle(Message message) throws Exception {
    String messageBody = message.getBody();
    AmazonSNSMessage sns = JSON_MAPPER.readValue(messageBody, AmazonSNSMessage.class);
    String decryptedMessage = messageDeserializer.decrypt(sns.getMessage());
    String eventName = sns.getSubject();
    String typeName = sns.getType();
    if (empty(eventName) && empty(typeName)) {
        throw new MessagingException(
                "Received message without event name or type. MessageDispatcher requires a message subject or type "
                + "in order to know which handler to route the message to. Make sure that you publish your message "
                + "with a message subject or type before trying to receive it."
        );
    }
    if (!empty(eventName) && messageHandlersPerEventName.containsKey(eventName)) {
        messageHandlersPerEventName.get(eventName).callAllHandlers(decryptedMessage);
    } else if (!empty(typeName) && messageHandlersPerEventName.containsKey(typeName)) {
        messageHandlersPerEventName.get(typeName).callAllHandlers(decryptedMessage);
    } else {
        if (empty(defaultMessageHandlers)) {
            throw new MessagingException(
                "No handlers for message with event: " + eventName + " and type: " + typeName
            );
        }
        callAllHandlers(defaultMessageHandlers, sns);
    }
}
 
開發者ID:iZettle,項目名稱:izettle-toolbox,代碼行數:28,代碼來源:MessageDispatcher.java

示例11: doReceive

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
protected void doReceive() {
	// This is where the interesting stuff happens
	while (isListening()) {
		synchronized (this.monitor) {
			try {
				this.monitor.wait(this.getVisibilityTimeout() * 1000);
			} catch (InterruptedException e) {

			}
		}
		boolean messagesReceived = false;
		do {
			ReceiveMessageRequest request = new ReceiveMessageRequest().withQueueUrl(this.queueUrl)
					.withWaitTimeSeconds(1).withMaxNumberOfMessages(10);
			ReceiveMessageResult result = sqs.receiveMessage(request);
			List<Message> messages = result.getMessages();
			messagesReceived = messages.size() > 0;
			if (!messagesReceived) {
				break;
			}
			List<DeleteMessageBatchRequestEntry> deletes = new ArrayList<DeleteMessageBatchRequestEntry>();
			for (Message message : messages) {
				String messageBody = message.getBody();
				try {
					this.messageConsumer.accept(messageBody);
					DeleteMessageBatchRequestEntry entry = new DeleteMessageBatchRequestEntry(
							UUID.randomUUID().toString(), message.getReceiptHandle());
					deletes.add(entry);
				} catch (Throwable exp) {
					Logger.getLogger(getSqsQueueName()).log(Level.WARNING,
							"Could not process message: " + messageBody, exp);
				}
			}
			if (!deletes.isEmpty()) {
				DeleteMessageBatchRequest deleteBatch = new DeleteMessageBatchRequest(this.queueUrl, deletes);
				sqs.deleteMessageBatch(deleteBatch);
			}
		} while (messagesReceived);
	}

}
 
開發者ID:olegdulin,項目名稱:sqs-retryqueue,代碼行數:42,代碼來源:SQSRetryQueue.java

示例12: toMessage

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
@Override
protected BasicMessage toMessage(final Message sqsMessage) {
    return new SimpleBasicMessage(sqsMessage.getBody(), sqsMessage.getMessageId(), sqsMessage.getReceiptHandle());
}
 
開發者ID:travel-cloud,項目名稱:Cheddar,代碼行數:5,代碼來源:SqsBasicMessageQueue.java

示例13: SQSTextMessage

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
/**
 * Convert received SQSMessage into TextMessage.
 */
public SQSTextMessage(Acknowledger acknowledger, String queueUrl, Message sqsMessage) throws JMSException{
    super(acknowledger, queueUrl, sqsMessage);
    this.text = sqsMessage.getBody();
}
 
開發者ID:awslabs,項目名稱:amazon-sqs-java-messaging-lib,代碼行數:8,代碼來源:SQSTextMessage.java

示例14: SQSObjectMessage

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
/**
 * Convert received SQSMessage into ObjectMessage
 */
public SQSObjectMessage(Acknowledger acknowledger, String queueUrl, Message sqsMessage) throws JMSException {
    super(acknowledger, queueUrl, sqsMessage);
    body = sqsMessage.getBody();
}
 
開發者ID:awslabs,項目名稱:amazon-sqs-java-messaging-lib,代碼行數:8,代碼來源:SQSObjectMessage.java

示例15: getMessageId

import com.amazonaws.services.sqs.model.Message; //導入方法依賴的package包/類
/**
 * Read `MessageId` from given message.body
 *
 * @param message
 * @return Message Id
 * */
@CheckForNull
public static String getMessageId(Message message) {
    String body = message.getBody();
    return StringUtils.findByUniqueJsonKey(body, "MessageId");
}
 
開發者ID:riboseinc,項目名稱:aws-codecommit-trigger-plugin,代碼行數:12,代碼來源:StringUtils.java


注:本文中的com.amazonaws.services.sqs.model.Message.getBody方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。