List of usage examples for com.rabbitmq.client Channel basicPublish
void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;
From source file:uk.org.openeyes.oink.proxy.test.ITProxyRoute.java
License:Open Source License
@Ignore @Test/* w ww . j av a2 s . com*/ public void testGetRequestGetsProxied() throws Exception { // Mock endpoint server InputStream is = ITProxyRoute.class.getResourceAsStream("/example-messages/fhir/patient.json"); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer); String jsonPatient = writer.toString(); byte[] expectedResponseBody = jsonPatient.getBytes(); server.setResponse(200, expectedResponseBody, "application/json+fhir"); server.start(); // Build Oink request String resourcePath = "/Patient/1123"; String parameters = "foo=bar&foo2=bar2"; String method = "GET"; OINKRequestMessage request = new OINKRequestMessage(); request.setResourcePath(resourcePath); request.setParameters(parameters); request.setMethod(HttpMethod.valueOf(method)); // Send Oink request over rabbit Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); String replyQueueName = channel.queueDeclare().getQueue(); channel.queueBind(replyQueueName, testProperties.getProperty("rabbit.defaultExchange"), replyQueueName); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(replyQueueName, true, consumer); BasicProperties props = new BasicProperties().builder().replyTo(replyQueueName).build(); byte[] requestBody = camelCtx.getTypeConverter().convertTo(byte[].class, request); channel.basicPublish(testProperties.getProperty("rabbit.defaultExchange"), testProperties.getProperty("rabbit.routingKey"), props, requestBody); // Wait Thread.sleep(1000); // Assert mocked server receives request intact assertEquals(method, server.getRequestMethod()); assertEquals(parameters, server.getRequestParams()); assertEquals("/oink" + resourcePath, server.getRequestPath()); // Assert response QueueingConsumer.Delivery delivery = consumer.nextDelivery(5000); assertNotNull(delivery); byte[] responseBody = delivery.getBody(); OINKResponseMessage response = camelCtx.getTypeConverter().convertTo(OINKResponseMessage.class, responseBody); String responsePatientJson = camelCtx.getTypeConverter().convertTo(String.class, response.getBody().getResource()); assertEquals(200, response.getStatus()); assertEquals(jsonPatient, responsePatientJson); server.stop(); }
From source file:uk.org.openeyes.oink.proxy.test.ITProxyRoute.java
License:Open Source License
@Ignore @Test/* w ww. j a v a 2 s . c om*/ public void testPostRequestGetsProxied() throws Exception { // Mock endpoint server server.setResponse(201, null, null); server.start(); // Build Oink request OINKRequestMessage request = new OINKRequestMessage(); request.setResourcePath("/Patient"); request.setMethod(HttpMethod.POST); FhirBody body = buildFhirBodyFromResource("/example-messages/fhir/patient.json"); request.setBody(body); // Send Oink request over rabbit Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); String replyQueueName = channel.queueDeclare().getQueue(); channel.queueBind(replyQueueName, testProperties.getProperty("rabbit.defaultExchange"), replyQueueName); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(replyQueueName, true, consumer); BasicProperties props = new BasicProperties().builder().replyTo(replyQueueName).build(); byte[] requestBody = camelCtx.getTypeConverter().convertTo(byte[].class, request); channel.basicPublish(testProperties.getProperty("rabbit.defaultExchange"), testProperties.getProperty("rabbit.routingKey"), props, requestBody); // Wait Thread.sleep(1000); // Assert mocked server receives request intact String requestBodyReceivedByServer = server.getRequestBody(); StringWriter writer = new StringWriter(); IOUtils.copy(ITProxyRoute.class.getResourceAsStream("/example-messages/fhir/patient.json"), writer); String expectedBodyReceivedByServer = writer.toString(); assertEquals(expectedBodyReceivedByServer, requestBodyReceivedByServer); // Assert response QueueingConsumer.Delivery delivery = consumer.nextDelivery(10000); assertNotNull(delivery); byte[] responseBody = delivery.getBody(); OINKResponseMessage response = camelCtx.getTypeConverter().convertTo(OINKResponseMessage.class, responseBody); assertEquals(201, response.getStatus()); server.stop(); }
From source file:uk.org.openeyes.oink.proxy.test.support.RabbitClient.java
License:Open Source License
public byte[] sendAndRecieve(byte[] message, String routingKey, String exchange) throws Exception { log.debug("Sending message to direct exchange:" + exchange + " with routing key:" + routingKey); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchange, "direct", true, false, null); String replyQueueName = channel.queueDeclare().getQueue(); log.debug("Reply queue name is " + replyQueueName); channel.queueBind(replyQueueName, exchange, replyQueueName); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(replyQueueName, true, consumer); String corrId = java.util.UUID.randomUUID().toString(); BasicProperties props = new BasicProperties.Builder().correlationId(corrId).replyTo(replyQueueName).build(); channel.basicPublish(exchange, routingKey, props, message); log.debug("Waiting for delivery"); QueueingConsumer.Delivery delivery = consumer.nextDelivery(20000); connection.close();//from ww w.j ava 2 s . co m if (delivery == null || !delivery.getProperties().getCorrelationId().equals(corrId)) { return null; } else { byte[] response = delivery.getBody(); return response; } }
From source file:uniko.west.test.TwitterLogSender.java
public static void main(String[] args) { /* String strJSONFilePaths = { "/home/ubuntu/data/rawtweet-log-short.log", "/home/ubuntu/data/IITNNO-prepare-json-example.json", "/home/ubuntu/data/json/IITNNO-raw-JSON-example.json", "/home/ubuntu/data/json/ITINNO-aggregated-geoparse-example.json" "/home/ubuntu/data/json/CERTH-RSS-example.json" }; *//* ww w. jav a2 s. c o m*/ // String strJSONFilePath = "/home/ubuntu/data/rawtweet-log-short.log"; //short twitter log // String strJSONFilePath = "/home/ubuntu/data/json/IITNNO-prepare-json-example.json"; //String strJSONFilePath = "/home/ubuntu/data/json/IITNNO-raw-JSON-example.json"; //short itinno // example // String strJSONFilePath = "/home/ubuntu/data/json/ITINNO-aggregated-geoparse-example.json"; //another itinno example String strJSONFilePath = "/home/ubuntu/data/json/simplified-ITINNO-aggregated-geoparse-example.json"; String exchangeName = "ukob_test"; // for (String strJSONFilePath : strJSONFilePaths) { try (BufferedReader br = new BufferedReader(new FileReader(strJSONFilePath))) { // send a UTF-8 encoded JSON tweet to the RabbitMQ (for // stormspout // to pick up and send to bolt) // read UTF-8 JSON text from file Logger.getLogger(TwitterLogSender.class.getName()).log(Level.INFO, "ExampleRabbitmqClient started"); // connect to rabbitmq broker // first of all create connection factory ConnectionFactory factory = new ConnectionFactory(); factory.setUri("amqp://guest:guest@localhost:5672/%2F"); // initialise connection and define channel Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); String jsonLine; while ((jsonLine = br.readLine()) != null) { long timestampSinceEpoch = System.currentTimeMillis() / 1000; // initialise amqp basic peoperties object BasicProperties.Builder basicProperties = new AMQP.BasicProperties.Builder(); basicProperties.build(); basicProperties.timestamp(new Date(timestampSinceEpoch)).build(); basicProperties.contentType("text/json").build(); basicProperties.deliveryMode(1).build(); // publish message channel.basicPublish(exchangeName, "test-routing", basicProperties.build(), jsonLine.getBytes("UTF-8")); } // close connection and channel channel.close(); connection.close(); Logger.getLogger(TwitterLogSender.class.getName()).log(Level.INFO, "ExampleRabbitmqClient finished"); } catch (URISyntaxException | NoSuchAlgorithmException | KeyManagementException | IOException ex) { Logger.getLogger(TwitterLogSender.class.getName()).log(Level.SEVERE, null, ex); // } } }
From source file:user.Client.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("rabbitmq.akhfa.me"); factory.setUsername(username);/* w w w . j ava 2s . c o m*/ factory.setPassword(password); factory.setVirtualHost("pat"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); ArrayList<String> daftarNick = getAllQueues(); String nick = ""; while (true) { Scanner in = new Scanner(System.in); System.out.print("Please enter your command: "); String command = in.nextLine(); String[] com = command.split(" ", 2); try { switch (com[0]) { case "/NICK": if (!nick.equals("")) { System.out.println("You have registered with nickname: " + nick); } else { if (!daftarNick.contains(com[1])) { channel.queueDeclare(com[1], false, false, true, null); nick = com[1]; System.out.println("Your nickname is " + nick); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); 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"); filterChannel(message); } }; channel.basicConsume(nick, true, consumer); } else { System.out.println("Nickname exists."); } } break; case "/JOIN": channel.exchangeDeclare(com[1], "fanout", false, false, false, null); channel.queueBind(nick, com[1], ""); System.out.println("You have successfully join " + com[1]); break; case "/LEAVE": channel.queueUnbind(nick, com[1], ""); System.out.println("Leave " + com[1]); break; case "/EXIT": System.out.println("bye bye... :D"); System.exit(0); default: String message = nick + ' ' + command; channel.basicPublish(com[0].substring(1), "", null, message.getBytes("UTF-8")); break; } } catch (Exception e) { if (command.compareTo("/NICK") == 0) { //random nick String random; if (!nick.equals("")) { System.out.println("You have registered with nickname: " + nick); } else { do { random = randomNick(); } while (daftarNick.contains(random)); nick = random; channel.queueDeclare(random, false, false, true, null); System.out.println("Your nickname is " + random); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); 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"); filterChannel(message); } }; channel.basicConsume(nick, true, consumer); } } else if ((command.compareTo("/JOIN") == 0) || (command.compareTo("/LEAVE") == 0)) { //error System.out.println("Please enter channel name!"); } else if (command.charAt(0) == '@') { System.out.println("Please enter your command for the channel."); } else { System.out.println("Invalid command."); } } } }
From source file:v2.APAdmin.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); String queueName = channel.queueDeclare().getQueue(); String bindingKey = "AP.*"; channel.queueBind(queueName, EXCHANGE_NAME, bindingKey); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override/* ww w .j ava 2 s . c om*/ 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 '" + envelope.getRoutingKey() + "':'" + message + "'"); //REPLY HERE String response = "You are in, breh"; BasicProperties replyProps = new BasicProperties.Builder() .correlationId(properties.getCorrelationId()).build(); channel.basicPublish("", properties.getReplyTo(), replyProps, response.getBytes()); } }; channel.basicConsume(queueName, true, consumer); }
From source file:v2.Student.java
public static void main(String[] argv) { Connection connection = null; Channel channel = null; try {//w w w . j av a2 s . co m ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); String routingKey = "AP.DAT";//getRouting(argv); String message = "Plz enroll me, breh";//getMessage(argv); String corrId = java.util.UUID.randomUUID().toString(); String callbackQueueName = channel.queueDeclare().getQueue(); String response = null; QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(callbackQueueName, true, consumer); BasicProperties props = new BasicProperties.Builder().replyTo(callbackQueueName).build(); channel.basicPublish(EXCHANGE_NAME, routingKey, props, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'"); while (true) { System.out.println("blocked?"); QueueingConsumer.Delivery delivery = consumer.nextDelivery(); System.out.println("unblocked"); System.out.println(delivery); response = new String(delivery.getBody()); System.out.println(response); // if (delivery.getProperties().getCorrelationId().equals(corrId)) { // response = new String(delivery.getBody()); // System.out.println(response); // break; // } } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }
From source file:wiki.messaging.NewTask.java
License:Open Source License
public static void main(String[] args) throws IOException { int n = 500;/* w ww .j a v a 2s . c om*/ String url = null; String rabbitMqUrl = null; for (int i = 0; i < args.length; i++) { if (args[i].equals("ds")) { url = args[i + 1]; } else if (args[i].equals("rq")) { rabbitMqUrl = args[i + 1]; } else if (args[i].equals("n")) { n = Integer.valueOf(args[i + 1]); } } DbConnector ds = new DbConnector(url); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rabbitMqUrl); factory.setUsername("wiki"); factory.setPassword("wiki"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); RandomDocGetter rdg = new RandomDocGetter(ds); for (int i = 0; i < n; i++) { String message = getMessage(rdg); channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); } channel.close(); connection.close(); }
From source file:wiki.messaging.Receive.java
License:Open Source License
private static void saveResult(Channel results) throws IOException { if (jobs < maxJobs) { return;//w w w . j a v a2 s . c om } try { Future<Result> result = threadPool.take(); byte[] message = encodeResult(result.get()).getBytes(); results.basicPublish("", RESULT_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message); System.out.println(" [x] Sent '" + new String(message) + "'"); // result.get().save(results); jobs--; } catch (ExecutionException | InterruptedException e) { e.printStackTrace(); System.exit(1); } }
From source file:wiki.messaging.Treeceive.java
License:Open Source License
private static void saveResults(Channel resultChannel) throws IOException { if (jobs < maxJobs) { return;/*from w ww.ja v a 2 s . co m*/ } try { Future<ArrayList<Result>> results = threadPool.take(); ArrayList<Result> resultList = results.get(); for (Result r : resultList) { byte[] message = encodeResult(r).getBytes(); resultChannel.basicPublish("", RESULT_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message); System.out.println(" [x] Sent '" + new String(message) + "'"); } jobs--; } catch (ExecutionException | InterruptedException e) { e.printStackTrace(); System.exit(1); } }