Search in sources :

Example 6 with Envelope

use of com.rabbitmq.client.Envelope in project spring-integration by spring-projects.

the class AmqpMessageSourceTests method testAck.

@Test
public void testAck() throws Exception {
    Channel channel = mock(Channel.class);
    willReturn(true).given(channel).isOpen();
    Envelope envelope = new Envelope(123L, false, "ex", "rk");
    BasicProperties props = new BasicProperties.Builder().build();
    GetResponse getResponse = new GetResponse(envelope, props, "bar".getBytes(), 0);
    willReturn(getResponse).given(channel).basicGet("foo", false);
    Connection connection = mock(Connection.class);
    willReturn(true).given(connection).isOpen();
    willReturn(channel).given(connection).createChannel();
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    willReturn(connection).given(connectionFactory).newConnection((ExecutorService) isNull(), anyString());
    CachingConnectionFactory ccf = new CachingConnectionFactory(connectionFactory);
    AmqpMessageSource source = new AmqpMessageSource(ccf, "foo");
    source.setRawMessageHeader(true);
    Message<?> received = source.receive();
    assertThat(received.getHeaders().get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE), instanceOf(org.springframework.amqp.core.Message.class));
    assertThat(received.getHeaders().get(AmqpHeaders.CONSUMER_QUEUE), equalTo("foo"));
    // make sure channel is not cached
    org.springframework.amqp.rabbit.connection.Connection conn = ccf.createConnection();
    // should not have been "closed"
    Channel notCached = conn.createChannel(false);
    verify(connection, times(2)).createChannel();
    StaticMessageHeaderAccessor.getAcknowledgmentCallback(received).acknowledge(Status.ACCEPT);
    verify(channel).basicAck(123L, false);
    // should have been "closed"
    Channel cached = conn.createChannel(false);
    verify(connection, times(2)).createChannel();
    notCached.close();
    cached.close();
    ccf.destroy();
    verify(channel, times(2)).close();
    verify(connection).close(30000);
}
Also used : Message(org.springframework.messaging.Message) BasicProperties(com.rabbitmq.client.AMQP.BasicProperties) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) Envelope(com.rabbitmq.client.Envelope) GetResponse(com.rabbitmq.client.GetResponse) CachingConnectionFactory(org.springframework.amqp.rabbit.connection.CachingConnectionFactory) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) CachingConnectionFactory(org.springframework.amqp.rabbit.connection.CachingConnectionFactory) Test(org.junit.Test)

Example 7 with Envelope

use of com.rabbitmq.client.Envelope in project flink by apache.

the class RMQSource method processMessage.

private void processMessage(Delivery delivery, RMQCollectorImpl collector) throws IOException {
    AMQP.BasicProperties properties = delivery.getProperties();
    byte[] body = delivery.getBody();
    Envelope envelope = delivery.getEnvelope();
    collector.setFallBackIdentifiers(properties.getCorrelationId(), envelope.getDeliveryTag());
    deliveryDeserializer.deserialize(envelope, properties, body, collector);
}
Also used : AMQP(com.rabbitmq.client.AMQP) Envelope(com.rabbitmq.client.Envelope)

Example 8 with Envelope

use of com.rabbitmq.client.Envelope in project pinpoint by naver.

the class RabbitMQConsumerDispatchInterceptor method createTrace.

private Trace createTrace(Object target, Object[] args) {
    final Channel channel = ((ChannelGetter) target)._$PINPOINT$_getChannel();
    if (channel == null) {
        logger.debug("channel is null, skipping trace");
        return null;
    }
    final Connection connection = channel.getConnection();
    if (connection == null) {
        logger.debug("connection is null, skipping trace");
        return null;
    }
    Envelope envelope = ArrayArgumentUtils.getArgument(args, 2, Envelope.class);
    String exchange = envelope.getExchange();
    if (RabbitMQClientPluginConfig.isExchangeExcluded(exchange, excludeExchangeFilter)) {
        if (isDebug) {
            logger.debug("exchange {} is excluded", exchange);
        }
        return null;
    }
    // args[3] may be null
    AMQP.BasicProperties properties = (AMQP.BasicProperties) args[3];
    Map<String, Object> headers = getHeadersFromBasicProperties(properties);
    // If this transaction is not traceable, mark as disabled.
    if (headers.get(RabbitMQClientConstants.META_SAMPLED) != null) {
        return traceContext.disableSampling();
    }
    final TraceId traceId = populateTraceIdFromRequest(headers);
    // If there's no trasanction id, a new trasaction begins here.
    final Trace trace = traceId == null ? traceContext.newTraceObject() : traceContext.continueTraceObject(traceId);
    if (trace.canSampled()) {
        final SpanRecorder recorder = trace.getSpanRecorder();
        recordRootSpan(recorder, connection, envelope, headers);
    }
    return trace;
}
Also used : Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) AMQConnection(com.rabbitmq.client.impl.AMQConnection) Envelope(com.rabbitmq.client.Envelope) Trace(com.navercorp.pinpoint.bootstrap.context.Trace) SpanRecorder(com.navercorp.pinpoint.bootstrap.context.SpanRecorder) AMQP(com.rabbitmq.client.AMQP) ChannelGetter(com.navercorp.pinpoint.plugin.rabbitmq.client.field.getter.ChannelGetter) TraceId(com.navercorp.pinpoint.bootstrap.context.TraceId)

Example 9 with Envelope

use of com.rabbitmq.client.Envelope in project flux by eclipse.

the class RabbitMQMessageConnector method createInbox.

