Example usage for javax.jms ConnectionFactory createConnection

List of usage examples for javax.jms ConnectionFactory createConnection

Introduction

In this page you can find the example usage for javax.jms ConnectionFactory createConnection.

Prototype


Connection createConnection() throws JMSException;

Source Link

Document

Creates a connection with the default user identity.

Usage

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public void createConnection(final CreateConnectionCommand command) {
    try {//from  w  w  w. j  a  va  2s.  co m
        final ConnectionFactory connectionFactory = (ConnectionFactory) _context
                .lookup(command.getConnectionFactoryName());
        final Connection newConnection = connectionFactory.createConnection();
        addConnection(command.getConnectionName(), newConnection);
    } catch (final NamingException ne) {
        throw new DistributedTestException(
                "Unable to lookup factoryName: " + command.getConnectionFactoryName(), ne);
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to create connection: " + command.getConnectionName()
                + " (using factory name: " + command.getConnectionFactoryName() + ")", jmse);
    }
}

From source file:org.gss_project.gss.server.ejb.AdminAPIBean.java

public void indexFile(Long fileId, boolean delete) {
    Connection qConn = null;//  w  w  w .j a va  2  s.co m
    Session session = null;
    MessageProducer sender = null;
    try {
        Context jndiCtx = new InitialContext();
        ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA");
        Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue");
        qConn = factory.createConnection();
        session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        sender = session.createProducer(queue);

        MapMessage map = session.createMapMessage();
        map.setObject("id", fileId);
        map.setBoolean("delete", delete);
        sender.send(map);
    } catch (NamingException e) {
        logger.error("Index was not updated: ", e);
    } catch (JMSException e) {
        logger.error("Index was not updated: ", e);
    } finally {
        try {
            if (sender != null)
                sender.close();
            if (session != null)
                session.close();
            if (qConn != null)
                qConn.close();
        } catch (JMSException e) {
            logger.warn(e);
        }
    }
}

From source file:nl.nn.adapterframework.jms.JmsMessagingSourceFactory.java

public String getConnectionFactoryInfo(ConnectionFactory connectionFactory) {
    if (IbisContext.getApplicationServerType().equals("TIBCOAMX")) {
        // Workaround to prevent the following exception:
        // [org.apache.geronimo.connector.outbound.MCFConnectionInterceptor] - Error occurred creating ManagedConnection for org.apache.geronimo.connector.outbound.ConnectionInfo@#######
        // javax.resource.ResourceException: JMSJCA-E084: Failed to create session: The JNDI name is null
        return null;
    }// w  ww . j a  v  a2s  . co m
    String info = null;
    Connection connection = null;
    try {
        connection = connectionFactory.createConnection();
        ConnectionMetaData metaData = connection.getMetaData();
        info = "jms provider name [" + metaData.getJMSProviderName() + "] jms provider version ["
                + metaData.getProviderVersion() + "] jms version [" + metaData.getJMSVersion() + "]";
    } catch (JMSException e) {
        log.warn("Exception determining connection factory info", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e1) {
                log.warn("Exception closing connection for metadata", e1);
            }
        }
    }
    return info;
}

From source file:org.dhatim.routing.jms.JMSRouter.java

protected MessageProducer createMessageProducer(final Destination destination, final Context context)
        throws JMSException {
    try {//from ww w. j  av  a 2s  . co  m
        final ConnectionFactory connFactory = (ConnectionFactory) context
                .lookup(jmsProperties.getConnectionFactoryName());

        connection = (jmsProperties.getSecurityPrincipal() == null
                && jmsProperties.getSecurityCredential() == null) ? connFactory.createConnection()
                        : connFactory.createConnection(jmsProperties.getSecurityPrincipal(),
                                jmsProperties.getSecurityCredential());

        session = connection.createSession(jmsProperties.isTransacted(), AcknowledgeModeEnum
                .getAckMode(jmsProperties.getAcknowledgeMode().toUpperCase()).getAcknowledgeModeInt());

        msgProducer = session.createProducer(destination);
        connection.start();
        logger.info("JMS Connection started");
    } catch (JMSException e) {
        final String errorMsg = "JMSException while trying to create MessageProducer for Queue ["
                + jmsProperties.getDestinationName() + "]";
        releaseJMSResources();
        throw new SmooksConfigurationException(errorMsg, e);
    } catch (NamingException e) {
        final String errorMsg = "NamingException while trying to lookup ConnectionFactory ["
                + jmsProperties.getConnectionFactoryName() + "]";
        releaseJMSResources();
        throw new SmooksConfigurationException(errorMsg, e);
    }

    return msgProducer;
}

