Example usage for com.rabbitmq.client Envelope getRoutingKey

List of usage examples for com.rabbitmq.client Envelope getRoutingKey

Introduction

In this page you can find the example usage for com.rabbitmq.client Envelope getRoutingKey.

Prototype

public String getRoutingKey() 

Source Link

Document

Get the routing key included in this parameter envelope

Usage

From source file:it.av.fac.messaging.rabbitmq.RabbitMQServer.java

/**
 * Instantiates a RabbitMQ connection to receive a request only. Cannot send
 * messages.//from   w ww .  j a v  a 2 s .  c  o  m
 *
 * @param connWrapper The object that contains a connection to the RabbitMQ
 * server.
 * @param queueIn The queue where this connection should read messages from.
 * @param handler The handler to call when new messages are available in the
 * queueIn. Replaces the receive method.
 * @throws Exception If there is a connection issue to the RabbitMQ server.
 */
public RabbitMQServer(RabbitMQConnectionWrapper connWrapper, String queueIn,
        IServerHandler<byte[], String> handler) throws Exception {
    this.queueIn = queueIn;
    this.queueOut = null;
    this.routingKeyIn = queueIn + ".#";
    this.routingKeyOut = null;
    this.canSend = false;

    this.conn = connWrapper.getConnection();
    this.channel = RabbitMQChannelPool.createChannel(conn, this.queueIn, this.queueOut, this.routingKeyIn,
            this.routingKeyOut);

    this.channel.basicConsume(this.queueIn, true, new DefaultConsumer(this.channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String clientKey = envelope.getRoutingKey().substring(queueIn.length() + 1);
            handler.handle(body, clientKey);
        }

    });
}

From source file:loanbroker.Aggregator.java

