Example usage for com.rabbitmq.client BasicProperties getCorrelationId

List of usage examples for com.rabbitmq.client BasicProperties getCorrelationId

Introduction

In this page you can find the example usage for com.rabbitmq.client BasicProperties getCorrelationId.

Prototype

public abstract String getCorrelationId();

Source Link

Document

Retrieve the value in the correlationId field.

Usage

From source file:javarpc_server.JavaRPC_Server.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/*from   w  w  w.j  a  v a  2 s  .c o m*/
 * @throws java.lang.InterruptedException
 */
public static void main(String[] args) throws IOException, InterruptedException {
    // TODO code application logic here

    ConnectionFactory factory = new ConnectionFactory();
    System.out.println(factory.getUsername() + " " + factory.getPassword());
    factory.setHost("localhost");

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);

    channel.basicQos(1);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(RPC_QUEUE_NAME, false, consumer);

    System.out.println(" [x] Awaiting RPC requests");

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();

        BasicProperties props = delivery.getProperties();
        BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                .build();

        String message = new String(delivery.getBody());

        System.out.println(" [.] convert(" + message + ")");
        String response = "" + convert(message);

        channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes());

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
}

From source file:net.echinopsii.ariane.community.messaging.rabbitmq.MsgRequestActor.java

License:Open Source License

/**
 * {@link akka.actor.UntypedActor#onReceive(Object)} implementation.
 * if message instance of {@link com.rabbitmq.client.QueueingConsumer.Delivery} :
 * <br/> decode the message/* www .ja  v a2  s . c  o  m*/
 * <br/> then request treatment from attached worker and send reply if needed.
 * else unhandled
 * @param message the akka message received by actor
 * @throws IOException if problem encountered while publishing reply or ack request
 */
@Override
public void onReceive(Object message) throws IOException {
    if (message instanceof QueueingConsumer.Delivery) {
        Envelope envelope = ((QueueingConsumer.Delivery) message).getEnvelope();
        BasicProperties properties = ((QueueingConsumer.Delivery) message).getProperties();
        byte[] body = ((QueueingConsumer.Delivery) message).getBody();

        Map<String, Object> finalMessage = ((MsgTranslator) super.getTranslator())
                .decode(new Message().setEnvelope(envelope).setProperties(properties).setBody(body));
        if (((HashMap) finalMessage).containsKey(MomMsgTranslator.MSG_TRACE)) {
            if (super.getClient().isMsgDebugOnTimeout())
                ((MomLogger) log).setMsgTraceLevel(true);
            else
                finalMessage.remove(MomMsgTranslator.MSG_TRACE);
        }
        ((MomLogger) log).traceMessage("MsgRequestActor.onReceive - in", finalMessage);

        Map<String, Object> reply = null;
        if (finalMessage.get(MsgTranslator.MSG_CORRELATION_ID) != null
                && super.getReplyFromCache((String) finalMessage.get(MsgTranslator.MSG_CORRELATION_ID)) != null)
            reply = super.getReplyFromCache((String) finalMessage.get(MsgTranslator.MSG_CORRELATION_ID));
        if (reply == null)
            reply = super.getMsgWorker().apply(finalMessage);
        else
            log.debug("reply from cache !");

        if (finalMessage.get(MsgTranslator.MSG_CORRELATION_ID) != null)
            super.putReplyToCache((String) finalMessage.get(MsgTranslator.MSG_CORRELATION_ID), reply);

        if (properties.getReplyTo() != null && properties.getCorrelationId() != null && reply != null) {
            reply.put(MsgTranslator.MSG_CORRELATION_ID, properties.getCorrelationId());
            if (super.getClient().getClientID() != null)
                reply.put(MsgTranslator.MSG_APPLICATION_ID, super.getClient().getClientID());
            Message replyMessage = ((MsgTranslator) super.getTranslator()).encode(reply);
            String replyTo = properties.getReplyTo();
            channel.basicPublish("", replyTo, (AMQP.BasicProperties) replyMessage.getProperties(),
                    replyMessage.getBody());
        }
        channel.basicAck(((QueueingConsumer.Delivery) message).getEnvelope().getDeliveryTag(), false);

        ((MomLogger) log).traceMessage("MsgRequestActor.onReceive - out", finalMessage);
        if (((HashMap) finalMessage).containsKey(MomMsgTranslator.MSG_TRACE))
            ((MomLogger) log).setMsgTraceLevel(false);
    } else
        unhandled(message);
}

From source file:net.echinopsii.ariane.community.messaging.rabbitmq.MsgTranslator.java

