List of usage examples for org.springframework.amqp.core MessageProperties getHeaders
public Map<String, Object> getHeaders()
From source file:com.jbrisbin.vpc.jobsched.SecureMessageConverter.java
public boolean isAuthorized(MessageProperties props) { Object incomingKey = props.getHeaders().get(SECURITY_KEY_HDR); return (null == incomingKey ? false : incomingKey.toString().equals(securityKey)); }
From source file:org.carewebframework.amqp.rabbitmq.Subscriber.java
@Override protected void invokeListener(Channel channel, Message message) throws Exception { MessageProperties props = message.getMessageProperties(); String recipients = props == null ? null : (String) props.getHeaders().get(Broker.RECIPIENTS_PROPERTY); boolean found = true; if (recipients != null) { for (String recipient : recipients.split("\\,")) { found = recipientIds.contains(recipient); if (found) { break; }/*from w ww. ja v a2s. c o m*/ } } if (found) { super.invokeListener(channel, message); } }
From source file:com.jbrisbin.vpc.jobsched.RequeueListener.java
@Override public void onMessage(Message message, Channel channel) throws Exception { MessageProperties props = message.getMessageProperties(); Map<String, Object> headers = props.getHeaders(); int requeued = 0; if (headers.containsKey(REQUEUED)) { requeued = (Integer) headers.get(REQUEUED); }/*from w w w .j a v a 2s . com*/ long delay = retryDelays[requeued]; if (requeued < maxRetries) { headers.put(REQUEUED, requeued + 1); Object exchange = headers.get("exchange"); if (null == exchange) { exchange = props.getReceivedExchange(); } else { headers.remove("exchange"); } Object route = headers.get("route"); if (null == route) { route = props.getReceivedRoutingKey(); } else { headers.remove("route"); } log.info(String.format("Requeing message %s in %s...", new String(props.getCorrelationId()), convertMillis(delay))); timer.schedule(new DelayedSend(message, exchange.toString(), route.toString()), delay); } }
From source file:com.jbrisbin.vpc.jobsched.SubmitClosure.java
@Override public Object call(Object[] args) { log.debug("args: " + args); String exch = args[0].toString(); String route = args[1].toString(); final Object body = args[2]; Map headers = null;/*w ww.j a v a2s . c o m*/ final BlockingQueue<Object> resultsQueue = new LinkedBlockingQueue<Object>(); Queue replyQueue = rabbitAdmin.declareQueue(); SimpleMessageListenerContainer listener = new SimpleMessageListenerContainer(); listener.setQueues(replyQueue); if (args.length > 3) { for (int i = 3; i <= args.length; i++) { if (args[i] instanceof MessageListener) { MessageListener callback = (MessageListener) args[3]; listener.setMessageListener(callback); } else if (args[i] instanceof Map) { headers = (Map) args[i]; } } } else { listener.setMessageListener(new MessageListener() { public void onMessage(Message message) { byte[] body = message.getBody(); try { resultsQueue.add(mapper.readValue(body, 0, body.length, Map.class)); } catch (IOException e) { log.error(e.getMessage(), e); } } }); } final Map msgHdrs = headers; rabbitTemplate.send(exch, route, new MessageCreator() { public Message createMessage() { MessageProperties props = new RabbitMessageProperties(); props.setContentType("application/json"); if (null != msgHdrs) { props.getHeaders().putAll(msgHdrs); } String uuid = UUID.randomUUID().toString(); props.setCorrelationId(uuid.getBytes()); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { mapper.writeValue(out, body); } catch (IOException e) { log.error(e.getMessage(), e); } Message msg = new Message(out.toByteArray(), props); return msg; } }); Object results = null; try { results = resultsQueue.poll(5, TimeUnit.SECONDS); } catch (InterruptedException e) { log.error(e.getMessage(), e); } listener.stop(); return results; }
From source file:com.jbrisbin.vpc.jobsched.batch.BatchMessageConverter.java
public Object fromMessage(Message message) throws MessageConversionException { MessageProperties props = message.getMessageProperties(); if (isAuthorized(props) && props.getContentType().equals("application/zip")) { BatchMessage msg = new BatchMessage(); msg.setId(new String(props.getCorrelationId())); String timeout = "2"; if (props.getHeaders().containsKey("timeout")) { timeout = props.getHeaders().get("timeout").toString(); }/* w w w . j a va2 s. c om*/ msg.setTimeout(Integer.parseInt(timeout)); ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(message.getBody())); ZipEntry zentry; try { while (null != (zentry = zin.getNextEntry())) { byte[] buff = new byte[4096]; StringWriter json = new StringWriter(); for (int bytesRead = 0; bytesRead > -1; bytesRead = zin.read(buff)) { json.write(new String(buff, 0, bytesRead)); } msg.getMessages().put(zentry.getName(), json.toString()); } } catch (IOException e) { throw new MessageConversionException(e.getMessage(), e); } return msg; } else { throw new MessageConversionException("Invalid security key."); } }
From source file:com.jbrisbin.vpc.jobsched.mapred.MapReduceMessageConverter.java
public Object fromMessage(Message message) throws MessageConversionException { MessageProperties props = message.getMessageProperties(); if (isAuthorized(props)) { //Map<String, Object> headers = props.getHeaders(); byte[] bytes = message.getBody(); MapReduceMessage msg = new MapReduceMessage(); msg.setId(new String(props.getCorrelationId())); try {//w w w .ja v a 2 s . com msg.setReplyTo(props.getReplyTo().toString()); } catch (NullPointerException ignored) { } msg.setKey(props.getHeaders().get("mapreduce.key").toString()); msg.setSrc(props.getHeaders().get("mapreduce.src").toString()); msg.setType(props.getReceivedRoutingKey()); try { try { msg.setData(mapObject(bytes, List.class)); } catch (JsonMappingException e1) { try { msg.setData(mapObject(bytes, Map.class)); } catch (JsonMappingException e2) { try { msg.setData(mapObject(bytes, Integer.class)); } catch (JsonMappingException e3) { try { msg.setData(mapObject(bytes, String.class)); } catch (JsonMappingException e4) { } } } } } catch (IOException ioe) { throw new MessageConversionException(ioe.getMessage(), ioe); } return msg; } else { throw new MessageConversionException("Invalid security key."); } }
From source file:amqp.spring.converter.XStreamConverter.java
@Override protected Message createMessage(Object object, MessageProperties messageProperties) { try {/*from www. j ava 2 s .c o m*/ byte[] body = null; if (object != null) { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); StaxWriter writer = new StaxWriter(new QNameMap(), this.outputFactory.createXMLStreamWriter(outStream)); this.objectMapper.marshal(object, writer); body = outStream.toByteArray(); } messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON); messageProperties.setContentEncoding(this.encoding); messageProperties.setContentLength(body != null ? body.length : 0); classMapper.fromClass(object.getClass(), messageProperties); return new Message(body, messageProperties); } catch (XMLStreamException ex) { String typeId = (String) messageProperties.getHeaders() .get(DefaultClassMapper.DEFAULT_CLASSID_FIELD_NAME); LOG.error("XMLStreamException trying to marshal message of type {}", typeId, ex); throw new MessageConversionException("Could not marshal message of type " + typeId, ex); } catch (XStreamException ex) { //For some reason messages appear to be getting eaten at this stage... very nasty when you try to troubleshoot. String typeId = (String) messageProperties.getHeaders() .get(DefaultClassMapper.DEFAULT_CLASSID_FIELD_NAME); LOG.error("XStreamException trying to marshal message of type {}", typeId, ex); throw new MessageConversionException("Could not marshal message of type " + typeId, ex); } }
From source file:amqp.spring.converter.XStreamConverter.java
@Override public Object fromMessage(Message message) throws MessageConversionException { MessageProperties messageProperties = message.getMessageProperties(); if (messageProperties == null) throw new MessageConversionException("Cannot decode a message with no properties!"); byte[] body = message.getBody(); if (body == null) return null; String messageEncoding = messageProperties.getContentEncoding(); if (messageEncoding == null) messageEncoding = getEncoding(); String contentType = messageProperties.getContentType(); if (!MessageProperties.CONTENT_TYPE_JSON.equalsIgnoreCase(contentType)) throw new MessageConversionException("Cannot understand a message of type " + contentType); try {// w ww . j av a 2 s . c om ByteArrayInputStream inStream = new ByteArrayInputStream(body); StaxReader reader = new StaxReader(new QNameMap(), this.inputFactory.createXMLStreamReader(inStream, messageEncoding)); return this.objectMapper.unmarshal(reader); } catch (XMLStreamException ex) { String typeId = (String) messageProperties.getHeaders() .get(DefaultClassMapper.DEFAULT_CLASSID_FIELD_NAME); LOG.error("XMLStreamException trying to unmarshal message of type {}", typeId, ex); throw new MessageConversionException("Could not unmarshal message of type " + typeId, ex); } catch (XStreamException ex) { //For some reason messages appear to be getting eaten at this stage... very nasty when you try to troubleshoot. String typeId = (String) messageProperties.getHeaders() .get(DefaultClassMapper.DEFAULT_CLASSID_FIELD_NAME); LOG.error("XStreamException trying to unmarshal message of type {}", typeId, ex); throw new MessageConversionException("Could not unmarshal message of type " + typeId, ex); } }
From source file:org.kurento.rabbitmq.RabbitTemplate.java
/** * Send the given message to the specified exchange. * * @param channel/*from w ww .j a va2 s .c om*/ * The RabbitMQ Channel to operate within. * @param exchange * The name of the RabbitMQ exchange to send to. * @param routingKey * The routing key. * @param message * The Message to send. * @param correlationData * The correlation data. * @throws IOException * If thrown by RabbitMQ API methods */ protected void doSend(Channel channel, String exchange, String routingKey, Message message, CorrelationData correlationData) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Publishing message on exchange [" + exchange + "], routingKey = [" + routingKey + "]"); } if (exchange == null) { // try to send to configured exchange exchange = this.exchange; } if (routingKey == null) { // try to send to configured routing key routingKey = this.routingKey; } if (this.confirmCallback != null && channel instanceof PublisherCallbackChannel) { PublisherCallbackChannel publisherCallbackChannel = (PublisherCallbackChannel) channel; publisherCallbackChannel.addPendingConfirm(this, channel.getNextPublishSeqNo(), new PendingConfirm(correlationData, System.currentTimeMillis())); } boolean mandatory = this.returnCallback != null && this.mandatory; MessageProperties messageProperties = message.getMessageProperties(); if (mandatory) { messageProperties.getHeaders().put(PublisherCallbackChannel.RETURN_CORRELATION, this.uuid); } BasicProperties convertedMessageProperties = this.messagePropertiesConverter .fromMessageProperties(messageProperties, encoding); channel.basicPublish(exchange, routingKey, mandatory, convertedMessageProperties, message.getBody()); // Check if commit needed if (isChannelLocallyTransacted(channel)) { // Transacted channel created by this template -> commit. RabbitUtils.commitIfNecessary(channel); } }
From source file:org.kurento.rabbitmq.RabbitTemplate.java
@SuppressWarnings("unchecked") private <R, S> boolean doReceiveAndReply(final String queueName, final ReceiveAndReplyCallback<R, S> callback, final ReplyToAddressCallback<S> replyToAddressCallback) throws AmqpException { return this.execute(new ChannelCallback<Boolean>() { @Override// www. ja v a 2s.c o m public Boolean doInRabbit(Channel channel) throws Exception { boolean channelTransacted = RabbitTemplate.this.isChannelTransacted(); GetResponse response = channel.basicGet(queueName, !channelTransacted); // Response can be null in the case that there is no message on // the queue. if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); boolean channelLocallyTransacted = RabbitTemplate.this.isChannelLocallyTransacted(channel); if (channelLocallyTransacted) { channel.basicAck(deliveryTag, false); } else if (channelTransacted) { // Not locally transacted but it is transacted so it // could be synchronized with an external transaction ConnectionFactoryUtils.registerDeliveryTag(RabbitTemplate.this.getConnectionFactory(), channel, deliveryTag); } Message receiveMessage = RabbitTemplate.this.buildMessageFromResponse(response); Object receive = receiveMessage; if (!(ReceiveAndReplyMessageCallback.class.isAssignableFrom(callback.getClass()))) { receive = RabbitTemplate.this.getRequiredMessageConverter().fromMessage(receiveMessage); } S reply; try { reply = callback.handle((R) receive); } catch (ClassCastException e) { StackTraceElement[] trace = e.getStackTrace(); if (trace[0].getMethodName().equals("handle") && trace[1].getFileName().equals("RabbitTemplate.java")) { throw new IllegalArgumentException("ReceiveAndReplyCallback '" + callback + "' can't handle received object '" + receive + "'", e); } else { throw e; } } if (reply != null) { Address replyTo = replyToAddressCallback.getReplyToAddress(receiveMessage, reply); Message replyMessage = RabbitTemplate.this.convertMessageIfNecessary(reply); MessageProperties receiveMessageProperties = receiveMessage.getMessageProperties(); MessageProperties replyMessageProperties = replyMessage.getMessageProperties(); Object correlation = RabbitTemplate.this.correlationKey == null ? receiveMessageProperties.getCorrelationId() : receiveMessageProperties.getHeaders().get(RabbitTemplate.this.correlationKey); if (RabbitTemplate.this.correlationKey == null || correlation == null) { // using standard correlationId property if (correlation == null) { String messageId = receiveMessageProperties.getMessageId(); if (messageId != null) { correlation = messageId.getBytes(RabbitTemplate.this.encoding); } } replyMessageProperties.setCorrelationId((byte[]) correlation); } else { replyMessageProperties.setHeader(RabbitTemplate.this.correlationKey, correlation); } // 'doSend()' takes care about 'channel.txCommit()'. RabbitTemplate.this.doSend(channel, replyTo.getExchangeName(), replyTo.getRoutingKey(), replyMessage, null); } else if (channelLocallyTransacted) { channel.txCommit(); } return true; } return false; } }); }