Example usage for com.rabbitmq.client DefaultConsumer DefaultConsumer

List of usage examples for com.rabbitmq.client DefaultConsumer DefaultConsumer

Introduction

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

Prototype

public DefaultConsumer(Channel channel) 

Source Link

Document

Constructs a new instance and records its association to the passed-in channel.

Usage

From source file:mobisocial.musubi.service.AMQPService.java

License:Apache License

void attachToQueues() throws IOException {
    Log.i(TAG, "Setting up identity exchange and device queue");

    DefaultConsumer consumer = new DefaultConsumer(mIncomingChannel) {
        @Override//from w  w  w  .  j  a v a2s  . c  om
        public void handleDelivery(final String consumerTag, final Envelope envelope,
                final BasicProperties properties, final byte[] body) throws IOException {
            if (DBG)
                Log.i(TAG, "recevied message: " + envelope.getExchange());
            assert (body != null);
            //TODO: throttle if we have too many incoming?
            //TODO: check blacklist up front?
            //TODO: check hash up front?
            MEncodedMessage encoded = new MEncodedMessage();
            encoded.encoded_ = body;
            mEncodedMessageManager.insertEncoded(encoded);
            getContentResolver().notifyChange(MusubiService.ENCODED_RECEIVED, null);

            //we have to do this in our AMQP thread, or add synchronization logic
            //for all of the AMQP related fields.
            mAMQPHandler.post(new Runnable() {
                public void run() {
                    if (mIncomingChannel == null) {
                        //it can close in this time window
                        return;
                    }
                    try {
                        mIncomingChannel.basicAck(envelope.getDeliveryTag(), false);
                        if (mFailedOperation == FailedOperationType.FailedReceive) {
                            mFailureDelay = MIN_DELAY;
                            mFailedOperation = FailedOperationType.FailedNone;
                        }
                    } catch (Throwable e) {
                        Log.e(TAG, "failed to ack message on AMQP", e);
                        //next connection that receives a packet wins
                        closeConnection(FailedOperationType.FailedReceive);
                    }

                }
            });
        }
    };
    byte[] device_name = new byte[8];
    ByteBuffer.wrap(device_name).putLong(mDeviceManager.getLocalDeviceName());
    String device_queue_name = encodeAMQPname("ibedevice-", device_name);
    //leaving these since they mark the beginning of the connection and shouldn't be too frequent (once per drop)
    Log.v(TAG, "queueDeclare " + device_queue_name);
    mIncomingChannel.queueDeclare(device_queue_name, true, false, false, null);
    //TODO: device_queue_name needs to involve the identities some how? or be a larger byte array
    List<MIdentity> mine = mIdentitiesManager.getOwnedIdentities();
    for (MIdentity me : mine) {
        IBHashedIdentity id = IdentitiesManager.toIBHashedIdentity(me, 0);
        String identity_exchange_name = encodeAMQPname("ibeidentity-", id.identity_);
        Log.v(TAG, "exchangeDeclare " + identity_exchange_name);
        mIncomingChannel.exchangeDeclare(identity_exchange_name, "fanout", true);
        Log.v(TAG, "queueBind " + device_queue_name + " " + identity_exchange_name);
        mIncomingChannel.queueBind(device_queue_name, identity_exchange_name, "");
        try {
            Log.v(TAG, "queueDeclarePassive " + "initial-" + identity_exchange_name);
            Channel incoming_initial = mConnection.createChannel();
            incoming_initial.queueDeclarePassive("initial-" + identity_exchange_name);
            try {
                Log.v(TAG, "queueUnbind " + "initial-" + identity_exchange_name + " " + identity_exchange_name);
                //   we now have claimed our identity, unbind this queue
                incoming_initial.queueUnbind("initial-" + identity_exchange_name, identity_exchange_name, "");
                //but also drain it
            } catch (IOException e) {
            }
            Log.v(TAG, "basicConsume " + "initial-" + identity_exchange_name);
            mIncomingChannel.basicConsume("initial-" + identity_exchange_name, consumer);
        } catch (IOException e) {
            //no one sent up messages before we joined
            //IF we deleted it: we already claimed our identity, so we ate this queue up
        }
    }

    Log.v(TAG, "basicConsume " + device_queue_name);
    mIncomingChannel.basicConsume(device_queue_name, false, "", true, true, null, consumer);
}