From source file:org.apache.james.queue.jms.JMSMailQueue.java

public JMSMailQueue(ConnectionFactory connectionFactory,
        MailQueueItemDecoratorFactory mailQueueItemDecoratorFactory, String queueName,
        MetricFactory metricFactory, GaugeRegistry gaugeRegistry) {
    try {/*from  ww w. j av a2 s.  c o  m*/
        connection = connectionFactory.createConnection();
        connection.start();
    } catch (JMSException e) {
        throw new RuntimeException(e);
    }
    this.mailQueueItemDecoratorFactory = mailQueueItemDecoratorFactory;
    this.queueName = queueName;
    this.metricFactory = metricFactory;
    this.enqueuedMailsMetric = metricFactory.generate(ENQUEUED_METRIC_NAME_PREFIX + queueName);
    this.dequeuedMailsMetric = metricFactory.generate(DEQUEUED_METRIC_NAME_PREFIX + queueName);

    this.gaugeRegistry = gaugeRegistry;
    this.gaugeRegistry.register(QUEUE_SIZE_METRIC_NAME_PREFIX + queueName, queueSizeGauge());

    this.joiner = Joiner.on(JAMES_MAIL_SEPARATOR).skipNulls();
    this.splitter = Splitter.on(JAMES_MAIL_SEPARATOR).omitEmptyStrings() // ignore null values. See JAMES-1294
            .trimResults();
    try {
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        queue = session.createQueue(queueName);
        producer = session.createProducer(queue);
    } catch (JMSException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.dawnsci.commandserver.ui.view.StatusQueueView.java

/**
 * Listens to a topic//from   w w w.  ja v a2s. c  om
 */
private void createTopicListener(final URI uri) throws Exception {

    // Use job because connection might timeout.
    final Job topicJob = new Job("Create topic listener") {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {
                ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
                StatusQueueView.this.topicConnection = connectionFactory.createConnection();
                topicConnection.start();

                Session session = topicConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

                Topic topic = session.createTopic(getTopicName());
                MessageConsumer consumer = session.createConsumer(topic);

                final Class clazz = getBeanClass();
                final ObjectMapper mapper = new ObjectMapper();

                MessageListener listener = new MessageListener() {
                    public void onMessage(Message message) {
                        try {
                            if (message instanceof TextMessage) {
                                TextMessage t = (TextMessage) message;
                                final StatusBean bean = mapper.readValue(t.getText(), clazz);
                                mergeBean(bean);
                            }
                        } catch (Exception e) {
                            logger.error("Updating changed bean from topic", e);
                        }
                    }
                };
                consumer.setMessageListener(listener);

                // Create a listener for administrator broadcast messages.
                topic = session.createTopic(Constants.ADMIN_MESSAGE_TOPIC);
                consumer = session.createConsumer(topic);
                listener = new MessageListener() {
                    public void onMessage(Message message) {
                        try {
                            if (message instanceof TextMessage) {
                                // AdministratorMessage shows a message to the user.
                                final Class msgClass = AdministratorMessage.class;

                                TextMessage t = (TextMessage) message;
                                final AdministratorMessage bean = mapper.readValue(t.getText(), msgClass);

                                getSite().getShell().getDisplay().syncExec(new Runnable() {
                                    public void run() {
                                        MessageDialog.openError(getViewSite().getShell(), bean.getTitle(),
                                                bean.getMessage());

                                        viewer.refresh();
                                    }
                                });
                            }
                        } catch (Exception e) {
                            // Not a big deal if they do not get admin messages.
                        }
                    }
                };
                consumer.setMessageListener(listener);

                return Status.OK_STATUS;

            } catch (Exception ne) {
                logger.error("Cannot listen to topic changes because command server is not there", ne);
                return Status.CANCEL_STATUS;
            }
        }

    };

    topicJob.setPriority(Job.INTERACTIVE);
    topicJob.setSystem(true);
    topicJob.setUser(false);
    topicJob.schedule();
}

From source file:com.seajas.search.profiler.service.profiler.ProfilerService.java

/**
 * Default constructor./*  ww w  .  ja  va2s. co m*/
 * 
 * @param jobNames
 * @param jobDescriptions
 * @param availableApplicationLanguages
 * @param availableSearchLanguages
 * @param jmsRequestQueue
 * @param jmsConnectionFactory
 * @throws Exception
 */
@Autowired
public ProfilerService(@Value("${profiler.project.search.enricher.jobs}") final String jobNames,
        @Value("${profiler.project.search.enricher.jobs.descriptions}") final String jobDescriptions,
        @Value("${profiler.project.languages.available}") final String availableApplicationLanguages,
        @Value("${profiler.project.search.languages}") final String availableSearchLanguages,
        @Qualifier("jmsPrimaryRequestQueue") final ActiveMQQueue jmsRequestQueue,
        @Qualifier("connectionFactory") final ConnectionFactory jmsConnectionFactory) throws Exception {
    /* InputStream caCertificate = getClass().getClassLoader().getResourceAsStream("ca.crt"); LicenseValidator.validateLicenseFile(caCertificate, licenseFile);
     * 
     * try { caCertificate.close(); } catch (IOException e) { logger.error("Could not close the CA certificate stream."); } */

    String[] names = jobNames.split(",");
    String[] descriptions = jobDescriptions.split(",");

    this.jobNames = new LinkedHashMap<String, String>();

    for (int i = 0; i < names.length; i++)
        this.jobNames.put(names[i].trim(), descriptions[i].trim());

    this.availableApplicationLanguages = Arrays
            .asList(StringUtils.tokenizeToStringArray(availableApplicationLanguages, ",", true, true));
    this.availableSearchLanguages = Arrays
            .asList(StringUtils.tokenizeToStringArray(availableSearchLanguages, ",", true, true));

    // Keep track of the active consumers on the request channel

    Connection connection = jmsConnectionFactory.createConnection();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);

    connection.start();

    Destination destinationAdvisory = AdvisorySupport.getConsumerAdvisoryTopic(jmsRequestQueue);
    MessageConsumer consumerAdvisory = session.createConsumer(destinationAdvisory);

    consumerAdvisory.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(final Message message) {
            try {
                Object consumerCount = ((ActiveMQMessage) message).getProperty("consumerCount");

                if (consumerCount != null) {
                    String clientId = ((ActiveMQMessage) message).getConnection().getConnectionInfo()
                            .getClientId();

                    if (activeContenderClients.contains(clientId) && ((Integer) consumerCount == 0)) {
                        if (staticLogger.isInfoEnabled())
                            staticLogger.info("Client with ID " + clientId
                                    + " was dropped from the current consumer-clients");

                        activeContenderClients.remove(clientId);
                    } else if (!activeContenderClients.contains(clientId) && ((Integer) consumerCount > 0)) {
                        if (staticLogger.isInfoEnabled())
                            staticLogger.info("Client with ID " + clientId
                                    + " was added to the current consumer-clients");

                        activeContenderClients.add(clientId);
                    }
                }
            } catch (IOException e) {
                staticLogger.error("Could not retrieve consumer count from connection message", e);
            }
        }
    });
}

From source file:org.gss_project.gss.server.ejb.ExternalAPIBean.java

private void indexFile(Long fileId, boolean delete) {
     Connection qConn = null;// w ww  . jav a  2 s.  c o m
     Session session = null;
     MessageProducer sender = null;
     try {
         Context jndiCtx = new InitialContext();
         ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA");
         Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue");
         qConn = factory.createConnection();
         session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
         sender = session.createProducer(queue);

         MapMessage map = session.createMapMessage();
         map.setObject("id", fileId);
         map.setBoolean("delete", delete);
         sender.send(map);
     } catch (NamingException e) {
         logger.error("Index was not updated: ", e);
     } catch (JMSException e) {
         logger.error("Index was not updated: ", e);
     } finally {
         try {
             if (sender != null)
                 sender.close();
             if (session != null)
                 session.close();
             if (qConn != null)
                 qConn.close();
         } catch (JMSException e) {
             logger.warn(e);
         }
     }
 }