Search in sources :

Example 1 with GetResponse

use of com.rabbitmq.client.GetResponse in project nifi by apache.

the class ConsumeAMQP method processResource.

/**
 * Will construct a {@link FlowFile} containing the body of the consumed AMQP message (if {@link GetResponse} returned by {@link AMQPConsumer} is
 * not null) and AMQP properties that came with message which are added to a {@link FlowFile} as attributes, transferring {@link FlowFile} to
 * 'success' {@link Relationship}.
 */
@Override
protected void processResource(final Connection connection, final AMQPConsumer consumer, final ProcessContext context, final ProcessSession session) {
    final GetResponse response = consumer.consume();
    if (response == null) {
        context.yield();
        return;
    }
    FlowFile flowFile = session.create();
    flowFile = session.write(flowFile, out -> out.write(response.getBody()));
    final BasicProperties amqpProperties = response.getProps();
    final Map<String, String> attributes = buildAttributes(amqpProperties);
    flowFile = session.putAllAttributes(flowFile, attributes);
    session.getProvenanceReporter().receive(flowFile, connection.toString() + "/" + context.getProperty(QUEUE).getValue());
    session.transfer(flowFile, REL_SUCCESS);
}
Also used : StandardValidators(org.apache.nifi.processor.util.StandardValidators) CapabilityDescription(org.apache.nifi.annotation.documentation.CapabilityDescription) FlowFile(org.apache.nifi.flowfile.FlowFile) ProcessContext(org.apache.nifi.processor.ProcessContext) Set(java.util.Set) HashMap(java.util.HashMap) ProcessSession(org.apache.nifi.processor.ProcessSession) WritesAttribute(org.apache.nifi.annotation.behavior.WritesAttribute) Connection(com.rabbitmq.client.Connection) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) List(java.util.List) InputRequirement(org.apache.nifi.annotation.behavior.InputRequirement) WritesAttributes(org.apache.nifi.annotation.behavior.WritesAttributes) Relationship(org.apache.nifi.processor.Relationship) Map(java.util.Map) Requirement(org.apache.nifi.annotation.behavior.InputRequirement.Requirement) Tags(org.apache.nifi.annotation.documentation.Tags) Collections(java.util.Collections) BasicProperties(com.rabbitmq.client.AMQP.BasicProperties) GetResponse(com.rabbitmq.client.GetResponse) FlowFile(org.apache.nifi.flowfile.FlowFile) BasicProperties(com.rabbitmq.client.AMQP.BasicProperties) GetResponse(com.rabbitmq.client.GetResponse)

Example 2 with GetResponse

use of com.rabbitmq.client.GetResponse in project nifi by apache.

the class PublishAMQPTest method validateSuccessfullPublishAndTransferToSuccess.

@Test
public void validateSuccessfullPublishAndTransferToSuccess() throws Exception {
    final PublishAMQP pubProc = new LocalPublishAMQP();
    final TestRunner runner = TestRunners.newTestRunner(pubProc);
    runner.setProperty(PublishAMQP.HOST, "injvm");
    runner.setProperty(PublishAMQP.EXCHANGE, "myExchange");
    runner.setProperty(PublishAMQP.ROUTING_KEY, "key1");
    final Map<String, String> attributes = new HashMap<>();
    attributes.put("foo", "bar");
    attributes.put("amqp$contentType", "foo/bar");
    attributes.put("amqp$contentEncoding", "foobar123");
    attributes.put("amqp$headers", "foo=bar,foo2=bar2,foo3");
    attributes.put("amqp$deliveryMode", "1");
    attributes.put("amqp$priority", "2");
    attributes.put("amqp$correlationId", "correlationId123");
    attributes.put("amqp$replyTo", "replyTo123");
    attributes.put("amqp$expiration", "expiration123");
    attributes.put("amqp$messageId", "messageId123");
    attributes.put("amqp$timestamp", "123456789");
    attributes.put("amqp$type", "type123");
    attributes.put("amqp$userId", "userId123");
    attributes.put("amqp$appId", "appId123");
    attributes.put("amqp$clusterId", "clusterId123");
    runner.enqueue("Hello Joe".getBytes(), attributes);
    runner.run();
    final MockFlowFile successFF = runner.getFlowFilesForRelationship(PublishAMQP.REL_SUCCESS).get(0);
    assertNotNull(successFF);
    final Channel channel = ((LocalPublishAMQP) pubProc).getConnection().createChannel();
    final GetResponse msg1 = channel.basicGet("queue1", true);
    assertNotNull(msg1);
    assertEquals("foo/bar", msg1.getProps().getContentType());
    assertEquals("foobar123", msg1.getProps().getContentEncoding());
    final Map<String, Object> headerMap = msg1.getProps().getHeaders();
    final Object foo = headerMap.get("foo");
    final Object foo2 = headerMap.get("foo2");
    final Object foo3 = headerMap.get("foo3");
    assertEquals("bar", foo.toString());
    assertEquals("bar2", foo2.toString());
    assertNull(foo3);
    assertEquals((Integer) 1, msg1.getProps().getDeliveryMode());
    assertEquals((Integer) 2, msg1.getProps().getPriority());
    assertEquals("correlationId123", msg1.getProps().getCorrelationId());
    assertEquals("replyTo123", msg1.getProps().getReplyTo());
    assertEquals("expiration123", msg1.getProps().getExpiration());
    assertEquals("messageId123", msg1.getProps().getMessageId());
    assertEquals(new Date(123456789L), msg1.getProps().getTimestamp());
    assertEquals("type123", msg1.getProps().getType());
    assertEquals("userId123", msg1.getProps().getUserId());
    assertEquals("appId123", msg1.getProps().getAppId());
    assertEquals("clusterId123", msg1.getProps().getClusterId());
    assertNotNull(channel.basicGet("queue2", true));
}
Also used : MockFlowFile(org.apache.nifi.util.MockFlowFile) HashMap(java.util.HashMap) TestRunner(org.apache.nifi.util.TestRunner) Channel(com.rabbitmq.client.Channel) GetResponse(com.rabbitmq.client.GetResponse) Date(java.util.Date) Test(org.junit.Test)

