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.apache.airavata.wsmg.client.amqp.rabbitmq.AMQPSenderImpl.java
License:Apache License
public void Send(OMElement message) throws AMQPException { try {/*from w w w .j ava2s . c om*/ if (isRoutable(message)) { Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(AMQPUtil.EXCHANGE_NAME_DIRECT, AMQPUtil.EXCHANGE_TYPE_DIRECT); List<String> routingKeys = new ArrayList<String>(); getRoutingKeys(message, routingKeys); for (String routingKey : routingKeys) { channel.basicPublish(AMQPUtil.EXCHANGE_NAME_DIRECT, routingKey, null, message.toString().getBytes()); } channel.close(); connection.close(); } } catch (IOException e) { throw new AMQPException(e); } }
From source file:org.apache.airavata.wsmg.client.amqp.rabbitmq.AMQPTopicSenderImpl.java
License:Apache License
public void Send(OMElement message) throws AMQPException { try {//w w w . j a va 2 s . c o m if (isRoutable(message)) { Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(AMQPUtil.EXCHANGE_NAME_TOPIC, AMQPUtil.EXCHANGE_TYPE_TOPIC); List<String> routingKeys = new ArrayList<String>(); getRoutingKeys(message, routingKeys); for (String routingKey : routingKeys) { channel.basicPublish(AMQPUtil.EXCHANGE_NAME_TOPIC, routingKey, null, message.toString().getBytes()); } channel.close(); connection.close(); } } catch (IOException e) { throw new AMQPException(e); } }
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 *//*from w w w . j av a 2 s . co 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.beam.sdk.io.rabbitmq.RabbitMqIOTest.java
License:Apache License
@Test public void testReadQueue() throws Exception { final int maxNumRecords = 10; PCollection<RabbitMqMessage> raw = p.apply(RabbitMqIO.read().withUri("amqp://guest:guest@localhost:" + port) .withQueue("READ").withMaxNumRecords(maxNumRecords)); PCollection<String> output = raw.apply(MapElements.into(TypeDescriptors.strings()) .via((RabbitMqMessage message) -> new String(message.getBody(), StandardCharsets.UTF_8))); List<String> records = generateRecords(maxNumRecords).stream() .map(record -> new String(record, StandardCharsets.UTF_8)).collect(Collectors.toList()); PAssert.that(output).containsInAnyOrder(records); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri("amqp://guest:guest@localhost:" + port); Connection connection = null; Channel channel = null; try {//from ww w . j ava 2 s .c o m connection = connectionFactory.newConnection(); channel = connection.createChannel(); channel.queueDeclare("READ", false, false, false, null); for (String record : records) { channel.basicPublish("", "READ", null, record.getBytes(StandardCharsets.UTF_8)); } p.run(); } finally { if (channel != null) { channel.close(); } if (connection != null) { connection.close(); } } }
From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java
License:Apache License
@Test(timeout = 60 * 1000) public void testReadExchange() throws Exception { final int maxNumRecords = 10; PCollection<RabbitMqMessage> raw = p.apply(RabbitMqIO.read().withUri("amqp://guest:guest@localhost:" + port) .withExchange("READEXCHANGE", "fanout", "test").withMaxNumRecords(maxNumRecords)); PCollection<String> output = raw.apply(MapElements.into(TypeDescriptors.strings()) .via((RabbitMqMessage message) -> new String(message.getBody(), StandardCharsets.UTF_8))); List<String> records = generateRecords(maxNumRecords).stream() .map(record -> new String(record, StandardCharsets.UTF_8)).collect(Collectors.toList()); PAssert.that(output).containsInAnyOrder(records); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri("amqp://guest:guest@localhost:" + port); Connection connection = null; Channel channel = null;// www .ja v a2s . co m try { connection = connectionFactory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare("READEXCHANGE", "fanout"); Channel finalChannel = channel; Thread publisher = new Thread(() -> { try { Thread.sleep(5000); } catch (Exception e) { LOG.error(e.getMessage(), e); } for (int i = 0; i < maxNumRecords; i++) { try { finalChannel.basicPublish("READEXCHANGE", "test", null, ("Test " + i).getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { LOG.error(e.getMessage(), e); } } }); publisher.start(); p.run(); publisher.join(); } finally { if (channel != null) { channel.close(); } if (connection != null) { connection.close(); } } }
From source file:org.apache.camel.component.rabbitmq.RabbitMQConsumerIntTest.java
License:Apache License
@Test public void sentMessageIsReceived() throws InterruptedException, IOException { to.expectedMessageCount(1);//from w w w . j av a2 s .c o m to.expectedHeaderReceived(RabbitMQConstants.REPLY_TO, "myReply"); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setPort(5672); factory.setUsername("cameltest"); factory.setPassword("cameltest"); factory.setVirtualHost("/"); Connection conn = factory.newConnection(); AMQP.BasicProperties.Builder properties = new AMQP.BasicProperties.Builder(); properties.replyTo("myReply"); Channel channel = conn.createChannel(); channel.basicPublish(EXCHANGE, "", properties.build(), "hello world".getBytes()); to.assertIsSatisfied(); }
From source file:org.apache.cloudstack.mom.rabbitmq.RabbitMQEventBus.java
License:Apache License
private void publishEventToExchange(Channel channel, String exchangeName, String routingKey, String eventDescription) throws Exception { try {//from w w w. j av a 2 s . c o m byte[] messageBodyBytes = eventDescription.getBytes(); channel.basicPublish(exchangeName, routingKey, MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes); } catch (Exception e) { s_logger.error("Failed to publish event " + routingKey + " on exchange " + exchangeName + " of message broker due to " + e.getMessage()); throw e; } }
From source file:org.apache.druid.examples.rabbitmq.RabbitMQProducerMain.java
License:Apache License
public static void main(String[] args) throws Exception { // We use a List to keep track of option insertion order. See below. final List<Option> optionList = new ArrayList<Option>(); optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h")); optionList.add(OptionBuilder.withLongOpt("hostname").hasArg() .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b")); optionList.add(OptionBuilder.withLongOpt("port").hasArg() .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n")); optionList.add(OptionBuilder.withLongOpt("username").hasArg() .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]") .create("u")); optionList.add(OptionBuilder.withLongOpt("password").hasArg() .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]") .create("p")); optionList.add(OptionBuilder.withLongOpt("vhost").hasArg() .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]") .create("v")); optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg() .withDescription("name of the AMQP exchange [required - no default]").create("e")); optionList.add(OptionBuilder.withLongOpt("key").hasArg() .withDescription("the routing key to use when sending messages [default: 'default.routing.key']") .create("k")); optionList.add(OptionBuilder.withLongOpt("type").hasArg() .withDescription("the type of exchange to create [default: 'topic']").create("t")); optionList.add(OptionBuilder.withLongOpt("durable") .withDescription("if set, a durable exchange will be declared [default: not set]").create("d")); optionList.add(OptionBuilder.withLongOpt("autodelete") .withDescription("if set, an auto-delete exchange will be declared [default: not set]") .create("a")); optionList.add(OptionBuilder.withLongOpt("single") .withDescription("if set, only a single message will be sent [default: not set]").create("s")); optionList.add(OptionBuilder.withLongOpt("start").hasArg() .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]") .create());//w w w . j a v a2s .c o m optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription( "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]") .create()); optionList.add(OptionBuilder.withLongOpt("interval").hasArg() .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]") .create()); optionList.add(OptionBuilder.withLongOpt("delay").hasArg() .withDescription("the delay between sending messages in milliseconds [default: 100]").create()); // An extremely silly hack to maintain the above order in the help formatting. HelpFormatter formatter = new HelpFormatter(); // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order. //noinspection ComparatorCombinators -- don't replace with comparingInt() to preserve comments formatter.setOptionComparator((o1, o2) -> { // I know this isn't fast, but who cares! The list is short. //noinspection SuspiciousMethodCalls return Integer.compare(optionList.indexOf(o1), optionList.indexOf(o2)); }); // Now we can add all the options to an Options instance. This is dumb! Options options = new Options(); for (Option option : optionList) { options.addOption(option); } CommandLine cmd = null; try { cmd = new BasicParser().parse(options, args); } catch (ParseException e) { formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null); System.exit(1); } if (cmd.hasOption("h")) { formatter.printHelp("RabbitMQProducerMain", options); System.exit(2); } ConnectionFactory factory = new ConnectionFactory(); if (cmd.hasOption("b")) { factory.setHost(cmd.getOptionValue("b")); } if (cmd.hasOption("u")) { factory.setUsername(cmd.getOptionValue("u")); } if (cmd.hasOption("p")) { factory.setPassword(cmd.getOptionValue("p")); } if (cmd.hasOption("v")) { factory.setVirtualHost(cmd.getOptionValue("v")); } if (cmd.hasOption("n")) { factory.setPort(Integer.parseInt(cmd.getOptionValue("n"))); } String exchange = cmd.getOptionValue("e"); String routingKey = "default.routing.key"; if (cmd.hasOption("k")) { routingKey = cmd.getOptionValue("k"); } boolean durable = cmd.hasOption("d"); boolean autoDelete = cmd.hasOption("a"); String type = cmd.getOptionValue("t", "topic"); boolean single = cmd.hasOption("single"); int interval = Integer.parseInt(cmd.getOptionValue("interval", "10")); int delay = Integer.parseInt(cmd.getOptionValue("delay", "100")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH); Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date()))); Random r = ThreadLocalRandom.current(); Calendar timer = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH); timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00"))); String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}"; Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchange, type, durable, autoDelete, null); do { int wp = (10 + r.nextInt(90)) * 100; String gender = r.nextBoolean() ? "male" : "female"; int age = 20 + r.nextInt(70); String line = StringUtils.format(msg_template, sdf.format(timer.getTime()), wp, gender, age); channel.basicPublish(exchange, routingKey, null, StringUtils.toUtf8(line)); System.out.println("Sent message: " + line); timer.add(Calendar.SECOND, interval); Thread.sleep(delay); } while ((!single && stop.after(timer.getTime()))); connection.close(); }
From source file:org.apache.helix.recipes.rabbitmq.Emitter.java
License:Apache License
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("USAGE: java Emitter rabbitmqServer (e.g. localhost) numberOfMessage (optional)"); System.exit(1);//w w w .jav a 2s.c o m } final String mqServer = args[0]; // "zzhang-ld"; int count = Integer.MAX_VALUE; if (args.length > 1) { try { count = Integer.parseInt(args[1]); } catch (Exception e) { // TODO: handle exception } } System.out.println("Sending " + count + " messages with random topic id"); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(mqServer); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); for (int i = 0; i < count; i++) { int rand = ((int) (Math.random() * 10000) % SetupConsumerCluster.DEFAULT_PARTITION_NUMBER); String routingKey = "topic_" + rand; String message = "message_" + rand; channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes()); System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'"); Thread.sleep(1000); } connection.close(); }
From source file:org.apache.james.transport.mailets.AmqpForwardAttribute.java
License:Apache License
private void sendContentOnChannel(Channel channel, Map<String, byte[]> content) throws IOException { for (Map.Entry<String, byte[]> entry : content.entrySet()) { byte[] rawMime = entry.getValue(); byte[] attachmentContent = extractContent(rawMime); channel.basicPublish(exchange, routingKey, new AMQP.BasicProperties(), attachmentContent); }/*from ww w . j av a2s . c o m*/ }