From source file:ms.dew.core.cluster.spi.rabbit.RabbitClusterMQ.java

License:Apache License

private DefaultConsumer getDefaultConsumer(Channel channel, String flag, String exchange, String routingKey,
        String queueName, Consumer<String> consumer) {
    return new DefaultConsumer(channel) {
        @Override//from   w  ww .  j  a va2  s. c o m
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            setMQHeader(flag, properties.getHeaders());
            String message = new String(body, StandardCharsets.UTF_8);
            Object funResult = receiveBeforeFun.invoke(exchange, routingKey, queueName, properties);
            try {
                consumer.accept(message);
            } catch (RuntimeException e) {
                receiveErrorFun.invoke(e, funResult);
                throw e;
            } finally {
                channel.basicAck(envelope.getDeliveryTag(), false);
                receiveFinishFun.invoke(funResult);
            }
        }
    };
}

From source file:mx.bigdata.utils.amqp.ReconnectingConsumer.java

License:Apache License

private boolean initConsumer() {
    Channel channel = null;/* w ww .j  ava  2  s . c  om*/
    try {
        channel = amqp.declareChannel(factory, key);
        String queue = createQueue(amqp, channel, key);
        this.consumer = new DefaultConsumer(channel) {

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

            @Override
            public void handleConsumeOk(String consumerTag) {
                ReconnectingConsumer.this.consumerTag = consumerTag;
            }

            @Override
            public void handleCancel(String consumerTag) throws IOException {
                logger.warn(tag + " handleCancel for consumer tag: " + consumerTag);
                try {
                    this.getChannel().basicCancel(ReconnectingConsumer.this.consumerTag);
                } catch (Exception ignore) {
                }
                this.getChannel().getConnection().abort(5000);
                reconnect();
            }

            @Override
            public void handleShutdownSignal(java.lang.String consumerTag, ShutdownSignalException sig) {
                try {
                    getChannel().basicCancel(ReconnectingConsumer.this.consumerTag);
                } catch (Exception ignore) {
                    ;
                }
                getChannel().getConnection().abort(5000);
                if (!sig.isInitiatedByApplication()) {
                    logger.warn(tag + " ShutdownSignal for tag: " + tag + "\n\t consumer tag: " + consumerTag
                            + "\n\t reason: " + sig.getReason() + "\n\t reference: " + sig.getReason()
                            + "\n\t ", sig);
                    reconnect();
                } else {
                    logger.debug(tag + " ShutdownSignal for tag: " + tag + "\n\t consumer tag: " + consumerTag
                            + "\n\t reason: " + sig.getReason() + "\n\t reference: " + sig.getReason()
                            + "\n\t ", sig);
                    consumer = null;
                }
            }
        };

        channel.basicConsume(queue, false, consumer);
        logger.info("Consumer " + tag + " initilized");
        return true;
    } catch (Throwable e) {
        logger.error("Exception initializing consumer " + tag + ": ", e);
        if (channel != null) {
            channel.getConnection().abort(5000);
        }
    }
    return false;
}

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();//from  w  w  w.  j av a 2 s . c  o  m
    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:nl.uva.sne.drip.api.rpc.DRIPCaller.java

License:Apache License

