List of usage examples for javax.jms QueueConnection 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 w w 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:io.datalayer.activemq.consumer.SimpleQueueReceiver.java
/** * Main method./*from ww w . j a v a 2s.co m*/ * * @param args the queue used by the example */ public static void main(String... args) { String queueName = null; Context jndiContext = null; QueueConnectionFactory queueConnectionFactory = null; QueueConnection queueConnection = null; QueueSession queueSession = null; Queue queue = null; QueueReceiver queueReceiver = null; TextMessage message = null; /* * Read queue name from command line and display it. */ if (args.length != 1) { LOG.info("Usage: java " + "SimpleQueueReceiver <queue-name>"); System.exit(1); } queueName = args[0]; LOG.info("Queue name is " + queueName); /* * Create a JNDI API InitialContext object if none exists yet. */ try { jndiContext = new InitialContext(); } catch (NamingException e) { LOG.info("Could not create JNDI API " + "context: " + e.toString()); System.exit(1); } /* * Look up connection factory and queue. If either does not exist, exit. */ try { queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory"); queue = (Queue) jndiContext.lookup(queueName); } catch (NamingException e) { LOG.info("JNDI API lookup failed: " + e.toString()); System.exit(1); } /* * Create connection. Create session from connection; false means * session is not transacted. Create receiver, then start message * delivery. Receive all text messages from queue until a non-text * message is received indicating end of message stream. Close * connection. */ try { queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queueReceiver = queueSession.createReceiver(queue); queueConnection.start(); while (true) { Message m = queueReceiver.receive(1); if (m != null) { if (m instanceof TextMessage) { message = (TextMessage) m; LOG.info("Reading message: " + message.getText()); } else { break; } } } } catch (JMSException e) { LOG.info("Exception occurred: " + e.toString()); } finally { if (queueConnection != null) { try { queueConnection.close(); } catch (JMSException e) { } } } }
From source file:io.datalayer.activemq.producer.SimpleQueueSender.java
/** * Main method.//www.j a v a 2 s .c o m * * @param args the queue used by the example and, optionally, the number of * messages to send */ public static void main(String... args) { String queueName = null; Context jndiContext = null; QueueConnectionFactory queueConnectionFactory = null; QueueConnection queueConnection = null; QueueSession queueSession = null; Queue queue = null; QueueSender queueSender = null; TextMessage message = null; final int numMsgs; if ((args.length < 1) || (args.length > 2)) { LOG.info("Usage: java SimpleQueueSender " + "<queue-name> [<number-of-messages>]"); System.exit(1); } queueName = args[0]; LOG.info("Queue name is " + queueName); if (args.length == 2) { numMsgs = (new Integer(args[1])).intValue(); } else { numMsgs = 1; } /* * Create a JNDI API InitialContext object if none exists yet. */ try { jndiContext = new InitialContext(); } catch (NamingException e) { LOG.info("Could not create JNDI API context: " + e.toString()); System.exit(1); } /* * Look up connection factory and queue. If either does not exist, exit. */ try { queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory"); queue = (Queue) jndiContext.lookup(queueName); } catch (NamingException e) { LOG.info("JNDI API lookup failed: " + e); System.exit(1); } /* * Create connection. Create session from connection; false means * session is not transacted. Create sender and text message. Send * messages, varying text slightly. Send end-of-messages message. * Finally, close connection. */ try { queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queueSender = queueSession.createSender(queue); message = queueSession.createTextMessage(); for (int i = 0; i < numMsgs; i++) { message.setText("This is message " + (i + 1)); LOG.info("Sending message: " + message.getText()); queueSender.send(message); } /* * Send a non-text control message indicating end of messages. */ queueSender.send(queueSession.createMessage()); } catch (JMSException e) { LOG.info("Exception occurred: " + e.toString()); } finally { if (queueConnection != null) { try { queueConnection.close(); } catch (JMSException e) { } } } }
From source file:edu.harvard.iq.dvn.core.index.IndexServiceBean.java
private void sendMessage(final IndexEdit op) { QueueConnection conn = null; QueueSession session = null;/*from www . j a va 2s.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: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;// w w w .j a v a 2 s .com 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:org.dawnsci.commandserver.core.consumer.RemoteSubmission.java
/** * Monitors a given bean in the status queue. * If the bean is not there throws exception. * If the bean is in a final state, returns the bean straight away. * /* w ww .ja v a 2 s . c o m*/ * Polls the queue for the unique id of the bean we want until it * encounters a final state of that bean. * * Polling rate is less than 1s * * NOTE this class can poll forever if the job it is looking at never finishes. * * @param obean * @param string * @return the bean once it is in a final state. * @throws exception if broker or queue absent */ public StatusBean monitor(StatusBean obean) throws Exception { if (getQueueName() == null || "".equals(getQueueName())) throw new Exception("Please specify a queue name!"); QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); 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); Class clazz = obean.getClass(); ObjectMapper mapper = new ObjectMapper(); try { POLL: while (true) { Thread.sleep(500); @SuppressWarnings("rawtypes") Enumeration e = qb.getEnumeration(); while (e.hasMoreElements()) { // We must final the bean somewhere. 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); if (bean.getUniqueId().equals(obean.getUniqueId())) { if (bean.getStatus().isFinal()) return bean; System.out.println(bean.getPercentComplete()); continue POLL; } } } throw new Exception( "The bean with id " + obean.getUniqueId() + " does not exist in " + getQueueName() + "!"); } } finally { qCon.close(); } }
From source file:org.dawnsci.commandserver.core.producer.Broadcaster.java
/** * /* w w w .j a v a2s . c o m*/ * @param bean * @throws Exception */ private void updateQueue(StatusBean bean) throws Exception { QueueConnection qCon = null; try { QueueBrowser qb = qSes.createBrowser(queue); @SuppressWarnings("rawtypes") Enumeration e = qb.getEnumeration(); ObjectMapper mapper = new ObjectMapper(); String jMSMessageID = null; while (e.hasMoreElements()) { Message m = (Message) e.nextElement(); if (m == null) continue; if (m instanceof TextMessage) { TextMessage t = (TextMessage) m; @SuppressWarnings("unchecked") final StatusBean qbean = mapper.readValue(t.getText(), bean.getClass()); if (qbean == null) continue; if (qbean.getUniqueId() == null) continue; // Definitely not our bean if (qbean.getUniqueId().equals(bean.getUniqueId())) { jMSMessageID = t.getJMSMessageID(); break; } } } qb.close(); if (jMSMessageID != null) { MessageConsumer consumer = qSes.createConsumer(queue, "JMSMessageID = '" + jMSMessageID + "'"); Message m = consumer.receive(1000); if (m != null && m instanceof TextMessage) { MessageProducer producer = qSes.createProducer(queue); producer.send(qSes.createTextMessage(mapper.writeValueAsString(bean))); } } } finally { if (qCon != null) qCon.close(); } }
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 {//from www . j av a2s . c o 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;/*from w ww . ja 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.dawnsci.commandserver.core.producer.ProcessConsumer.java
/** * Parse the queue for stale jobs and things that should be rerun. * @param bean//from w ww .j a va 2 s .c o 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(); } }