public void reciveFromNormalizer(Hashtable<String, Message> messageFroumBankList,
        Hashtable<String, Message> messagesFromNormalizer, ArrayList<Message> foundMessages)
        throws IOException, TimeoutException, Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostName);//from   w ww  .j a  v a 2 s  .  c  o m
    factory.setPort(5672);
    factory.setUsername("student");
    factory.setPassword("cph");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    // channel.exchangeDeclare(inputEXCHANGE_NAME, "direct");
    String queueName = channel.queueDeclare().getQueue();

    channel.queueBind(queueName, ExchangeName.GLOBAL, RoutingKeys.NormalizerToAggregator);
    System.out.println(" [*] Waiting for messages on " + ExchangeName.GLOBAL
            + RoutingKeys.NormalizerToAggregator + ". To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String m = new String(body, "UTF-8");

            Gson gson = new GsonBuilder().create();
            LoanResponse lp = gson.fromJson(m, LoanResponse.class);
            Message fm = new Message("" + lp.getSsn(), (int) lp.getInterestRate(), 0, lp.getBank());
            messagesFromNormalizer.put(lp.getCorrelationId(), fm);

            System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + fm.toString() + "'");
            try {
                checkLoanMessages(messageFroumBankList, messagesFromNormalizer, foundMessages);
            } catch (InterruptedException ex) {
                Logger.getLogger(Aggregator.class.getName()).log(Level.SEVERE, null, ex);
            } catch (TimeoutException ex) {
                Logger.getLogger(Aggregator.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(Aggregator.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:loanbroker.Aggregator.java

public void reciveFromRecieptList(Hashtable<String, Message> messagesFromBankList)
        throws IOException, TimeoutException, Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostName);/*w  w w  . ja va  2 s .c  o  m*/
    factory.setPort(5672);
    factory.setUsername("student");
    factory.setPassword("cph");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(ExchangeName.GLOBAL, "direct");
    String queueName = channel.queueDeclare().getQueue();

    channel.queueBind(queueName, ExchangeName.GLOBAL, RoutingKeys.RecipientListToAggregator);
    System.out.println(" [*] Waiting for messages on " + ExchangeName.GLOBAL
            + RoutingKeys.RecipientListToAggregator + ".. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String m = new String(body, "UTF-8");
            // System.out.println("reciveFromRecieptList" + m);
            String p = properties.getCorrelationId();
            if (p != null) {
                //send to translator
                Gson g = new Gson();
                Message fm = g.fromJson(m, Message.class);
                if (fm.getBanks() != null) {
                    Message k = new Message(fm.getSsn(), fm.getCreditScore(), fm.getLoanAmount(),
                            fm.getLoanDuration());

                    k.setBanks(fm.getBanks());

                    messagesFromBankList.put(p, k);
                }

                System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + fm.toString() + "'");
                //   System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + m + "'");
            } else {
                System.out.println("No correlationId");
            }

        }
    };
    channel.basicConsume(queueName, true, consumer);
}

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/*from w  w w .  jav  a2 s  .  c o  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.lshift.camdisplay.Main.java

License:Open Source License

public Main(String host, String exch, String nickname, final String mixerSpec) throws IOException {
    frame = new JFrame("RabbitCam: " + host + "/" + exch);
    panel = new JPanel();
    componentMap = new HashMap();

    setupWindowDressing(exch, nickname, frame, panel);
    frame.pack();//w  ww. j  a  va2 s  . com
    frame.show();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    textInput.requestFocusInWindow();

    ConnectionFactory cf = new ConnectionFactory();
    cf.setHost(host);
    cf.setRequestedHeartbeat(0);
    conn = cf.newConnection();

    ch = conn.createChannel();

    ch.exchangeDeclare(exch, "fanout");

    String queueName = ch.queueDeclare().getQueue();
    ch.queueBind(queueName, exch, "");
    ch.basicConsume(queueName, true, new DefaultConsumer(ch) {
        public void handleShutdownSignal(String consumerTag, ShutdownSignalException s) {
            if (s.getReason() instanceof java.io.EOFException) {
                JOptionPane.showMessageDialog(frame, "AMQP server disconnected.", "Connection closed",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                SwingUtil.complain("Connection closed", null, s);
            }
            System.exit(1);
        }

        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String routingKey = envelope.getRoutingKey();
            String contentType = properties.getContentType();

            if (contentType.equals("text/plain")) {
                handleText(routingKey, new String(body));
                return;
            }

            CamstreamComponent comp;
            if (!componentMap.containsKey(routingKey)) {
                comp = new CamstreamComponent(mixerSpec);
                addComponent(routingKey, comp);
                frame.pack();
            } else {
                comp = (CamstreamComponent) componentMap.get(routingKey);
            }
            if (comp.handleDelivery(contentType, body)) {
                frame.pack();
            }
        }
    });
}

From source file:net.roboconf.messaging.rabbitmq.internal.impl.RoboconfConsumer.java

License:Apache License

@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
        throws IOException {

    try {//from w w  w.  j  a v  a  2  s.  c  o  m
        Message message = SerializationUtils.deserializeObject(body);
        this.logger.finer(this.sourceName + " received a message " + message.getClass().getSimpleName()
                + " on routing key '" + envelope.getRoutingKey() + "'.");

        this.messageQueue.add(message);

    } catch (ClassNotFoundException | IOException e) {
        this.logger.severe(
                this.sourceName + ": a message could not be deserialized. => " + e.getClass().getSimpleName());
        Utils.logException(this.logger, e);
        this.messageQueue.errorWhileReceivingMessage();
    }
}

From source file:org.apache.airavata.gfac.monitor.impl.push.amqp.BasicConsumer.java

License:Apache License

public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
        byte[] body) {

    logger.debug("job update for: " + envelope.getRoutingKey());
    String message = new String(body);
    message = message.replaceAll("(?m)^", "    ");
    // Here we parse the message and get the job status and push it
    // to the Event bus, this will be picked by
    //        AiravataJobStatusUpdator and store in to registry

    logger.debug("************************************************************");
    logger.debug("AMQP Message recieved \n" + message);
    logger.debug("************************************************************");
    try {/*from   w ww .j a  v a2  s .  co  m*/
        String jobID = envelope.getRoutingKey().split("\\.")[0];
        MonitorID monitorID = new MonitorID(null, jobID, null, null, null, null, null);
        monitorID.setStatus(parser.parseMessage(message));
        publisher.publish(monitorID);
    } catch (AiravataMonitorException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.airavata.messaging.core.impl.ExperimentConsumer.java

License:Apache License

@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
        throws IOException {

    Message message = new Message();

    try {//w ww  . ja  va  2s .  co m
        ThriftUtils.createThriftFromBytes(body, message);
        long deliveryTag = envelope.getDeliveryTag();
        if (message.getMessageType() == MessageType.EXPERIMENT
                || message.getMessageType() == MessageType.EXPERIMENT_CANCEL) {
            TBase event = null;
            String gatewayId = null;
            ExperimentSubmitEvent experimentEvent = new ExperimentSubmitEvent();
            ThriftUtils.createThriftFromBytes(message.getEvent(), experimentEvent);
            log.info(" Message Received with message id '" + message.getMessageId()
                    + "' and with message type '" + message.getMessageType() + "'  for experimentId:" + " "
                    + experimentEvent.getExperimentId());
            event = experimentEvent;
            gatewayId = experimentEvent.getGatewayId();
            MessageContext messageContext = new MessageContext(event, message.getMessageType(),
                    message.getMessageId(), gatewayId, deliveryTag);
            messageContext.setUpdatedTime(AiravataUtils.getTime(message.getUpdatedTime()));
            messageContext.setIsRedeliver(envelope.isRedeliver());
            handler.onMessage(messageContext);
        } else {
            log.error("{} message type is not handle in ProcessLaunch Subscriber. Sending ack for "
                    + "delivery tag {} ", message.getMessageType().name(), deliveryTag);
            sendAck(deliveryTag);
        }
    } catch (TException e) {
        String msg = "Failed to de-serialize the thrift message, from routing keys:" + envelope.getRoutingKey();
        log.warn(msg, e);
    }

}

From source file:org.apache.airavata.messaging.core.impl.ProcessConsumer.java

License:Apache License

@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties basicProperties,
        byte[] body) throws IOException {

    Message message = new Message();

    try {/* w  w  w. ja v a2 s  .  com*/
        ThriftUtils.createThriftFromBytes(body, message);
        TBase event = null;
        String gatewayId = null;
        long deliveryTag = envelope.getDeliveryTag();
        if (message.getMessageType().equals(MessageType.LAUNCHPROCESS)) {
            ProcessSubmitEvent processSubmitEvent = new ProcessSubmitEvent();
            ThriftUtils.createThriftFromBytes(message.getEvent(), processSubmitEvent);
            log.info(" Message Received with message id '" + message.getMessageId() + " and with message type:"
                    + message.getMessageType() + ", for processId:" + processSubmitEvent.getProcessId()
                    + ", expId:" + processSubmitEvent.getExperimentId());
            event = processSubmitEvent;
            gatewayId = processSubmitEvent.getGatewayId();
            MessageContext messageContext = new MessageContext(event, message.getMessageType(),
                    message.getMessageId(), gatewayId, deliveryTag);
            messageContext.setUpdatedTime(AiravataUtils.getTime(message.getUpdatedTime()));
            messageContext.setIsRedeliver(envelope.isRedeliver());
            handler.onMessage(messageContext);
        } else {
            log.error("{} message type is not handle in ProcessLaunch Subscriber. Sending ack for "
                    + "delivery tag {} ", message.getMessageType().name(), deliveryTag);
            sendAck(deliveryTag);
        }
    } catch (TException e) {
        String msg = "Failed to de-serialize the thrift message, from routing keys:" + envelope.getRoutingKey();
        log.warn(msg, e);
    }

}

