Example usage for com.rabbitmq.client Envelope getDeliveryTag

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

Introduction

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

Prototype

public long getDeliveryTag() 

Source Link

Document

Get the delivery tag included in this parameter envelope

Usage

From source file:org.springframework.amqp.rabbit.support.RabbitUtils.java

License:Apache License

public static MessageProperties createMessageProperties(final BasicProperties source, final Envelope envelope,
        final String charset) {
    MessageProperties target = new MessageProperties();
    Map<String, Object> headers = source.getHeaders();
    if (!CollectionUtils.isEmpty(headers)) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) {
            target.setHeader(entry.getKey(), entry.getValue());
        }/*from  w  ww.ja va  2  s .  c  o  m*/
    }
    target.setTimestamp(source.getTimestamp());
    target.setMessageId(source.getMessageId());
    target.setUserId(source.getUserId());
    target.setAppId(source.getAppId());
    target.setClusterId(source.getClusterId());
    target.setType(source.getType());
    Integer deliverMode = source.getDeliveryMode();
    if (deliverMode != null) {
        target.setDeliveryMode(MessageDeliveryMode.fromInt(deliverMode));
    }
    target.setExpiration(source.getExpiration());
    target.setPriority(source.getPriority());
    target.setContentType(source.getContentType());
    target.setContentEncoding(source.getContentEncoding());
    String correlationId = source.getCorrelationId();
    if (correlationId != null) {
        try {
            target.setCorrelationId(source.getCorrelationId().getBytes(charset));
        } catch (UnsupportedEncodingException ex) {
            throw new AmqpUnsupportedEncodingException(ex);
        }
    }
    String replyTo = source.getReplyTo();
    if (replyTo != null) {
        target.setReplyTo(new Address(replyTo));
    }
    if (envelope != null) {
        target.setReceivedExchange(envelope.getExchange());
        target.setReceivedRoutingKey(envelope.getRoutingKey());
        target.setRedelivered(envelope.isRedeliver());
        target.setDeliveryTag(envelope.getDeliveryTag());
    }
    // TODO: what about messageCount?
    return target;
}

From source file:org.teksme.server.queue.consumer.impl.InboundConsumer.java

License:Apache License

@SuppressWarnings("unused")
@Override//from w  w w .j a  v a 2  s  . com
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
        throws IOException {
    long deliveryTag = envelope.getDeliveryTag();

    InboundMessage message = null;
    try {
        message = (InboundMessage) new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(body))
                .readObject();
        // inbound.readMessage(message);
    } catch (java.io.IOException ioe) {
        System.err.println(ioe.getMessage());
    } catch (java.lang.ClassNotFoundException cnfe) {
        System.err.println(cnfe.getMessage());
    }
    // TODO: implement HTTP callback to client application

    getChannel().basicAck(deliveryTag, false);
}

From source file:org.teksme.server.queue.consumer.impl.OutboundMessageConsumer.java

