Search in sources :

Example 11 with MessageProducer

use of javax.jms.MessageProducer in project gocd by gocd.

the class ActiveMqMessagingService method createQueueSender.

public MessageSender createQueueSender(String queueName) {
    try {
        Session session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(session.createQueue(queueName));
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        return new ActiveMqMessageSender(session, producer);
    } catch (Exception e) {
        throw bomb(e);
    }
}
Also used : MessageProducer(javax.jms.MessageProducer) JMSException(javax.jms.JMSException) Session(javax.jms.Session)

Example 12 with MessageProducer

use of javax.jms.MessageProducer in project qpid-broker-j by apache.

the class MessageTest method getJmsMessage.

@Test
public void getJmsMessage() throws Exception {
    final String messageProperty = "myProp";
    final String messagePropertyValue = "myValue";
    Connection connection = getConnection();
    try {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME));
        Message message = session.createMessage();
        message.setStringProperty(messageProperty, messagePropertyValue);
        producer.send(message);
    } finally {
        connection.close();
    }
    List<Map<String, Object>> messages = getHelper().postJson("queue/myqueue/getMessageInfo", Collections.singletonMap("includeHeaders", Boolean.TRUE), LIST_MAP_TYPE_REF, SC_OK);
    assertThat(messages.size(), is(equalTo(1)));
    Map<String, Object> message = messages.get(0);
    @SuppressWarnings("unchecked") Map<String, Object> headers = (Map<String, Object>) message.get("headers");
    assertThat(headers.get(messageProperty), is(equalTo(messagePropertyValue)));
}
Also used : MapMessage(javax.jms.MapMessage) Message(javax.jms.Message) TextMessage(javax.jms.TextMessage) StreamMessage(javax.jms.StreamMessage) BytesMessage(javax.jms.BytesMessage) HttpURLConnection(java.net.HttpURLConnection) Connection(javax.jms.Connection) MessageProducer(javax.jms.MessageProducer) HashMap(java.util.HashMap) Map(java.util.Map) Session(javax.jms.Session) Test(org.junit.Test)

Example 13 with MessageProducer

use of javax.jms.MessageProducer in project qpid-broker-j by apache.

the class ObjectMessageClassWhitelistingTest method testObjectMessage.

@Test
public void testObjectMessage() throws Exception {
    Queue destination = createQueue(getTestName());
    final Connection c = getConnectionBuilder().setDeserializationPolicyWhiteList("*").build();
    try {
        c.start();
        Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer _consumer = s.createConsumer(destination);
        MessageProducer _producer = s.createProducer(destination);
        sendTestObjectMessage(s, _producer);
        Message receivedMessage = _consumer.receive(getReceiveTimeout());
        assertNotNull("did not receive message within receive timeout", receivedMessage);
        assertTrue("message is of wrong type", receivedMessage instanceof ObjectMessage);
        ObjectMessage receivedObjectMessage = (ObjectMessage) receivedMessage;
        Object payloadObject = receivedObjectMessage.getObject();
        assertTrue("payload is of wrong type", payloadObject instanceof HashMap);
        @SuppressWarnings("unchecked") HashMap<String, Integer> payload = (HashMap<String, Integer>) payloadObject;
        assertEquals("payload has wrong value", (Integer) TEST_VALUE, payload.get("value"));
    } finally {
        c.close();
    }
}
Also used : MessageConsumer(javax.jms.MessageConsumer) ObjectMessage(javax.jms.ObjectMessage) Message(javax.jms.Message) HashMap(java.util.HashMap) Connection(javax.jms.Connection) ObjectMessage(javax.jms.ObjectMessage) MessageProducer(javax.jms.MessageProducer) Queue(javax.jms.Queue) Session(javax.jms.Session) Test(org.junit.Test)

Example 14 with MessageProducer

use of javax.jms.MessageProducer in project qpid-broker-j by apache.

