Search in sources :

Example 1 with JmsProcessingSummary

use of org.apache.nifi.processors.standard.util.JmsProcessingSummary in project nifi by apache.

the class JmsConsumer method map2FlowFile.

public static JmsProcessingSummary map2FlowFile(final ProcessContext context, final ProcessSession session, final Message message, final boolean addAttributes, ComponentLog logger) throws Exception {
    // Currently not very useful, because always one Message == one FlowFile
    final AtomicInteger msgsThisFlowFile = new AtomicInteger(1);
    FlowFile flowFile = session.create();
    try {
        // MapMessage is exception, add only name-value pairs to FlowFile attributes
        if (message instanceof MapMessage) {
            MapMessage mapMessage = (MapMessage) message;
            flowFile = session.putAllAttributes(flowFile, createMapMessageValues(mapMessage));
        } else {
            // all other message types, write Message body to FlowFile content
            flowFile = session.write(flowFile, new OutputStreamCallback() {

                @Override
                public void process(final OutputStream rawOut) throws IOException {
                    try (final OutputStream out = new BufferedOutputStream(rawOut, 65536)) {
                        final byte[] messageBody = JmsFactory.createByteArray(message);
                        out.write(messageBody);
                    } catch (final JMSException e) {
                        throw new ProcessException("Failed to receive JMS Message due to " + e.getMessage(), e);
                    }
                }
            });
        }
        if (addAttributes) {
            flowFile = session.putAllAttributes(flowFile, JmsFactory.createAttributeMap(message));
        }
        session.getProvenanceReporter().receive(flowFile, context.getProperty(URL).getValue());
        session.transfer(flowFile, REL_SUCCESS);
        logger.info("Created {} from {} messages received from JMS Server and transferred to 'success'", new Object[] { flowFile, msgsThisFlowFile.get() });
        return new JmsProcessingSummary(flowFile.getSize(), message, flowFile);
    } catch (Exception e) {
        session.remove(flowFile);
        throw e;
    }
}
Also used : FlowFile(org.apache.nifi.flowfile.FlowFile) ProcessException(org.apache.nifi.processor.exception.ProcessException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MapMessage(javax.jms.MapMessage) OutputStream(java.io.OutputStream) BufferedOutputStream(org.apache.nifi.stream.io.BufferedOutputStream) JMSException(javax.jms.JMSException) OutputStreamCallback(org.apache.nifi.processor.io.OutputStreamCallback) JmsProcessingSummary(org.apache.nifi.processors.standard.util.JmsProcessingSummary) BufferedOutputStream(org.apache.nifi.stream.io.BufferedOutputStream) ProcessException(org.apache.nifi.processor.exception.ProcessException) IOException(java.io.IOException) JMSException(javax.jms.JMSException)

Example 2 with JmsProcessingSummary

use of org.apache.nifi.processors.standard.util.JmsProcessingSummary in project nifi by apache.

the class TestJmsConsumer method testMap2FlowFileBytesMessage.

/**
 * Test BytesMessage to FlowFile conversion
 *
 * @throws java.lang.Exception ex
 */
@Test
public void testMap2FlowFileBytesMessage() throws Exception {
    TestRunner runner = TestRunners.newTestRunner(GetJMSQueue.class);
    BytesMessage bytesMessage = new ActiveMQBytesMessage();
    String sourceString = "Apache NiFi is an easy to use, powerful, and reliable system to process and distribute data.!";
    byte[] payload = sourceString.getBytes("UTF-8");
    bytesMessage.writeBytes(payload);
    bytesMessage.reset();
    ProcessContext context = runner.getProcessContext();
    ProcessSession session = runner.getProcessSessionFactory().createSession();
    ProcessorInitializationContext pic = new MockProcessorInitializationContext(runner.getProcessor(), (MockProcessContext) runner.getProcessContext());
    JmsProcessingSummary summary = JmsConsumer.map2FlowFile(context, session, bytesMessage, true, pic.getLogger());
    assertEquals("BytesMessage content length should equal to FlowFile content size", payload.length, summary.getLastFlowFile().getSize());
    final byte[] buffer = new byte[payload.length];
    runner.clearTransferState();
    session.read(summary.getLastFlowFile(), new InputStreamCallback() {

        @Override
        public void process(InputStream in) throws IOException {
            StreamUtils.fillBuffer(in, buffer, false);
        }
    });
    String contentString = new String(buffer, "UTF-8");
    assertEquals("", sourceString, contentString);
}
Also used : ProcessSession(org.apache.nifi.processor.ProcessSession) TestRunner(org.apache.nifi.util.TestRunner) InputStream(java.io.InputStream) MockProcessorInitializationContext(org.apache.nifi.util.MockProcessorInitializationContext) ActiveMQBytesMessage(org.apache.activemq.command.ActiveMQBytesMessage) BytesMessage(javax.jms.BytesMessage) JmsProcessingSummary(org.apache.nifi.processors.standard.util.JmsProcessingSummary) IOException(java.io.IOException) ProcessContext(org.apache.nifi.processor.ProcessContext) MockProcessContext(org.apache.nifi.util.MockProcessContext) MockProcessorInitializationContext(org.apache.nifi.util.MockProcessorInitializationContext) ProcessorInitializationContext(org.apache.nifi.processor.ProcessorInitializationContext) ActiveMQBytesMessage(org.apache.activemq.command.ActiveMQBytesMessage) InputStreamCallback(org.apache.nifi.processor.io.InputStreamCallback) Test(org.junit.Test)

Example 3 with JmsProcessingSummary

use of org.apache.nifi.processors.standard.util.JmsProcessingSummary in project nifi by apache.

the class TestJmsConsumer method testMap2FlowFileMapMessage.

/**
 * Test MapMessage to FlowFile conversion
 *
 * @throws java.lang.Exception ex
 */
@Test
public void testMap2FlowFileMapMessage() throws Exception {
    TestRunner runner = TestRunners.newTestRunner(GetJMSQueue.class);
    MapMessage mapMessage = createMapMessage();
    ProcessContext context = runner.getProcessContext();
    ProcessSession session = runner.getProcessSessionFactory().createSession();
    ProcessorInitializationContext pic = new MockProcessorInitializationContext(runner.getProcessor(), (MockProcessContext) runner.getProcessContext());
    JmsProcessingSummary summary = JmsConsumer.map2FlowFile(context, session, mapMessage, true, pic.getLogger());
    assertEquals("MapMessage should not create FlowFile content", 0, summary.getBytesReceived());
    Map<String, String> attributes = summary.getLastFlowFile().getAttributes();
    assertEquals("", "Arnold", attributes.get(JmsConsumer.MAP_MESSAGE_PREFIX + "name"));
    assertEquals("", "97", attributes.get(JmsConsumer.MAP_MESSAGE_PREFIX + "age"));
    assertEquals("", "89686.564", attributes.get(JmsConsumer.MAP_MESSAGE_PREFIX + "xyz"));
    assertEquals("", "true", attributes.get(JmsConsumer.MAP_MESSAGE_PREFIX + "good"));
}
Also used : ProcessSession(org.apache.nifi.processor.ProcessSession) TestRunner(org.apache.nifi.util.TestRunner) ActiveMQMapMessage(org.apache.activemq.command.ActiveMQMapMessage) MapMessage(javax.jms.MapMessage) MockProcessorInitializationContext(org.apache.nifi.util.MockProcessorInitializationContext) JmsProcessingSummary(org.apache.nifi.processors.standard.util.JmsProcessingSummary) ProcessContext(org.apache.nifi.processor.ProcessContext) MockProcessContext(org.apache.nifi.util.MockProcessContext) MockProcessorInitializationContext(org.apache.nifi.util.MockProcessorInitializationContext) ProcessorInitializationContext(org.apache.nifi.processor.ProcessorInitializationContext) Test(org.junit.Test)

Example 4 with JmsProcessingSummary

use of org.apache.nifi.processors.standard.util.JmsProcessingSummary in project nifi by apache.

the class JmsConsumer method consume.

public void consume(final ProcessContext context, final ProcessSession session, final WrappedMessageConsumer wrappedConsumer) throws ProcessException {
    final ComponentLog logger = getLogger();
    final MessageConsumer consumer = wrappedConsumer.getConsumer();
    final boolean clientAcknowledge = context.getProperty(ACKNOWLEDGEMENT_MODE).getValue().equalsIgnoreCase(ACK_MODE_CLIENT);
    final long timeout = context.getProperty(TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS);
    final boolean addAttributes = context.getProperty(JMS_PROPS_TO_ATTRIBUTES).asBoolean();
    final int batchSize = context.getProperty(BATCH_SIZE).asInteger();
    final JmsProcessingSummary processingSummary = new JmsProcessingSummary();
    final StopWatch stopWatch = new StopWatch(true);
    for (int i = 0; i < batchSize; i++) {
        final Message message;
        try {
            // all messages that are immediately available.
            if (processingSummary.getMessagesReceived() == 0) {
                message = consumer.receive(timeout);
            } else {
                message = consumer.receiveNoWait();
            }
        } catch (final JMSException e) {
            logger.error("Failed to receive JMS Message due to {}", e);
            wrappedConsumer.close(logger);
            break;
        }
        if (message == null) {
            // if no messages, we're done
            break;
        }
        try {
            processingSummary.add(map2FlowFile(context, session, message, addAttributes, logger));
        } catch (Exception e) {
            logger.error("Failed to receive JMS Message due to {}", e);
            wrappedConsumer.close(logger);
            break;
        }
    }
    if (processingSummary.getFlowFilesCreated() == 0) {
        context.yield();
        return;
    }
    session.commit();
    stopWatch.stop();
    if (processingSummary.getFlowFilesCreated() > 0) {
        final float secs = (stopWatch.getDuration(TimeUnit.MILLISECONDS) / 1000F);
        float messagesPerSec = (processingSummary.getMessagesReceived()) / secs;
        final String dataRate = stopWatch.calculateDataRate(processingSummary.getBytesReceived());
        logger.info("Received {} messages in {} milliseconds, at a rate of {} messages/sec or {}", new Object[] { processingSummary.getMessagesReceived(), stopWatch.getDuration(TimeUnit.MILLISECONDS), messagesPerSec, dataRate });
    }
    // if we need to acknowledge the messages, do so now.
    final Message lastMessage = processingSummary.getLastMessageReceived();
    if (clientAcknowledge && lastMessage != null) {
        try {
            // acknowledge all received messages by acknowledging only the last.
            lastMessage.acknowledge();
        } catch (final JMSException e) {
            logger.error("Failed to acknowledge {} JMS Message(s). This may result in duplicate messages. Reason for failure: {}", new Object[] { processingSummary.getMessagesReceived(), e });
        }
    }
}
Also used : WrappedMessageConsumer(org.apache.nifi.processors.standard.util.WrappedMessageConsumer) MessageConsumer(javax.jms.MessageConsumer) MapMessage(javax.jms.MapMessage) Message(javax.jms.Message) JMSException(javax.jms.JMSException) JmsProcessingSummary(org.apache.nifi.processors.standard.util.JmsProcessingSummary) ComponentLog(org.apache.nifi.logging.ComponentLog) ProcessException(org.apache.nifi.processor.exception.ProcessException) IOException(java.io.IOException) JMSException(javax.jms.JMSException) StopWatch(org.apache.nifi.util.StopWatch)

Example 5 with JmsProcessingSummary

use of org.apache.nifi.processors.standard.util.JmsProcessingSummary in project nifi by apache.

the class TestJmsConsumer method testMap2FlowFileTextMessage.

@Test
public void testMap2FlowFileTextMessage() throws Exception {
    TestRunner runner = TestRunners.newTestRunner(GetJMSQueue.class);
    TextMessage textMessage = new ActiveMQTextMessage();
    String payload = "Hello world!";
    textMessage.setText(payload);
    ProcessContext context = runner.getProcessContext();
    ProcessSession session = runner.getProcessSessionFactory().createSession();
    ProcessorInitializationContext pic = new MockProcessorInitializationContext(runner.getProcessor(), (MockProcessContext) runner.getProcessContext());
    JmsProcessingSummary summary = JmsConsumer.map2FlowFile(context, session, textMessage, true, pic.getLogger());
    assertEquals("TextMessage content length should equal to FlowFile content size", payload.length(), summary.getLastFlowFile().getSize());
    final byte[] buffer = new byte[payload.length()];
    runner.clearTransferState();
    session.read(summary.getLastFlowFile(), new InputStreamCallback() {

        @Override
        public void process(InputStream in) throws IOException {
            StreamUtils.fillBuffer(in, buffer, false);
        }
    });
    String contentString = new String(buffer, "UTF-8");
    assertEquals("", payload, contentString);
}
Also used : ProcessSession(org.apache.nifi.processor.ProcessSession) TestRunner(org.apache.nifi.util.TestRunner) InputStream(java.io.InputStream) MockProcessorInitializationContext(org.apache.nifi.util.MockProcessorInitializationContext) JmsProcessingSummary(org.apache.nifi.processors.standard.util.JmsProcessingSummary) IOException(java.io.IOException) ProcessContext(org.apache.nifi.processor.ProcessContext) MockProcessContext(org.apache.nifi.util.MockProcessContext) MockProcessorInitializationContext(org.apache.nifi.util.MockProcessorInitializationContext) ProcessorInitializationContext(org.apache.nifi.processor.ProcessorInitializationContext) ActiveMQTextMessage(org.apache.activemq.command.ActiveMQTextMessage) InputStreamCallback(org.apache.nifi.processor.io.InputStreamCallback) TextMessage(javax.jms.TextMessage) ActiveMQTextMessage(org.apache.activemq.command.ActiveMQTextMessage) Test(org.junit.Test)

Aggregations

JmsProcessingSummary (org.apache.nifi.processors.standard.util.JmsProcessingSummary)5 IOException (java.io.IOException)4 MapMessage (javax.jms.MapMessage)3 ProcessContext (org.apache.nifi.processor.ProcessContext)3 ProcessSession (org.apache.nifi.processor.ProcessSession)3 ProcessorInitializationContext (org.apache.nifi.processor.ProcessorInitializationContext)3 MockProcessContext (org.apache.nifi.util.MockProcessContext)3 MockProcessorInitializationContext (org.apache.nifi.util.MockProcessorInitializationContext)3 TestRunner (org.apache.nifi.util.TestRunner)3 Test (org.junit.Test)3 InputStream (java.io.InputStream)2 JMSException (javax.jms.JMSException)2 ProcessException (org.apache.nifi.processor.exception.ProcessException)2 InputStreamCallback (org.apache.nifi.processor.io.InputStreamCallback)2 OutputStream (java.io.OutputStream)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 BytesMessage (javax.jms.BytesMessage)1 Message (javax.jms.Message)1 MessageConsumer (javax.jms.MessageConsumer)1 TextMessage (javax.jms.TextMessage)1