License:Open Source License

/**
 * Decode given Message into Map message
 * @param message a RabbitMQ friendly message
 * @return Map message//w  w w . j  a v a 2  s .  co m
 */
@Override
public Map<String, Object> decode(Message message) {
    Envelope envelope = message.getEnvelope();
    BasicProperties properties = (BasicProperties) message.getProperties();
    byte[] body = message.getBody();

    LinkedHashMap<String, Object> decodedMessage = new LinkedHashMap<String, Object>();
    if (envelope != null) {
        decodedMessage.put(MSG_RBQ_DELIVERY_TAG, envelope.getDeliveryTag());
        decodedMessage.put(MSG_RBQ_EXCHANGE, envelope.getExchange());
        decodedMessage.put(MSG_RBQ_ROUTINGKEY, envelope.getRoutingKey());
    }

    if (properties != null) {
        decodedMessage.put(MSG_APPLICATION_ID, properties.getAppId());
        decodedMessage.put(MSG_RBQ_CONTENT_ENCODING, properties.getContentEncoding());
        decodedMessage.put(MSG_RBQ_CONTENT_TYPE, properties.getContentType());
        decodedMessage.put(MSG_CORRELATION_ID, properties.getCorrelationId());
        decodedMessage.put(MSG_DELIVERY_MODE, properties.getDeliveryMode());
        decodedMessage.put(MSG_EXPIRATION, properties.getExpiration());
        decodedMessage.put(MSG_MESSAGE_ID, properties.getMessageId());
        decodedMessage.put(MSG_PRIORITY, properties.getPriority());
        decodedMessage.put(MSG_REPLY_TO, properties.getReplyTo());
        decodedMessage.put(MSG_TIMESTAMP, properties.getTimestamp());
        decodedMessage.put(MSG_TYPE, properties.getType());
        decodedMessage.put(MSG_RBQ_USER_ID, properties.getUserId());
        Map<String, Object> headerFields = properties.getHeaders();
        if (headerFields != null) {
            for (String key : headerFields.keySet())
                if (headerFields.get(key) != null) {
                    if (headerFields.get(key) instanceof LongString)
                        decodedMessage.put(key, headerFields.get(key).toString());
                    else
                        decodedMessage.put(key, headerFields.get(key));
                } else
                    decodedMessage.put(key, headerFields.get(key));
        }
    }

    if (body.length == 0)
        decodedMessage.put(MSG_BODY, null);
    else
        decodedMessage.put(MSG_BODY, body);

    return decodedMessage;
}

From source file:net.es.netshell.controller.client.SdnControllerClient.java

License:Open Source License

/**
 * Listen for SdnReceivePacket messages, corresponding to PACKET_IN messages
 * received at the controller./*from w  ww.  jav  a 2  s  . c om*/
 */
