List of usage examples for com.rabbitmq.client Channel basicPublish
void basicPublish(String exchange, String routingKey, boolean mandatory, BasicProperties props, byte[] body) throws IOException;
From source file:com.kurento.kmf.rabbitmq.RabbitTemplate.java
License:Apache License
/** * Send the given message to the specified exchange. * * @param channel/*from w ww. ja v a2 s .c om*/ * The RabbitMQ Channel to operate within. * @param exchange * The name of the RabbitMQ exchange to send to. * @param routingKey * The routing key. * @param message * The Message to send. * @param correlationData * The correlation data. * @throws IOException * If thrown by RabbitMQ API methods */ protected void doSend(Channel channel, String exchange, String routingKey, Message message, CorrelationData correlationData) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Publishing message on exchange [" + exchange + "], routingKey = [" + routingKey + "]"); } if (exchange == null) { // try to send to configured exchange exchange = this.exchange; } if (routingKey == null) { // try to send to configured routing key routingKey = this.routingKey; } if (this.confirmCallback != null && channel instanceof PublisherCallbackChannel) { PublisherCallbackChannel publisherCallbackChannel = (PublisherCallbackChannel) channel; publisherCallbackChannel.addPendingConfirm(this, channel.getNextPublishSeqNo(), new PendingConfirm(correlationData, System.currentTimeMillis())); } boolean mandatory = this.returnCallback != null && this.mandatory; MessageProperties messageProperties = message.getMessageProperties(); if (mandatory) { messageProperties.getHeaders().put(PublisherCallbackChannel.RETURN_CORRELATION, this.uuid); } BasicProperties convertedMessageProperties = this.messagePropertiesConverter .fromMessageProperties(messageProperties, encoding); channel.basicPublish(exchange, routingKey, mandatory, convertedMessageProperties, message.getBody()); // Check if commit needed if (isChannelLocallyTransacted(channel)) { // Transacted channel created by this template -> commit. RabbitUtils.commitIfNecessary(channel); } }
From source file:org.smartdeveloperhub.curator.connector.BrokerController.java
License:Apache License
private void publishMessage(final String exchangeName, final String routingKey, final String message) throws IOException { final Channel aChannel = currentChannel(); try {//from w w w . jav a2s . c o m LOGGER.debug("Publishing message to exchange '{}' and routing key '{}'. Payload: \n{}", exchangeName, routingKey, message); final Map<String, Object> headers = Maps.newLinkedHashMap(); headers.put(BROKER_CONTROLLER_MESSAGE, this.messageCounter.incrementAndGet()); aChannel.basicPublish(exchangeName, routingKey, true, MessageProperties.MINIMAL_PERSISTENT_BASIC.builder().headers(headers).build(), message.getBytes()); } catch (final IOException e) { discardChannel(aChannel); LOGGER.warn("Could not publish message [{}] to exchange '{}' and routing key '{}': {}", message, exchangeName, routingKey, e.getMessage()); throw e; } catch (final Exception e) { discardChannel(aChannel); final String errorMessage = String.format( "Unexpected failure while publishing message [%s] to exchange '%s' and routing key '%s' using broker %s:%s%s: %s", message, exchangeName, routingKey, this.broker.host(), this.broker.port(), this.broker.virtualHost(), e.getMessage()); LOGGER.error(errorMessage); throw new IOException(errorMessage, e); } }
From source file:org.smartdeveloperhub.harvesters.it.notification.CollectorController.java
License:Apache License
private void publish(final Channel aChannel, final String exchangeName, final String routingKey, final String payload) throws ControllerException { try {// w w w . jav a 2 s . c om LOGGER.trace("Publishing message to exchange '{}' and routing key '{}'. Payload: \n{}", exchangeName, routingKey, payload); final Map<String, Object> headers = Maps.newLinkedHashMap(); headers.put(HttpHeaders.CONTENT_TYPE, Notifications.MIME); aChannel.basicPublish(exchangeName, routingKey, true, MessageProperties.MINIMAL_PERSISTENT_BASIC.builder().headers(headers).build(), payload.getBytes()); } catch (final IOException e) { this.manager.discardChannel(); final String errorMessage = String.format( "Could not publish message [%s] to exchange '%s' and routing key '%s' using broker %s:%s%s: %s", payload, exchangeName, routingKey, this.collector.getBrokerHost(), this.collector.getBrokerPort(), this.collector.getVirtualHost(), e.getMessage()); LOGGER.error(errorMessage, e); throw new ControllerException(this.collector.getBrokerHost(), this.collector.getBrokerPort(), this.collector.getVirtualHost(), errorMessage, e); } catch (final Exception e) { this.manager.discardChannel(); final String errorMessage = String.format( "Unexpected failure while publishing message [%s] to exchange '%s' and routing key '%s' using broker %s:%s%s: %s", payload, exchangeName, routingKey, this.collector.getBrokerHost(), this.collector.getBrokerPort(), this.collector.getVirtualHost(), e.getMessage()); LOGGER.error(errorMessage, e); throw new ControllerException(this.collector.getBrokerHost(), this.collector.getBrokerPort(), this.collector.getVirtualHost(), errorMessage, e); } }
From source file:org.smartdeveloperhub.harvesters.it.notification.CollectorControllerTest.java
License:Apache License
@Test public void testPublishEvent$usesCurrentChannelAndImplementsNotificationProtocol(@Mocked final Channel channel) throws Exception { new MockUp<ConnectionManager>() { private boolean connected = false; @Mock(invocations = 1)/*from w w w . j a va 2 s. com*/ void connect() { this.connected = true; } @Mock(invocations = 1) void disconnect() { } @Mock boolean isConnected() { return this.connected; } @Mock Channel channel() { return channel; } @Mock(invocations = 1) Channel currentChannel() { return channel; } @Mock(invocations = 0) void discardChannel() { } }; final CollectorConfiguration defaultCollector = defaultCollector(); new Expectations() { { channel.basicPublish(defaultCollector.getExchangeName(), Notifications.routingKey(ProjectCreatedEvent.class), true, (BasicProperties) this.any, (byte[]) this.any); } }; final CollectorController sut = CollectorController.createPublisher(defaultCollector); final ProjectCreatedEvent event = new ProjectCreatedEvent(); event.setInstance(defaultCollector.getInstance()); event.setNewProjects(Arrays.asList("1", "2")); sut.connect(); try { sut.publishEvent(event); } finally { sut.disconnect(); } new Verifications() { { BasicProperties props; byte[] body; channel.basicPublish(defaultCollector.getExchangeName(), Notifications.routingKey(ProjectCreatedEvent.class), true, props = withCapture(), body = withCapture()); assertThat(new String(body), equalTo(EventUtil.marshall(event))); assertThat(props.getHeaders().get(CONTENT_TYPE), equalTo((Object) Notifications.MIME)); assertThat(props.getDeliveryMode(), equalTo(MessageProperties.MINIMAL_PERSISTENT_BASIC.builder().build().getDeliveryMode())); } }; }
From source file:org.smartdeveloperhub.harvesters.it.notification.CollectorControllerTest.java
License:Apache License
@Test public void testPublishEvent$discardsCurrentChannelOnCheckedException(@Mocked final Channel channel) throws Exception { new MockUp<ConnectionManager>() { private boolean connected = false; @Mock(invocations = 1)// w w w . j av a2s . c o m void connect() { this.connected = true; } @Mock(invocations = 1) void disconnect() { } @Mock boolean isConnected() { return this.connected; } @Mock Channel channel() { return channel; } @Mock(invocations = 1) Channel currentChannel() { return channel; } @Mock(invocations = 1) void discardChannel() { } }; final CollectorConfiguration defaultCollector = defaultCollector(); new Expectations() { { channel.basicPublish(defaultCollector.getExchangeName(), Notifications.routingKey(ProjectCreatedEvent.class), true, (BasicProperties) this.any, (byte[]) this.any); this.result = new IOException("Failure"); } }; final CollectorController sut = CollectorController.createPublisher(defaultCollector); final ProjectCreatedEvent event = new ProjectCreatedEvent(); event.setInstance(defaultCollector.getInstance()); event.setNewProjects(Arrays.asList("1", "2")); sut.connect(); try { sut.publishEvent(event); fail("Should fail to publish an event if the RabbitMQ client fails"); } catch (final ControllerException e) { assertThat(e.getMessage(), containsString(EventUtil.marshall(event))); assertThat(e.getMessage(), containsString(defaultCollector.getExchangeName())); assertThat(e.getMessage(), containsString(Notifications.routingKey(ProjectCreatedEvent.class))); assertThat(e.getMessage(), containsString(defaultCollector.getBrokerHost())); assertThat(e.getMessage(), containsString(":" + defaultCollector.getBrokerPort())); assertThat(e.getMessage(), containsString(defaultCollector.getVirtualHost())); assertThat(e.getCause(), instanceOf(IOException.class)); assertThat(e.getCause().getMessage(), equalTo("Failure")); } finally { sut.disconnect(); } }
From source file:org.smartdeveloperhub.harvesters.it.notification.CollectorControllerTest.java
License:Apache License
@Test public void testPublishEvent$discardsCurrentChannelOnRuntimeException(@Mocked final Channel channel) throws Exception { new MockUp<ConnectionManager>() { private boolean connected = false; @Mock(invocations = 1)// ww w .j a v a2s.c o m void connect() { this.connected = true; } @Mock(invocations = 1) void disconnect() { } @Mock boolean isConnected() { return this.connected; } @Mock Channel channel() { return channel; } @Mock(invocations = 1) Channel currentChannel() { return channel; } @Mock(invocations = 1) void discardChannel() { } }; final CollectorConfiguration defaultCollector = defaultCollector(); new Expectations() { { channel.basicPublish(defaultCollector.getExchangeName(), Notifications.routingKey(ProjectCreatedEvent.class), true, (BasicProperties) this.any, (byte[]) this.any); this.result = new RuntimeException("Failure"); } }; final CollectorController sut = CollectorController.createPublisher(defaultCollector); final ProjectCreatedEvent event = new ProjectCreatedEvent(); event.setInstance(defaultCollector.getInstance()); event.setNewProjects(Arrays.asList("1", "2")); sut.connect(); try { sut.publishEvent(event); fail("Should fail to publish an event if the RabbitMQ client fails"); } catch (final ControllerException e) { assertThat(e.getMessage(), containsString(EventUtil.marshall(event))); assertThat(e.getMessage(), containsString(defaultCollector.getExchangeName())); assertThat(e.getMessage(), containsString(Notifications.routingKey(ProjectCreatedEvent.class))); assertThat(e.getMessage(), containsString(defaultCollector.getBrokerHost())); assertThat(e.getMessage(), containsString(":" + defaultCollector.getBrokerPort())); assertThat(e.getMessage(), containsString(defaultCollector.getVirtualHost())); assertThat(e.getCause(), instanceOf(RuntimeException.class)); assertThat(e.getCause().getMessage(), equalTo("Failure")); } finally { sut.disconnect(); } }
From source file:org.smartdeveloperhub.harvesters.scm.backend.notification.CollectorControllerTest.java
License:Apache License
@Test public void testPublishEvent$usesCurrentChannelAndImplementsNotificationProtocol(@Mocked final Channel channel) throws Exception { new MockUp<ConnectionManager>() { private boolean connected = false; @Mock(invocations = 1)/*w w w . j a v a 2 s . c o m*/ void connect() { this.connected = true; } @Mock(invocations = 1) void disconnect() { } @Mock boolean isConnected() { return this.connected; } @Mock Channel channel() { return channel; } @Mock(invocations = 1) Channel currentChannel() { return channel; } @Mock(invocations = 0) void discardChannel() { } }; final Collector defaultCollector = defaultCollector(); new Expectations() { { channel.basicPublish(defaultCollector.getExchangeName(), Notifications.routingKey(RepositoryCreatedEvent.class), true, (BasicProperties) this.any, (byte[]) this.any); } }; final CollectorController sut = CollectorController.createPublisher(defaultCollector); final RepositoryCreatedEvent event = new RepositoryCreatedEvent(); event.setInstance(defaultCollector.getInstance()); event.setNewRepositories(Arrays.asList("1", "2")); sut.connect(); try { sut.publishEvent(event); } finally { sut.disconnect(); } new Verifications() { { BasicProperties props; byte[] body; channel.basicPublish(defaultCollector.getExchangeName(), Notifications.routingKey(RepositoryCreatedEvent.class), true, props = withCapture(), body = withCapture()); assertThat(new String(body), equalTo(EventUtil.marshall(event))); assertThat(props.getHeaders().get(HttpHeaders.CONTENT_TYPE), equalTo((Object) Notifications.MIME)); assertThat(props.getDeliveryMode(), equalTo(MessageProperties.MINIMAL_PERSISTENT_BASIC.builder().build().getDeliveryMode())); } }; }
From source file:org.smartdeveloperhub.harvesters.scm.backend.notification.CollectorControllerTest.java
License:Apache License
@Test public void testPublishEvent$discardsCurrentChannelOnCheckedException(@Mocked final Channel channel) throws Exception { new MockUp<ConnectionManager>() { private boolean connected = false; @Mock(invocations = 1)/* w ww. j a v a 2 s . c o m*/ void connect() { this.connected = true; } @Mock(invocations = 1) void disconnect() { } @Mock boolean isConnected() { return this.connected; } @Mock Channel channel() { return channel; } @Mock(invocations = 1) Channel currentChannel() { return channel; } @Mock(invocations = 1) void discardChannel() { } }; final Collector defaultCollector = defaultCollector(); new Expectations() { { channel.basicPublish(defaultCollector.getExchangeName(), Notifications.routingKey(RepositoryCreatedEvent.class), true, (BasicProperties) this.any, (byte[]) this.any); this.result = new IOException("Failure"); } }; final CollectorController sut = CollectorController.createPublisher(defaultCollector); final RepositoryCreatedEvent event = new RepositoryCreatedEvent(); event.setInstance(defaultCollector.getInstance()); event.setNewRepositories(Arrays.asList("1", "2")); sut.connect(); try { sut.publishEvent(event); fail("Should fail to publish an event if the RabbitMQ client fails"); } catch (final ControllerException e) { assertThat(e.getMessage(), containsString(EventUtil.marshall(event))); assertThat(e.getMessage(), containsString(defaultCollector.getExchangeName())); assertThat(e.getMessage(), containsString(Notifications.routingKey(RepositoryCreatedEvent.class))); assertThat(e.getMessage(), containsString(defaultCollector.getBrokerHost())); assertThat(e.getMessage(), containsString(":" + defaultCollector.getBrokerPort())); assertThat(e.getMessage(), containsString(defaultCollector.getVirtualHost())); assertThat(e.getCause(), instanceOf(IOException.class)); assertThat(e.getCause().getMessage(), equalTo("Failure")); } finally { sut.disconnect(); } }
From source file:org.smartdeveloperhub.harvesters.scm.backend.notification.CollectorControllerTest.java
License:Apache License
@Test public void testPublishEvent$discardsCurrentChannelOnRuntimeException(@Mocked final Channel channel) throws Exception { new MockUp<ConnectionManager>() { private boolean connected = false; @Mock(invocations = 1)/*from w w w. j ava 2s .c o m*/ void connect() { this.connected = true; } @Mock(invocations = 1) void disconnect() { } @Mock boolean isConnected() { return this.connected; } @Mock Channel channel() { return channel; } @Mock(invocations = 1) Channel currentChannel() { return channel; } @Mock(invocations = 1) void discardChannel() { } }; final Collector defaultCollector = defaultCollector(); new Expectations() { { channel.basicPublish(defaultCollector.getExchangeName(), Notifications.routingKey(RepositoryCreatedEvent.class), true, (BasicProperties) this.any, (byte[]) this.any); this.result = new RuntimeException("Failure"); } }; final CollectorController sut = CollectorController.createPublisher(defaultCollector); final RepositoryCreatedEvent event = new RepositoryCreatedEvent(); event.setInstance(defaultCollector.getInstance()); event.setNewRepositories(Arrays.asList("1", "2")); sut.connect(); try { sut.publishEvent(event); fail("Should fail to publish an event if the RabbitMQ client fails"); } catch (final ControllerException e) { assertThat(e.getMessage(), containsString(EventUtil.marshall(event))); assertThat(e.getMessage(), containsString(defaultCollector.getExchangeName())); assertThat(e.getMessage(), containsString(Notifications.routingKey(RepositoryCreatedEvent.class))); assertThat(e.getMessage(), containsString(defaultCollector.getBrokerHost())); assertThat(e.getMessage(), containsString(":" + defaultCollector.getBrokerPort())); assertThat(e.getMessage(), containsString(defaultCollector.getVirtualHost())); assertThat(e.getCause(), instanceOf(RuntimeException.class)); assertThat(e.getCause().getMessage(), equalTo("Failure")); } finally { sut.disconnect(); } }
From source file:org.springframework.amqp.rabbit.listener.adapter.AbstractAdaptableMessageListener.java
License:Apache License
/** * Send the given response message to the given destination. * @param channel the Rabbit channel to operate on * @param replyTo the Rabbit ReplyTo string to use when sending. Currently interpreted to be the routing key. * @param messageIn the Rabbit message to send * @throws Exception if thrown by Rabbit API methods * @see #postProcessResponse(Message, Message) *///from w ww.j a v a 2 s. co m protected void sendResponse(Channel channel, Address replyTo, Message messageIn) throws Exception { Message message; if (this.replyPostProcessor == null) { message = messageIn; } else { message = this.replyPostProcessor.postProcessMessage(messageIn); } postProcessChannel(channel, message); try { this.logger.debug("Publishing response to exchange = [" + replyTo.getExchangeName() + "], routingKey = [" + replyTo.getRoutingKey() + "]"); channel.basicPublish(replyTo.getExchangeName(), replyTo.getRoutingKey(), this.mandatoryPublish, this.messagePropertiesConverter.fromMessageProperties(message.getMessageProperties(), this.encoding), message.getBody()); } catch (Exception ex) { throw RabbitExceptionTranslator.convertRabbitAccessException(ex); } }