Example usage for javax.jms Session createQueue

List of usage examples for javax.jms Session createQueue

Introduction

In this page you can find the example usage for javax.jms Session createQueue.

Prototype

Queue createQueue(String queueName) throws JMSException;

Source Link

Document

Creates a Queue object which encapsulates a specified provider-specific queue name.

Usage

From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java

public void testCommonsEmailOneWaySeparateSessions() {

    Queue emailQueue = null;//from   w  ww.j a v  a  2 s.c o m
    MessageConsumer consumer = null;
    MessageProducer producer = null;
    Session clientSession = null;
    Session listenerSession = null;
    // it is not necessary to use the Email interface here
    // Email is used here just to allow for multiple types of emails to
    // occupy
    // the same varaible. SimpleEmail etc can each be used directly.
    List<Email> emails = new ArrayList<Email>();
    EmailMessagingService messagingService = new EmailMessagingService(vmURL, emailQueueName, emailType, null,
            null, null, null);
    emails.add(new SimpleEmail(messagingService));
    emails.add(new MultiPartEmail(messagingService));
    emails.add(new HtmlEmail(messagingService));
    try {

        listenerSession = listenerConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = listenerSession.createQueue(emailQueueName);

        consumer = listenerSession.createConsumer(emailQueue);

        consumer.setMessageListener(new EmailListener());

        listenerConn.start();

        listenerSession.run();

    } catch (JMSException e2) {
        e2.printStackTrace();
        Assert.assertTrue(false);
    }

    Wiser smtpServer = new Wiser();
    smtpServer.setPort(smtpTestPort);
    smtpServer.start();

    try {
        clientSession = clientConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = clientSession.createQueue(emailQueueName);
        producer = clientSession.createProducer(emailQueue);

        clientConn.start();
        clientSession.run();

    } catch (JMSException e) {
        e.printStackTrace();
        Assert.assertTrue(false);
    }

    for (Email em : emails) {

        try {
            em.addTo(TEST_EMAIL_TO);
            em.setFrom(TEST_EMAIL_FROM_ADDRESS, TEST_EMAIL_FROM_LABEL);
            // host and port will be ignored since the email session is
            // established
            // by
            // the listener
            em.setHostName("localhost");
            em.setSmtpPort(smtpTestPort);
            em.setSubject(TEST_EMAIL_SUBJECT);
            if (em instanceof HtmlEmail) {
                em.setMsg(TEST_EMAIL_BODY_HTMLEMAIL);
            } else if (em instanceof MultiPartEmail) {
                em.setMsg(TEST_EMAIL_BODY_MULTIPARTEMAIL);
            } else if (em instanceof SimpleEmail) {
                em.setMsg(TEST_EMAIL_BODY_SIMPLEEMAIL);
            }

        } catch (EmailException e1) {
            Assert.assertTrue(false);
            e1.printStackTrace();
        }

        try {
            em.buildMimeMessage();
        } catch (EmailException e1) {
            e1.printStackTrace();
            Assert.assertTrue(false);
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {

            em.getMimeMessage().writeTo(os);
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        } catch (IOException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

        String content = os.toString();

        ObjectMessage om;
        try {
            om = clientSession.createObjectMessage(content);

            om.setJMSType(emailType);

            LOG.info("Client: Sending test message....");
            producer.send(om);
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

    }

    long start = System.currentTimeMillis();
    while (listenerMessagesProcessed < 3 && System.currentTimeMillis() - start < 10000L) {
        // wait for transport
    }
    Assert.assertTrue(listenerMessagesProcessed == 3);

    List<WiserMessage> messages = smtpServer.getMessages();
    Assert.assertTrue(messages.size() + " != expected value of 3", messages.size() == 3);

    for (WiserMessage wisermsg : messages) {
        String body = null;
        String subject = null;
        MimeMessage testmail = null;

        try {
            testmail = wisermsg.getMimeMessage();
        } catch (MessagingException e) {
            Assert.assertTrue(false);
            e.printStackTrace();
        }

        if (testmail != null) {
            LOG.info("SMTP server: test email received: ");
            try {
                LOG.info("To: " + testmail.getHeader("To", ","));

                LOG.info("Subject: " + testmail.getHeader("Subject", ","));
                body = getBodyAsString(testmail.getContent());
                subject = testmail.getHeader("Subject", ",");
            } catch (MessagingException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            } catch (IOException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            }
            LOG.info("Body: " + body);
            Assert.assertTrue(subject.contains(TEST_EMAIL_SUBJECT));
            Assert.assertTrue(body.contains("This is a Commons"));
        } else {
            Assert.assertTrue(false);
        }
    }

    if (clientSession != null) {
        try {
            clientSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        clientSession = null;
    }

    if (listenerSession != null) {
        try {
            listenerSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        listenerSession = null;
    }

    smtpServer.stop();

}

From source file:org.sakaiproject.nakamura.email.outgoing.LiteOutgoingEmailMessageListener.java

@Activate
@Modified//from ww  w .  j av a 2 s  .c o  m
protected void activate(ComponentContext ctx) {
    @SuppressWarnings("rawtypes")
    Dictionary props = ctx.getProperties();

    Integer _maxRetries = PropertiesUtil.toInteger(props.get(MAX_RETRIES), -1);
    if (_maxRetries > -1) {
        if (diff(maxRetries, _maxRetries)) {
            maxRetries = _maxRetries;
        }
    } else {
        LOGGER.error("Maximum times to retry messages not set.");
    }

    Integer _retryInterval = PropertiesUtil.toInteger(props.get(RETRY_INTERVAL), -1);
    if (_retryInterval > -1) {
        if (diff(_retryInterval, retryInterval)) {
            retryInterval = _retryInterval;
        }
    } else {
        LOGGER.error("SMTP retry interval not set.");
    }

    if (maxRetries * retryInterval < 4320 /* minutes in 3 days */) {
        LOGGER.warn("SMTP retry window is very short.");
    }

    Integer _smtpPort = PropertiesUtil.toInteger(props.get(SMTP_PORT), -1);
    boolean validPort = _smtpPort != null && _smtpPort >= 0 && _smtpPort <= 65535;
    if (validPort) {
        if (diff(smtpPort, _smtpPort)) {
            smtpPort = _smtpPort;
        }
    } else {
        LOGGER.error("Invalid port set for SMTP");
    }

    String _smtpServer = PropertiesUtil.toString(props.get(SMTP_SERVER), "");
    if (!StringUtils.isBlank(_smtpServer)) {
        if (diff(smtpServer, _smtpServer)) {
            smtpServer = _smtpServer;
        }
    } else {
        LOGGER.error("No SMTP server set");
    }

    String _replyAsAddress = PropertiesUtil.toString(props.get(REPLY_AS_ADDRESS), "");
    if (!StringUtils.isBlank(_replyAsAddress)) {
        if (diff(replyAsAddress, _replyAsAddress)) {
            replyAsAddress = _replyAsAddress;
        }
    } else {
        LOGGER.error("No reply-as email address set");
    }

    String _replyAsName = PropertiesUtil.toString(props.get(REPLY_AS_NAME), "");
    if (!StringUtils.isBlank(_replyAsName)) {
        if (diff(replyAsName, _replyAsName)) {
            replyAsName = _replyAsName;
        }
    } else {
        LOGGER.error("No reply-as email name set");
    }

    useTls = PropertiesUtil.toBoolean(props.get(SMTP_USE_TLS), false);
    useSsl = PropertiesUtil.toBoolean(props.get(SMTP_USE_SSL), false);
    authUser = PropertiesUtil.toString(props.get(SMTP_AUTH_USER), "");
    authPass = PropertiesUtil.toString(props.get(SMTP_AUTH_PASS), "");

    try {
        connection = connFactoryService.getDefaultConnectionFactory().createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue dest = session.createQueue(QUEUE_NAME);
        MessageConsumer consumer = session.createConsumer(dest);
        consumer.setMessageListener(this);
        connection.start();
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e1) {
            }
        }
    }
}

From source file:org.sakaiproject.nakamura.email.outgoing.OutgoingEmailMessageListener.java

protected void activate(ComponentContext ctx) {
    @SuppressWarnings("rawtypes")
    Dictionary props = ctx.getProperties();

    Integer _maxRetries = (Integer) props.get(MAX_RETRIES);
    if (_maxRetries != null) {
        if (diff(maxRetries, _maxRetries)) {
            maxRetries = _maxRetries;/* w ww  .  j a  va 2 s.co  m*/
        }
    } else {
        LOGGER.error("Maximum times to retry messages not set.");
    }

    Integer _retryInterval = (Integer) props.get(RETRY_INTERVAL);
    if (_retryInterval != null) {
        if (diff(_retryInterval, retryInterval)) {
            retryInterval = _retryInterval;
        }
    } else {
        LOGGER.error("SMTP retry interval not set.");
    }

    if (maxRetries * retryInterval < 4320 /* minutes in 3 days */) {
        LOGGER.warn("SMTP retry window is very short.");
    }

    Integer _smtpPort = (Integer) props.get(SMTP_PORT);
    boolean validPort = _smtpPort != null && _smtpPort >= 0 && _smtpPort <= 65535;
    if (validPort) {
        if (diff(smtpPort, _smtpPort)) {
            smtpPort = _smtpPort;
        }
    } else {
        LOGGER.error("Invalid port set for SMTP");
    }

    String _smtpServer = (String) props.get(SMTP_SERVER);
    boolean smtpServerEmpty = _smtpServer == null || _smtpServer.trim().length() == 0;
    if (!smtpServerEmpty) {
        if (diff(smtpServer, _smtpServer)) {
            smtpServer = _smtpServer;
        }
    } else {
        LOGGER.error("No SMTP server set");
    }

    try {
        connection = connFactoryService.getDefaultConnectionFactory().createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue dest = session.createQueue(QUEUE_NAME);
        MessageConsumer consumer = session.createConsumer(dest);
        consumer.setMessageListener(this);
        connection.start();
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e1) {
            }
        }
    }
}

From source file:org.seedstack.jms.internal.JmsPlugin.java

private void configureMessageListeners(Collection<Class<?>> listenerCandidates) {
    for (Class<?> candidate : listenerCandidates) {
        if (MessageListener.class.isAssignableFrom(candidate)) {
            //noinspection unchecked
            Class<? extends MessageListener> messageListenerClass = (Class<? extends MessageListener>) candidate;
            String messageListenerName = messageListenerClass.getCanonicalName();
            JmsMessageListener annotation = messageListenerClass.getAnnotation(JmsMessageListener.class);

            boolean isTransactional;
            try {
                isTransactional = transactionPlugin
                        .isTransactional(messageListenerClass.getMethod("onMessage", Message.class));
            } catch (NoSuchMethodException e) {
                throw SeedException.wrap(e, JmsErrorCodes.UNEXPECTED_EXCEPTION);
            }/*from  w  w  w . j  a  v  a 2s  .  co m*/

            Connection listenerConnection = connections.get(annotation.connection());

            if (listenerConnection == null) {
                throw SeedException.createNew(JmsErrorCodes.MISSING_CONNECTION_FACTORY)
                        .put(ERROR_CONNECTION_NAME, annotation.connection())
                        .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
            }

            Session session;
            try {
                session = listenerConnection.createSession(isTransactional, Session.AUTO_ACKNOWLEDGE);
            } catch (JMSException e) {
                throw SeedException.wrap(e, JmsErrorCodes.UNABLE_TO_CREATE_SESSION)
                        .put(ERROR_CONNECTION_NAME, annotation.connection())
                        .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
            }

            Destination destination;
            DestinationType destinationType;

            if (!annotation.destinationTypeStr().isEmpty()) {
                try {
                    destinationType = DestinationType
                            .valueOf(application.substituteWithConfiguration(annotation.destinationTypeStr()));
                } catch (IllegalArgumentException e) {
                    throw SeedException.wrap(e, JmsErrorCodes.UNKNOWN_DESTINATION_TYPE)
                            .put(ERROR_DESTINATION_TYPE, annotation.destinationTypeStr())
                            .put(ERROR_CONNECTION_NAME, annotation.connection())
                            .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
                }
            } else {
                destinationType = annotation.destinationType();
            }
            try {
                switch (destinationType) {
                case QUEUE:
                    destination = session
                            .createQueue(application.substituteWithConfiguration(annotation.destinationName()));
                    break;
                case TOPIC:
                    destination = session
                            .createTopic(application.substituteWithConfiguration(annotation.destinationName()));
                    break;
                default:
                    throw SeedException.createNew(JmsErrorCodes.UNKNOWN_DESTINATION_TYPE)
                            .put(ERROR_CONNECTION_NAME, annotation.connection())
                            .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
                }
            } catch (JMSException e) {
                throw SeedException.wrap(e, JmsErrorCodes.UNABLE_TO_CREATE_DESTINATION)
                        .put(ERROR_DESTINATION_TYPE, destinationType.name())
                        .put(ERROR_CONNECTION_NAME, annotation.connection())
                        .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
            }

            Class<? extends MessagePoller> messagePollerClass = null;
            if (annotation.poller().length > 0) {
                messagePollerClass = annotation.poller()[0];
            }

            registerMessageListener(new MessageListenerDefinition(messageListenerName,
                    application.substituteWithConfiguration(annotation.connection()), session, destination,
                    application.substituteWithConfiguration(annotation.selector()), messageListenerClass,
                    messagePollerClass));
        }
    }
}

From source file:org.seedstack.seed.jms.internal.JmsPlugin.java

@SuppressWarnings("unchecked")
private void configureMessageListeners(Collection<Class<?>> listenerCandidates) {
    for (Class<?> candidate : listenerCandidates) {
        if (MessageListener.class.isAssignableFrom(candidate)) {
            Class<? extends MessageListener> messageListenerClass = (Class<? extends MessageListener>) candidate;
            String messageListenerName = messageListenerClass.getCanonicalName();
            JmsMessageListener annotation = messageListenerClass.getAnnotation(JmsMessageListener.class);

            boolean isTransactional;
            try {
                isTransactional = transactionPlugin
                        .isTransactional(messageListenerClass.getMethod("onMessage", Message.class));
            } catch (NoSuchMethodException e) {
                throw SeedException.wrap(e, JmsErrorCodes.UNEXPECTED_EXCEPTION);
            }/*from  w w  w.j av a2s .c om*/

            Connection listenerConnection = connections.get(annotation.connection());

            if (listenerConnection == null) {
                throw SeedException.createNew(JmsErrorCodes.MISSING_CONNECTION_FACTORY)
                        .put(ERROR_CONNECTION_NAME, annotation.connection())
                        .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
            }

            Session session;
            try {
                session = listenerConnection.createSession(isTransactional, Session.AUTO_ACKNOWLEDGE);
            } catch (JMSException e) {
                throw SeedException.wrap(e, JmsErrorCodes.UNABLE_TO_CREATE_SESSION)
                        .put(ERROR_CONNECTION_NAME, annotation.connection())
                        .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
            }

            Destination destination;
            try {
                switch (annotation.destinationType()) {
                case QUEUE:
                    destination = session.createQueue(annotation.destinationName());
                    break;
                case TOPIC:
                    destination = session.createTopic(annotation.destinationName());
                    break;
                default:
                    throw SeedException.createNew(JmsErrorCodes.UNKNOWN_DESTINATION_TYPE)
                            .put(ERROR_CONNECTION_NAME, annotation.connection())
                            .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
                }
            } catch (JMSException e) {
                throw SeedException.wrap(e, JmsErrorCodes.UNABLE_TO_CREATE_DESTINATION)
                        .put(ERROR_CONNECTION_NAME, annotation.connection())
                        .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
            }

            Class<? extends MessagePoller> messagePollerClass = null;
            if (annotation.poller().length > 0) {
                messagePollerClass = annotation.poller()[0];
            }

            registerMessageListener(new MessageListenerDefinition(messageListenerName, annotation.connection(),
                    session, destination, annotation.selector(), messageListenerClass, messagePollerClass));
        }
    }
}

From source file:org.seedstack.seed.ws.internal.jms.SoapJmsUri.java

static Destination getDestination(SoapJmsUri soapJmsUri, Session session) throws NamingException, JMSException {
    Destination destination;/*from   www.j a  v a 2  s. co  m*/

    String lookupVariant = soapJmsUri.getLookupVariant();
    if (SoapJmsUri.JNDI_LOOKUP_VARIANT.equals(lookupVariant)) {
        destination = (Destination) getContext(soapJmsUri).lookup(soapJmsUri.getDestinationName());
    } else if (SoapJmsUri.SEED_QUEUE_LOOKUP_VARIANT.equals(lookupVariant)) {
        destination = session.createQueue(soapJmsUri.getDestinationName());
    } else if (SoapJmsUri.SEED_TOPIC_LOOKUP_VARIANT.equals(lookupVariant)) {
        destination = session.createTopic(soapJmsUri.getDestinationName());
    } else {
        throw new IllegalArgumentException(
                "Unsupported lookup variant " + lookupVariant + " for JMS URI " + soapJmsUri.toString());
    }

    return destination;
}

From source file:org.seedstack.seed.ws.internal.jms.SoapJmsUri.java

static Destination getReplyToDestination(SoapJmsUri soapJmsUri, Session session)
        throws NamingException, JMSException {
    Destination destination = null;

    String lookupVariant = soapJmsUri.getLookupVariant();
    if (SoapJmsUri.JNDI_LOOKUP_VARIANT.equals(lookupVariant)) {
        String destinationName = soapJmsUri.getParameter("replyToName");
        if (destinationName != null) {
            destination = (Destination) getContext(soapJmsUri).lookup(destinationName);
        }/* w  ww  . j  a v a2  s.co m*/
    } else if (SoapJmsUri.SEED_QUEUE_LOOKUP_VARIANT.equals(lookupVariant)
            || SoapJmsUri.SEED_TOPIC_LOOKUP_VARIANT.equals(lookupVariant)) {
        String queueName = soapJmsUri.getParameter("replyToName");
        String topicName = soapJmsUri.getParameter("topicReplyToName");

        if (queueName != null) {
            destination = session.createQueue(queueName);
        } else if (topicName != null) {
            destination = session.createTopic(topicName);
        }
    } else {
        throw new IllegalArgumentException(
                "Unsupported lookup variant " + lookupVariant + " for JMS URI " + soapJmsUri.toString());
    }

    return destination;
}

From source file:org.springframework.cloud.stream.binder.jms.solace.SolaceQueueProvisioner.java

@Override
public Destinations provisionTopicAndConsumerGroup(String name, String... groups) {
    Destinations.Factory destinationsFactory = new Destinations.Factory();

    try {/*from w  ww .  java  2s  .co  m*/
        Topic topic = JCSMPFactory.onlyInstance().createTopic(name);
        JCSMPSession session = sessionFactory.build();
        Connection connection = connectionFactory.createConnection();
        javax.jms.Session jmsSession = connection.createSession(false, 1);

        // Using Durable... because non-durable Solace TopicEndpoints don't have names
        TopicEndpoint topicEndpoint = new DurableTopicEndpointImpl(name);
        session.provision(topicEndpoint, null, JCSMPSession.FLAG_IGNORE_ALREADY_EXISTS);
        destinationsFactory.withTopic(jmsSession.createTopic(name));

        if (ArrayUtils.isEmpty(groups)) {
            return destinationsFactory.build();
        }

        for (String group : groups) {
            destinationsFactory.addGroup(jmsSession.createQueue(group));
            doProvision(session, topic, group);
        }

        JmsUtils.commitIfNecessary(jmsSession);
        JmsUtils.closeSession(jmsSession);
        JmsUtils.closeConnection(connection);
    } catch (JCSMPErrorResponseException e) {
        if (JCSMPErrorResponseSubcodeEx.SUBSCRIPTION_ALREADY_PRESENT != e.getSubcodeEx()) {
            throw new RuntimeException(e);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return destinationsFactory.build();
}

From source file:org.trellisldp.app.triplestore.TrellisApplicationTest.java

@BeforeEach
public void aquireConnection() throws Exception {
    final ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
    connection = connectionFactory.createConnection();
    connection.start();//  w  ww. j  a  va 2 s  .c o  m
    final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final Destination destination = session.createQueue("trellis");
    consumer = session.createConsumer(destination);
    consumer.setMessageListener(this);
}

From source file:org.wso2.carbon.apimgt.jms.listener.utils.JMSTaskManager.java

/**
 * Return the JMS Destination for the JNDI name of the Destination from the InitialContext
 *
 * @param session which is used to create the destinations if not present and if possible
 * @return the JMS Destination to which this STM listens for messages
 *///w ww.  j a  va  2 s  .c  om
private Destination getDestination(Session session) {
    if (destination == null) {
        try {
            context = getInitialContext();
            destination = JMSUtils.lookupDestination(context, getDestinationJNDIName(),
                    JMSUtils.getDestinationTypeAsString(destinationType));
            if (log.isDebugEnabled()) {
                log.debug("JMS Destination with JNDI name : " + getDestinationJNDIName() + " found "
                        + jmsConsumerName);
            }
        } catch (NamingException e) {
            try {
                switch (destinationType) {
                case JMSConstants.QUEUE: {
                    destination = session.createQueue(getDestinationJNDIName());
                    break;
                }
                case JMSConstants.TOPIC: {
                    destination = session.createTopic("BURL:" + getDestinationJNDIName());
                    break;
                }
                default: {
                    handleException("Error looking up JMS destination : " + getDestinationJNDIName()
                            + " using JNDI properties : " + jmsProperties, e);
                }
                }
            } catch (JMSException j) {
                handleException("Error looking up JMS destination and auto " + "creating JMS destination : "
                        + getDestinationJNDIName() + " using JNDI properties : " + jmsProperties, e);
            }
        }
    }
    return destination;
}