public Message call(Message r) throws IOException, TimeoutException, InterruptedException, JSONException {

    String jsonInString = mapper.writeValueAsString(r);

    //Build a correlation ID to distinguish responds 
    final String corrId = UUID.randomUUID().toString();
    AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().correlationId(corrId)
            .replyTo(getReplyQueueName()).build();
    Logger.getLogger(DRIPCaller.class.getName()).log(Level.INFO, "Sending: {0}", jsonInString);
    getChannel().basicPublish("", requestQeueName, props, jsonInString.getBytes("UTF-8"));

    final BlockingQueue<String> response = new ArrayBlockingQueue(1);

    getChannel().basicConsume(getReplyQueueName(), true, new DefaultConsumer(getChannel()) {
        @Override/*  ww  w .j  a v a  2s .  com*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            if (properties.getCorrelationId().equals(corrId)) {
                response.offer(new String(body, "UTF-8"));
            }
        }
    });
    String resp = response.take();
    String clean = resp;
    if (resp.contains("'null'")) {
        clean = resp.replaceAll("'null'", "null").replaceAll("\'", "\"").replaceAll(" ", "");
    }
    if (clean.contains("\"value\":{\"")) {
        return Converter.string2Message(clean);
    }
    if (clean.contains("\"null\"")) {
        clean = clean.replaceAll("\"null\"", "null");
    }
    Logger.getLogger(DRIPCaller.class.getName()).log(Level.INFO, "Got: {0}", clean);

    return mapper.readValue(clean, Message.class);
}

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

License:Apache License

public String listen(final MessageHandler handler) throws AiravataException {
    try {/*  w w w  .  j  a  v a2  s. c  om*/
        Map<String, Object> props = handler.getProperties();
        final Object routing = props.get(MessagingConstants.RABBIT_ROUTING_KEY);
        if (routing == null) {
            throw new IllegalArgumentException("The routing key must be present");
        }

        List<String> keys = new ArrayList<String>();
        if (routing instanceof List) {
            for (Object o : (List) routing) {
                keys.add(o.toString());
            }
        } else if (routing instanceof String) {
            keys.add((String) routing);
        }

        String queueName = (String) props.get(MessagingConstants.RABBIT_QUEUE);
        String consumerTag = (String) props.get(MessagingConstants.RABBIT_CONSUMER_TAG);
        if (queueName == null) {
            if (!channel.isOpen()) {
                channel = connection.createChannel();
                channel.exchangeDeclare(exchangeName, "topic", false);
            }
            queueName = channel.queueDeclare().getQueue();
        } else {
            channel.queueDeclare(queueName, true, false, false, null);
        }

        final String id = getId(keys, queueName);
        if (queueDetailsMap.containsKey(id)) {
            throw new IllegalStateException("This subscriber is already defined for this Consumer, "
                    + "cannot define the same subscriber twice");
        }

        if (consumerTag == null) {
            consumerTag = "default";
        }

        // bind all the routing keys
        for (String routingKey : keys) {
            channel.queueBind(queueName, exchangeName, routingKey);
        }

        channel.basicConsume(queueName, true, consumerTag, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) {
                Message message = new Message();

                try {
                    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.WORKFLOWNODE)) {
                        WorkflowNodeStatusChangeEvent wfnStatusChangeEvent = new WorkflowNodeStatusChangeEvent();
                        ThriftUtils.createThriftFromBytes(message.getEvent(), wfnStatusChangeEvent);
                        log.debug(" Message Received with message id '" + message.getMessageId()
                                + "' and with message type '" + message.getMessageType() + "'  with status "
                                + wfnStatusChangeEvent.getState());
                        event = wfnStatusChangeEvent;
                        gatewayId = wfnStatusChangeEvent.getWorkflowNodeIdentity().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().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();
                    }
                    MessageContext messageContext = new MessageContext(event, message.getMessageType(),
                            message.getMessageId(), gatewayId);
                    messageContext.setUpdatedTime(AiravataUtils.getTime(message.getUpdatedTime()));
                    handler.onMessage(messageContext);
                } catch (TException e) {
                    String msg = "Failed to de-serialize the thrift message, from routing keys and queueName "
                            + id;
                    log.warn(msg, e);
                }
            }
        });
        // save the name for deleting the queue
        queueDetailsMap.put(id, new QueueDetails(queueName, keys));
        return id;
    } catch (Exception e) {
        String msg = "could not open channel for exchange " + exchangeName;
        log.error(msg);
        throw new AiravataException(msg, e);
    }
}

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

License:Apache License

