Example usage for javax.jms QueueConnection createQueueSession

List of usage examples for javax.jms QueueConnection createQueueSession

Introduction

In this page you can find the example usage for javax.jms QueueConnection createQueueSession.

Prototype

QueueSession createQueueSession(boolean transacted, int acknowledgeMode) throws JMSException;

Source Link

Document

Creates a QueueSession object, specifying transacted and acknowledgeMode .

Usage

From source file:com.zotoh.maedr.device.JmsIO.java

private void inizQueue(Context ctx, Object obj) throws Exception {

    QueueConnectionFactory f = (QueueConnectionFactory) obj;
    final JmsIO me = this;
    QueueConnection conn;
    Queue q = (Queue) ctx.lookup(_dest);

    if (!isEmpty(_jmsUser)) {
        conn = f.createQueueConnection(_jmsUser, _jmsPwd);
    } else {//ww  w.  j  a  va  2 s  .c o  m
        conn = f.createQueueConnection();
    }

    _conn = conn;

    QueueSession s = conn.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
    QueueReceiver r;

    r = s.createReceiver(q);
    r.setMessageListener(new MessageListener() {
        public void onMessage(Message msg) {
            me.onMessage(msg);
        }
    });
}

From source file:org.dawnsci.commandserver.core.producer.ProcessConsumer.java

/**
 * Parse the queue for stale jobs and things that should be rerun.
 * @param bean// w w  w .  j  a  v a2 s  . co  m
 * @throws Exception 
 */
private void processStatusQueue(URI uri, String statusQName) throws Exception {

    QueueConnection qCon = null;

    try {
        QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
        qCon = connectionFactory.createQueueConnection();
        QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = qSes.createQueue(statusQName);
        qCon.start();

        QueueBrowser qb = qSes.createBrowser(queue);

        @SuppressWarnings("rawtypes")
        Enumeration e = qb.getEnumeration();

        ObjectMapper mapper = new ObjectMapper();

        Map<String, StatusBean> failIds = new LinkedHashMap<String, StatusBean>(7);
        List<String> removeIds = new ArrayList<String>(7);
        while (e.hasMoreElements()) {
            Message m = (Message) e.nextElement();
            if (m == null)
                continue;
            if (m instanceof TextMessage) {
                TextMessage t = (TextMessage) m;

                try {
                    @SuppressWarnings("unchecked")
                    final StatusBean qbean = mapper.readValue(t.getText(), getBeanClass());
                    if (qbean == null)
                        continue;
                    if (qbean.getStatus() == null)
                        continue;
                    if (!qbean.getStatus().isStarted()) {
                        failIds.put(t.getJMSMessageID(), qbean);
                        continue;
                    }

                    // If it has failed, we clear it up
                    if (qbean.getStatus() == Status.FAILED) {
                        removeIds.add(t.getJMSMessageID());
                        continue;
                    }
                    if (qbean.getStatus() == Status.NONE) {
                        removeIds.add(t.getJMSMessageID());
                        continue;
                    }

                    // If it is running and older than a certain time, we clear it up
                    if (qbean.getStatus() == Status.RUNNING) {
                        final long submitted = qbean.getSubmissionTime();
                        final long current = System.currentTimeMillis();
                        if (current - submitted > getMaximumRunningAge()) {
                            removeIds.add(t.getJMSMessageID());
                            continue;
                        }
                    }

                    if (qbean.getStatus().isFinal()) {
                        final long submitted = qbean.getSubmissionTime();
                        final long current = System.currentTimeMillis();
                        if (current - submitted > getMaximumCompleteAge()) {
                            removeIds.add(t.getJMSMessageID());
                        }
                    }

                } catch (Exception ne) {
                    System.out.println("Message " + t.getText() + " is not legal and will be removed.");
                    removeIds.add(t.getJMSMessageID());
                }
            }
        }

        // We fail the non-started jobs now - otherwise we could
        // actually start them late. TODO check this
        final List<String> ids = new ArrayList<String>();
        ids.addAll(failIds.keySet());
        ids.addAll(removeIds);

        if (ids.size() > 0) {

            for (String jMSMessageID : ids) {
                MessageConsumer consumer = qSes.createConsumer(queue, "JMSMessageID = '" + jMSMessageID + "'");
                Message m = consumer.receive(1000);
                if (removeIds.contains(jMSMessageID))
                    continue; // We are done

                if (m != null && m instanceof TextMessage) {
                    MessageProducer producer = qSes.createProducer(queue);
                    final StatusBean bean = failIds.get(jMSMessageID);
                    bean.setStatus(Status.FAILED);
                    producer.send(qSes.createTextMessage(mapper.writeValueAsString(bean)));

                    System.out.println("Failed job " + bean.getName() + " messageid(" + jMSMessageID + ")");

                }
            }
        }
    } finally {
        if (qCon != null)
            qCon.close();
    }

}

