List of usage examples for com.rabbitmq.client Channel exchangeDeclare
Exchange.DeclareOk exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable) throws IOException;
From source file:org.apache.axis2.transport.rabbitmq.RabbitMQMessageSender.java
License:Open Source License
/** * Perform the creation of exchange/queue and the Outputstream * * @param message the RabbitMQ AMQP message * @param msgContext the Axis2 MessageContext *//* w w w .j a va2s . c o m*/ public void send(RabbitMQMessage message, MessageContext msgContext) throws AxisRabbitMQException { String exchangeName = null; AMQP.BasicProperties basicProperties = null; byte[] messageBody = null; if (connection != null) { Channel channel = null; String queueName = properties.get(RabbitMQConstants.QUEUE_NAME); String routeKey = properties.get(RabbitMQConstants.QUEUE_ROUTING_KEY); exchangeName = properties.get(RabbitMQConstants.EXCHANGE_NAME); String exchangeType = properties.get(RabbitMQConstants.EXCHANGE_TYPE); String durable = properties.get(RabbitMQConstants.EXCHANGE_DURABLE); String replyTo = properties.get(RabbitMQConstants.RABBITMQ_REPLY_TO); //if the user defined any replyTo value it will be set if (replyTo != null) { message.setReplyTo(replyTo); } try { if (routeKey == null && !"x-consistent-hash".equals(exchangeType)) { log.info("rabbitmq.queue.routing.key property not found. Using queue name as " + "the routing key."); routeKey = queueName; } channel = connection.createChannel(); //Declaring the queue if (queueName != null && !queueName.equals("")) { Boolean queueAvailable = false; try { // check availability of the named queue // if an error is encountered, including if the // queue does not exist and if the queue is // exclusively owned by another connection channel.queueDeclarePassive(queueName); queueAvailable = true; } catch (java.io.IOException e) { log.info("Queue :" + queueName + " not found.Declaring queue."); } if (!queueAvailable) { // Declare the named queue if it does not exists. if (!channel.isOpen()) { channel = connection.createChannel(); } try { channel.queueDeclare(queueName, RabbitMQUtils.isDurableQueue(properties), RabbitMQUtils.isExclusiveQueue(properties), RabbitMQUtils.isAutoDeleteQueue(properties), null); } catch (java.io.IOException e) { handleException("Error while creating queue: " + queueName + e); return; } } } //Declaring the exchange if (exchangeName != null && !exchangeName.equals("")) { Boolean exchangeAvailable = false; try { // check availability of the named exchange // Throws:java.io.IOException - the server will raise a // 404 channel exception if the named exchange does not // exists. channel.exchangeDeclarePassive(exchangeName); exchangeAvailable = true; } catch (java.io.IOException e) { log.info("Exchange :" + exchangeName + " not found.Declaring exchange."); } if (!exchangeAvailable) { // Declare the named exchange if it does not exists. if (!channel.isOpen()) { channel = connection.createChannel(); } try { if (exchangeType != null && !exchangeType.equals("")) { if (durable != null && !durable.equals("")) { channel.exchangeDeclare(exchangeName, exchangeType, Boolean.parseBoolean(durable)); } else { channel.exchangeDeclare(exchangeName, exchangeType, true); } } else { channel.exchangeDeclare(exchangeName, "direct", true); } } catch (java.io.IOException e) { handleException("Error occurred while declaring exchange."); } } if (queueName != null && !"x-consistent-hash".equals(exchangeType)) { // Create bind between the queue & // provided routeKey try { // no need to have configure permission to // perform channel.queueBind channel.queueBind(queueName, exchangeName, routeKey); } catch (java.io.IOException e) { handleException("Error occurred while creating the bind between the queue: " + queueName + " & exchange: " + exchangeName + e); } } } AMQP.BasicProperties.Builder builder = buildBasicProperties(message); // set delivery mode (default is Persistent): 1=NonPersistent , 2=Persistent String deliveryModeString = properties.get(RabbitMQConstants.QUEUE_DELIVERY_MODE); int deliveryMode = 2; if (deliveryModeString != null) { deliveryMode = Integer.parseInt(deliveryModeString); } builder.deliveryMode(deliveryMode); basicProperties = builder.build(); OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); try { messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext); } catch (AxisFault axisFault) { throw new AxisRabbitMQException("Unable to get the message formatter to use", axisFault); } //server plugging should be enabled before using x-consistent hashing //for x-consistent-hashing only exchangeName, exchangeType and routingKey should be // given. Queue/exchange creation, bindings should be done at the broker try { // generate random value as routeKey if the exchangeType is // x-consistent-hash type if (exchangeType != null && exchangeType.equals("x-consistent-hash")) { routeKey = UUID.randomUUID().toString(); } } catch (UnsupportedCharsetException ex) { handleException("Unsupported encoding " + format.getCharSetEncoding(), ex); } try { messageFormatter.writeTo(msgContext, format, out, false); messageBody = out.toByteArray(); } catch (IOException e) { handleException("IO Error while creating BytesMessage", e); } finally { if (out != null) { out.close(); channel.abort(); } } } catch (IOException e) { handleException("Error while publishing message to the queue ", e); } try { if (connection != null) { try { channel = connection.createChannel(); if (exchangeName != null && exchangeName != "") channel.basicPublish(exchangeName, routeKey, basicProperties, messageBody); else channel.basicPublish("", routeKey, basicProperties, messageBody); } catch (IOException e) { log.error("Error while publishing the message"); } finally { if (channel != null) { channel.close(); } } } } catch (IOException e) { handleException("Error while publishing message to the queue ", e); } } }
From source file:org.apache.cloudstack.mom.rabbitmq.RabbitMQEventBus.java
License:Apache License
private void createExchange(Channel channel, String exchangeName) throws Exception { try {/*from w ww. j av a 2 s . c om*/ channel.exchangeDeclare(exchangeName, "topic", true); } catch (java.io.IOException exception) { s_logger.error("Failed to create exchange" + exchangeName + " on RabbitMQ server"); throw exception; } }
From source file:org.apache.flume.amqp.AmqpConsumer.java
License:Apache License
/** * This method declares the exchange, queue and bindings needed by this consumer. * The method returns the queue name that will be used by this consumer. * * @param channel channel used to issue AMQP commands * @return queue that will have messages consumed from * @throws IOException thrown if there is any communication exception *///from w ww. ja v a 2s . c om @VisibleForTesting protected String declarationsForChannel(Channel channel) throws IOException { // setup exchange, queue and binding if (prefetchSize > 0) { channel.basicQos(prefetchSize); } // if exchange is provided if (exchangeName != null) { channel.exchangeDeclare(exchangeName, exchangeType, durableExchange); // named queue or server generated if (queueName == null) { queueName = channel.queueDeclare().getQueue(); } else { channel.queueDeclare(queueName, durableQueue, exclusiveQueue, autoDeleteQueue, null); } if (bindings.length > 0) { // multiple bindings for (String binding : bindings) { channel.queueBind(queueName, exchangeName, binding); } } else { // no binding given - this could be the case if it is a fanout exchange channel.queueBind(queueName, exchangeName, Constants.AMQP.SERVER_GENERATED_QUEUE_NAME); } } return queueName; }
From source file:org.archive.modules.AMQPProducer.java
License:Apache License
/** * Publish the message with the supplied properties. If this method returns * without throwing an exception, the message was published successfully. * * @param message//from ww w . java2s . c o m * @param props * @throws IOException * if message is not published successfully for any reason */ public void publishMessage(byte[] message, BasicProperties props) throws IOException { Channel channel = channel(); channel.exchangeDeclare(exchange, "direct", true); channel.basicPublish(exchange, routingKey, props, message); }
From source file:org.elasticsearch.river.rabbitmq.RabbitMQRiverBothScriptTest.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("script_filter") .field("script", "ctx.type1.field1 += param1").field("script_lang", "mvel") .startObject("script_params").field("param1", 1).endObject().endObject() .startObject("bulk_script_filter").field("script", "mock_script") .field("script_lang", "native").endObject().endObject()) .execute().actionGet();/*from ww w . j av a 2s . 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.RabbitMQRiverHeartbeatTest.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").startObject("rabbitmq").field("heartbeat", "1s").endObject().endObject()) .execute().actionGet();//from ww w . j a v a 2 s. 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\" : \"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.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();//from www . j av a 2 s. co 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\" : \"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();// w w w .j av a 2 s . 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\" : 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);// ww w .ja va 2s.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. ja va 2s . 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(); } }