Search in sources :

Example 61 with JMSException

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

the class AuthenticationTest method assertConnectivity.

private void assertConnectivity(final int port, final String userName, final String userPassword, final String mechanism) throws Exception {
    Connection connection = getConnectionBuilder().setPort(port).setUsername(userName).setPassword(userPassword).setSaslMechanisms(mechanism).build();
    try {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        TemporaryQueue queue = session.createTemporaryQueue();
        assertNotNull("Temporary queue was not created", queue);
    } finally {
        connection.close();
    }
    try {
        getConnectionBuilder().setPort(port).setUsername(userName).setPassword("invalid" + userPassword).setSaslMechanisms(mechanism).build();
        fail("Connection is established for invalid password");
    } catch (JMSException e) {
    // pass
    }
    try {
        getConnectionBuilder().setPort(port).setUsername("invalid" + userName).setPassword(userPassword).setSaslMechanisms(mechanism).build();
        fail("Connection is established for invalid user name");
    } catch (JMSException e) {
    // pass
    }
}
Also used : Connection(javax.jms.Connection) TemporaryQueue(javax.jms.TemporaryQueue) JMSException(javax.jms.JMSException) Session(javax.jms.Session)

Example 62 with JMSException

use of javax.jms.JMSException in project pentaho-kettle by pentaho.

the class WebsphereMQProvider method getContext.

@Override
public JMSContext getContext(JmsDelegate meta, VariableSpace variableSpace) {
    MQUrlResolver resolver = new MQUrlResolver(meta, variableSpace);
    MQConnectionFactory connFactory = isQueue(meta, variableSpace) ? new MQQueueConnectionFactory() : new MQTopicConnectionFactory();
    connFactory.setHostName(resolver.host);
    try {
        connFactory.setPort(resolver.port);
        connFactory.setQueueManager(resolver.queueManager);
        connFactory.setChannel(resolver.channel);
        connFactory.setTransportType(WMQConstants.WMQ_CM_CLIENT);
    } catch (JMSException e) {
        throw new RuntimeException(e);
    }
    return connFactory.createContext(variableSpace.environmentSubstitute(meta.ibmUsername), variableSpace.environmentSubstitute(meta.ibmPassword));
}
Also used : MQTopicConnectionFactory(com.ibm.mq.jms.MQTopicConnectionFactory) MQQueueConnectionFactory(com.ibm.mq.jms.MQQueueConnectionFactory) JMSException(javax.jms.JMSException) MQConnectionFactory(com.ibm.mq.jms.MQConnectionFactory)

Example 63 with JMSException

use of javax.jms.JMSException 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)

Example 64 with JMSException

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

the class GetJMSTopic method handleSubscriptions.

@OnScheduled
public void handleSubscriptions(final ProcessContext context) throws IOException, JMSException {
    boolean usingDurableSubscription = context.getProperty(DURABLE_SUBSCRIPTION).asBoolean();
    final Properties persistedProps = getSubscriptionPropertiesFromFile();
    final Properties currentProps = getSubscriptionPropertiesFromContext(context);
    if (persistedProps == null) {
        if (usingDurableSubscription) {
            // properties have not yet been persisted.
            persistSubscriptionInfo(context);
        }
        return;
    }
    // decrypt the passwords so the persisted and current properties can be compared...
    // we can modify this properties instance since the unsubscribe method will reload
    // the properties from disk
    decryptPassword(persistedProps, context);
    decryptPassword(currentProps, context);
    // check if current values are the same as the persisted values.
    boolean same = true;
    for (final Map.Entry<Object, Object> entry : persistedProps.entrySet()) {
        final Object key = entry.getKey();
        final Object value = entry.getValue();
        final Object curVal = currentProps.get(key);
        if (value == null && curVal == null) {
            continue;
        }
        if (value == null || curVal == null) {
            same = false;
            break;
        }
        if (SUBSCRIPTION_NAME_PROPERTY.equals(key)) {
            // ignore the random UUID part of the subscription name
            if (!JmsFactory.clientIdPrefixEquals(value.toString(), curVal.toString())) {
                same = false;
                break;
            }
        } else if (!value.equals(curVal)) {
            same = false;
            break;
        }
    }
    if (same && usingDurableSubscription) {
        // properties are the same.
        return;
    }
    // unsubscribe from the old subscription.
    try {
        unsubscribe(context);
    } catch (final InvalidDestinationException e) {
        getLogger().warn("Failed to unsubscribe from subscription due to {}; subscription does not appear to be active, so ignoring it", new Object[] { e });
    }
    // we've now got a new subscription, so we must persist that new info before we create the subscription.
    if (usingDurableSubscription) {
        persistSubscriptionInfo(context);
    } else {
        // remove old subscription info if it was persisted
        try {
            Files.delete(getSubscriptionPath());
        } catch (Exception ignore) {
        }
    }
}
Also used : InvalidDestinationException(javax.jms.InvalidDestinationException) JmsProperties(org.apache.nifi.processors.standard.util.JmsProperties) Properties(java.util.Properties) Map(java.util.Map) ProcessException(org.apache.nifi.processor.exception.ProcessException) InvalidDestinationException(javax.jms.InvalidDestinationException) IOException(java.io.IOException) JMSException(javax.jms.JMSException) OnScheduled(org.apache.nifi.annotation.lifecycle.OnScheduled)

Example 65 with JMSException

use of javax.jms.JMSException 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)

Aggregations

JMSException (javax.jms.JMSException)1094 Message (javax.jms.Message)355 Test (org.junit.Test)335 Session (javax.jms.Session)309 TextMessage (javax.jms.TextMessage)302 Connection (javax.jms.Connection)271 MessageProducer (javax.jms.MessageProducer)169 MessageConsumer (javax.jms.MessageConsumer)156 Destination (javax.jms.Destination)105 ObjectMessage (javax.jms.ObjectMessage)100 Queue (javax.jms.Queue)100 MapMessage (javax.jms.MapMessage)70 ConnectionFactory (javax.jms.ConnectionFactory)68 CountDownLatch (java.util.concurrent.CountDownLatch)64 IOException (java.io.IOException)62 BytesMessage (javax.jms.BytesMessage)59 ActiveMQConnectionFactory (org.apache.activemq.ActiveMQConnectionFactory)54 MessageListener (javax.jms.MessageListener)49 NamingException (javax.naming.NamingException)44 MessageFormatException (javax.jms.MessageFormatException)43