From source file:eu.planets_project.tb.impl.system.batch.backends.ifwee.TestbedWEEBatchProcessor.java

public void submitTicketForPollingToQueue(String ticket, String queueName, String batchProcessorSystemID)
        throws Exception {
    Context ctx = null;/*from w  ww. j a  va 2 s. co m*/
    QueueConnection cnn = null;
    QueueSession sess = null;
    Queue queue = null;
    QueueSender sender = null;
    try {
        ctx = new InitialContext();
        QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup(QueueConnectionFactoryName);
        queue = (Queue) ctx.lookup(queueName);
        cnn = factory.createQueueConnection();
        sess = cnn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

        //create the message to send to the MDB e.g. a TextMessage
        TextMessage message = sess.createTextMessage(ticket);
        message.setStringProperty(BatchProcessor.QUEUE_PROPERTY_NAME_FOR_SENDING, batchProcessorSystemID);

        //and finally send the message to the queue.
        sender = sess.createSender(queue);
        sender.send(message);
        log.debug("TestbedWEEBatchProcessor: sent message to queue, ID:" + message.getJMSMessageID());
    } finally {
        try {
            if (null != sender)
                sender.close();
        } catch (Exception ex) {
        }
        try {
            if (null != sess)
                sess.close();
        } catch (Exception ex) {
        }
        try {
            if (null != cnn)
                cnn.close();
        } catch (Exception ex) {
        }
        try {
            if (null != ctx)
                ctx.close();
        } catch (Exception ex) {
        }
    }
}

From source file:edu.harvard.iq.dvn.core.study.StudyFileServiceBean.java

