Example usage for com.rabbitmq.client BasicProperties.Builder BasicProperties.Builder

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

Introduction

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

Prototype

BasicProperties.Builder

Source Link

Usage

From source file:com.interop.webapp.WebApp.java

License:Apache License

@RequestMapping(value = "/effectrequest/{name}/{imagename:[a-zA-Z0-9%\\.]*}", headers = "Accept=*/*", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody EffectRequest effectRequest(@PathVariable("name") String name,
        @PathVariable("imagename") String imageName) {
    String user = getLoggedInUser();
    String hostName = this.config.getHostName();
    UserImageFileRepository store = new UserImageFileRepository(user, config.getImageFilesRoot());

    String status = "submitted";
    String correlationId = java.util.UUID.randomUUID().toString();

    Map<String, Object> mapObject = new HashMap<String, Object>();
    String imageFullPath = store.getPath(imageName);
    String ext = imageFullPath.substring(imageFullPath.lastIndexOf('.') + 1);
    String processedFileName = String.format("%s/%s/%s.%s", config.getImageFilesRoot(), processedFilesWebPath,
            correlationId, ext);/*from   w  w w.ja  v  a  2 s .  c  om*/

    long created = System.currentTimeMillis();
    mapObject.put("correlationId", correlationId);
    mapObject.put("user", user);
    mapObject.put("inputPath", imageFullPath);
    mapObject.put("ouputPath", processedFileName);
    mapObject.put("effectName", name);
    mapObject.put("requestHost", hostName);
    mapObject.put("requestCreated", created);

    JsonWrapper objJson = new JsonWrapper();
    String message = objJson.toJson(mapObject);

    BasicProperties props = new BasicProperties.Builder().correlationId(correlationId).replyTo(replyQueueName)
            .build();
    try {
        channel.basicPublish("", config.getQueueName(), props, message.getBytes());
        log.info(String.format("effectrequest\tsuccess\t%s\t%s\t%s", hostName, user, correlationId));
    } catch (IOException e) {
        log.error(String.format("effectrequest\tfail\t%s\t%s\t%s\t%s", hostName, user, correlationId,
                e.getMessage()));
        status = "failed";
    }
    return new EffectRequest(status, correlationId, created);
}

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

License:Apache License

public static void sendMessage(Channel channel, Route route, Object message) throws IOException {
    BasicProperties.Builder props = new BasicProperties.Builder();
    sendMessage(channel, route.exchange, route.key, message, props);
}

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

License:Apache License

public static void sendRequest(Channel channel, Route route, Object request, String callbackQueue,
        String correlationId) throws IOException {
    BasicProperties.Builder props = new BasicProperties.Builder().replyTo(callbackQueue)
            .correlationId(correlationId);
    sendMessage(channel, route.exchange, route.key, request, props);
}

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 w  w . ja va  2 s.  c o m*/
    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:cs.rsa.ts14dist.appserver.RabbitMQDaemon.java

License:Apache License

@Override
public void run() {

    Connection connection = null;
    Channel channel = null;/*from   w w  w . jav  a  2s  . c om*/
    try {
        ConnectionFactory factory = new ConnectionFactory();
        logger.info("Starting RabbitMQDaemon, MQ IP = " + hostname);
        factory.setHost(hostname);

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

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

        channel.basicQos(1);

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

        while (true) {
            String response = null;

            // Block and fetch next msg from queue
            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");
                logger.trace("Received msg: " + message);

                // Convert the message to a JSON request object
                JSONObject request = (JSONObject) JSONValue.parse(message);

                // Delegate to the server request handler for handling the
                // request and computing an answer
                JSONObject reply = serverRequestHandler.handleRequest(request);

                // Convert the answer back into a string for replying to
                // client
                response = reply.toJSONString();
            } catch (Exception e) {
                logger.error(" Exception in MQDAemon run()/while true] " + e.toString());
                response = "wrong";
            } finally {
                logger.trace("Returning answer: " + response);
                channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                logger.trace("Answer acknowledged.");
            }
        }
    } catch (Exception e) {
        logger.error("Exception in daemon's outer loop: nested exception" + e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:cs.rsa.ts14dist.appserver.RabbitMQRPCConnector.java

License:Apache License

@Override
public JSONObject sendHighPriorityRequestAndBlockUntilReply(JSONObject payload) throws IOException {
    String response = null;/*from   w w  w  .j  a va  2s  .  c  o  m*/
    String corrId = UUID.randomUUID().toString();

    BasicProperties props = new BasicProperties.Builder().correlationId(corrId)
            .replyTo(replyHighPriorityQueueName).build();

    String message = payload.toJSONString();

    logger.trace("Send request: " + message);
    channelHighPriority.basicPublish("", requestHighPriorityQueueName, props, message.getBytes());

    while (true) {
        QueueingConsumer.Delivery delivery = null;
        try {
            delivery = consumerHighPriority.nextDelivery();
        } catch (ShutdownSignalException e) {
            logger.error("ShutdownException: " + e.getMessage());
            e.printStackTrace();
        } catch (ConsumerCancelledException e) {
            logger.error("ConsumerCancelledException: " + e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            logger.error("InterruptedException: " + e.getMessage());
            e.printStackTrace();
        }
        if (delivery.getProperties().getCorrelationId().equals(corrId)) {
            response = new String(delivery.getBody(), "UTF-8");
            logger.trace("Retrieved reply: " + response);
            break;
        }
    }

    JSONObject reply = (JSONObject) JSONValue.parse(response);
    return reply;
}

From source file:cs.rsa.ts14dist.appserver.RabbitMQRPCConnector.java

License:Apache License

@Override
public JSONObject sendLowPriorityRequestAndBlockUntilReply(JSONObject payload) throws IOException {
    String response = null;//  w  w  w .  j  a v a2  s . c  o m
    String corrId = UUID.randomUUID().toString();

    BasicProperties props = new BasicProperties.Builder().correlationId(corrId)
            .replyTo(replyLowPriorityQueueName).build();

    String message = payload.toJSONString();

    logger.trace("Send request: " + message);
    channelLowPriority.basicPublish("", requestLowPriorityQueueName, props, message.getBytes());

    while (true) {
        QueueingConsumer.Delivery delivery = null;
        try {
            delivery = consumerLowPriority.nextDelivery();
        } catch (ShutdownSignalException e) {
            logger.error("ShutdownException: " + e.getMessage());
            e.printStackTrace();
        } catch (ConsumerCancelledException e) {
            logger.error("ConsumerCancelledException: " + e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            logger.error("InterruptedException: " + e.getMessage());
            e.printStackTrace();
        }
        if (delivery.getProperties().getCorrelationId().equals(corrId)) {
            response = new String(delivery.getBody(), "UTF-8");
            logger.trace("Retrieved reply: " + response);
            break;
        }
    }

    JSONObject reply = (JSONObject) JSONValue.parse(response);
    return reply;
}

From source file:loanbroker.normalizer.CallTeachersJsonBank.java

public static void main(String[] args) {
    Gson gson = new Gson();
    DtoJsonBank jsonBank = null;/*  www. j  a  va 2 s  . co  m*/
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("datdb.cphbusiness.dk");
        factory.setPort(5672);
        factory.setUsername("student");
        factory.setPassword("cph");

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

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

        //reply
        String corrId = java.util.UUID.randomUUID().toString();
        BasicProperties props = new BasicProperties.Builder().correlationId("test1122").replyTo(replyQueueName)
                .build();

        String message = gson.toJson(new DtoJsonBank("1605789787", 598, 10.0, ""));
        channel.basicPublish(EXCHANGE_NAME, "", props, message.getBytes());

        channel.close();
        connection.close();

    } catch (IOException | TimeoutException e) {
        e.printStackTrace();
    }

}

From source file:org.trianacode.TrianaCloud.Broker.RPCServer.java

License:Open Source License

public void run() {
    while (keepRunning) {
        try {//w w w  .  j  a v a  2  s  .  c om
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();

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

            byte[] del = delivery.getBody();

            byte[] method = Arrays.copyOfRange(del, 0, 7);
            byte[] message = Arrays.copyOfRange(del, 7, del.length);

            if (Arrays.equals(method, RPCClient.GET_TASK.getBytes())) {
                String[] plugins = (new String(message)).split("\n");

                ///TODO: grab tasks by plugin

                logger.info(" [.] Task Requested");
                Task t = td.getNextPending();
                if (t == null) {
                    t = new Task();
                    t.setNOTASK(true);
                    t.setTimeToWait(10);
                }
                channel.basicPublish("", props.getReplyTo(), replyProps, TaskOps.encodeTask(t));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } else if (Arrays.equals(method, RPCClient.RETURN_TASK.getBytes())) {
                Task rettask = TaskOps.decodeTask(message);

                if (rettask.getNOTASK()) {
                    byte[] ret = new byte[0];
                    channel.basicPublish("", props.getReplyTo(), replyProps, ret);
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                } else {
                    Task task = td.getByUUID(rettask.getUUID());

                    task.setReturnCode(rettask.getReturnCode());
                    task.setReturnData(rettask.getReturnData());
                    task.setReturnDataMD5(rettask.getReturnDataMD5());
                    task.setReturnDataType(rettask.getReturnDataType());
                    task.setState(Task.COMPLETE);

                    td.save(task);

                    logger.info(" [x] Task " + task.getUUID() + " Complete");

                    byte[] ret = new byte[1];
                    ret[0] = 0;
                    channel.basicPublish("", props.getReplyTo(), replyProps, ret);
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                }

            } //else if some other rpc call/method/thing
        } catch (ShutdownSignalException e) {
            System.out.println("Shutting down the RPC Server");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Error", e);
        }
    }

}