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:com.analogmountains.flume.RabbitMQSource.java

License:Open Source License

private Map<String, String> eventHeadersFromBasicProperties(BasicProperties properties) {
    Map<String, String> headers = new HashMap<String, String>();
    if (properties.getAppId() != null) {
        headers.put("appId", properties.getAppId());
    }/* ww w .ja  v a  2  s  . c o m*/
    if (properties.getContentEncoding() != null) {
        headers.put("contentEncoding", properties.getContentEncoding());
    }
    if (properties.getContentType() != null) {
        headers.put("contentType", properties.getContentType());
    }
    if (properties.getCorrelationId() != null) {
        headers.put("correlationId", properties.getCorrelationId());
    }
    if (properties.getDeliveryMode() != null) {
        headers.put("deliveryMode", Integer.toString(properties.getDeliveryMode()));
    }
    if (properties.getExpiration() != null) {
        headers.put("expiration", properties.getExpiration());
    }
    if (properties.getMessageId() != null) {
        headers.put("messageId", properties.getMessageId());
    }
    if (properties.getPriority() != null) {
        headers.put("priority", Integer.toString(properties.getPriority()));
    }
    if (properties.getReplyTo() != null) {
        headers.put("replyTo", properties.getReplyTo());
    }
    if (properties.getType() != null) {

        headers.put("type", properties.getType());
    }
    if (properties.getUserId() != null) {
        headers.put("userId", properties.getUserId());
    }
    return headers;
}

From source file:com.DeadLetterReceiver.java

License:Open Source License

public static void main(String[] args)
        throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOSTNAME);//from w  w w  .j  a  v a2 s . c  om
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    //creating reply queue
    try {
        channel.queueDeclarePassive(QUEUE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    }

    System.out.println(" [*] Waiting for responses. To exit press CTRL+C");
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(QUEUE_NAME, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        BasicProperties props = delivery.getProperties();
        String message = new String(delivery.getBody());
        System.out.println(" [x] Response received '" + message + "'");
        System.out.println("Correlation id : " + props.getCorrelationId());
    }
}

From source file:com.github.liyp.rabbitmq.rpc.RPCServer.java

License:Apache License

public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;/*from   w ww .j a  v a 2 s  .c  o  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:com.hopped.running.rabbitmq.rpc.ARPCServer.java

License:Open Source License

/**
 * /*from www . j  a  v  a  2  s . com*/
 */
public void consume() {
    checkConsumer();

    while (true) {
        try {
            Delivery delivery = consumer.nextDelivery();
            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();

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

            byte[] payload = processRequest(delivery);

            channel.basicPublish("", props.getReplyTo(), replyProps, payload);

        } catch (ShutdownSignalException | ConsumerCancelledException | InterruptedException | IOException e) {
            logger.error(e.getMessage());
            closeConnection();
        }
    }
}

From source file:com.shopwiki.roger.MessagingUtil.java

License:Apache License

public static String prettyPrint(BasicProperties props) {
    StringBuilder sb = new StringBuilder();
    sb.append("\t" + "ContentType: " + props.getContentType() + "\n");
    sb.append("\t" + "ContentEncoding: " + props.getContentEncoding() + "\n");
    sb.append("\t" + "Headers: " + props.getHeaders() + "\n");
    sb.append("\t" + "DeliveryMode: " + props.getDeliveryMode() + "\n");
    sb.append("\t" + "Priority: " + props.getPriority() + "\n");
    sb.append("\t" + "CorrelationId: " + props.getCorrelationId() + "\n");
    sb.append("\t" + "ReplyTo: " + props.getReplyTo() + "\n");
    sb.append("\t" + "Expiration: " + props.getExpiration() + "\n");
    sb.append("\t" + "MessageId: " + props.getMessageId() + "\n");
    sb.append("\t" + "Timestamp: " + props.getTimestamp() + "\n");
    sb.append("\t" + "Type: " + props.getType() + "\n");
    sb.append("\t" + "UserId: " + props.getUserId() + "\n");
    sb.append("\t" + "AppId: " + props.getAppId());
    return sb.toString();
}

From source file:com.shopwiki.roger.rpc.RequestConsumer.java