private String createInbox() throws IOException {
    DeclareOk ok = this.channel.queueDeclare("", /*durable*/
    false, /*exclusive*/
    false, /*autoDelete*/
    true, null);
    final String inbox = ok.getQueue();
    console.log("Inbox created: " + inbox);
    channel.basicConsume(inbox, new DefaultConsumer(channel) {

        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException {
            try {
                JSONObject obj = JSON.parse(body);
                if (!isSelfOriginated(obj)) {
                    handleIncomingMessage(obj.getString("type"), obj.getJSONObject("data"));
                }
            } catch (Exception e) {
                console.log(e);
            }
        }

        /**
         * Tests whether an incoming message originated from the same MessageConnector that
         * is receiving it. (Such messages are skipped in keeping with how socketio does the same
         * thing).
         */
        private boolean isSelfOriginated(JSONObject obj) {
            try {
                String origin = obj.getString("origin");
                return inbox.equals(origin);
            } catch (Exception e) {
                console.log(e);
            }
            return false;
        }
    });
    return inbox;
}
Also used : DeclareOk(com.rabbitmq.client.AMQP.Queue.DeclareOk) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) JSONObject(org.json.JSONObject) BasicProperties(com.rabbitmq.client.AMQP.BasicProperties) IOException(java.io.IOException) Envelope(com.rabbitmq.client.Envelope) IOException(java.io.IOException)

Example 10 with Envelope

use of com.rabbitmq.client.Envelope in project cloudstack by apache.

the class RabbitMQEventBus method subscribe.

/**
 * Call to subscribe to interested set of events
 *
 * @param topic defines category and type of the events being subscribed to
 * @param subscriber subscriber that intends to receive event notification
 * @return UUID that represents the subscription with event bus
 * @throws EventBusException
 */
@Override
public UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws EventBusException {
    if (subscriber == null || topic == null) {
        throw new EventBusException("Invalid EventSubscriber/EventTopic object passed.");
    }
    // create a UUID, that will be used for managing subscriptions and also used as queue name
    // for on the queue used for the subscriber on the AMQP broker
    UUID queueId = UUID.randomUUID();
    String queueName = queueId.toString();
    try {
        String bindingKey = createBindingKey(topic);
        // store the subscriber details before creating channel
        s_subscribers.put(queueName, new Ternary(bindingKey, null, subscriber));
        // create a channel dedicated for this subscription
        Connection connection = getConnection();
        Channel channel = createChannel(connection);
        // create a queue and bind it to the exchange with binding key formed from event topic
        createExchange(channel, amqpExchangeName);
        channel.queueDeclare(queueName, false, false, false, null);
        channel.queueBind(queueName, amqpExchangeName, bindingKey);
        // register a callback handler to receive the events that a subscriber subscribed to
        channel.basicConsume(queueName, s_autoAck, queueName, new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                Ternary<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName);
                if (queueDetails != null) {
                    EventSubscriber subscriber = queueDetails.third();
                    String routingKey = envelope.getRoutingKey();
                    String eventSource = getEventSourceFromRoutingKey(routingKey);
                    String eventCategory = getEventCategoryFromRoutingKey(routingKey);
                    String eventType = getEventTypeFromRoutingKey(routingKey);
                    String resourceType = getResourceTypeFromRoutingKey(routingKey);
                    String resourceUUID = getResourceUUIDFromRoutingKey(routingKey);
                    Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID);
                    event.setDescription(new String(body));
                    // deliver the event to call back object provided by subscriber
                    subscriber.onEvent(event);
                }
            }
        });
        // update the channel details for the subscription
        Ternary<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName);
        queueDetails.second(channel);
        s_subscribers.put(queueName, queueDetails);
    } catch (AlreadyClosedException closedException) {
        s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection", closedException);
    } catch (ConnectException connectException) {
        s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection", connectException);
    } catch (Exception e) {
        throw new EventBusException("Failed to subscribe to event due to " + e.getMessage());
    }
    return queueId;
}
Also used : EventSubscriber(org.apache.cloudstack.framework.events.EventSubscriber) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Ternary(com.cloud.utils.Ternary) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) IOException(java.io.IOException) AlreadyClosedException(com.rabbitmq.client.AlreadyClosedException) Envelope(com.rabbitmq.client.Envelope) TimeoutException(java.util.concurrent.TimeoutException) ConfigurationException(javax.naming.ConfigurationException) ShutdownSignalException(com.rabbitmq.client.ShutdownSignalException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ConnectException(java.net.ConnectException) EventBusException(org.apache.cloudstack.framework.events.EventBusException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) AlreadyClosedException(com.rabbitmq.client.AlreadyClosedException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AMQP(com.rabbitmq.client.AMQP) Event(org.apache.cloudstack.framework.events.Event) EventBusException(org.apache.cloudstack.framework.events.EventBusException) UUID(java.util.UUID) ConnectException(java.net.ConnectException)

Aggregations

Envelope (com.rabbitmq.client.Envelope)31 DefaultConsumer (com.rabbitmq.client.DefaultConsumer)20 AMQP (com.rabbitmq.client.AMQP)18 IOException (java.io.IOException)17 Channel (com.rabbitmq.client.Channel)16 Test (org.junit.Test)12 Connection (com.rabbitmq.client.Connection)11 ConnectionFactory (com.rabbitmq.client.ConnectionFactory)10 TimeoutException (java.util.concurrent.TimeoutException)9 GetResponse (com.rabbitmq.client.GetResponse)8 BasicProperties (com.rabbitmq.client.AMQP.BasicProperties)6 LongString (com.rabbitmq.client.LongString)5 Consumer (com.rabbitmq.client.Consumer)4 BasicProperties (de.gessnerfl.rabbitmq.queue.management.model.BasicProperties)4 Message (de.gessnerfl.rabbitmq.queue.management.model.Message)4 KeyManagementException (java.security.KeyManagementException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 UUID (java.util.UUID)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 Path (javax.ws.rs.Path)3