private void addFiles(StudyVersion studyVersion, List<StudyFileEditBean> newFiles, VDCUser user,
        String ingestEmail, int messageLevel) {

    Study study = studyVersion.getStudy();
    MD5Checksum md5Checksum = new MD5Checksum();

    // step 1: divide the files, based on subsettable or not
    List subsettableFiles = new ArrayList();
    List otherFiles = new ArrayList();

    Iterator iter = newFiles.iterator();
    while (iter.hasNext()) {
        StudyFileEditBean fileBean = (StudyFileEditBean) iter.next();
        // Note that for the "special" OtherFiles we want to utilize the 
        // same ingest scheme as for subsettables: they will be queued and 
        // processed asynchronously, and the user will be notified by email.
        // - L.A.
        if (fileBean.getStudyFile().isSubsettable() || fileBean.getStudyFile() instanceof SpecialOtherFile) {
            subsettableFiles.add(fileBean);
        } else {// ww w  .j a va  2 s.co  m
            otherFiles.add(fileBean);
            // also add to study, so that it will be flushed for the ids
            fileBean.getStudyFile().setStudy(study);
            study.getStudyFiles().add(fileBean.getStudyFile());

        }
    }

    if (otherFiles.size() > 0) {
        // Only persist the studyVersion we are adding a file that doesn't need to be ingested (non-subsettable)
        if (studyVersion.getId() == null) {
            em.persist(studyVersion);
            em.flush(); // populates studyVersion_id
        } else {
            // There is a problem merging the existing studyVersion,
            // so since all we need from the exisiting version is the versionNote,
            // we get a fresh copy of the object from the database, and update it with the versionNote.
            String versionNote = studyVersion.getVersionNote();
            studyVersion = em.find(StudyVersion.class, studyVersion.getId());
            studyVersion.setVersionNote(versionNote);
        }

    }

    // step 2: iterate through nonsubsettable files, moving from temp to new location
    File newDir = FileUtil.getStudyFileDir(study);
    iter = otherFiles.iterator();
    while (iter.hasNext()) {
        StudyFileEditBean fileBean = (StudyFileEditBean) iter.next();
        StudyFile f = fileBean.getStudyFile();
        File tempFile = new File(fileBean.getTempSystemFileLocation());
        File newLocationFile = new File(newDir, f.getFileSystemName());
        try {
            FileUtil.copyFile(tempFile, newLocationFile);
            tempFile.delete();
            f.setFileSystemLocation(newLocationFile.getAbsolutePath());

            fileBean.getFileMetadata().setStudyVersion(studyVersion);

            em.persist(fileBean.getStudyFile());
            em.persist(fileBean.getFileMetadata());

        } catch (IOException ex) {
            throw new EJBException(ex);
        }
        f.setMd5(md5Checksum.CalculateMD5(f.getFileSystemLocation()));
    }

    // step 3: iterate through subsettable files, sending a message via JMS
    if (subsettableFiles.size() > 0) {
        QueueConnection conn = null;
        QueueSession session = null;
        QueueSender sender = null;
        try {
            conn = factory.createQueueConnection();
            session = conn.createQueueSession(false, 0);
            sender = session.createSender(queue);

            DSBIngestMessage ingestMessage = new DSBIngestMessage(messageLevel);
            ingestMessage.setFileBeans(subsettableFiles);
            ingestMessage.setIngestEmail(ingestEmail);
            ingestMessage.setIngestUserId(user.getId());
            ingestMessage.setStudyId(study.getId());
            ingestMessage.setStudyVersionId(studyVersion.getId());
            ingestMessage.setVersionNote(studyVersion.getVersionNote());

            ingestMessage.setStudyTitle(studyVersion.getMetadata().getTitle());
            ingestMessage.setStudyGlobalId(studyVersion.getStudy().getGlobalId());
            ingestMessage.setStudyVersionNumber(studyVersion.getVersionNumber().toString());
            ingestMessage.setDataverseName(studyVersion.getStudy().getOwner().getName());

            Message message = session.createObjectMessage(ingestMessage);

            String detail = "Ingest processing for " + subsettableFiles.size() + " file(s).";
            studyService.addStudyLock(study.getId(), user.getId(), detail);
            try {
                sender.send(message);
            } catch (Exception ex) {
                // If anything goes wrong, remove the study lock.
                studyService.removeStudyLock(study.getId());
                ex.printStackTrace();
            }

            // send an e-mail
            if (ingestMessage.sendInfoMessage()) {
                mailService.sendIngestRequestedNotification(ingestMessage, subsettableFiles);
            }

        } catch (JMSException ex) {
            ex.printStackTrace();
        } finally {
            try {

                if (sender != null) {
                    sender.close();
                }
                if (session != null) {
                    session.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (JMSException ex) {
                ex.printStackTrace();
            }
        }
    }

    if (!otherFiles.isEmpty()) {
        studyService.saveStudyVersion(studyVersion, user.getId());

    }

}

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

protected Collection<StatusBean> getStatusBeans(final URI uri, final String queueName,
        final IProgressMonitor monitor) throws Exception {

    QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    monitor.worked(1);// www.  ja  va  2 s .  com
    QueueConnection qCon = connectionFactory.createQueueConnection(); // This times out when the server is not there.
    QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = qSes.createQueue(queueName);
    qCon.start();

    QueueBrowser qb = qSes.createBrowser(queue);
    monitor.worked(1);

    @SuppressWarnings("rawtypes")
    Enumeration e = qb.getEnumeration();

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

    final Collection<StatusBean> list = new TreeSet<StatusBean>(new Comparator<StatusBean>() {
        @Override
        public int compare(StatusBean o1, StatusBean o2) {
            // Newest first!
            long t1 = o2.getSubmissionTime();
            long t2 = o1.getSubmissionTime();
            return (t1 < t2 ? -1 : (t1 == t2 ? 0 : 1));
        }
    });

    while (e.hasMoreElements()) {
        Message m = (Message) e.nextElement();
        if (m == null)
            continue;
        if (m instanceof TextMessage) {
            TextMessage t = (TextMessage) m;
            final StatusBean bean = mapper.readValue(t.getText(), clazz);
            list.add(bean);
        }
    }
    return list;
}

From source file:org.socraticgrid.taskmanager.TaskManagerImpl.java

/**
 * Queue the message to the task handler.
 *
 * @param msgObject//from  w w  w .j  a va 2s.c  o  m
 * @return
 */
private QueueResponse queueMessage(java.io.Serializable msgObject) {
    QueueResponse response = new QueueResponse();
    String taskQ = null;
    QueueConnection queueConnection = null;

    try {
        //Get task queue name & queue factory
        taskQ = PropertyAccessor.getProperty(TASKMANAGER_PROPERTY_FILE, PROPERTY_TASK_QUEUE);
        String taskQFactory = PropertyAccessor.getProperty(TASKMANAGER_PROPERTY_FILE,
                PROPERTY_TASK_QUEUE_FACTORY);

        //Get queue connection
        Context jndiContext = new InitialContext();
        QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext
                .lookup(taskQFactory);
        Queue queue = (Queue) jndiContext.lookup(taskQ);

        //Create connection session
        queueConnection = queueConnectionFactory.createQueueConnection();
        QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        QueueSender queueSender = queueSession.createSender(queue);

        //Create message
        ObjectMessage message = queueSession.createObjectMessage(msgObject);

        //Send message
        queueSender.send(message);

        //Set response info
        response.ticket = message.getJMSMessageID();
        response.detail = TASK_MESSAGE_SUCCESS;
    } catch (PropertyAccessException pae) {
        String msg = TASK_MESSAGE_FAILURE + ": error accessing task properties in file:"
                + TASKMANAGER_PROPERTY_FILE + ".";
        log.error(msg, pae);
        response.ticket = TASK_MESSAGE_FAILURE_ID;
        response.detail = msg;
    } catch (NamingException ne) {
        String msg = TASK_MESSAGE_FAILURE + ": error creating connection to queue: " + taskQ + ".";
        log.error(msg, ne);
        response.ticket = TASK_MESSAGE_FAILURE_ID;
        response.detail = msg;
    } catch (JMSException jmse) {
        String msg = TASK_MESSAGE_FAILURE + ": error occurred trying to send notificaiton to task queue: "
                + taskQ + ".";
        log.error(msg, jmse);
        response.ticket = TASK_MESSAGE_FAILURE_ID;
        response.detail = msg;
    } finally {
        //Close queue
        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
            }
        }
    }

    return response;
}

