List of usage examples for com.rabbitmq.client Connection createChannel
Channel createChannel() throws IOException;
From source file:org.apache.airavata.wsmg.client.amqp.rabbitmq.AMQPTopicReceiverImpl.java
License:Apache License
public void Subscribe(AMQPRoutingKey topic) throws AMQPException { if (callback != null) { try {/*from w ww . ja v a2 s .c om*/ Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(AMQPUtil.EXCHANGE_NAME_TOPIC, AMQPUtil.EXCHANGE_TYPE_TOPIC); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, AMQPUtil.EXCHANGE_NAME_TOPIC, topic.getNativeKey()); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); callback.onMessage(message); } } catch (Exception 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 {//from ww w .j a v a 2 s .co 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.amqp.out.AMQPSender.java
License:Apache License
/** * Performs the actual sending of the AMQP message *//* w ww . j a va2 s . c o m*/ @Override public void sendMessage(MessageContext msgCtx, String targetAddress, OutTransportInfo outTransportInfo) throws AxisFault { AMQPConnectionFactory conFac = null; AMQPTransportInfo amqpOut = null; AMQPMessageSender messageSender = null; Connection con = null; Channel chan = null; if (targetAddress != null) { amqpOut = new AMQPTransportInfo(targetAddress); // do we have a definition for a connection factory to use for this // address? conFac = getAMQPConnectionFactory(amqpOut); try { if (conFac != null) { con = conFac.getConnection(); chan = con.createChannel(); messageSender = new AMQPMessageSender(chan, DestinationFactory.parseAddress(targetAddress)); } else { messageSender = amqpOut.createAMQPSender(); } } catch (IOException e) { e.printStackTrace(); } } else if (outTransportInfo != null && outTransportInfo instanceof AMQPTransportInfo) { amqpOut = (AMQPTransportInfo) outTransportInfo; try { messageSender = amqpOut.createAMQPSender(); } catch (IOException e) { e.printStackTrace(); } } // The message property to be used to send the content type is // determined by the out transport info, i.e. either from the EPR if we are sending a // request, or, if we are sending a response, from the configuration of the // service that received the request). The property name can be overridden by a // message context property. String contentTypeProperty = (String) msgCtx.getProperty(AMQPConstants.CONTENT_TYPE_PROPERTY_PARAM); if (contentTypeProperty == null) { contentTypeProperty = amqpOut.getContentTypeProperty(); } try { sendOverAMQP(msgCtx, messageSender, contentTypeProperty, chan, amqpOut); } finally { try { chan.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:org.apache.axis2.transport.rabbitmq.RabbitMQSender.java
License:Open Source License
private void processResponse(RabbitMQConnectionFactory factory, MessageContext msgContext, String correlationID, String replyTo, Hashtable<String, String> eprProperties) throws IOException { Connection connection = factory.createConnection(); if (!RabbitMQUtils.isQueueAvailable(connection, replyTo)) { log.info("Reply-to queue : " + replyTo + " not available, hence creating a new one"); RabbitMQUtils.declareQueue(connection, replyTo, eprProperties); }//from w w w. j a v a 2 s . c o m Channel channel = connection.createChannel(); QueueingConsumer consumer = new QueueingConsumer(channel); QueueingConsumer.Delivery delivery = null; RabbitMQMessage message = new RabbitMQMessage(); boolean responseFound = false; int timeout = RabbitMQConstants.DEFAULT_REPLY_TO_TIMEOUT; String timeoutStr = eprProperties.get(RabbitMQConstants.REPLY_TO_TIMEOUT); if (!StringUtils.isEmpty(timeoutStr)) { try { timeout = Integer.parseInt(timeoutStr); } catch (NumberFormatException e) { log.warn( "Number format error in reading replyto timeout value. Proceeding with default value (30000ms)", e); } } //start consuming without acknowledging String consumerTag = channel.basicConsume(replyTo, false, consumer); try { while (!responseFound) { log.debug("Waiting for next delivery from reply to queue " + replyTo); delivery = consumer.nextDelivery(timeout); if (delivery != null) { if (delivery.getProperties().getCorrelationId().equals(correlationID)) { responseFound = true; log.debug( "Found matching response with correlation ID : " + correlationID + ". Sending ack"); //acknowledge correct message channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } else { //not acknowledge wrong messages and re-queue log.debug("Found messages with wrong correlation ID. Re-queueing and sending nack"); channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true); } } } } catch (ShutdownSignalException e) { log.error("Error receiving message from RabbitMQ broker " + e.getLocalizedMessage()); } catch (InterruptedException e) { log.error("Error receiving message from RabbitMQ broker " + e.getLocalizedMessage()); } catch (ConsumerCancelledException e) { log.error("Error receiving message from RabbitMQ broker" + e.getLocalizedMessage()); } finally { if (channel != null || channel.isOpen()) { //stop consuming channel.basicCancel(consumerTag); } } if (delivery != null) { log.debug("Processing response from reply-to queue"); AMQP.BasicProperties properties = delivery.getProperties(); Map<String, Object> headers = properties.getHeaders(); message.setBody(delivery.getBody()); message.setDeliveryTag(delivery.getEnvelope().getDeliveryTag()); message.setReplyTo(properties.getReplyTo()); message.setMessageId(properties.getMessageId()); //get content type from message String contentType = properties.getContentType(); if (contentType == null) { //if not get content type from transport parameter contentType = eprProperties.get(RabbitMQConstants.REPLY_TO_CONTENT_TYPE); if (contentType == null) { //if none is given, set to default content type log.warn("Setting default content type " + RabbitMQConstants.DEFAULT_CONTENT_TYPE); contentType = RabbitMQConstants.DEFAULT_CONTENT_TYPE; } } message.setContentType(contentType); message.setContentEncoding(properties.getContentEncoding()); message.setCorrelationId(properties.getCorrelationId()); if (headers != null) { message.setHeaders(headers); if (headers.get(RabbitMQConstants.SOAP_ACTION) != null) { message.setSoapAction(headers.get(RabbitMQConstants.SOAP_ACTION).toString()); } } MessageContext responseMsgCtx = createResponseMessageContext(msgContext); RabbitMQUtils.setSOAPEnvelope(message, responseMsgCtx, contentType); handleIncomingMessage(responseMsgCtx, RabbitMQUtils.getTransportHeaders(message), message.getSoapAction(), message.getContentType()); } }
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;//from w ww . j ava 2s . com try { 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;/*from w w w . j a va2s . c o 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.beam.sdk.io.rabbitmq.RabbitMqIOTest.java
License:Apache License
@Test public void testWriteQueue() throws Exception { final int maxNumRecords = 1000; List<RabbitMqMessage> data = generateRecords(maxNumRecords).stream() .map(bytes -> new RabbitMqMessage(bytes)).collect(Collectors.toList()); p.apply(Create.of(data))/* w w w .j a v a2s . c o m*/ .apply(RabbitMqIO.write().withUri("amqp://guest:guest@localhost:" + port).withQueue("TEST")); final List<String> received = new ArrayList<>(); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri("amqp://guest:guest@localhost:" + port); Connection connection = null; Channel channel = null; try { connection = connectionFactory.newConnection(); channel = connection.createChannel(); channel.queueDeclare("TEST", true, false, false, null); Consumer consumer = new TestConsumer(channel, received); channel.basicConsume("TEST", true, consumer); p.run(); while (received.size() < maxNumRecords) { Thread.sleep(500); } assertEquals(maxNumRecords, received.size()); for (int i = 0; i < maxNumRecords; i++) { assertTrue(received.contains("Test " + i)); } } 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 public void testWriteExchange() throws Exception { final int maxNumRecords = 1000; List<RabbitMqMessage> data = generateRecords(maxNumRecords).stream() .map(bytes -> new RabbitMqMessage(bytes)).collect(Collectors.toList()); p.apply(Create.of(data)).apply(//from ww w . j a va 2s.c o m RabbitMqIO.write().withUri("amqp://guest:guest@localhost:" + port).withExchange("WRITE", "fanout")); final List<String> received = new ArrayList<>(); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri("amqp://guest:guest@localhost:" + port); Connection connection = null; Channel channel = null; try { connection = connectionFactory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare("WRITE", "fanout"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, "WRITE", ""); Consumer consumer = new TestConsumer(channel, received); channel.basicConsume(queueName, true, consumer); p.run(); while (received.size() < maxNumRecords) { Thread.sleep(500); } assertEquals(maxNumRecords, received.size()); for (int i = 0; i < maxNumRecords; i++) { assertTrue(received.contains("Test " + i)); } } 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 ww. java 2s .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.camel.component.rabbitmq.RabbitMQProducerIntTest.java
License:Apache License
@Test public void producedMessageIsReceived() throws InterruptedException, IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setPort(5672);//w w w . j ava2 s . c om factory.setUsername("cameltest"); factory.setPassword("cameltest"); factory.setVirtualHost("/"); Connection conn = factory.newConnection(); final List<Envelope> received = new ArrayList<Envelope>(); Channel channel = conn.createChannel(); channel.queueDeclare("sammyq", false, false, true, null); channel.queueBind("sammyq", EXCHANGE, "route1"); channel.basicConsume("sammyq", true, new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { received.add(envelope); } }); template.sendBodyAndHeader("new message", RabbitMQConstants.EXCHANGE_NAME, "ex1"); Thread.sleep(500); assertEquals(1, received.size()); }