From source file:org.apache.airavata.messaging.core.impl.StatusConsumer.java

License:Apache License

@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
        throws IOException {
    Message message = new Message();

    try {/*from w ww.  ja v a 2s. c  o  m*/
        ThriftUtils.createThriftFromBytes(body, message);
        TBase event = null;
        String gatewayId = null;

        if (message.getMessageType().equals(MessageType.EXPERIMENT)) {
            ExperimentStatusChangeEvent experimentStatusChangeEvent = new ExperimentStatusChangeEvent();
            ThriftUtils.createThriftFromBytes(message.getEvent(), experimentStatusChangeEvent);
            log.debug(" Message Received with message id '" + message.getMessageId()
                    + "' and with message type '" + message.getMessageType() + "'  with status "
                    + experimentStatusChangeEvent.getState());
            event = experimentStatusChangeEvent;
            gatewayId = experimentStatusChangeEvent.getGatewayId();
        } else if (message.getMessageType().equals(MessageType.PROCESS)) {
            ProcessStatusChangeEvent processStatusChangeEvent = new ProcessStatusChangeEvent();
            ThriftUtils.createThriftFromBytes(message.getEvent(), processStatusChangeEvent);
            log.debug("Message Recieved with message id :" + message.getMessageId() + " and with "
                    + "message type " + message.getMessageType() + " with status "
                    + processStatusChangeEvent.getState());
            event = processStatusChangeEvent;
            gatewayId = processStatusChangeEvent.getProcessIdentity().getGatewayId();
        } else if (message.getMessageType().equals(MessageType.TASK)) {
            TaskStatusChangeEvent taskStatusChangeEvent = new TaskStatusChangeEvent();
            ThriftUtils.createThriftFromBytes(message.getEvent(), taskStatusChangeEvent);
            log.debug(
                    " Message Received with message id '" + message.getMessageId() + "' and with message type '"
                            + message.getMessageType() + "'  with status " + taskStatusChangeEvent.getState());
            event = taskStatusChangeEvent;
            gatewayId = taskStatusChangeEvent.getTaskIdentity().getGatewayId();
        } else if (message.getMessageType() == MessageType.PROCESSOUTPUT) {
            TaskOutputChangeEvent taskOutputChangeEvent = new TaskOutputChangeEvent();
            ThriftUtils.createThriftFromBytes(message.getEvent(), taskOutputChangeEvent);
            log.debug(" Message Received with message id '" + message.getMessageId()
                    + "' and with message type '" + message.getMessageType());
            event = taskOutputChangeEvent;
            gatewayId = taskOutputChangeEvent.getTaskIdentity().getGatewayId();
        } else if (message.getMessageType().equals(MessageType.JOB)) {
            JobStatusChangeEvent jobStatusChangeEvent = new JobStatusChangeEvent();
            ThriftUtils.createThriftFromBytes(message.getEvent(), jobStatusChangeEvent);
            log.debug(
                    " Message Received with message id '" + message.getMessageId() + "' and with message type '"
                            + message.getMessageType() + "'  with status " + jobStatusChangeEvent.getState());
            event = jobStatusChangeEvent;
            gatewayId = jobStatusChangeEvent.getJobIdentity().getGatewayId();
        } else if (message.getMessageType().equals(MessageType.LAUNCHPROCESS)) {
            TaskSubmitEvent taskSubmitEvent = new TaskSubmitEvent();
            ThriftUtils.createThriftFromBytes(message.getEvent(), taskSubmitEvent);
            log.debug(" Message Received with message id '" + message.getMessageId()
                    + "' and with message type '" + message.getMessageType() + "'  for experimentId: "
                    + taskSubmitEvent.getExperimentId() + "and taskId: " + taskSubmitEvent.getTaskId());
            event = taskSubmitEvent;
            gatewayId = taskSubmitEvent.getGatewayId();
        } else if (message.getMessageType().equals(MessageType.TERMINATEPROCESS)) {
            TaskTerminateEvent taskTerminateEvent = new TaskTerminateEvent();
            ThriftUtils.createThriftFromBytes(message.getEvent(), taskTerminateEvent);
            log.debug(" Message Received with message id '" + message.getMessageId()
                    + "' and with message type '" + message.getMessageType() + "'  for experimentId: "
                    + taskTerminateEvent.getExperimentId() + "and taskId: " + taskTerminateEvent.getTaskId());
            event = taskTerminateEvent;
            gatewayId = null;
        }
        MessageContext messageContext = new MessageContext(event, message.getMessageType(),
                message.getMessageId(), gatewayId);
        messageContext.setUpdatedTime(AiravataUtils.getTime(message.getUpdatedTime()));
        messageContext.setIsRedeliver(envelope.isRedeliver());
        handler.onMessage(messageContext);
    } catch (TException e) {
        String msg = "Failed to de-serialize the thrift message, from routing keys: "
                + envelope.getRoutingKey();
        log.warn(msg, e);
    }
}