From source file:edu.harvard.iq.dvn.core.index.IndexServiceBean.java

private void sendMessage(final IndexEdit op) {
    QueueConnection conn = null;
    QueueSession session = null;/*w  w  w.  j a  va 2 s. c o m*/
    QueueSender sender = null;
    try {
        conn = factory.createQueueConnection();
        session = conn.createQueueSession(false, 0);
        sender = session.createSender(queue);

        Message message = session.createObjectMessage(op);
        sender.send(message);

    } catch (JMSException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (sender != null) {
                sender.close();
            }
            if (session != null) {
                session.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (JMSException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.wso2.carbon.andes.core.QueueManagerServiceImpl.java

/**
 * Publish message to given JMS queue//from  ww  w . j  av a 2  s.  c  o m
 *
 * @param nameOfQueue queue name
 * @param userName username
 * @param accessKey access key
 * @param jmsType jms type
 * @param jmsCorrelationID message correlation id
 * @param numberOfMessages number of messages to publish
 * @param message message body
 * @param deliveryMode delivery mode
 * @param priority message priority
 * @param expireTime message expire time
 * @throws QueueManagerException
 */
private void send(String nameOfQueue, String userName, String accessKey, String jmsType,
        String jmsCorrelationID, int numberOfMessages, String message, int deliveryMode, int priority,
        long expireTime) throws QueueManagerException {
    QueueConnectionFactory connFactory;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    QueueSender queueSender = null;
    try {
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, ANDES_ICF);
        properties.put(CF_NAME_PREFIX + CF_NAME, Utils.getTCPConnectionURL(userName, accessKey));
        properties.put(QUEUE_NAME_PREFIX + nameOfQueue, nameOfQueue);
        properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");
        InitialContext ctx = new InitialContext(properties);
        connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        queueConnection = connFactory.createQueueConnection();
        Queue queue = (Queue) ctx.lookup(nameOfQueue);
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        queueConnection.start();
        TextMessage textMessage = queueSession.createTextMessage();
        if (queueSender != null && textMessage != null) {
            if (jmsType != null) {
                textMessage.setJMSType(jmsType);
            }
            if (jmsCorrelationID != null) {
                textMessage.setJMSCorrelationID(jmsCorrelationID);
            }

            if (message != null) {
                textMessage.setText(message);
            } else {
                textMessage.setText("Type message here..");
            }

            for (int i = 0; i < numberOfMessages; i++) {
                queueSender.send(textMessage, deliveryMode, priority, expireTime);
            }
        }
    } catch (FileNotFoundException | NamingException | UnknownHostException | XMLStreamException
            | JMSException e) {
        throw new QueueManagerException("Unable to send message.", e);
    } finally {
        try {
            if (queueConnection != null) {
                queueConnection.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue connection", e);
        }
        try {
            if (queueSession != null) {
                queueSession.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue session", e);
        }
        try {
            if (queueSender != null) {
                queueSender.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue sender", e);
        }
    }
}

From source file:org.miloss.fgsms.bueller.Bueller.java

private String doJmsURL(boolean pooled, String endpoint) {
    try {//from   w  w  w  . ja  v a  2s  .c  om

        boolean ok = false;
        String server = endpoint.split("#")[0];
        server = server.replace("jms:", "jnp://");
        String name = endpoint.split("#")[1];
        String msg = "";
        String[] info = DBSettingsLoader.GetCredentials(pooled, endpoint);
        String username = null;
        String password = null;
        if (info != null) {
            username = info[0];
            password = info[1];
        } else {
            info = DBSettingsLoader.GetDefaultBuellerCredentials(pooled);
            if (info != null) {
                username = info[0];
                password = info[1];
            }
        }

        if (name.startsWith("topic")) {
            try {
                Properties properties1 = new Properties();
                properties1.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.jnp.interfaces.NamingContextFactory");
                properties1.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.naming:org.jnp.interfaces");
                //properties1.put(Context.PROVIDER_URL, "jnp://127.0.0.1:1099");
                properties1.put(Context.PROVIDER_URL, server);

                InitialContext iniCtx = new InitialContext(properties1);

                TopicConnectionFactory tcf = (TopicConnectionFactory) iniCtx.lookup("TopicConnectionFactory");
                TopicConnection createTopicConnection = null;
                if (info != null) {
                    createTopicConnection = tcf.createTopicConnection(username, Utility.DE(password)); //Topic topic = (Topic) iniCtx.lookup("/topic/quickstart_jmstopic_topic");
                } else {
                    createTopicConnection = tcf.createTopicConnection(); //Topic topic = (Topic) iniCtx.lookup("/topic/quickstart_jmstopic_topic");
                }
                createTopicConnection.start();
                createTopicConnection.stop();
                createTopicConnection.close();
                //Topic topic = (Topic) iniCtx.lookup("//" + name);
                ok = true;

                //topic = null;
                iniCtx.close();

            } catch (Exception ex) {
                System.out.println(ex);
                msg = ex.getLocalizedMessage();
                //return ex.getLocalizedMessage();
            }
        } else if (name.startsWith("queue")) {
            try {

                Properties properties1 = new Properties();
                properties1.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.jnp.interfaces.NamingContextFactory");
                properties1.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.naming:org.jnp.interfaces");
                properties1.put(Context.PROVIDER_URL, server);
                InitialContext iniCtx = new InitialContext(properties1);
                QueueConnection conn;
                QueueSession session;
                Queue que;

                Object tmp = iniCtx.lookup("ConnectionFactory");
                QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
                if (info != null) {
                    conn = qcf.createQueueConnection(username, Utility.DE(password));
                } else {
                    conn = qcf.createQueueConnection();
                }

                que = (Queue) iniCtx.lookup(name);
                session = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
                conn.start();

                //System.out.println("Connection Started");
                ok = true;

                conn.stop();
                session.close();
                iniCtx.close();

            } catch (Exception ex) {
                log.log(Level.WARN, "Could not bind to jms queue", ex);
                msg = ex.getLocalizedMessage();
            }
            if (ok) {
                return "OK";
            }
            return "Unable to bind to JMS queue: " + msg;
        } else {
            return "Unsupported Protocol";
        }
    } catch (Exception ex) {
        log.log(Level.WARN, "service " + endpoint + " is offline or an error occured", ex);
        return "Offline " + ex.getLocalizedMessage();
    }
    return "undeterminable";
}

From source file:org.wso2.extension.siddhi.io.jms.source.client.JMSClient.java

public void sendJMSEvents(String filePath, String topicName, String queueName, String format, String broker,
        String providerURL) {//  w  ww  .  ja v  a  2  s  . c  om
    if (format == null || "map".equals(format)) {
        format = "csv";
    }
    if ("".equalsIgnoreCase(broker)) {
        broker = "activemq";
    }
    Session session = null;
    Properties properties = new Properties();
    if (!"activemq".equalsIgnoreCase(broker) && !"mb".equalsIgnoreCase(broker)
            && !"qpid".equalsIgnoreCase(broker)) {
        log.error("Please enter a valid JMS message broker. (ex: activemq, mb, qpid");
        return;
    }
    try {
        if (topicName != null && !"".equalsIgnoreCase(topicName)) {
            TopicConnection topicConnection;
            TopicConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                // to provide custom provider urls
                if (providerURL != null) {
                    properties.put(Context.PROVIDER_URL, providerURL);
                }
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                topicConnection = connFactory.createTopicConnection();
                topicConnection.start();
                session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Topic topic = session.createTopic(topicName);
                    MessageProducer producer = session.createProducer(topic);
                    List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + topicName + "' topic");
                            JMSClientUtil.publishMapMessage(producer, session, messagesList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + topicName + "' topic");
                            JMSClientUtil.publishTextMessage(producer, session, messagesList);
                        }
                        log.info("All Order Messages sent");
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        topicConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else if (queueName != null && !queueName.equalsIgnoreCase("")) {
            QueueConnection queueConnection;
            QueueConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                queueConnection = connFactory.createQueueConnection();
                queueConnection.start();
                session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Queue queue = session.createQueue(queueName);
                    MessageProducer producer = session.createProducer(queue);
                    List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + queueName + "' queue");
                            JMSClientUtil.publishMapMessage(producer, session, messagesList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + queueName + "' queue");
                            JMSClientUtil.publishTextMessage(producer, session, messagesList);
                        }
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        queueConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else {
            log.error("Enter queue name or topic name to be published!");
        }
    } catch (Exception e) {
        log.error("Error when publishing" + e.getMessage(), e);
    }
}