Example 3 with GetResponse

use of com.rabbitmq.client.GetResponse in project nifi by apache.

the class TestChannel method basicPublish.

@Override
public void basicPublish(final String exchange, final String routingKey, boolean mandatory, final BasicProperties props, final byte[] body) throws IOException {
    if (this.corrupted) {
        throw new IOException("Channel is corrupted");
    }
    if (exchange.equals("")) {
        // default exchange; routingKey corresponds to a queue.
        BlockingQueue<GetResponse> messages = this.getMessageQueue(routingKey);
        GetResponse response = new GetResponse(null, props, body, messages.size());
        messages.offer(response);
    } else {
        String rKey = this.exchangeToRoutingKeyMappings.get(exchange);
        if (rKey.equals(routingKey)) {
            List<String> queueNames = this.routingKeyToQueueMappings.get(routingKey);
            if (queueNames == null || queueNames.isEmpty()) {
                this.discard(exchange, routingKey, mandatory, props, body);
            } else {
                for (String queueName : queueNames) {
                    BlockingQueue<GetResponse> messages = this.getMessageQueue(queueName);
                    GetResponse response = new GetResponse(null, props, body, messages.size());
                    messages.offer(response);
                }
            }
        } else {
            this.discard(exchange, routingKey, mandatory, props, body);
        }
    }
}
Also used : IOException(java.io.IOException) GetResponse(com.rabbitmq.client.GetResponse)

Example 4 with GetResponse

use of com.rabbitmq.client.GetResponse in project rabbitmq-jms-client by rabbitmq.

the class DelayedReceiver method get.

/**
 * Get a message; if there isn't one, try again at intervals not exceeding the total time available. Aborts if closed while polling.
 * @param tt - keeps track of the time available
 * @return message gotten, or <code>null</code> if timeout or connection closed.
 */
public GetResponse get(TimeTracker tt) {
    try {
        synchronized (this.responseLock) {
            GetResponse resp = this.rmqMessageConsumer.getFromRabbitQueue();
            if (resp != null)
                return resp;
            while (!this.aborted && !tt.timedOut()) {
                resp = this.rmqMessageConsumer.getFromRabbitQueue();
                if (resp != null)
                    break;
                new TimeTracker(POLLING_INTERVAL).timedWait(this.responseLock);
            }
            return resp;
        }
    } catch (InterruptedException e) {
        logger.warn("Get interrupted while buffer.poll-ing.", e);
        Thread.currentThread().interrupt();
        return null;
    }
}
Also used : TimeTracker(com.rabbitmq.jms.util.TimeTracker) GetResponse(com.rabbitmq.client.GetResponse)

Example 5 with GetResponse

use of com.rabbitmq.client.GetResponse in project rabbitmq-jms-client by rabbitmq.

the class RMQMessageConsumer method receive.

private RMQMessage receive(TimeTracker tt) throws JMSException {
    /* Pseudocode:
     *  get (synchronous read)
     *  if something return it;
     *  if nothing, then poll (intervals up to time limit given)
     *  if still nothing return nothing.
     */
    if (!this.session.syncAllowed()) {
        throw new IllegalStateException("A session may not receive() when a MessageListener is set. (See JMS 1.1 ยง4.4.6.)");
    }
    this.numberOfReceives.incrementAndGet();
    try {
        if (// stopped?
        !this.receiveManager.enter(tt))
            // timed out while stopped
            return null;
        /* Try to receive a message, there's some time left! */
        try {
            GetResponse resp = this.delayedReceiver.get(tt);
            // nothing received in time or aborted
            if (resp == null)
                return null;
            this.dealWithAcknowledgements(this.isAutoAck(), resp.getEnvelope().getDeliveryTag());
            return RMQMessage.convertMessage(this.session, this.destination, resp);
        } finally {
            this.receiveManager.exit();
        }
    } catch (AbortedException e) {
        /* If we were aborted (closed) we return null, too. */
        return null;
    } catch (InterruptedException e) {
        /* Someone interrupted us -- we ought to terminate */
        // reset interrupt status
        Thread.currentThread().interrupt();
        return null;
    } finally {
        this.numberOfReceives.decrementAndGet();
    }
}
Also used : IllegalStateException(javax.jms.IllegalStateException) AbortedException(com.rabbitmq.jms.util.AbortedException) GetResponse(com.rabbitmq.client.GetResponse)

Aggregations

GetResponse (com.rabbitmq.client.GetResponse)55 Test (org.junit.Test)27 Channel (com.rabbitmq.client.Channel)10 IOException (java.io.IOException)10 Envelope (com.rabbitmq.client.Envelope)8 Connection (com.rabbitmq.client.Connection)7 Message (de.gessnerfl.rabbitmq.queue.management.model.Message)6 HashMap (java.util.HashMap)6 AMQP (com.rabbitmq.client.AMQP)5 LongString (com.rabbitmq.client.LongString)5 BasicProperties (com.rabbitmq.client.AMQP.BasicProperties)4 BasicProperties (de.gessnerfl.rabbitmq.queue.management.model.BasicProperties)4 RMQDestination (com.rabbitmq.jms.admin.RMQDestination)3 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 List (java.util.List)3 Map (java.util.Map)3 Queue (javax.jms.Queue)3 QueueSender (javax.jms.QueueSender)3 QueueSession (javax.jms.QueueSession)3