License:Apache License

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

    try {/*w ww.  j  a  v  a  2s .com*/

        String routingKey = envelope.getRoutingKey();
        // String contentType = properties.contentType;
        long deliveryTag = envelope.getDeliveryTag();

        logger.info("Oubound message consumer invoked to handle routing key: " + routingKey);

        // TODO implement a better messaging handler
        //         if (AMQPQueueType.OUTBOUND_QUEUE.getSmsRoutingKey().equals(routingKey)) {
        //            logger.info("Partial matching based on the message key: " + AMQPQueueType.OUTBOUND_QUEUE.getSmsRoutingKey());
        OutboundMessage outMsg = (OutboundMessage) new java.io.ObjectInputStream(
                new java.io.ByteArrayInputStream(body)).readObject();
        logger.info("Channel(s) : " + outMsg.getChannels());
        logger.info("Gateway: " + outMsg.getRouting().getLiteral());
        dispatcher.fire(outMsg);
        //         }

        getChannel().basicAck(deliveryTag, false);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.wso2.siddhi.debs2017.input.DebsBenchmarkSystem.java

License:Open Source License

private void registerConsumerFor(RabbitQueue queue) throws IOException {
    Channel channel = queue.getChannel();
    channel.basicConsume(queue.getName(), false, new DefaultConsumer(channel) {
        @Override/*  w w w  .j  a  v  a2 s  . c o m*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            getChannel().basicAck(envelope.getDeliveryTag(), false);
            DebsBenchmarkSystem.this.handleDelivery(body);
        }
    });
}

From source file:pl.nask.hsn2.bus.rabbitmq.endpoint.RbtDefaultConsumer.java

License:Open Source License

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

    super.handleDelivery(consumerTag, envelope, properties, body);

    Message message = new Message(properties.getType(), body, properties.getCorrelationId(),
            new RbtDestination(RABBITMQ_DEFAULT_EXCHANGE_NAME, properties.getReplyTo()));

    message.setDestination(new RbtDestination(RABBITMQ_DEFAULT_EXCHANGE_NAME, envelope.getRoutingKey()));

    message.setContentType(properties.getContentType());

    // take retries count
    try {//w  w  w .  ja  va  2 s  . com
        if (properties.getHeaders() != null) {
            Object xretriesObject = properties.getHeaders().get("x-retries");
            if (xretriesObject != null) {
                int xretries = 0;
                if (xretriesObject instanceof Integer) {
                    xretries = (Integer) xretriesObject;
                } else if (xretriesObject instanceof String) {
                    xretries = Integer.parseInt((String) xretriesObject);
                } else {
                    LOGGER.error("Unknown object type of x-retries property.");
                }
                message.setRetries(xretries);
            }
        }
    } catch (NumberFormatException ex) {
        // not important
    }

    try {
        responseHandler.handleMessage(message);
        if (!autoack) {
            getChannel().basicAck(envelope.getDeliveryTag(), false);
        }
    } catch (ConsumeHandlerException ex) {
        if (!autoack) {
            getChannel().basicReject(envelope.getDeliveryTag(), true);
        }
        // nothing can do :(
    } catch (Throwable t) {
        if (!autoack) {
            getChannel().basicReject(envelope.getDeliveryTag(), true);
        }
        LOGGER.error("Error handling message.", t);
    }
}

From source file:rapture.exchange.rabbitmq.MessageConsumer.java

License:Open Source License

@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
        byte[] body) {
    final String routingKey = envelope.getRoutingKey();
    final String contentType = properties.getContentType();
    final long deliveryTag = envelope.getDeliveryTag();
    log.debug(String.format(Messages.getString("RabbitExchangeHandler.receivedMessage"), deliveryTag)); //$NON-NLS-1$                     
    final RapturePipelineTask task = JacksonUtil.objectFromJson(new String(body), RapturePipelineTask.class);
    log.debug(Messages.getString("RabbitExchangeHandler.PlacingTask")); //$NON-NLS-1$
    try {/* w  w  w  . jav  a 2 s. c o  m*/
        service.execute(new Runnable() {

            @Override
            public void run() {
                boolean ret;
                try {
                    ret = handler.handleMessage(tag, routingKey, contentType, task);
                    log.debug(
                            String.format(Messages.getString("RabbitExchangeHandler.acknowledgeMessage"), ret)); //$NON-NLS-1$
                } catch (Exception e) {
                    log.error(String.format(Messages.getString("RabbitExchangeHandler.noAcknowledge"),
                            ExceptionToString.format(e)));
                } finally {
                    try {
                        getChannel().basicAck(deliveryTag, false);
                    } catch (IOException e) {
                        log.error(String.format("Error while acknowledging message with tag '%s':\n%s",
                                deliveryTag, ExceptionToString.format(e)));
                    }
                }
                log.debug(Messages.getString("RabbitExchangeHandler.deliveryHandled")); //$NON-NLS-1$
            }

        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:server.Server.java

License:Open Source License

/**
 * @param rootDirectory/*from  w  w w  . j  a v a  2s . c  o  m*/
 * @param port
 */
public Server(String rootDirectory, int port, String host, WebServer window) throws Exception {
    this.rootDirectory = rootDirectory;
    this.port = port;
    this.host = host;
    this.stop = false;
    this.connections = 0;
    this.serviceTime = 0;
    this.window = window;
    this.counter = 0;

    // performance improvement - queue
    this.clientRequests = new HashMap<String, Integer>();
    this.bannedClients = new ArrayList<String>();
    this.clients = new HashMap<String, ConnectionHandler>();

    // initialize responseCodes map
    this.responseCodes = new HashMap<Integer, String>();
    this.responseCodes.put(Protocol.OK_CODE, Protocol.GET);
    this.responseCodes.put(Protocol.POST_CODE, Protocol.POST);
    this.responseCodes.put(Protocol.PUT_CODE, Protocol.PUT);
    this.responseCodes.put(Protocol.DELETE_CODE, Protocol.DELETE);

    // create Worker Servers
    WorkerServer wsGet = new WorkerServer(Protocol.GET_QUEUE, this);
    WorkerServer wsGet2 = new WorkerServer(Protocol.GET_QUEUE, this);
    WorkerServer wsPut = new WorkerServer(Protocol.PUT_QUEUE, this);
    WorkerServer wsPost = new WorkerServer(Protocol.POST_QUEUE, this);
    WorkerServer wsDelete = new WorkerServer(Protocol.DELETE_QUEUE, this);

    Thread getThread = new Thread(wsGet);
    Thread get2Thread = new Thread(wsGet2);
    Thread putThread = new Thread(wsPut);
    Thread postThread = new Thread(wsPost);
    Thread deleteThread = new Thread(wsDelete);

    getThread.start();
    get2Thread.start();
    putThread.start();
    postThread.start();
    deleteThread.start();

    // retrieve responses from responses queue
    factory = new ConnectionFactory();
    factory.setHost("localhost");
    connection = factory.newConnection();
    channel = connection.createChannel();
    boolean durable = true;
    channel.queueDeclare(Protocol.RESPONSE_QUEUE, durable, false, false, null);

    channel.basicQos(1);

    final Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
            try {
                HttpResponse response;

                String[] requestParts = message.split("\\" + Protocol.DELIMITER);
                String status = requestParts[0];
                String key = requestParts[requestParts.length - 1];

                String requestType = responseCodes.get(Integer.parseInt(status));

                if (requestType != null) {
                    String file = requestParts[1];
                    File f = new File(file);

                    response = HttpResponseFactory.createRequestWithFile(f, Protocol.CLOSE, requestType);
                } else {
                    response = HttpResponseFactory.createRequest(status, Protocol.CLOSE);
                }
                ConnectionHandler ch = clients.get(key);
                ch.setResponse(response);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println(" [x] Done");
                channel.basicAck(envelope.getDeliveryTag(), false); // send a proper acknowledgment from the worker, once we're done with a task
            }
        }
    };
    channel.basicConsume(Protocol.RESPONSE_QUEUE, false, consumer);
}

From source file:server.WorkerServer.java

License:Open Source License

@Override
public void run() {
    //System.out.println("Running worker queue for: " + QUEUE_NAME);
    try {//from  w w  w. j  a  va  2s .co  m
        factory = new ConnectionFactory();
        factory.setHost("localhost");
        connection = factory.newConnection();
        channel = connection.createChannel();
        boolean durable = true;
        channel.queueDeclare(QUEUE_NAME, durable, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        channel.basicQos(10);

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                HttpRequest request = createRequest(message);
                System.out.println(" [x] Received '" + message + "'");
                try {
                    doWork(request);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    System.out.println(" [x] Done");

                    // send a proper acknowledgment from the worker, once we're done with a task
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            }

            private HttpRequest createRequest(String message) {
                String[] requestParts = message.split("\\" + Protocol.DELIMITER);
                String method = requestParts[0];
                String uri = requestParts[1];
                String version = requestParts[2];
                HashMap<String, String> header = new HashMap<String, String>();
                for (int i = 3; i < requestParts.length - 2; i += 2) {
                    header.put(requestParts[i], requestParts[i + 1]);
                }
                String body = requestParts[requestParts.length - 2];
                String key = requestParts[requestParts.length - 1];
                return new HttpRequest(method, uri, version, header, body, key);
            }
        };
        channel.basicConsume(QUEUE_NAME, false, consumer);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:stock84885orderreceiver.OrderReceiverController.java

public void run() throws IOException, TimeoutException {
    try {/* ww w  . j a  v a 2 s  . co  m*/
        connFactory = new ConnectionFactory();
        connFactory.setHost(hostName);
        connection = connFactory.newConnection();
        ordersChannel = connection.createChannel();
        resultsChannel = connection.createChannel();
        shippingChannel = connection.createChannel();
        ordersChannel.queueDeclare(ordersExchangeName, true, //Passive declaration
                false, //Non-durable queue
                false, //Non-exclusive queue
                null //No arguments
        );
        resultsChannel.exchangeDeclare(resultsExchangeName, "direct");
        shippingChannel.queueDeclare(shippingExchangeName, true, //Passive declaration
                false, //Non-durable queue
                false, //Non-exclusive queue
                null //No arguments
        );
        traceLogger.trace(name + " waiting for orders");
        ordersChannel.basicQos(1);
        final Consumer consumer = new DefaultConsumer(ordersChannel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                Order order = Order.deserialize(body);
                try {
                    processOrder(order);
                } catch (InterruptedException | TimeoutException ex) {
                    traceLogger.error(ex.toString());
                } finally {
                    ordersChannel.basicAck(envelope.getDeliveryTag(), false);
                }
            }
        };
        ordersChannel.basicConsume(ordersExchangeName, false, consumer);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                try {
                    releaseNetworkResources();
                } catch (IOException | TimeoutException ex) {
                    try {
                        traceLogger.error(ex.toString());
                    } catch (IOException ex1) {
                        System.err.println(ex1.toString());
                    }
                }
            }
        });
    } catch (IOException | TimeoutException e) {
        releaseNetworkResources();
        throw e;
    }
}

From source file:stock84885queryhandler.QueryHandlerController.java

public void run() throws IOException, TimeoutException {
    try {/*from   w w  w.jav  a 2s .co  m*/
        connFactory = new ConnectionFactory();
        connFactory.setHost(hostName);
        connection = connFactory.newConnection();
        queriesChannel = connection.createChannel();
        queriesResultsChannel = connection.createChannel();
        queriesChannel.queueDeclare(queriesExchangeName, true, //Passive declaration
                false, //Non-durable queue
                false, //Non-exclusive queue
                null //No arguments
        );
        queriesResultsChannel.exchangeDeclare(queriesResultsExchangeName, "direct");
        logger.trace(name + " waiting for queries...");
        queriesChannel.basicQos(1);
        final Consumer consumer = new DefaultConsumer(queriesChannel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                String userName = new String(body, "UTF-8");
                try {
                    processQuery(userName);
                } catch (Exception ex) {
                    logger.error(ex.toString());
                } finally {
                    queriesChannel.basicAck(envelope.getDeliveryTag(), false);
                }
            }
        };
        queriesChannel.basicConsume(queriesExchangeName, false, consumer);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                try {
                    releaseNetworkResources();
                } catch (IOException | TimeoutException ex) {
                    try {
                        logger.error(ex.toString());
                    } catch (IOException ex1) {
                        System.err.println(ex1.toString());
                    }
                }
            }
        });
    } catch (IOException | TimeoutException e) {
        releaseNetworkResources();
        throw e;
    }
}