Example usage for org.springframework.amqp.core MessageProperties getCorrelationId

List of usage examples for org.springframework.amqp.core MessageProperties getCorrelationId

Introduction

In this page you can find the example usage for org.springframework.amqp.core MessageProperties getCorrelationId.

Prototype

public String getCorrelationId() 

Source Link

Document

Get the correlation id.

Usage

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. jav  a  2s.  co  m*/
        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 {//from ww  w.  j ava2s  . c o  m
            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:com.jbrisbin.vpc.jobsched.sql.SqlMessageConverter.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();
        SqlMessage msg;/*from www. j  a va  2s . c o m*/
        try {
            msg = mapObject(bytes, SqlMessage.class);
            msg.setId(new String(props.getCorrelationId()));
            msg.setReplyTo(props.getReplyTo().toString());
            if (log.isDebugEnabled()) {
                log.debug(String.format(" MSG: %s", msg));
            }
        } 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.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  ww .j a  va2 s .  c  om*/

    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.ushahidi.swiftriver.core.dropqueue.MetadataResponseHandlerTest.java

@Test
public void onRulesMessage() throws Exception {
    Message mockMessage = mock(Message.class);
    MessageProperties mockMessageProperties = mock(MessageProperties.class);
    Channel mockChannel = mock(Channel.class);

    String body = "{\"source\":\"rules\",\"identity_orig_id\": \"http://feeds.bbci.co.uk/news/rss.xml\", \"droplet_raw\": \"The danger of growing resistance to antibiotics should be treated as seriously as the threat of terrorism, England's chief medical officer says.\", \"droplet_orig_id\": \"c558d88a44fc70da36d04746574e05e4\", \"droplet_locale\": \"en-gb\", \"identity_username\": \"http://www.bbc.co.uk/news/#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa\", \"droplet_date_pub\": \"Mon, 11 Mar 2013 07:32:59 +0000\", \"droplet_type\": \"original\", \"identity_avatar\": \"http://news.bbcimg.co.uk/nol/shared/img/bbc_news_120x60.gif\", \"droplet_title\": \"Antibiotic resistance 'threat to UK'\", \"links\": [{\"url\": \"http://www.bbc.co.uk/news/health-21737844#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa\", \"original_url\": true}], \"droplet_content\": \"The danger of growing resistance to antibiotics should be treated as seriously as the threat of terrorism, England's chief medical officer says.\", \"identity_name\": \"BBC News - Home\", \"channel\": \"rss\", \"river_id\": [2]}";
    when(mockMessage.getBody()).thenReturn(body.getBytes());
    when(mockMessage.getMessageProperties()).thenReturn(mockMessageProperties);
    when(mockMessageProperties.getCorrelationId()).thenReturn("correlation_id".getBytes());

    RawDrop rawDrop = new RawDrop();
    dropsMap.put("correlation_id", rawDrop);

    metadataResponseHandler.onMessage(mockMessage, mockChannel);
    assertTrue(rawDrop.isRulesComplete());
}

From source file:com.ushahidi.swiftriver.core.dropqueue.MetadataResponseHandlerTest.java

@Test
public void onSemanticsMessage() throws Exception {
    Message mockMessage = mock(Message.class);
    MessageProperties mockMessageProperties = mock(MessageProperties.class);
    Channel mockChannel = mock(Channel.class);

    String body = "{\"source\":\"semantics\",\"identity_orig_id\": \"http://feeds.bbci.co.uk/news/rss.xml\", \"droplet_raw\": \"The danger of growing resistance to antibiotics should be treated as seriously as the threat of terrorism, England's chief medical officer says.\", \"droplet_orig_id\": \"c558d88a44fc70da36d04746574e05e4\", \"droplet_locale\": \"en-gb\", \"identity_username\": \"http://www.bbc.co.uk/news/#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa\", \"droplet_date_pub\": \"Mon, 11 Mar 2013 07:32:59 +0000\", \"droplet_type\": \"original\", \"identity_avatar\": \"http://news.bbcimg.co.uk/nol/shared/img/bbc_news_120x60.gif\", \"droplet_title\": \"Antibiotic resistance 'threat to UK'\", \"links\": [{\"url\": \"http://www.bbc.co.uk/news/health-21737844#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa\", \"original_url\": true}], \"droplet_content\": \"The danger of growing resistance to antibiotics should be treated as seriously as the threat of terrorism, England's chief medical officer says.\", \"identity_name\": \"BBC News - Home\", \"channel\": \"rss\", \"river_id\": [2]}";
    when(mockMessage.getBody()).thenReturn(body.getBytes());
    when(mockMessage.getMessageProperties()).thenReturn(mockMessageProperties);
    when(mockMessageProperties.getCorrelationId()).thenReturn("correlation_id".getBytes());

    RawDrop rawDrop = new RawDrop();
    dropsMap.put("correlation_id", rawDrop);

    metadataResponseHandler.onMessage(mockMessage, mockChannel);

    assertTrue(rawDrop.isSemanticsComplete());
}

From source file:com.ushahidi.swiftriver.core.dropqueue.MetadataResponseHandlerTest.java

@Test
public void onMediaExtractorMessage() throws Exception {
    Message mockMessage = mock(Message.class);
    MessageProperties mockMessageProperties = mock(MessageProperties.class);
    Channel mockChannel = mock(Channel.class);

    String body = "{\"source\":\"mediaextractor\",\"identity_orig_id\": \"http://feeds.bbci.co.uk/news/rss.xml\", \"droplet_raw\": \"The danger of growing resistance to antibiotics should be treated as seriously as the threat of terrorism, England's chief medical officer says.\", \"droplet_orig_id\": \"c558d88a44fc70da36d04746574e05e4\", \"droplet_locale\": \"en-gb\", \"identity_username\": \"http://www.bbc.co.uk/news/#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa\", \"droplet_date_pub\": \"Mon, 11 Mar 2013 07:32:59 +0000\", \"droplet_type\": \"original\", \"identity_avatar\": \"http://news.bbcimg.co.uk/nol/shared/img/bbc_news_120x60.gif\", \"droplet_title\": \"Antibiotic resistance 'threat to UK'\", \"links\": [{\"url\": \"http://www.bbc.co.uk/news/health-21737844#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa\", \"original_url\": true}], \"droplet_content\": \"The danger of growing resistance to antibiotics should be treated as seriously as the threat of terrorism, England's chief medical officer says.\", \"identity_name\": \"BBC News - Home\", \"channel\": \"rss\", \"river_id\": [2]}";
    when(mockMessage.getBody()).thenReturn(body.getBytes());
    when(mockMessage.getMessageProperties()).thenReturn(mockMessageProperties);
    when(mockMessageProperties.getCorrelationId()).thenReturn("correlation_id".getBytes());

    RawDrop rawDrop = new RawDrop();
    dropsMap.put("correlation_id", rawDrop);

    metadataResponseHandler.onMessage(mockMessage, mockChannel);

    assertTrue(rawDrop.isMediaComplete());
}

From source file:com.ushahidi.swiftriver.core.dropqueue.MetadataResponseHandlerTest.java

@Test
public void onMessage() throws Exception {
    Message mockMessage = mock(Message.class);
    MessageProperties mockMessageProperties = mock(MessageProperties.class);
    Channel mockChannel = mock(Channel.class);

    String body = "{\"source\":\"rules\",\"identity_orig_id\": \"http://feeds.bbci.co.uk/news/rss.xml\", \"droplet_raw\": \"The danger of growing resistance to antibiotics should be treated as seriously as the threat of terrorism, England's chief medical officer says.\", \"droplet_orig_id\": \"c558d88a44fc70da36d04746574e05e4\", \"droplet_locale\": \"en-gb\", \"identity_username\": \"http://www.bbc.co.uk/news/#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa\", \"droplet_date_pub\": \"Mon, 11 Mar 2013 07:32:59 +0000\", \"droplet_type\": \"original\", \"identity_avatar\": \"http://news.bbcimg.co.uk/nol/shared/img/bbc_news_120x60.gif\", \"droplet_title\": \"Antibiotic resistance 'threat to UK'\", \"links\": [{\"url\": \"http://www.bbc.co.uk/news/health-21737844#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa\", \"original_url\": true}], \"droplet_content\": \"The danger of growing resistance to antibiotics should be treated as seriously as the threat of terrorism, England's chief medical officer says.\", \"identity_name\": \"BBC News - Home\", \"channel\": \"rss\", \"river_id\": [2]}";
    when(mockMessage.getBody()).thenReturn(body.getBytes());
    when(mockMessage.getMessageProperties()).thenReturn(mockMessageProperties);
    when(mockMessageProperties.getCorrelationId()).thenReturn("correlation_id".getBytes());

    RawDrop rawDrop = new RawDrop();
    List<Long> riverIds = new ArrayList<Long>();
    riverIds.add(2L);/* www.  j a  va 2s  .c o m*/

    rawDrop.setSemanticsComplete(true);
    rawDrop.setMediaComplete(true);
    rawDrop.setRulesComplete(true);
    rawDrop.setRiverIds(riverIds);
    dropsMap.put("correlation_id", rawDrop);
    deliveryFramesMap.put("correlation_id", new DeliveryFrame(22, mockChannel));

    int size = dropFilterQueue.size();
    metadataResponseHandler.onMessage(mockMessage, mockChannel);
    assertTrue(dropsMap.isEmpty());
    assertTrue(publishQueue.contains(rawDrop));
    assertEquals(size + 1, dropFilterQueue.size());
    assertTrue(deliveryFramesMap.isEmpty());
}

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/*w w  w .j a  v a2s  .c  om*/
        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;
        }
    });
}