License:Apache License

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

    I request = null;/*from w ww .  j  av a 2 s.  c  om*/
    ResponseStatus status = null;
    Object response = null;
    Throwable thrown = null;
    long timeTaken = -1;

    try {
        long startTime = System.currentTimeMillis();

        try {
            request = MessagingUtil.getDeliveryBody(body, requestType);
        } catch (Exception e) {
            response = new ExceptionResponse(e);
            status = ResponseStatus.MALFORMED_REQUEST;
            thrown = e;
        }

        if (DEBUG) {
            System.out.println(
                    "*** RequestHandler " + handler.getClass().getCanonicalName() + " RECEIVED REQUEST ***");
            System.out.println("*** consumerTag: " + consumerTag);
            System.out.println("*** envelope:\n" + MessagingUtil.prettyPrint(envelope));
            System.out.println("*** requestProps:\n" + MessagingUtil.prettyPrint(requestProps));
            System.out.println("*** request: " + MessagingUtil.prettyPrintMessage(request));
            System.out.println();
        }

        if (request != null) {
            try {
                response = handler.handleRequest(request);
                status = ResponseStatus.OK;
            } catch (NackException e) {
                thrown = e;
                channel.basicNack(envelope.getDeliveryTag(), false, true);
                return;
            } catch (IllegalArgumentException e) {
                response = new ExceptionResponse(e);
                status = ResponseStatus.INVALID_REQUEST;
                thrown = e;
            } catch (Throwable e) {
                response = new ExceptionResponse(e);
                status = ResponseStatus.HANDLER_ERROR;
                thrown = e;
            }
        }

        timeTaken = System.currentTimeMillis() - startTime;

        // Ack before or after the reply is sent ???
        channel.basicAck(envelope.getDeliveryTag(), false);

        String replyTo = requestProps.getReplyTo();
        String correlationId = requestProps.getCorrelationId();

        if (correlationId != null && replyTo != null) {
            Map<String, Object> headers = new LinkedHashMap<String, Object>();
            headers.put("status", String.valueOf(status));
            headers.put("handler_time_millis", String.valueOf(timeTaken));
            headers.put("hostname", hostname);

            BasicProperties.Builder replyProps = new BasicProperties.Builder();
            replyProps = replyProps.headers(headers);
            replyProps = replyProps.correlationId(correlationId);
            // TODO: delivery mode ???
            MessagingUtil.sendResponse(channel, replyTo, response, replyProps);
        }
    } catch (Throwable e) {
        status = ResponseStatus.NUCLEAR;
        thrown = e;
    } finally {
        if (pps != null) {
            pps.process(handler, queueName, status, request, response, thrown, timeTaken);
        }
    }
}

From source file:com.springsource.insight.plugin.rabbitmqClient.AbstractRabbitMQCollectionAspect.java

License:Apache License

protected void applyPropertiesData(Operation op, BasicProperties props) {
    OperationMap map = op.createMap("props");

    map.putAnyNonEmpty("Type", props.getType());
    map.putAnyNonEmpty("App Id", props.getAppId());
    map.putAnyNonEmpty("User Id", props.getUserId());
    map.put("Class Id", props.getClassId());
    map.putAnyNonEmpty("Reply To", props.getReplyTo());
    map.putAnyNonEmpty("Priority", props.getPriority());
    map.putAnyNonEmpty("Class Name", props.getClassName());
    map.putAnyNonEmpty("Timestamp", props.getTimestamp());
    map.putAnyNonEmpty("Message Id", props.getMessageId());
    map.putAnyNonEmpty("Expiration", props.getExpiration());
    map.putAnyNonEmpty("Content Type", props.getContentType());
    map.putAnyNonEmpty("Delivery Mode", props.getDeliveryMode());
    map.putAnyNonEmpty("Correlation Id", props.getCorrelationId());
    map.putAnyNonEmpty("Content Encoding", props.getContentEncoding());

    Map<String, Object> headers = props.getHeaders();

    if (headers != null) {
        OperationMap headersMap = op.createMap("headers");

        for (Entry<String, Object> entry : headers.entrySet()) {
            Object value = entry.getValue();

            if (value instanceof LongString) {
                byte[] bytes = ((LongString) value).getBytes();
                value = new String(bytes);
            }//from  ww  w .  j  av  a2s .co m

            headersMap.putAnyNonEmpty(entry.getKey(), value);
        }
    }
}

From source file:com.streamsets.pipeline.stage.origin.rabbitmq.RabbitSource.java

License:Apache License