public String listen(final MessageHandler handler) throws AiravataException {
    try {//w w  w.j a v a2s  .  co m
        Map<String, Object> props = handler.getProperties();
        final Object routing = props.get(MessagingConstants.RABBIT_ROUTING_KEY);
        if (routing == null) {
            throw new IllegalArgumentException("The routing key must be present");
        }

        List<String> keys = new ArrayList<String>();
        if (routing instanceof List) {
            for (Object o : (List) routing) {
                keys.add(o.toString());
            }
        } else if (routing instanceof String) {
            keys.add((String) routing);
        }

        String queueName = (String) props.get(MessagingConstants.RABBIT_QUEUE);
        String consumerTag = (String) props.get(MessagingConstants.RABBIT_CONSUMER_TAG);
        if (queueName == null) {
            if (!channel.isOpen()) {
                channel = connection.createChannel();
                channel.exchangeDeclare(exchangeName, "topic", false);
            }
            queueName = channel.queueDeclare().getQueue();
        } else {
            channel.queueDeclare(queueName, true, false, false, null);
        }

        final String id = getId(keys, queueName);
        if (queueDetailsMap.containsKey(id)) {
            throw new IllegalStateException("This subscriber is already defined for this Consumer, "
                    + "cannot define the same subscriber twice");
        }

        if (consumerTag == null) {
            consumerTag = "default";
        }

        // bind all the routing keys
        for (String routingKey : keys) {
            channel.queueBind(queueName, exchangeName, routingKey);
        }

        channel.basicConsume(queueName, true, consumerTag, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) {
                Message message = new Message();

                try {
                    ThriftUtils.createThriftFromBytes(body, message);
                    TBase event = null;
                    String gatewayId = null;
                    if (message.getMessageType().equals(MessageType.OUTPUT_PARSED)) {
                        ExperimentOutputParsedEvent experimentOutputParsedEvent = new ExperimentOutputParsedEvent();
                        ThriftUtils.createThriftFromBytes(message.getEvent(), experimentOutputParsedEvent);
                        log.debug(" Message Received with message id '" + message.getMessageId()
                                + "' and with message type '" + message.getMessageType());
                        event = experimentOutputParsedEvent;
                        //FIXME : transfer the gatewayID
                        gatewayId = "temp";
                    }
                    MessageContext messageContext = new MessageContext(event, message.getMessageType(),
                            message.getMessageId(), gatewayId);
                    messageContext.setUpdatedTime(AiravataUtils.getTime(message.getUpdatedTime()));
                    handler.onMessage(messageContext);
                } catch (TException e) {
                    String msg = "Failed to de-serialize the thrift message, from routing keys and queueName "
                            + id;
                    log.warn(msg, e);
                }
            }
        });
        // save the name for deleting the queue
        queueDetailsMap.put(id, new QueueDetails(queueName, keys));
        return id;
    } catch (Exception e) {
        String msg = "could not open channel for exchange " + exchangeName;
        log.error(msg);
        throw new AiravataException(msg, e);
    }
}

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

License:Apache License

public String listen(final MessageHandler handler) throws AiravataException {
    try {//from ww w.  j a  v  a  2  s.  c  o  m
        Map<String, Object> props = handler.getProperties();
        final Object routing = props.get(MessagingConstants.RABBIT_ROUTING_KEY);
        if (routing == null) {
            throw new IllegalArgumentException("The routing key must be present");
        }

        List<String> keys = new ArrayList<String>();
        if (routing instanceof List) {
            for (Object o : (List) routing) {
                keys.add(o.toString());
            }
        } else if (routing instanceof String) {
            keys.add((String) routing);
        }

        String queueName = (String) props.get(MessagingConstants.RABBIT_QUEUE);
        String consumerTag = (String) props.get(MessagingConstants.RABBIT_CONSUMER_TAG);
        if (queueName == null) {
            if (!channel.isOpen()) {
                channel = connection.createChannel();
                channel.exchangeDeclare(exchangeName, "topic", false);
            }
            queueName = channel.queueDeclare().getQueue();
        } else {
            channel.queueDeclare(queueName, true, false, false, null);
        }

        final String id = getId(keys, queueName);
        if (queueDetailsMap.containsKey(id)) {
            throw new IllegalStateException("This subscriber is already defined for this Consumer, "
                    + "cannot define the same subscriber twice");
        }

        if (consumerTag == null) {
            consumerTag = "default";
        }

        // bind all the routing keys
        for (String routingKey : keys) {
            channel.queueBind(queueName, exchangeName, routingKey);
        }

        channel.basicConsume(queueName, true, consumerTag, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) {
                Message message = new Message();

                try {
                    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 and queueName "
                            + id;
                    log.warn(msg, e);
                }
            }
        });
        // save the name for deleting the queue
        queueDetailsMap.put(id, new QueueDetails(queueName, keys));
        return id;
    } catch (Exception e) {
        String msg = "could not open channel for exchange " + exchangeName;
        log.error(msg);
        throw new AiravataException(msg, e);
    }
}

