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:org.elasticsearch.river.rabbitmq.RabbitMQRiverScriptTest.java
License:Apache License
public static void main(String[] args) throws Exception { Settings settings = ImmutableSettings.settingsBuilder().put("gateway.type", "none") .put("index.number_of_shards", 1).put("index.number_of_replicas", 0) .put("script.native.mock_script.type", MockScriptFactory.class).build(); Node node = NodeBuilder.nodeBuilder().settings(settings).node(); node.client().prepareIndex("_river", "test1", "_meta") .setSource(jsonBuilder().startObject().field("type", "rabbitmq").startObject("bulk_script_filter") .field("script", "mock_script").field("script_lang", "native").endObject().endObject()) .execute().actionGet();/* ww w .ja va2s . c om*/ ConnectionFactory cfconn = new ConnectionFactory(); cfconn.setHost("localhost"); cfconn.setPort(AMQP.PROTOCOL.PORT); Connection conn = cfconn.newConnection(); Channel ch = conn.createChannel(); ch.exchangeDeclare("elasticsearch", "direct", true); ch.queueDeclare("elasticsearch", true, false, false, null); String message = "{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n" + "{ \"type1\" : { \"field1\" : \"value1\" } }\n" + "{ \"delete\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n" + "{ \"create\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"3\" } }\n" + "{ \"type1\" : { \"field3\" : \"value3\" } }" + ""; ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes()); ch.close(); conn.close(); Thread.sleep(100000); }
From source file:org.elasticsearch.river.rabbitmq.RabbitMQRiverSingleLineScriptTest.java
License:Apache License
public static void main(String[] args) throws Exception { Settings settings = ImmutableSettings.settingsBuilder().put("gateway.type", "none") .put("index.number_of_shards", 1).put("index.number_of_replicas", 0).build(); Node node = NodeBuilder.nodeBuilder().settings(settings).node(); node.client().prepareIndex("_river", "test1", "_meta") .setSource(jsonBuilder().startObject().field("type", "rabbitmq").startObject("script_filter") .field("script", "ctx.type1.field1 += param1").field("script_lang", "mvel") .startObject("script_params").field("param1", 1).endObject().endObject().endObject()) .execute().actionGet();//from w ww. jav a 2 s . c o m ConnectionFactory cfconn = new ConnectionFactory(); cfconn.setHost("localhost"); cfconn.setPort(AMQP.PROTOCOL.PORT); Connection conn = cfconn.newConnection(); Channel ch = conn.createChannel(); ch.exchangeDeclare("elasticsearch", "direct", true); ch.queueDeclare("elasticsearch", true, false, false, null); String message = "{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n" + "{ \"type1\" : { \"field1\" : 1 } }\n" + "{ \"delete\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n" + "{ \"create\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"3\" } }\n" + "{ \"type1\" : { \"field1\" : 2 } }" + ""; ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes()); ch.close(); conn.close(); Thread.sleep(10000); }
From source file:org.elasticsearch.river.rabbitmq.RabbitMQRiverTest.java
License:Apache License
public static void main(String[] args) throws Exception { Node node = NodeBuilder.nodeBuilder() .settings(ImmutableSettings.settingsBuilder().put("gateway.type", "none")).node(); node.client().prepareIndex("_river", "test1", "_meta") .setSource(jsonBuilder().startObject().field("type", "rabbitmq").endObject()).execute().actionGet(); ConnectionFactory cfconn = new ConnectionFactory(); cfconn.setHost("localhost"); cfconn.setPort(AMQP.PROTOCOL.PORT);/*from ww w. ja va 2 s . c o m*/ Connection conn = cfconn.newConnection(); Channel ch = conn.createChannel(); ch.exchangeDeclare("elasticsearch", "direct", true); ch.queueDeclare("elasticsearch", true, false, false, null); String message = "{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n" + "{ \"type1\" : { \"field1\" : \"value1\" } }\n" + "{ \"delete\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n" + "{ \"create\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" }\n" + "{ \"type1\" : { \"field1\" : \"value1\" } }"; ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes()); ch.close(); conn.close(); Thread.sleep(100000); }
From source file:org.elasticsearch.river.rabbitmq.RabbitMQRiverWithCustomActionsTest.java
License:Apache License
public static void main(String[] args) throws Exception { String rabbitHost = "rabbit-qa1"; Node node = NodeBuilder.nodeBuilder().settings( ImmutableSettings.settingsBuilder().put("gateway.type", "none").put("cluster.name", "es-mqtest")) .node();//w w w.j a va2 s .c om node.client().prepareIndex("_river", "mqtest1", "_meta") .setSource(jsonBuilder().startObject().field("type", "rabbitmq").startObject("rabbitmq") .field("host", rabbitHost).endObject().startObject("index").field("ordered", "true") .field("warnOnBulkErrors", "false").endObject().endObject()) .execute().actionGet(); ConnectionFactory cfconn = new ConnectionFactory(); cfconn.setHost(rabbitHost); cfconn.setPort(AMQP.PROTOCOL.PORT); Connection conn = cfconn.newConnection(); Channel ch = conn.createChannel(); ch.exchangeDeclare("elasticsearch", "direct", true); ch.queueDeclare("elasticsearch", true, false, false, null); Thread.sleep(5000); String message = "{ \"index\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"2\"} }\n" + "{ \"type1\" : { \"field1\" : \"value1\" } }\n" + "{ \"delete\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n" + "{ \"create\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"2\"} }\n" + "{ \"create\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"1\"} }\n" + "{ \"type1\" : { \"field1\" : \"value1\" } }"; String messageWithWrongIndex = "{ \"index\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"2\"} }\n" + "{ \"type1\" : { \"field1\" : \"value1\" } }\n" + "{ \"delete\" : { \"_index\" : \"This.Is.An.Invalid.Name\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n" + "{ \"create\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"2\"} }\n" + "{ \"create\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"1\"} }\n" + "{ \"type1\" : { \"field1\" : \"value1\" } }"; String mapping = "{ \"type2\" : { \"properties\" : {\"data\" : {\"dynamic\" : true,\"properties\" : {\"myString\" : {\"type\" : \"string\",\"boost\" : 1.0,\"index\" : \"not_analyzed\",\"store\" : \"no\"},\"myText\" : {\"type\" : \"string\",\"include_in_all\" : true,\"index\" : \"analyzed\",\"store\" : \"no\"}}}}}}"; String mappingMessage = "{ \"_index\" : \"mqtest\", \"_type\" : \"type2\"}\n" + mapping; String partialmappingMessage = "{ \"_index\" : \"mqtest\", \"_type\" : \"type2\"}"; String deleteByQuery = "{ \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_queryString\" : \"_id:1\"}\n"; ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes()); HashMap<String, Object> headers = new HashMap<String, Object>(); headers.put("X-ES-Command", "mapping"); BasicProperties props = MessageProperties.MINIMAL_BASIC; props = props.builder().headers(headers).build(); ch.basicPublish("elasticsearch", "elasticsearch", props, mappingMessage.getBytes()); headers.put("X-ES-Command", "deleteByQuery"); props = props.builder().headers(headers).build(); ch.basicPublish("elasticsearch", "elasticsearch", props, deleteByQuery.getBytes()); Thread.sleep(5000); ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes()); ch.basicPublish("elasticsearch", "elasticsearch", null, messageWithWrongIndex.getBytes()); ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes()); ch.basicPublish("elasticsearch", "elasticsearch", props, deleteByQuery.getBytes()); Thread.sleep(5000); ch.close(); conn.close(); Thread.sleep(5000); Boolean exists = node.client().get(new GetRequest("mqtest").id("1")).get().isExists(); ClusterState state = node.client().admin().cluster() .state(new ClusterStateRequest().filteredIndices("mqtest")).get().getState(); ImmutableOpenMap<String, MappingMetaData> mappings = state.getMetaData().index("mqtest").mappings(); MappingMetaData typeMap = mappings.get("type2"); if (null != typeMap) { String gotMapping = typeMap.source().toString(); } }
From source file:org.elasticsearch.river.rabbitmq.RabbitMQTestRunner.java
License:Apache License
/** * Helper method to inject x messages containing y index requests * @param ch RabbitMQ channel// w ww . j ava 2 s. c om * @param nbMessages number of messages to inject (x) * @param nbDocs number of docs per message to inject (y) * @throws IOException */ protected static void pushMessages(Channel ch, int nbMessages, int nbDocs) throws IOException { for (int i = 0; i < nbMessages; i++) { StringBuffer message = new StringBuffer(); for (int j = 0; j < nbDocs; j++) { message.append("{ \"index\" : { \"_index\" : \"" + INDEX + "\", \"_type\" : \"typex\", \"_id\" : \"" + i + "_" + j + "\" } }\n"); message.append("{ \"typex\" : { \"field\" : \"" + i + "_" + j + "\" } }\n"); } ch.basicPublish("elasticsearch", "elasticsearch", null, message.toString().getBytes()); } }
From source file:org.hobbit.core.rabbit.EchoServer.java
License:Open Source License
@Override public void run() { running = true;/*from w w w . ja v a 2 s. c o m*/ Connection connection = null; try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rabbitHost); connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.basicQos(1); channel.queueDeclare(queueName, false, false, true, null); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { BasicProperties replyProps = new BasicProperties.Builder() .correlationId(properties.getCorrelationId()).deliveryMode(2).build(); channel.basicPublish("", properties.getReplyTo(), replyProps, body); } }; channel.basicConsume(queueName, true, consumer); while (running) { Thread.sleep(3000); } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (IOException e) { } } } }
From source file:org.hp.samples.ProcessMessage.java
License:Open Source License
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.setStatus(200);/*from w w w. j a v a 2s . c om*/ PrintWriter writer = response.getWriter(); writer.println("Here's your message:"); // Pull out the RABBITMQ_URL environment variable String uri = System.getenv("RABBITMQ_URL"); ConnectionFactory factory = new ConnectionFactory(); try { factory.setUri(uri); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // Create the queue channel.queueDeclare("hello", false, false, false, null); String routingKey = "thekey"; String exchangeName = "exchange"; // Declare an exchange and bind it to the queue channel.exchangeDeclare(exchangeName, "direct", true); channel.queueBind("hello", exchangeName, routingKey); // Grab the message from the HTML form and publish it to the queue String message = request.getParameter("message"); channel.basicPublish(exchangeName, routingKey, null, message.getBytes()); writer.println(" Message sent to queue '" + message + "'"); boolean autoAck = false; // Get the response message GetResponse responseMsg = channel.basicGet("hello", autoAck); if (responseMsg == null) { // No message retrieved. } else { byte[] body = responseMsg.getBody(); // Since getBody() returns a byte array, convert to a string for // the user. String bodyString = new String(body); long deliveryTag = responseMsg.getEnvelope().getDeliveryTag(); writer.println("Message received: " + bodyString); // Acknowledge that we received the message so that the queue // removes the message so that it's not sent to us again. channel.basicAck(deliveryTag, false); } writer.close(); }
From source file:org.mobicents.servlet.sip.example.SimpleSipServlet.java
License:Open Source License
/** * {@inheritDoc}// w w w. j a va 2 s.co m */ protected void doNotify(SipServletRequest request) throws ServletException, IOException { Channel channel = null; String routingKey = ""; //a trick to change routingKey value. //routingKey = getBindingKey(); try { channel = pool.borrowObject(); String message = request.getCallId(); channel.exchangeDeclare(EXCHANGE_NAME, "topic", true); channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes()); logger.info("PUBLISH A MESSAGE : " + message); logger.info("*************************************"); logger.info("**" + "Number active : " + pool.getNumActive() + " ***"); logger.info("**" + "Number idle : " + pool.getNumIdle() + " ***"); logger.info("*************************************"); } catch (NoSuchElementException e) { logger.error(e.getMessage()); throw new ServletException(e); } catch (IllegalStateException e) { logger.error(e.getMessage()); throw new ServletException(e); } catch (Exception e) { logger.error(e.getMessage()); throw new ServletException(e); } finally { if (channel != null) { try { pool.returnObject(channel); } catch (Exception e) { e.printStackTrace(); logger.error("Failed to return channel back to pool. Exception message: " + e.getMessage()); } //logger.info("RETURN CHANNEL TO THE POOL"); } } SipServletResponse sipServletResponse = request.createResponse(SipServletResponse.SC_OK); sipServletResponse.send(); }
From source file:org.ninjav.rabbitmq.SendTest.java
@Test public void canSendMessageToQueue() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); for (int i = 0; i < 1000000; i++) { String message = "Hello world " + i; channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); }//from w ww . ja v a2s . c o m channel.close(); connection.close(); }
From source file:org.objectweb.joram.mom.dest.amqp.AmqpDistribution.java
License:Open Source License
public void distribute(Message message) throws Exception { List<String> connectionNames = this.connectionNames; // Convert message properties AMQP.BasicProperties props = new AMQP.BasicProperties(); if (message.persistent) { props.setDeliveryMode(Integer.valueOf(2)); } else {//from www.j a va 2s .co m props.setDeliveryMode(Integer.valueOf(1)); } props.setCorrelationId(message.correlationId); props.setPriority(Integer.valueOf(message.priority)); props.setTimestamp(new Date(message.timestamp)); props.setMessageId(message.id); props.setType(String.valueOf(message.type)); props.setExpiration(String.valueOf(message.expiration)); if (message.properties != null) { Map<String, Object> headers = new HashMap<String, Object>(); message.properties.copyInto(headers); props.setHeaders(headers); Object customRouting = message.properties.get(ROUTING_PROP); if (customRouting != null && customRouting instanceof String) { connectionNames = AmqpConnectionService.convertToList((String) customRouting); } } // Update channels if necessary long now = System.currentTimeMillis(); if (now - lastUpdate > updatePeriod) { if (logger.isLoggable(BasicLevel.DEBUG)) { logger.log(BasicLevel.DEBUG, "Updating channels."); } List<LiveServerConnection> connections = AmqpConnectionService.getInstance().getConnections(); for (LiveServerConnection connection : connections) { if (!channels.containsKey(connection.getName())) { if (logger.isLoggable(BasicLevel.DEBUG)) { logger.log(BasicLevel.DEBUG, connection.getName() + ": New channel available for distribution."); } try { Channel channel = connection.getConnection().createChannel(); if (amqpQueuePassive) { channel.queueDeclarePassive(amqpQueue); } else { channel.queueDeclare(amqpQueue, amqpQueueDurable, amqpQueueExclusive, amqpQueueAutoDelete, null); } channels.put(connection.getName(), channel); } catch (IOException exc) { if (logger.isLoggable(BasicLevel.DEBUG)) { logger.log(BasicLevel.DEBUG, "Channel is not usable.", exc); } } } } lastUpdate = now; } // Send the message Iterator<Map.Entry<String, Channel>> iter = channels.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, Channel> entry = iter.next(); try { Channel chan = entry.getValue(); String cnxName = entry.getKey(); if (!chan.isOpen()) { iter.remove(); continue; } if (connectionNames != null && !connectionNames.contains(cnxName)) { continue; } if (logger.isLoggable(BasicLevel.DEBUG)) { logger.log(BasicLevel.DEBUG, "Sending message on " + cnxName); } chan.basicPublish("", amqpQueue, props, message.getBody()); channels.get(cnxName); // Access the used connection to update the LRU map return; } catch (IOException exc) { if (logger.isLoggable(BasicLevel.DEBUG)) { logger.log(BasicLevel.DEBUG, "Channel is not usable, remove from table.", exc); } iter.remove(); } catch (AlreadyClosedException exc) { if (logger.isLoggable(BasicLevel.DEBUG)) { logger.log(BasicLevel.DEBUG, "Channel is not usable, remove from table.", exc); } iter.remove(); } } throw new Exception("Message could not be sent, no usable channel found."); }