public void run() {
    try {
        packetInChannel = connection.createChannel();

        // Create an emphemeral queue and bind it to the exchange so we can get
        // notifications.
        String queueName = packetInChannel.queueDeclare().getQueue();
        packetInChannel.queueBind(queueName, Common.notificationExchangeName, "");
        packetInChannel.basicQos(1);
        // Set up consumer to read from this queue on this channel
        packetInConsumer = new QueueingConsumer(packetInChannel);
        packetInChannel.basicConsume(queueName, false, packetInConsumer);
    } catch (Exception e) {
        e.printStackTrace();
    }

    while (true) {
        try {
            // Grab the next PACKET_IN
            QueueingConsumer.Delivery delivery = packetInConsumer.nextDelivery();

            // Get the properties for the request message, set up the properties
            // for the reply message.
            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();

            try {
                // Parse the body.  Get the string containing the JSON data.
                String message = new String(delivery.getBody(), "UTF-8");

                // Figure out the message type as a string so we know how to parse it.
                SdnReply rep = mapper.readValue(message, SdnReply.class);

                if (rep.getReplyType().equals(SdnReceivePacketReply.TYPE)) {
                    // Do PACKET_IN processing here.  Log, and invoke callback if it's
                    // been configured.
                    logger.debug("Got PACKET_IN");
                    SdnReceivePacketReply packetIn = mapper.readValue(message, SdnReceivePacketReply.class);
                    if (callback != null) {
                        callback.packetInCallback(packetIn.getDpid(), packetIn.getInPort(),
                                packetIn.getPayload());
                    }
                } else {
                    // Unknown message.
                    logger.error("Unknown message when PACKET_IN expected");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // ACK the old message
                packetInChannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            // We can get here if there was a problem reading a message from the AMPQ service.
            // Sleep for a second to avoid us busy-waiting in this loop.
            try {
                Thread.sleep(1000);
            } catch (Exception e2) {
            }
        }
    }
}

From source file:net.es.netshell.controller.impl.SdnController.java

License:Open Source License

public void run() {

    // Loop forever
    while (true) {
        try {/*w ww .  ja  v  a  2s  .  c  o m*/

            // Get the next message
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();

            // Get the properties for the request message, set up the properties
            // for the reply message.
            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();

            // Placeholder for a reply, if we have one to send
            String message2 = null;

            try {
                // Parse the body.  Get the string containing the JSON data.
                String message = new String(delivery.getBody(), "UTF-8");

                logger.info("Received: " + message);

                // Figure out the message type as a string so we know how to parse it.
                SdnRequest req = mapper.readValue(message, SdnRequest.class);
                SdnReply rep = null;

                // Dispatch to command handlers depending on the type of message
                //
                // Handle ping requests here since they're pretty trivial
                if (req.getRequestType().equals(SdnPingRequest.TYPE)) {
                    SdnPingRequest pingReq = mapper.readValue(message, SdnPingRequest.class);
                    SdnPingReply pingRep = new SdnPingReply();
                    pingRep.setError(false);
                    pingRep.setPayload(pingReq.getPayload());
                    rep = pingRep;
                }

                // Other request types dispatch to handler functions in this module.
                // Place in alphabetical order.
                else if (req.getRequestType().equals(SdnDeleteMeterRequest.TYPE)) {
                    SdnDeleteMeterRequest meterReq = mapper.readValue(message, SdnDeleteMeterRequest.class);
                    rep = doSdnDeleteMeter(meterReq);
                } else if (req.getRequestType().equals(SdnDeleteForwardRequest.TYPE)) {
                    SdnDeleteForwardRequest forwardReq = mapper.readValue(message,
                            SdnDeleteForwardRequest.class);
                    rep = doSdnDeleteForward(forwardReq);
                } else if (req.getRequestType().equals(SdnForwardRequest.TYPE)) {
                    SdnForwardRequest forwardReq = mapper.readValue(message, SdnForwardRequest.class);
                    rep = doSdnForward(forwardReq);
                } else if (req.getRequestType().equals(SdnForwardToControllerRequest.TYPE)) {
                    SdnForwardToControllerRequest flowReq = mapper.readValue(message,
                            SdnForwardToControllerRequest.class);
                    rep = doSdnForwardToController(flowReq);
                } else if (req.getRequestType().equals(SdnInstallMeterRequest.TYPE)) {
                    SdnInstallMeterRequest meterReq = mapper.readValue(message, SdnInstallMeterRequest.class);
                    rep = doSdnInstallMeter(meterReq);
                } else if (req.getRequestType().equals(SdnTransmitPacketRequest.TYPE)) {
                    SdnTransmitPacketRequest packetReq = mapper.readValue(message,
                            SdnTransmitPacketRequest.class);
                    rep = doSdnTransmitPacket(packetReq);
                } else {
                    // Unknown message.
                    rep = new SdnReply();
                    rep.setError(true);
                    rep.setErrorMessage("Unknown message type");
                }

                // If there's a response, then get it in JSON representation
                if (rep != null) {
                    message2 = mapper.writeValueAsString(rep);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // If we have a reply to send, then great, send it and ACK the old message
                if (message2 != null) {
                    logger.info("Reply: " + message2);
                    channel.basicPublish("", props.getReplyTo(), replyProps, message2.getBytes("UTF-8"));
                }
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // We can get here if there was a problem reading a message from the AMPQ service.
            // Sleep for a second to avoid us busy-waiting in this loop.
            try {
                Thread.sleep(1000);
            } catch (Exception e2) {
            }
        }
    }
}

From source file:org.apache.axis2.transport.amqp.common.AMQPUtils.java

License:Apache License

/**
 * Extract transport level headers for AMQP from the given message into a Map
 * //from  w  w  w. jav  a2  s  .c o  m
 * @param message
 *            the AMQP message
 * @return a Map of the transport headers
 * @throws AxisFault 
 */
public static Map<String, Object> getTransportHeaders(AMQPMessage message) throws AxisFault {
    // create a Map to hold transport headers
    Map<String, Object> map = new HashMap<String, Object>();
    Map<String, Object> headers = message.getProperties().getHeaders();
    BasicProperties msg_prop = message.getProperties();
    Envelope msg_env = message.getEnvelope();

    // correlation ID
    if (msg_prop.getCorrelationId() != null) {
        map.put(AMQPConstants.AMQP_CORRELATION_ID, msg_prop.getCorrelationId());
    }
    // set the delivery mode as persistent or not
    map.put(AMQPConstants.AMQP_DELIVERY_MODE, Integer.toString(msg_prop.getDeliveryMode()));
    // FIXME ? Extract destination from... where?
    /*// destination name
     if (message.getAMQPDestination() != null) {
    Destination dest = message.getAMQPDestination();
    map.put(AMQPConstants.AMQP_DESTINATION, dest instanceof Queue ? ((Queue) dest).getQueueName() : ((Topic) dest).getTopicName());
     }*/
    // expiration
    map.put(AMQPConstants.AMQP_EXPIRATION, msg_prop.getExpiration());
    // if a AMQP message ID is found
    if (msg_prop.getMessageId() != null) {
        map.put(AMQPConstants.AMQP_MESSAGE_ID, msg_prop.getMessageId());
    }
    // priority
    map.put(AMQPConstants.AMQP_PRIORITY, Long.toString(msg_prop.getPriority()));
    // redelivered
    map.put(AMQPConstants.AMQP_REDELIVERED, Boolean.toString(msg_env.isRedeliver()));
    // replyto destination name
    if (msg_prop.getReplyTo() != null) {
        Destination dest = DestinationFactory.parseAddress(msg_prop.getReplyTo());
        map.put(AMQPConstants.AMQP_REPLY_TO, dest);
    }
    // priority
    map.put(AMQPConstants.AMQP_TIMESTAMP, Long.toString(msg_prop.getTimestamp().getTime()));
    // message type
    if (msg_prop.getType() != null) {
        map.put(AMQPConstants.AMQP_TYPE, msg_prop.getType());
    }
    // any other transport properties / headers
    Set<String> e = null;
    e = msg_prop.getHeaders().keySet();
    for (String headerName : e) {
        Object o = headers.get(e);
        if (o instanceof String)
            map.put(headerName, (String) o);
        if (o instanceof Boolean)
            map.put(headerName, (Boolean) o);
        if (o instanceof Integer)
            map.put(headerName, (Integer) o);
        if (o instanceof Long)
            map.put(headerName, (Long) o);
        if (o instanceof Double)
            map.put(headerName, (Double) o);
        if (o instanceof Float)
            map.put(headerName, (Float) o);
    }
    return map;
}

From source file:org.apache.niolex.rabbit.rpc.RPCServer.java

License:Apache License

public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;//from  w w w .ja v  a2s.  co  m
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        connection = factory.newConnection();
        channel = connection.createChannel();

        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);

        channel.basicQos(1);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);

        System.out.println(" [x] Awaiting RPC requests");

        while (true) {
            String response = null;

            QueueingConsumer.Delivery delivery = consumer.nextDelivery();

            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();

            try {
                String message = new String(delivery.getBody(), "UTF-8");
                int n = Integer.parseInt(message);

                System.out.println(" [.] fib(" + message + ")");
                response = "" + fib(n);
            } catch (Exception e) {
                System.out.println(" [.] " + e.toString());
                response = "";
            } finally {
                channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:org.eclipse.ditto.services.connectivity.messaging.rabbitmq.RabbitMQConsumerActor.java

License:Open Source License

private void handleDelivery(final Delivery delivery) {
    final BasicProperties properties = delivery.getProperties();
    final Envelope envelope = delivery.getEnvelope();
    final byte[] body = delivery.getBody();
    final String hashKey = envelope.getExchange() + ":" + envelope.getRoutingKey();

    Map<String, String> headers = null;
    try {//from  ww  w .j a v a 2  s  . c o m
        final String correlationId = properties.getCorrelationId();
        LogUtil.enhanceLogWithCorrelationId(log, correlationId);
        if (log.isDebugEnabled()) {
            log.debug("Received message from RabbitMQ ({}//{}): {}", envelope, properties,
                    new String(body, StandardCharsets.UTF_8));
        }
        headers = extractHeadersFromMessage(properties, envelope);
        final ExternalMessageBuilder externalMessageBuilder = ExternalMessageFactory
                .newExternalMessageBuilder(headers);
        final String contentType = properties.getContentType();
        final String text = new String(body, CharsetDeterminer.getInstance().apply(contentType));
        if (shouldBeInterpretedAsBytes(contentType)) {
            externalMessageBuilder.withBytes(body);
        } else {
            externalMessageBuilder.withTextAndBytes(text, body);
        }
        externalMessageBuilder.withAuthorizationContext(authorizationContext);
        externalMessageBuilder.withEnforcement(headerEnforcementFilterFactory.getFilter(headers));
        externalMessageBuilder.withHeaderMapping(headerMapping);
        externalMessageBuilder.withSourceAddress(sourceAddress);
        final ExternalMessage externalMessage = externalMessageBuilder.build();
        inboundMonitor.success(externalMessage);
        forwardToMappingActor(externalMessage, hashKey);
    } catch (final DittoRuntimeException e) {
        log.warning("Processing delivery {} failed: {}", envelope.getDeliveryTag(), e.getMessage());
        if (headers != null) {
            // send response if headers were extracted successfully
            forwardToMappingActor(e.setDittoHeaders(DittoHeaders.of(headers)), hashKey);
            inboundMonitor.failure(headers, e);
        } else {
            inboundMonitor.failure(e);
        }
    } catch (final Exception e) {
        log.warning("Processing delivery {} failed: {}", envelope.getDeliveryTag(), e.getMessage());
        if (headers != null) {
            inboundMonitor.exception(headers, e);
        } else {
            inboundMonitor.exception(e);
        }
    }
}

From source file:org.eclipse.ditto.services.connectivity.messaging.rabbitmq.RabbitMQConsumerActor.java

License:Open Source License

private static Map<String, String> extractHeadersFromMessage(final BasicProperties properties,
        final Envelope envelope) {

    final Map<String, String> headersFromProperties = getHeadersFromProperties(properties.getHeaders());

    // set headers specific to rmq messages
    if (properties.getReplyTo() != null) {
        headersFromProperties.put(ExternalMessage.REPLY_TO_HEADER, properties.getReplyTo());
    }/*from w  w  w.  j  ava 2 s  .  c o m*/
    if (properties.getCorrelationId() != null) {
        headersFromProperties.put(DittoHeaderDefinition.CORRELATION_ID.getKey(), properties.getCorrelationId());
    }
    if (properties.getContentType() != null) {
        headersFromProperties.put(ExternalMessage.CONTENT_TYPE_HEADER, properties.getContentType());
    }
    headersFromProperties.put(MESSAGE_ID_HEADER, Long.toString(envelope.getDeliveryTag()));

    return headersFromProperties;
}

From source file:org.mule.transport.amqp.AmqpMuleMessageFactory.java

License:Open Source License

private void addBasicProperties(final DefaultMuleMessage muleMessage,
        final Map<String, Object> messageProperties, final BasicProperties amqpProperties) {
    if (amqpProperties == null)
        return;//from  ww w  .  ja  v  a  2  s  . c om

    putIfNonNull(messageProperties, AmqpConstants.APP_ID, amqpProperties.getAppId());
    putIfNonNull(messageProperties, AmqpConstants.CONTENT_ENCODING, amqpProperties.getContentEncoding());
    putIfNonNull(messageProperties, AmqpConstants.CONTENT_TYPE, amqpProperties.getContentType());

    final String correlationId = amqpProperties.getCorrelationId();
    putIfNonNull(messageProperties, AmqpConstants.CORRELATION_ID, correlationId);
    putIfNonNull(messageProperties, MuleProperties.MULE_CORRELATION_ID_PROPERTY, correlationId);
    muleMessage.setCorrelationId(correlationId);

    putIfNonNull(messageProperties, AmqpConstants.DELIVERY_MODE, amqpProperties.getDeliveryMode());
    putIfNonNull(messageProperties, AmqpConstants.EXPIRATION, amqpProperties.getExpiration());

    final String messageId = amqpProperties.getMessageId();
    putIfNonNull(messageProperties, AmqpConstants.MESSAGE_ID, messageId);
    putIfNonNull(messageProperties, MuleProperties.MULE_MESSAGE_ID_PROPERTY, messageId);
    muleMessage.setUniqueId(messageId);

    putIfNonNull(messageProperties, AmqpConstants.PRIORITY, amqpProperties.getPriority());

    final String replyTo = amqpProperties.getReplyTo();
    putIfNonNull(messageProperties, AmqpConstants.REPLY_TO, replyTo);
    muleMessage.setReplyTo(replyTo);

    putIfNonNull(messageProperties, AmqpConstants.TIMESTAMP, amqpProperties.getTimestamp());
    putIfNonNull(messageProperties, AmqpConstants.TYPE, amqpProperties.getType());
    putIfNonNull(messageProperties, AmqpConstants.USER_ID, amqpProperties.getUserId());

    messageProperties.putAll(amqpProperties.getHeaders());
}