From source file:org.apache.camel.component.rabbitmq.RabbitMQProducerIntTest.java

License:Apache License

@Test
public void producedMessageIsReceived() throws InterruptedException, IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5672);/*  w w  w  . j  a v a2s.  c o  m*/
    factory.setUsername("cameltest");
    factory.setPassword("cameltest");
    factory.setVirtualHost("/");
    Connection conn = factory.newConnection();

    final List<Envelope> received = new ArrayList<Envelope>();

    Channel channel = conn.createChannel();
    channel.queueDeclare("sammyq", false, false, true, null);
    channel.queueBind("sammyq", EXCHANGE, "route1");
    channel.basicConsume("sammyq", true, new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            received.add(envelope);
        }
    });

    template.sendBodyAndHeader("new message", RabbitMQConstants.EXCHANGE_NAME, "ex1");
    Thread.sleep(500);
    assertEquals(1, received.size());
}

From source file:org.apache.cloudstack.mom.rabbitmq.RabbitMQEventBus.java

License:Apache License

/** Call to subscribe to interested set of events
 *
 * @param topic defines category and type of the events being subscribed to
 * @param subscriber subscriber that intends to receive event notification
 * @return UUID that represents the subscription with event bus
 * @throws EventBusException//from   w ww .  j a  va2 s. co m
 */
@Override
public UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws EventBusException {

    if (subscriber == null || topic == null) {
        throw new EventBusException("Invalid EventSubscriber/EventTopic object passed.");
    }

    // create a UUID, that will be used for managing subscriptions and also used as queue name
    // for on the queue used for the subscriber on the AMQP broker
    UUID queueId = UUID.randomUUID();
    String queueName = queueId.toString();

    try {
        String bindingKey = createBindingKey(topic);

        // store the subscriber details before creating channel
        _subscribers.put(queueName, new Ternary(bindingKey, null, subscriber));

        // create a channel dedicated for this subscription
        Connection connection = getConnection();
        Channel channel = createChannel(connection);

        // create a queue and bind it to the exchange with binding key formed from event topic
        createExchange(channel, amqpExchangeName);
        channel.queueDeclare(queueName, false, false, false, null);
        channel.queueBind(queueName, amqpExchangeName, bindingKey);

        // register a callback handler to receive the events that a subscriber subscribed to
        channel.basicConsume(queueName, _autoAck, queueName, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                Ternary<String, Channel, EventSubscriber> queueDetails = _subscribers.get(queueName);
                if (queueDetails != null) {
                    EventSubscriber subscriber = queueDetails.third();
                    String routingKey = envelope.getRoutingKey();
                    String eventSource = getEventSourceFromRoutingKey(routingKey);
                    String eventCategory = getEventCategoryFromRoutingKey(routingKey);
                    String eventType = getEventTypeFromRoutingKey(routingKey);
                    String resourceType = getResourceTypeFromRoutingKey(routingKey);
                    String resourceUUID = getResourceUUIDFromRoutingKey(routingKey);
                    Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID);
                    event.setDescription(new String(body));

                    // deliver the event to call back object provided by subscriber
                    subscriber.onEvent(event);
                }
            }
        });

        // update the channel details for the subscription
        Ternary<String, Channel, EventSubscriber> queueDetails = _subscribers.get(queueName);
        queueDetails.second(channel);
        _subscribers.put(queueName, queueDetails);

    } catch (AlreadyClosedException closedException) {
        s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName
                + " will be active after reconnection");
    } catch (ConnectException connectException) {
        s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName
                + " will be active after reconnection");
    } catch (Exception e) {
        throw new EventBusException("Failed to subscribe to event due to " + e.getMessage());
    }

    return queueId;
}