List of usage examples for com.rabbitmq.client BasicProperties getCorrelationId
public abstract String getCorrelationId();
From source file:cs.rsa.ts14dist.appserver.RabbitMQDaemon.java
License:Apache License
@Override public void run() { Connection connection = null; Channel channel = null;//from ww w . j av a2 s . co m 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:dfki.sb.rabbitmqjava.RabbitMQObjectStreamServer.java
License:Open Source License
private static void processSendAndRecivePackets(QueueingConsumer consumer, Channel channel) throws InterruptedException, IOException { while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()) .build();//from w w w . j ava 2 s.c o m try { byte[] body = delivery.getBody(); if (body.length == 0) { break; } else { Object obj = SerializationUtils.deserialize(body); if (obj instanceof MarketData) { MarketData response = sendMarketData((MarketData) obj); channel.basicPublish("", props.getReplyTo(), replyProps, SerializationUtils.serialize(response)); } else { QuoteRequest response = sendQuoteRequest((QuoteRequest) obj); channel.basicPublish("", props.getReplyTo(), replyProps, SerializationUtils.serialize(response)); } } } catch (IOException e) { System.out.println(" [.] " + e.toString()); } finally { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } }
From source file:dfki.sb.rabbitmqjava.RabbitMQServer.java
License:Open Source License
public static void main(String[] argv) { Connection connection = null; Channel channel = null;/*from w w w . j a v a 2s .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("Starting server waiting for client requests:"); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()) .build(); DataInputStream dis = new DataInputStream( new BufferedInputStream(new ByteArrayInputStream(delivery.getBody()))); try { int type = dis.readInt(); byte[] response; if (type == 2) { response = handleMarketRequest(dis); } else { response = handleQuoteRequest(dis); } channel.basicPublish("", props.getReplyTo(), replyProps, response); dis.close(); } catch (IOException | ClassNotFoundException e) { System.out.println(" [.] " + e.toString()); } finally { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (IOException | InterruptedException | ShutdownSignalException | ConsumerCancelledException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (IOException ignore) { } } } }
From source file:es.devcircus.rabbitmq_examples.rabbitmq_rpc.RPCServer.java
License:Open Source License
/** * * @param argv//from w ww. j av a2s . c o m */ public static void main(String[] argv) { Connection connection = null; Channel channel = null; try { ConnectionFactory factory = new ConnectionFactory(); // factory.setHost("localhost"); factory.setHost("192.168.0.202"); // factory.setPort(5671); // factory.useSslProtocol(); 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 (IOException | InterruptedException | ShutdownSignalException | ConsumerCancelledException e) { System.out.println(e.toString()); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }
From source file:gash.router.server.MessageServer.java
License:Apache License
public void createQueue() throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException, SQLException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("inbound_queue", false, false, false, null); channel.basicQos(1);/* w w w . j a v a2 s . co m*/ postgre = new PostgreSQL(url, username, password, dbname, ssl); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume("inbound_queue", false, consumer); // Map<String, byte[]> map = new HashMap<String, byte[]>(); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); String request = props.getType(); System.out.println(request); if (request != null) { if (request.equals("get")) { String key = new String(delivery.getBody()); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); byte[] image = postgre.get(key); channel.basicPublish("", props.getReplyTo(), replyProps, image); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } if (request.equals("put")) { byte[] image = delivery.getBody(); postgre.put(props.getUserId(), image); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); channel.basicPublish("", props.getReplyTo(), replyProps, image); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } if (request.equals("post")) { System.out.println("Message Server"); String key = postgre.post(delivery.getBody()); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); channel.basicPublish("", props.getReplyTo(), replyProps, key.getBytes()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } if (request.equals("delete")) { String key = new String(delivery.getBody()); postgre.delete(key); } } } }
From source file:in.cs654.chariot.ashva.AshvaServer.java
License:Open Source License
public static void main(String[] args) { Connection connection = null; Channel channel;/*from www . java2s . com*/ try { final ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST_IP_ADDR); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); final QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_QUEUE_NAME, false, consumer); LOGGER.info("Ashva Server started. Waiting for requests..."); AshvaHelper.joinOrStartChariotPool(); AshvaHelper.startHeartbeat(); while (true) { final QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicResponse response = new BasicResponse(); BasicRequest request = new BasicRequest(); final BasicProperties props = delivery.getProperties(); final BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); try { final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>( BasicRequest.class); decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder); request = avroReader.read(request, decoder); response = AshvaProcessor.process(request); } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in handling request: " + e.getMessage()); response = ResponseFactory.getErrorResponse(request); } finally { baos.reset(); final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>( BasicResponse.class); encoder = EncoderFactory.get().binaryEncoder(baos, encoder); avroWriter.write(response, encoder); encoder.flush(); LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus()); channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in RPC server: " + e.getMessage()); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }
From source file:in.cs654.chariot.prashti.PrashtiServer.java
License:Open Source License
public static void main(String[] args) { Connection connection = null; Channel channel;/* w w w . j a va2 s . c om*/ try { final ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST_IP_ADDR); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); final QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_QUEUE_NAME, false, consumer); LOGGER.info("Prashti Server started. Waiting for requests..."); final List<Prashti> prashtiList = D2Client.getOnlinePrashtiServers(); final String ipAddr = CommonUtils.getIPAddress(); prashtiList.add(new Prashti(ipAddr)); LOGGER.info("Notifying D2 to set Prashti Server IP Address"); D2Client.setPrashtiServers(prashtiList); while (true) { final QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicResponse response = new BasicResponse(); BasicRequest request = new BasicRequest(); final BasicProperties props = delivery.getProperties(); final BasicProperties replyProps = new BasicProperties.Builder() .correlationId(props.getCorrelationId()).build(); try { final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>( BasicRequest.class); decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder); request = avroReader.read(request, decoder); response = RequestProcessor.process(request); } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in handling request: " + e.getMessage()); response = ResponseFactory.getErrorResponse(request); } finally { baos.reset(); final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>( BasicResponse.class); encoder = EncoderFactory.get().binaryEncoder(baos, encoder); avroWriter.write(response, encoder); encoder.flush(); LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus()); channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (Exception e) { e.printStackTrace(); LOGGER.severe("Error in RPC server: " + e.getMessage()); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }
From source file:io.ventu.rpc.amqp.AmqpResponderImpl.java
License:MIT License
CompletableFuture<Void> handleDeliveryInternal(String consumerTag, Envelope envelope, BasicProperties props, byte[] body) { CompletableFuture<byte[]> answer = handleDelivery(envelope.getRoutingKey(), props.getHeaders(), body); return answer.handleAsync((payload, throwable) -> { try {// ww w.j ava2 s . c om if (throwable != null) { payload = String.format("{\"error\": \"Unhandled internal error: %s\"}", throwable.getMessage()) .getBytes(); } BasicProperties resprops = new Builder().correlationId(props.getCorrelationId()) .contentType(CONTENT_TYPE).contentEncoding(ENCODING).build(); channel.basicPublish(channelProvider.rpcExchange(), props.getReplyTo(), resprops, payload); } catch (IOException e) { // this is suppressed in the public call throw new IllegalStateException(e); } return null; }); }
From source file:io.ventu.rpc.amqp.AmqpResponderImplTest.java
License:MIT License
@Test public void handleDeliveryInternal_responsePayloadPublished() throws TimeoutException, IOException, EncodingException, ExecutionException, InterruptedException { String routingKeyPattern = "routingKeyPattern"; String correlationId = "123456789"; Channel channel = mock(Channel.class); ChannelProvider provider = mock(ChannelProvider.class); doReturn("replyExchange").when(provider).rpcExchange(); doReturn(channel).when(provider).provide(anyString(), any()); Map<String, Object> headers = Maps.newHashMap(); headers.put("apikey", "234435345345"); final List<Boolean> invocations = Lists.newArrayList(); final CompletableFuture<byte[]> promise = new CompletableFuture<>(); AmqpResponderImpl responder = new AmqpResponderImpl(provider, routingKeyPattern) { @Override/*from w w w. jav a2s . c om*/ <RQ, RS> CompletableFuture<byte[]> handleDelivery(String routingKey, Map<String, Object> actualHeaders, byte[] payload) { invocations.add(Boolean.TRUE); assertEquals(Req.class.getName(), routingKey); assertEquals("ABC", new String(payload)); assertEquals(headers.get("apikey"), actualHeaders.get("apikey")); promise.complete("CBA".getBytes()); return promise; } }; Envelope env = new Envelope(1L, false, "incomingEexchange", Req.class.getName()); BasicProperties props = new Builder().correlationId(correlationId).replyTo("replyHere").headers(headers) .build(); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { invocations.add(Boolean.TRUE); assertEquals("replyExchange", invocation.getArguments()[0]); assertEquals("replyHere", invocation.getArguments()[1]); BasicProperties respProps = (BasicProperties) invocation.getArguments()[2]; assertEquals(correlationId, respProps.getCorrelationId()); assertEquals(CONTENT_TYPE, respProps.getContentType()); assertEquals(ENCODING, respProps.getContentEncoding()); assertEquals("CBA", new String((byte[]) invocation.getArguments()[3])); return null; } }).when(channel).basicPublish(anyString(), anyString(), any(), any()); responder.handleDeliveryInternal("consumerTag", env, props, "ABC".getBytes()).get(1, TimeUnit.SECONDS); verify(channel).basicPublish(anyString(), anyString(), any(), any()); verifyNoMoreInteractions(channel); assertEquals(2, invocations.size()); }
From source file:io.ventu.rpc.amqp.AmqpResponderImplTest.java
License:MIT License
@Test public void handleDeliveryInternal_onPropagatedThrowable_apiErrorPublished() throws TimeoutException, IOException, EncodingException, ExecutionException, InterruptedException { String routingKeyPattern = "routingKeyPattern"; String correlationId = "123456789"; Channel channel = mock(Channel.class); ChannelProvider provider = mock(ChannelProvider.class); doReturn("replyExchange").when(provider).rpcExchange(); doReturn(channel).when(provider).provide(anyString(), any()); Map<String, Object> headers = Maps.newHashMap(); headers.put("apikey", "234435345345"); final List<Boolean> invocations = Lists.newArrayList(); final CompletableFuture<byte[]> promise = new CompletableFuture<>(); AmqpResponderImpl responder = new AmqpResponderImpl(provider, routingKeyPattern) { @Override// w ww .j a va2 s . c o m <RQ, RS> CompletableFuture<byte[]> handleDelivery(String routingKey, Map<String, Object> actualHeaders, byte[] payload) { invocations.add(Boolean.TRUE); promise.completeExceptionally(new IndexOutOfBoundsException("boom")); return promise; } }; Envelope env = new Envelope(1L, false, "incomingEexchange", Req.class.getName()); BasicProperties props = new Builder().correlationId(correlationId).replyTo("replyHere").headers(headers) .build(); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { invocations.add(Boolean.TRUE); assertEquals("replyExchange", invocation.getArguments()[0]); assertEquals("replyHere", invocation.getArguments()[1]); BasicProperties respProps = (BasicProperties) invocation.getArguments()[2]; assertEquals(correlationId, respProps.getCorrelationId()); assertEquals(CONTENT_TYPE, respProps.getContentType()); assertEquals(ENCODING, respProps.getContentEncoding()); byte[] data = (byte[]) invocation.getArguments()[3]; Map<Object, Object> payload = new DefaultSerializer().decode(data, Map.class); assertEquals("Unhandled internal error: boom", payload.get("error")); return null; } }).when(channel).basicPublish(anyString(), anyString(), any(), any()); responder.handleDeliveryInternal("consumerTag", env, props, "ABC".getBytes()).get(1, TimeUnit.SECONDS); verify(channel).basicPublish(anyString(), anyString(), any(), any()); verifyNoMoreInteractions(channel); assertEquals(2, invocations.size()); }