the class ObjectMessageClassWhitelistingTest method testNotWhiteListedByConnectionUrlObjectMessage.

@Test
public void testNotWhiteListedByConnectionUrlObjectMessage() throws Exception {
    Queue destination = createQueue(getTestName());
    final Connection c = getConnectionBuilder().setDeserializationPolicyWhiteList("org.apache.qpid").build();
    try {
        c.start();
        Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer consumer = s.createConsumer(destination);
        MessageProducer producer = s.createProducer(destination);
        sendTestObjectMessage(s, producer);
        Message receivedMessage = consumer.receive(getReceiveTimeout());
        assertNotNull("did not receive message within receive timeout", receivedMessage);
        assertTrue("message is of wrong type", receivedMessage instanceof ObjectMessage);
        ObjectMessage receivedObjectMessage = (ObjectMessage) receivedMessage;
        try {
            receivedObjectMessage.getObject();
            fail("should not deserialize class");
        } catch (MessageFormatException e) {
        // pass
        }
    } finally {
        c.close();
    }
}
Also used : MessageFormatException(javax.jms.MessageFormatException) MessageConsumer(javax.jms.MessageConsumer) ObjectMessage(javax.jms.ObjectMessage) Message(javax.jms.Message) ObjectMessage(javax.jms.ObjectMessage) Connection(javax.jms.Connection) MessageProducer(javax.jms.MessageProducer) Queue(javax.jms.Queue) Session(javax.jms.Session) Test(org.junit.Test)

Example 15 with MessageProducer

use of javax.jms.MessageProducer in project nifi by apache.