From source file:com.ushahidi.swiftriver.core.rules.DropFilterQueueConsumerTest.java

@Test
public void onMessage() throws Exception {
    Message mockMessage = mock(Message.class);
    Channel mockChannel = mock(Channel.class);
    MessageProperties mockMessageProperties = mock(MessageProperties.class);

    String dropJSON = "{\"source\":\"semantics\",\"identity_orig_id\": \"http://feeds.bbci.co.uk/news/rss.xml\", \"droplet_raw\": \"The danger of growing resistance to antibiotics should be treated as seriously as the threat of terrorism, England's chief medical officer says.\", \"droplet_orig_id\": \"c558d88a44fc70da36d04746574e05e4\", \"droplet_locale\": \"en-gb\", \"identity_username\": \"http://www.bbc.co.uk/news/#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa\", \"droplet_date_pub\": \"Mon, 11 Mar 2013 07:32:59 +0000\", \"droplet_type\": \"original\", \"identity_avatar\": \"http://news.bbcimg.co.uk/nol/shared/img/bbc_news_120x60.gif\", \"droplet_title\": \"Antibiotic resistance 'threat to UK'\", \"links\": [{\"url\": \"http://www.bbc.co.uk/news/health-21737844#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa\", \"original_url\": true}], \"droplet_content\": \"The danger of growing resistance to antibiotics should be treated as seriously as the threat of terrorism, England's chief medical officer says.\", \"identity_name\": \"BBC News - Home\", \"channel\": \"rss\", \"river_id\": [2], \"bucket_id\": []}";

    when(mockMessage.getBody()).thenReturn(dropJSON.getBytes());
    when(mockMessage.getMessageProperties()).thenReturn(mockMessageProperties);
    when(mockMessageProperties.getReplyTo()).thenReturn("reply-to-queue");
    when(mockMessageProperties.getCorrelationId()).thenReturn("drop-correlation-id".getBytes());

    // Send the drop to the rules executor
    dropFilterQueueConsumer.onMessage(mockMessage, mockChannel);

    ArgumentCaptor<RawDrop> dropArgument = ArgumentCaptor.forClass(RawDrop.class);
    ArgumentCaptor<String> routingKeyArgument = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<MessagePostProcessor> postProcessorArgument = ArgumentCaptor
            .forClass(MessagePostProcessor.class);

    verify(mockRulesExecutor).applyRules(dropArgument.capture(), rulesMapArgument.capture());
    verify(mockAmqpTemplate).convertAndSend(routingKeyArgument.capture(), dropArgument.capture(),
            postProcessorArgument.capture());

    String routingKey = routingKeyArgument.getValue();
    assertEquals("reply-to-queue", routingKey);
    RawDrop drop = dropArgument.getValue();
    assertEquals("rules", drop.getSource());

}