List of usage examples for javax.jms QueueSession close
void close() throws JMSException;
From source file:org.dawnsci.commandserver.mx.example.ActiveMQProducer.java
public static void main(String[] args) throws Exception { QueueConnectionFactory connectionFactory = ConnectionFactoryFacade .createConnectionFactory("tcp://ws097.diamond.ac.uk:61616"); Connection send = connectionFactory.createConnection(); Session session = send.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue("testQ"); final MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.PERSISTENT); Message message = session.createTextMessage("Hello World"); producer.send(message);//from ww w. j a v a 2 s . c o m message = session.createTextMessage("...and another message"); producer.send(message); message = session.createObjectMessage(new TestObjectBean("this could be", "anything")); producer.send(message); // Test JSON SweepBean col = new SweepBean("fred", "d0000000001", 0, 100); ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(col); message = session.createTextMessage(jsonString); producer.send(message); producer.close(); session.close(); send.close(); // Now we peak at the queue // If the consumer is not going, the messages should still be there if (REQUIRE_PEAK) { QueueConnection qCon = connectionFactory.createQueueConnection(); QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queue = qSes.createQueue("testQ"); qCon.start(); QueueBrowser qb = qSes.createBrowser(queue); Enumeration e = qb.getEnumeration(); if (e.hasMoreElements()) System.out.println("Peak at queue:"); while (e.hasMoreElements()) { Message m = (Message) e.nextElement(); if (m == null) continue; if (m instanceof TextMessage) { TextMessage t = (TextMessage) m; System.out.println(t.getText()); } else if (m instanceof ObjectMessage) { ObjectMessage o = (ObjectMessage) m; System.out.println(o.getObject()); } } qb.close(); qSes.close(); qCon.close(); } }
From source file:org.panksdmz.jms.tibco.MessageSenderBean.java
public void send() { try {//from w ww . j a v a 2 s. c o m QueueConnection connection = connectionFactory.createQueueConnection(); QueueSession session = connection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(sendQueueName); QueueSender sender = session.createSender(queue); TextMessage message = session .createTextMessage("Message @ " + CaliHDateTime.now().getTimeInMillis() + " from thread " + Thread.currentThread().getId() + " from session [" + session.toString() + "]"); sender.send(message); session.close(); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
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;/* www . ja v a2s. c o 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.index.IndexServiceBean.java
private void sendMessage(final IndexEdit op) { QueueConnection conn = null;/*from www . j ava 2s .co m*/ QueueSession session = null; 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.miloss.fgsms.bueller.Bueller.java
private String doJmsURL(boolean pooled, String endpoint) { try {//from w w w . ja v a2s .co m 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: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 {// w w w . ja v a 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:edu.harvard.iq.dataverse.ingest.IngestServiceBean.java
public void startIngestJobs(Dataset dataset, AuthenticatedUser user) { int count = 0; List<DataFile> scheduledFiles = new ArrayList<>(); IngestMessage ingestMessage = null;/*w w w. j a v a 2 s.c o m*/ for (DataFile dataFile : dataset.getFiles()) { if (dataFile.isIngestScheduled()) { // todo: investigate why when calling save with the file object // gotten from the loop, the roles assignment added at create is removed // (switching to refinding via id resolves that) dataFile = fileService.find(dataFile.getId()); long ingestSizeLimit = -1; try { ingestSizeLimit = systemConfig.getTabularIngestSizeLimit( getTabDataReaderByMimeType(dataFile.getContentType()).getFormatName()); } catch (IOException ioex) { logger.warning( "IO Exception trying to retrieve the ingestable format identifier from the plugin for type " + dataFile.getContentType() + " (non-fatal);"); } if (ingestSizeLimit == -1 || dataFile.getFilesize() < ingestSizeLimit) { dataFile.SetIngestInProgress(); dataFile = fileService.save(dataFile); scheduledFiles.add(dataFile); logger.fine("Attempting to queue the file " + dataFile.getFileMetadata().getLabel() + " for ingest, for dataset: " + dataset.getGlobalId()); count++; } else { dataFile.setIngestDone(); dataFile = fileService.save(dataFile); logger.info("Skipping tabular ingest of the file " + dataFile.getFileMetadata().getLabel() + ", because of the size limit (set to " + ingestSizeLimit + " bytes)."); // TODO: (urgent!) // send notification to the user! } } } if (count > 0) { String info = "Attempting to ingest " + count + " tabular data file(s)."; logger.info(info); if (user != null) { datasetService.addDatasetLock(dataset.getId(), user.getId(), info); } else { datasetService.addDatasetLock(dataset.getId(), null, info); } DataFile[] scheduledFilesArray = (DataFile[]) scheduledFiles.toArray(new DataFile[count]); scheduledFiles = null; // Sort ingest jobs by file size: Arrays.sort(scheduledFilesArray, new Comparator<DataFile>() { @Override public int compare(DataFile d1, DataFile d2) { long a = d1.getFilesize(); long b = d2.getFilesize(); return Long.valueOf(a).compareTo(b); } }); ingestMessage = new IngestMessage(IngestMessage.INGEST_MESAGE_LEVEL_INFO); for (int i = 0; i < count; i++) { ingestMessage.addFileId(scheduledFilesArray[i].getId()); logger.fine("Sorted order: " + i + " (size=" + scheduledFilesArray[i].getFilesize() + ")"); } QueueConnection conn = null; QueueSession session = null; QueueSender sender = null; try { conn = factory.createQueueConnection(); session = conn.createQueueSession(false, 0); sender = session.createSender(queue); //ingestMessage.addFile(new File(tempFileLocation)); Message message = session.createObjectMessage(ingestMessage); //try { sender.send(message); //} catch (JMSException ex) { // ex.printStackTrace(); //} } catch (JMSException ex) { ex.printStackTrace(); //throw new IOException(ex.getMessage()); } 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.apache.stratos.status.monitor.agent.clients.service.CEPServerClient.java
private static void executeService() throws SQLException { int serviceID = MySQLConnectionInitializer.getServiceID(StatusMonitorConstants.CEP); AuthConfigBean authConfigBean = StatusMonitorConfigurationBuilder.getAuthConfigBean(); String userName = authConfigBean.getUserName(); tcpUserName = userName.replace('@', '!'); //check whether login success if (ServiceLoginClient.loginChecker(StatusMonitorConstants.CEP_HOST, serviceID)) { Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, StatusMonitorAgentConstants.QPID_ICF); properties.put(StatusMonitorAgentConstants.CF_NAME_PREFIX + StatusMonitorAgentConstants.CF_NAME, getTCPConnectionURL(tcpUserName, authConfigBean.getPassword())); InitialContext ctx;/* w ww . j av a 2 s. c o m*/ try { ctx = new InitialContext(properties); // Lookup connection factory QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx .lookup(StatusMonitorAgentConstants.CF_NAME); QueueConnection queueConnection = connFactory.createQueueConnection(); queueConnection.start(); QueueSession queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); // Send message Queue queue = queueSession.createQueue( StatusMonitorAgentConstants.QUEUE_NAME_CEP + ";{create:always, node:{durable: True}}"); // create the message to send TextMessage textMessage = queueSession.createTextMessage("Test Message Hello"); javax.jms.QueueSender queueSender = queueSession.createSender(queue); queueSender.setTimeToLive(100000000); QueueReceiver queueReceiver = queueSession.createReceiver(queue); queueSender.send(textMessage); TextMessage message = (TextMessage) queueReceiver.receiveNoWait(); if (log.isDebugEnabled()) { log.debug("Message in the execute() of CEPServer Client: " + message.getText()); } if (message.getText().equals("Test Message Hello")) { MySQLConnector.insertStats(serviceID, true); MySQLConnector.insertState(serviceID, true, ""); } else { MySQLConnector.insertStats(serviceID, false); MySQLConnector.insertState(serviceID, false, "Send or retrieve messages failed"); } queueSender.close(); queueSession.close(); queueConnection.close(); } catch (JMSException e) { MySQLConnector.insertStats(serviceID, false); MySQLConnector.insertState(serviceID, false, e.getMessage()); String msg = "JMS Exception in inserting stats into the DB for the CEPServerClient"; log.warn(msg, e); } catch (NamingException e) { MySQLConnector.insertStats(serviceID, false); MySQLConnector.insertState(serviceID, false, e.getMessage()); String msg = "Naming Exception in inserting stats into the DB for the CEPServerClient"; log.warn(msg, e); } } }
From source file:org.apache.stratos.status.monitor.agent.clients.service.MessageBrokerServiceClient.java
private static void executeService() throws SQLException { int serviceID = MySQLConnectionInitializer.getServiceID(StatusMonitorConstants.MESSAGING); AuthConfigBean authConfigBean = StatusMonitorConfigurationBuilder.getAuthConfigBean(); String userName = authConfigBean.getUserName(); tcpUserName = userName.replace('@', '!'); //check whether login success if (ServiceLoginClient.loginChecker(StatusMonitorConstants.MESSAGING_HOST, serviceID)) { Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, StatusMonitorAgentConstants.QPID_ICF); properties.put(StatusMonitorAgentConstants.CF_NAME_PREFIX + StatusMonitorAgentConstants.CF_NAME, getTCPConnectionURL(tcpUserName, authConfigBean.getPassword())); if (log.isDebugEnabled()) { log.debug("getTCPConnectionURL(username,password) = " + getTCPConnectionURL(tcpUserName, authConfigBean.getPassword())); }/* w ww . j a v a2 s .co m*/ try { InitialContext ctx = new InitialContext(properties); // Lookup connection factory QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx .lookup(StatusMonitorAgentConstants.CF_NAME); QueueConnection queueConnection = connFactory.createQueueConnection(); queueConnection.start(); QueueSession queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); // Send message Queue queue = queueSession.createQueue( StatusMonitorAgentConstants.QUEUE_NAME_MB + ";{create:always, node:{durable: True}}"); // create the message to send TextMessage textMessage = queueSession.createTextMessage("Test Message Hello"); javax.jms.QueueSender queueSender = queueSession.createSender(queue); queueSender.setTimeToLive(100000000); QueueReceiver queueReceiver = queueSession.createReceiver(queue); queueSender.send(textMessage); TextMessage message = (TextMessage) queueReceiver.receiveNoWait(); if (message.getText().equals("Test Message Hello")) { MySQLConnector.insertStats(serviceID, true); MySQLConnector.insertState(serviceID, true, ""); } else { MySQLConnector.insertStats(serviceID, false); MySQLConnector.insertState(serviceID, false, "Send and retrieve messages failed"); } queueSender.close(); queueSession.close(); queueConnection.close(); } catch (JMSException e) { MySQLConnector.insertStats(serviceID, false); MySQLConnector.insertState(serviceID, false, e.getMessage()); String msg = "Exception in executing the client - " + "Status Monitor Agent for MessageBrokerServiceClient"; log.warn(msg, e); } catch (NamingException e) { MySQLConnector.insertStats(serviceID, false); MySQLConnector.insertState(serviceID, false, e.getMessage()); String msg = "Naming exception in executing the client - " + "Status Monitor agent for MessageBrokerServiceClient"; log.warn(msg, e); } } }
From source file:org.easybatch.jms.JmsIntegrationTest.java
@Test public void testJmsRecordWriter() throws Exception { Context jndiContext = getJndiContext(); Queue queue = (Queue) jndiContext.lookup("q"); QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext .lookup("QueueConnectionFactory"); QueueConnection queueConnection = queueConnectionFactory.createQueueConnection(); QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queueConnection.start();/*w ww . j av a 2 s. c om*/ String dataSource = "foo" + LINE_SEPARATOR + "bar"; aNewJob().reader(new StringRecordReader(dataSource)).processor(new JmsMessageTransformer(queueSession)) .writer(new JmsQueueRecordWriter(queueConnectionFactory, queue)).call(); // Assert that queue contains 2 messages: "foo" and "bar" QueueBrowser queueBrowser = queueSession.createBrowser(queue); Enumeration enumeration = queueBrowser.getEnumeration(); assertThat(enumeration.hasMoreElements()).isTrue(); TextMessage message1 = (TextMessage) enumeration.nextElement(); assertThat(message1.getText()).isEqualTo("foo"); assertThat(enumeration.hasMoreElements()).isTrue(); TextMessage message2 = (TextMessage) enumeration.nextElement(); assertThat(message2.getText()).isEqualTo("bar"); assertThat(enumeration.hasMoreElements()).isFalse(); queueSession.close(); queueConnection.close(); }