the class PutJMS method onTrigger.

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final ComponentLog logger = getLogger();
    final List<FlowFile> flowFiles = session.get(context.getProperty(BATCH_SIZE).asInteger().intValue());
    if (flowFiles.isEmpty()) {
        return;
    }
    WrappedMessageProducer wrappedProducer = producerQueue.poll();
    if (wrappedProducer == null) {
        try {
            wrappedProducer = JmsFactory.createMessageProducer(context, true);
            logger.info("Connected to JMS server {}", new Object[] { context.getProperty(URL).getValue() });
        } catch (final JMSException e) {
            logger.error("Failed to connect to JMS Server due to {}", new Object[] { e });
            session.transfer(flowFiles, REL_FAILURE);
            context.yield();
            return;
        }
    }
    final Session jmsSession = wrappedProducer.getSession();
    final MessageProducer producer = wrappedProducer.getProducer();
    final int maxBufferSize = context.getProperty(MAX_BUFFER_SIZE).asDataSize(DataUnit.B).intValue();
    try {
        final Set<FlowFile> successfulFlowFiles = new HashSet<>();
        for (FlowFile flowFile : flowFiles) {
            if (flowFile.getSize() > maxBufferSize) {
                session.transfer(flowFile, REL_FAILURE);
                logger.warn("Routing {} to failure because its size exceeds the configured max", new Object[] { flowFile });
                continue;
            }
            // Read the contents of the FlowFile into a byte array
            final byte[] messageContent = new byte[(int) flowFile.getSize()];
            session.read(flowFile, new InputStreamCallback() {

                @Override
                public void process(final InputStream in) throws IOException {
                    StreamUtils.fillBuffer(in, messageContent, true);
                }
            });
            final Long ttl = context.getProperty(MESSAGE_TTL).asTimePeriod(TimeUnit.MILLISECONDS);
            final String replyToQueueName = context.getProperty(REPLY_TO_QUEUE).evaluateAttributeExpressions(flowFile).getValue();
            final Destination replyToQueue = replyToQueueName == null ? null : JmsFactory.createQueue(context, replyToQueueName);
            int priority = DEFAULT_MESSAGE_PRIORITY;
            try {
                final Integer priorityInt = context.getProperty(MESSAGE_PRIORITY).evaluateAttributeExpressions(flowFile).asInteger();
                priority = priorityInt == null ? priority : priorityInt;
            } catch (final NumberFormatException e) {
                logger.warn("Invalid value for JMS Message Priority: {}; defaulting to priority of {}", new Object[] { context.getProperty(MESSAGE_PRIORITY).evaluateAttributeExpressions(flowFile).getValue(), DEFAULT_MESSAGE_PRIORITY });
            }
            try {
                final Message message = createMessage(jmsSession, context, messageContent, flowFile, replyToQueue, priority);
                if (ttl == null) {
                    producer.setTimeToLive(0L);
                } else {
                    producer.setTimeToLive(ttl);
                }
                producer.send(message);
            } catch (final JMSException e) {
                logger.error("Failed to send {} to JMS Server due to {}", new Object[] { flowFile, e });
                session.transfer(flowFiles, REL_FAILURE);
                context.yield();
                try {
                    jmsSession.rollback();
                } catch (final JMSException jmse) {
                    logger.warn("Unable to roll back JMS Session due to {}", new Object[] { jmse });
                }
                wrappedProducer.close(logger);
                return;
            }
            successfulFlowFiles.add(flowFile);
            session.getProvenanceReporter().send(flowFile, context.getProperty(URL).getValue());
        }
        try {
            jmsSession.commit();
            session.transfer(successfulFlowFiles, REL_SUCCESS);
            final String flowFileDescription = successfulFlowFiles.size() > 10 ? successfulFlowFiles.size() + " FlowFiles" : successfulFlowFiles.toString();
            logger.info("Sent {} to JMS Server and transferred to 'success'", new Object[] { flowFileDescription });
        } catch (JMSException e) {
            logger.error("Failed to commit JMS Session due to {} and transferred to 'failure'", new Object[] { e });
            session.transfer(flowFiles, REL_FAILURE);
            context.yield();
            wrappedProducer.close(logger);
        }
    } finally {
        if (!wrappedProducer.isClosed()) {
            producerQueue.offer(wrappedProducer);
        }
    }
}
Also used : FlowFile(org.apache.nifi.flowfile.FlowFile) Destination(javax.jms.Destination) StreamMessage(javax.jms.StreamMessage) Message(javax.jms.Message) BytesMessage(javax.jms.BytesMessage) InputStream(java.io.InputStream) JMSException(javax.jms.JMSException) IOException(java.io.IOException) ComponentLog(org.apache.nifi.logging.ComponentLog) WrappedMessageProducer(org.apache.nifi.processors.standard.util.WrappedMessageProducer) InputStreamCallback(org.apache.nifi.processor.io.InputStreamCallback) MessageProducer(javax.jms.MessageProducer) WrappedMessageProducer(org.apache.nifi.processors.standard.util.WrappedMessageProducer) Session(javax.jms.Session) ProcessSession(org.apache.nifi.processor.ProcessSession) HashSet(java.util.HashSet)

Aggregations

MessageProducer (javax.jms.MessageProducer)1512 Session (javax.jms.Session)1302 MessageConsumer (javax.jms.MessageConsumer)987 Connection (javax.jms.Connection)915 TextMessage (javax.jms.TextMessage)888 Test (org.junit.Test)850 Message (javax.jms.Message)646 Queue (javax.jms.Queue)404 JMSException (javax.jms.JMSException)213 Destination (javax.jms.Destination)190 ConnectionFactory (javax.jms.ConnectionFactory)147 BytesMessage (javax.jms.BytesMessage)140 Topic (javax.jms.Topic)140 TopicSession (javax.jms.TopicSession)135 TopicConnection (javax.jms.TopicConnection)115 ActiveMQQueue (org.apache.activemq.command.ActiveMQQueue)108 ObjectMessage (javax.jms.ObjectMessage)98 CountDownLatch (java.util.concurrent.CountDownLatch)91 SimpleString (org.apache.activemq.artemis.api.core.SimpleString)90 ActiveMQConnectionFactory (org.apache.activemq.ActiveMQConnectionFactory)88