@Override
public String produce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException {
    if (!isConnected() && !conf.advanced.automaticRecoveryEnabled) {
        // If we don't have automatic recovery enabled and the connection is closed, we should stop the pipeline.
        throw new StageException(Errors.RABBITMQ_05);
    }/*from  w  w w .  j a v a 2 s. co m*/

    long maxTime = System.currentTimeMillis() + conf.basicConfig.maxWaitTime;
    int maxRecords = Math.min(maxBatchSize, conf.basicConfig.maxBatchSize);
    int numRecords = 0;
    String nextSourceOffset = lastSourceOffset;
    while (System.currentTimeMillis() < maxTime && numRecords < maxRecords) {
        try {
            RabbitMessage message = messages.poll(conf.basicConfig.maxWaitTime, TimeUnit.MILLISECONDS);
            if (message == null) {
                continue;
            }
            String recordId = message.getEnvelope().toString();
            List<Record> records = parseRabbitMessage(recordId, message.getBody());
            for (Record record : records) {
                Envelope envelope = message.getEnvelope();
                BasicProperties properties = message.getProperties();
                Record.Header outHeader = record.getHeader();
                if (envelope != null) {
                    setHeaderIfNotNull(outHeader, "deliveryTag", envelope.getDeliveryTag());
                    setHeaderIfNotNull(outHeader, "exchange", envelope.getExchange());
                    setHeaderIfNotNull(outHeader, "routingKey", envelope.getRoutingKey());
                    setHeaderIfNotNull(outHeader, "redelivered", envelope.isRedeliver());
                }
                setHeaderIfNotNull(outHeader, "contentType", properties.getContentType());
                setHeaderIfNotNull(outHeader, "contentEncoding", properties.getContentEncoding());
                setHeaderIfNotNull(outHeader, "deliveryMode", properties.getDeliveryMode());
                setHeaderIfNotNull(outHeader, "priority", properties.getPriority());
                setHeaderIfNotNull(outHeader, "correlationId", properties.getCorrelationId());
                setHeaderIfNotNull(outHeader, "replyTo", properties.getReplyTo());
                setHeaderIfNotNull(outHeader, "expiration", properties.getExpiration());
                setHeaderIfNotNull(outHeader, "messageId", properties.getMessageId());
                setHeaderIfNotNull(outHeader, "timestamp", properties.getTimestamp());
                setHeaderIfNotNull(outHeader, "messageType", properties.getType());
                setHeaderIfNotNull(outHeader, "userId", properties.getUserId());
                setHeaderIfNotNull(outHeader, "appId", properties.getAppId());
                Map<String, Object> inHeaders = properties.getHeaders();
                if (inHeaders != null) {
                    for (Map.Entry<String, Object> pair : inHeaders.entrySet()) {
                        // I am concerned about overlapping with the above headers but it seems somewhat unlikely
                        // in addition the behavior of copying these attributes in with no custom prefix is
                        // how the jms origin behaves
                        setHeaderIfNotNull(outHeader, pair.getKey(), pair.getValue());
                    }
                }
                batchMaker.addRecord(record);
                nextSourceOffset = outHeader.getAttribute("deliveryTag");
                numRecords++;
            }
        } catch (InterruptedException e) {
            LOG.warn("Pipeline is shutting down.");
        }
    }
    return nextSourceOffset;
}

From source file:com.surgeplay.visage.slave.RenderThread.java

License:Open Source License

@Override
public void run() {
    try {/* w ww.j  a v  a  2 s.co  m*/
        Visage.log.info("Waiting for jobs");
        try {
            while (run) {
                if (!toProcess.isEmpty()) {
                    Delivery delivery = toProcess.pop();
                    try {
                        processDelivery(delivery);
                    } catch (Exception e) {
                        Visage.log.log(Level.SEVERE, "An unexpected error occurred while rendering", e);
                        BasicProperties props = delivery.getProperties();
                        BasicProperties replyProps = new BasicProperties.Builder()
                                .correlationId(props.getCorrelationId()).build();
                        ByteArrayOutputStream ex = new ByteArrayOutputStream();
                        ObjectOutputStream oos = new ObjectOutputStream(ex);
                        oos.writeObject(e);
                        oos.flush();
                        parent.channel.basicPublish("", props.getReplyTo(), replyProps,
                                buildResponse(1, ex.toByteArray()));
                        parent.channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                    }
                } else {
                    synchronized (toProcess) {
                        toProcess.wait();
                    }
                }
            }
            for (Renderer r : renderers) {
                if (r != null) {
                    r.destroy();
                }
            }
        } catch (Exception e) {
            Visage.log.log(Level.SEVERE, "A fatal error has occurred in the render thread run loop.", e);
        }
    } catch (Exception e) {
        Visage.log.log(Level.SEVERE, "A fatal error has occurred while setting up a render thread.", e);
    }
}

From source file:com.surgeplay.visage.slave.RenderThread.java

License:Open Source License

private void processDelivery(Delivery delivery) throws Exception {
    BasicProperties props = delivery.getProperties();
    BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()).build();
    DataInputStream data = new DataInputStream(
            new InflaterInputStream(new ByteArrayInputStream(delivery.getBody())));
    RenderMode mode = RenderMode.values()[data.readUnsignedByte()];
    int width = data.readUnsignedShort();
    int height = data.readUnsignedShort();
    int supersampling = data.readUnsignedByte();
    GameProfile profile = Profiles.readGameProfile(data);
    Map<String, String[]> params = Maps.newHashMap();
    int len = data.readUnsignedShort();
    for (int i = 0; i < len; i++) {
        String key = data.readUTF();
        String[] val = new String[data.readUnsignedByte()];
        for (int v = 0; v < val.length; v++) {
            val[v] = data.readUTF();
        }/*from w  w  w . j  a  v  a 2  s .c o m*/
        params.put(key, val);
    }
    byte[] skinData = new byte[data.readInt()];
    data.readFully(skinData);
    BufferedImage skinRaw = new PngImage().read(new ByteArrayInputStream(skinData), false);
    BufferedImage skin = Images.toARGB(skinRaw);
    Visage.log.info("Received a job to render a " + width + "x" + height + " " + mode.name().toLowerCase()
            + " (" + supersampling + "x supersampling) for " + (profile == null ? "null" : profile.getName()));
    byte[] pngBys = draw(mode, width, height, supersampling, profile, skin, params);
    if (Visage.trace)
        Visage.log.finest("Got png bytes");
    parent.channel.basicPublish("", props.getReplyTo(), replyProps, buildResponse(0, pngBys));
    if (Visage.trace)
        Visage.log.finest("Published response");
    parent.channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    if (Visage.trace)
        Visage.log.finest("Ack'd message");
}