@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); Connection connection = null; out.write("<h1>Produce JMS ObjectMessages</h1>"); try { connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); ObjectMessage message = session.createObjectMessage(); MyResource resource = new MyResource("This is my resource"); message.setObject(resource); producer.send(message); out.write("<p>Send JMS Message with object: " + resource + "</p>"); } catch (JMSException e) { e.printStackTrace(); out.write("<h2>A problem occurred during the delivery of this message</h2>"); out.write("</br>"); out.write( "<p><i>Go your the JBoss Application Server console or Server log to see the error stack trace</i></p>"); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { e.printStackTrace(); } } if (out != null) { out.close(); } } }
public static synchronized void resetInstance() { if (jmsProducer != null) { if (jmsProducer.topicConnection != null) { try { jmsProducer.topicConnection.stop(); } catch (JMSException ex) { ex.printStackTrace(); } } if (jmsProducer.producer != null) { try { jmsProducer.producer.close(); } catch (JMSException ex) { ex.printStackTrace(); } } if (jmsProducer.session != null) { try { jmsProducer.session.close(); } catch (JMSException ex) { ex.printStackTrace(); } } if (jmsProducer.topicConnection != null) { try { jmsProducer.topicConnection.close(); } catch (JMSException ex) { ex.printStackTrace(); } } } jmsProducer = null; }
public void stop() { try { session.close(); } catch (JMSException e) { e.printStackTrace(); } try { conn.close(); } catch (JMSException e) { e.printStackTrace(); } }
public void receiveMessage() { Properties prop = new Properties(); prop.put(InitialContext.INITIAL_CONTEXT_FACTORY, "org.exolab.jms.jndi.InitialContextFactory"); prop.put(InitialContext.PROVIDER_URL, "tcp://192.168.122.1:3035/"); try { context = new InitialContext(prop); factory = (ConnectionFactory) context.lookup("ConnectionFactory"); destination = (Destination) context.lookup("queue1"); connection = factory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); consumer = session.createConsumer(destination); connection.start(); Message message = consumer.receive(); if (message instanceof ObjectMessage) { ObjectMessage object = (ObjectMessage) message; System.out.println("Received: " + object.getObject()); } } catch (NamingException e) { e.printStackTrace(); } catch (JMSException e) { e.printStackTrace(); } try { if (consumer != null) consumer.close(); } catch (JMSException e) { e.printStackTrace(); } try { if (session != null) session.close(); } catch (JMSException e) { e.printStackTrace(); } try { if (connection != null) connection.close(); } catch (JMSException e) { e.printStackTrace(); } try { if (context != null) context.close(); } catch (NamingException e) { e.printStackTrace(); } }
public void onMessage(final Message message) { try { // Step 9. We know the client is sending a text message so we cast TextMessage textMessage = (TextMessage) message; // Step 10. get the text from the message. String text = textMessage.getText(); System.out.println("message " + text + " received"); if (!textMessage.getJMSRedelivered()) { // Step 11. On first delivery get the transaction, take a look, and throw an exception Transaction tx = tm.getTransaction(); if (tx != null) { System.out.println("something is wrong, there should be no global transaction: " + tx); } else { System.out.println( "there is no global transaction, although the message delivery is using a local transaction"); System.out.println("let's throw an exception and see what happens"); throw new RuntimeException("DOH!"); } } else { // Step 12. Print the message System.out.println( "The message was redelivered since the message delivery used a local transaction"); } } catch (JMSException e) { e.printStackTrace(); } catch (SystemException e) { e.printStackTrace(); } }
@Override public void blogracyContentReceived(BlogracyContent message) { if (message == null) return; TextMessage response; try { response = session.createTextMessage(); JSONObject record = new JSONObject(); record.put("request", "contentReceived"); record.put("senderUserId", message.getSenderUserId()); record.put("contentRecipientUserId", message.getContentRecipientUserId()); JSONObject content = new JSONObject(message.getContent()); record.put("contentData", content); record.put("contentId", content.getJSONObject("object").getString("id")); response.setText(record.toString()); producer.send(outgoingQueue, response); } catch (JMSException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } }
public void start() { try { conn.start(); } catch (JMSException e) { e.printStackTrace(); } }
public void init( Connection connection, String queue, boolean isTopic, MessageListener mlisten, boolean isActive) { try { // Session: 一个发送或接收消息的线程 session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); if (isTopic) { destination = session.createTopic(queue); } else { destination = session.createQueue(queue); } consumer = session.createConsumer(destination); if (isActive) { System.out.println(queue); LogSys.nodeLogger.info("创建一个主动方式获取消息的Receiver:" + queue); } else { if (mlisten == null) consumer.setMessageListener(this); else consumer.setMessageListener(mlisten); } } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public QLender(String queuecf, String requestQueue) { try { // Connect to the provider and get the JMS connection Context ctx = new InitialContext(); QueueConnectionFactory qFactory = (QueueConnectionFactory) ctx.lookup(queuecf); qConnect = qFactory.createQueueConnection(); // Create the JMS Session qSession = qConnect.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); // Lookup the request queue requestQ = (Queue) ctx.lookup(requestQueue); // Now that setup is complete, start the Connection qConnect.start(); // Create the message listener QueueReceiver qReceiver = qSession.createReceiver(requestQ); qReceiver.setMessageListener(this); System.out.println("Waiting for loan requests..."); } catch (JMSException jmse) { jmse.printStackTrace(); System.exit(1); } catch (NamingException jne) { jne.printStackTrace(); System.exit(1); } }
public void onMessage(Message message) { if (!started) { startLatch.countDown(); started = true; } try { int foo = message.getIntProperty("foo"); if (foo != count) { e = new Exception("received out of order expected " + count + " received " + foo); failed = true; conn.close(); } count++; } catch (JMSException e) { this.e = e; failed = true; try { conn.close(); } catch (JMSException e1) { e1 .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } } }
/** @see MessageListener#onMessage(Message) */ public void onMessage(Message message) { TextMessage tmsg = null; tmsg = (TextMessage) message; String parameter0 = null; String parameter1 = null; System.out.println("<sms module>"); // parsing message into opcode, and parameters String preParse; try { preParse = tmsg.getText(); String[] postParse = preParse.split("[|]+"); parameter0 = postParse[0]; parameter1 = postParse[1]; } catch (JMSException e1) { e1.printStackTrace(); } try { // TODO sendSMS(parameter0, parameter1); } catch (Exception e) { e.printStackTrace(); } }
public void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) { msg = (TextMessage) inMessage; System.out.println("MESSAGE BEAN: Message received: " + msg.getText()); long sleepTime = msg.getLongProperty("sleeptime"); System.out.println("Sleeping for : " + sleepTime + " milli seconds "); Thread.sleep(sleepTime); queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queueSender = queueSession.createSender(queue); TextMessage message = queueSession.createTextMessage(); message.setText("REPLIED:" + msg.getText()); message.setIntProperty("replyid", msg.getIntProperty("id")); System.out.println("Sending message: " + message.getText()); queueSender.send(message); } else { System.out.println("Message of wrong type: " + inMessage.getClass().getName()); } } catch (JMSException e) { e.printStackTrace(); } catch (Throwable te) { te.printStackTrace(); } finally { try { queueSession.close(); queueConnection.close(); } catch (Exception e) { } } } // onMessage
public static void main(String[] args) { // File file = new File("c:/Experiment/h2-2_MS_1_004.img.bz2"); File file = new File("c:/Experiment/baa5d5/high.mtz"); String serverLocation = "http://localhost:8161/fileserver/"; String filename = ""; String entryType = "ENTRY_CREATE"; String ID = "c:/Experiment/5d5.mtz"; URL url = null; // Generate checksum for the file here byte[] fileContents; try { fileContents = FileUtil.getBytesFromFile(file); filename = "5d5.mtz"; // FileUtil.getFileName("c:/Experiment/h2-2_MS_1_002.bz2"); url = new URL(serverLocation + filename); MD5ChecksumProcessor c = new MD5ChecksumProcessor(); String checksum = c.generateChecksum(file); String domain = "crystallography"; ADQueueWriterImpl qu = new ADQueueWriterImpl(); // upload a file to a webserver FileServerClient client = new FileServerClient(url); // boolean uploaded = client.upload(fileContents); // If upload is true send a blob message with this file url // if (uploaded=true){ // qu.sendBlobMessage(url,ID,domain,checksum,entryType,"12/10/2010 12:22:22"); try { qu.sendByteArrayMessage( fileContents, ID, checksum, domain, "baa5d5", entryType, "12/10/2010 12:22:22"); } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } // } // qu.sendMessage(fileContents, ID, entryType, ""); // qu.sendBlobMessage("c:/Experiment/hello123.xml", "123.xml"); qu.disconnect(); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); // } catch (XMLStreamException e) { // TODO Auto-generated catch block // e.printStackTrace(); } catch (FactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ChecksumProcessorException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** Constructor del encargado de enviar mensajes JMS. */ public RespuestaConsultaValue() { try { final Properties env = new Properties(); env.put("org.jboss.ejb.client.scoped.context", true); env.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); env.put("endpoint.name", "endpoint-client"); ictx = new InitialContext(env); Object tmp = ictx.lookup("ConnectionFactory"); QueueConnectionFactory qcf = (QueueConnectionFactory) tmp; conn = qcf.createQueueConnection(); this.cola = (Queue) ictx.lookup("queue/test"); queueSession = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); conn.start(); } catch (JMSException e) { e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public static final void printMessageHeaders(Message pMessge, Object pHandler) { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); try { writer.println("==================================================="); writer.println("MDB Event Handler class=[" + pHandler.getClass().getName() + "]"); writer.println(""); writer.println("JMS Message Id: " + pMessge.getJMSMessageID()); for (Enumeration em = pMessge.getPropertyNames(); em.hasMoreElements(); ) { String property = (String) em.nextElement(); writer.println( "JMS Prop=[" + property + "] value=[" + pMessge.getStringProperty(property) + "]"); } writer.println("==================================================="); } catch (JMSException e) { e.printStackTrace(); } writer.flush(); System.out.println(stringWriter.toString()); }
private int receiveUntilEmpty(Session session, Queue queue) { Message message = null; int count = 0; do { try { message = receiveMessage(session, queue); if (message != null) { // JCA queue returns a message of the ObjectMessage type Object messageText = (message instanceof TextMessage ? ((TextMessage) message).getText() : ((ObjectMessage) message).getObject()); System.out.println("===== Received message: " + messageText + " ====="); } } catch (Exception e) { e.printStackTrace(); } count++; } while (message != null); if (count != 0) { try { System.out.println( "===== Received " + count + " messages from queue " + queue.getQueueName() + " ====="); } catch (JMSException e) { e.printStackTrace(); } } return count; }
/** * Send a command via JMS. * * <p>Note: Opens and closes the connection per invocation of this method which, when run outside * a JavaEE container, is not very efficient. * * @param command * @throws JMSException */ public void sendCommandMessage(Command command) throws JMSException { Connection connection = null; Session session = null; try { connection = connectionFactory.createConnection(); session = connection.createSession(TRANSACTIONAL, Session.AUTO_ACKNOWLEDGE); // Construct a JMS "TextMessage" final TextMessage newMessage = session.createTextMessage(); newMessage.setStringProperty("issuer", command.getIssuer()); newMessage.setStringProperty("type", command.getType()); newMessage.setText(command.getPayload()); // Send the message final MessageProducer producer = session.createProducer(this.commandQueue); producer.send(newMessage); if (TRANSACTIONAL) { // JavaEE containers would manage this session.commit(); } } finally { if (connection != null) { try { if (session != null) { session.close(); } connection.stop(); connection.close(); } catch (JMSException e) { e.printStackTrace(); } } } }
private void closeReceiver() { try { connection.close(); } catch (JMSException e) { e.printStackTrace(System.err); } }
void processTask(ETask task, ObjectMessage msg, EntityManager em) { EMethod method; EModel model; Collection<EBounds> bounds; TaskMessage tm; System.out.println("Processing task [id=" + String.valueOf(task.getId()) + "]..."); method = task.getMethod(); model = task.getModel(); bounds = getBoundsForModel(model, em); try { tm = (TaskMessage) msg.getObject(); if (method.getIdent().equals(EMethod.fba)) { FbaMethod.run(task, model, bounds); } else if (method.getIdent().equals(EMethod.fva)) { FvaMethod.run(task, model, bounds, (MultipleReactionsTaskMessage) tm); } else if (method.getIdent().equals(EMethod.rscan)) { RscanMethod.run(task, model, bounds, (MultipleReactionsTaskMessage) tm); } else if (method.getIdent().equals(EMethod.kgene)) { KgeneMethod.run(task, model, bounds); } msg.acknowledge(); } catch (AmkfbaException e) { AcornLogger.logError("AmkfbaException: " + e.getMessage()); markAsBroken(task, em); } catch (JMSException e) { e.printStackTrace(System.err); throw new Error("JMSException, aborting..."); } }
/** * Message listener interface. * * @param msg message */ public void onMessage(Message msg) { try { String msgText; if (msg instanceof TextMessage) { msgText = ((TextMessage) msg).getText(); } else { msgText = msg.toString(); } // System.out.println("Message Received: "+ msgText ); // ClientTools clientTools = new ClientTools(); // ClientTools.getRequestAsFile(msgText); // DataTools dataTools = new DataTools(); NonCimDataTools nonCimDataTools = new NonCimDataTools(); if (!nonCimDataTools.deleteOperation(msgText)) { // ClientTools.getDataAsFile(msgText); nonCimDataTools.rdfToConsole(msgText); } // System.out.println("OK"); if (msgText.equalsIgnoreCase("quit")) { synchronized (this) { quit = true; this.notifyAll(); // Notify main thread to quit } } } catch (JMSException jmse) { jmse.printStackTrace(); } }
public DigitalLibraryServer() { try { Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces"); properties.put(Context.PROVIDER_URL, "localhost"); InitialContext jndi = new InitialContext(properties); ConnectionFactory conFactory = (ConnectionFactory) jndi.lookup("XAConnectionFactory"); connection = conFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { counterTopic = (Topic) jndi.lookup("counterTopic"); } catch (NamingException NE1) { System.out.println("NamingException: " + NE1 + " : Continuing anyway..."); } if (null == counterTopic) { counterTopic = session.createTopic("counterTopic"); jndi.bind("counterTopic", counterTopic); } consumer = session.createConsumer(counterTopic); consumer.setMessageListener(this); System.out.println("Server started waiting for client requests"); connection.start(); } catch (NamingException NE) { System.out.println("Naming Exception: " + NE); } catch (JMSException JMSE) { System.out.println("JMS Exception: " + JMSE); JMSE.printStackTrace(); } }
public void sendMessage(Order order) { ConnectionFactory factory = new ActiveMQConnectionFactory("failover://tcp://localhost:61616"); Queue queue = new ActiveMQQueue("sequence"); Connection conn = null; Session sen = null; MessageProducer producer = null; TextMessage msg = null; JSONMapper mapper = new JSONMapper(); Destination des = null; try { conn = factory.createConnection(); sen = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = sen.createProducer(queue); conn.start(); String str = mapper.writeObjectAsString(order); System.out.println(str); msg = sen.createTextMessage(str); producer.send(msg); producer.close(); sen.close(); conn.close(); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Override public void onMessage(Message message) { if (!(message instanceof ObjectMessage)) { return; } try { Object objectInMessage = ((ObjectMessage) message).getObject(); if (!(objectInMessage instanceof LectureWrapperDTO)) { return; } final String messageAction = message.getStringProperty("action"); if (messageAction == null) { return; } LectureWrapperDTO lectureWrapperDTO = (LectureWrapperDTO) objectInMessage; if (messageAction.equals(ISchedulerListener.InfoType.CREATED.toString())) { schedulerListener.notify(ISchedulerListener.InfoType.CREATED, lectureWrapperDTO); } else if (messageAction.equals(ISchedulerListener.InfoType.INFO.toString())) { schedulerListener.notify(ISchedulerListener.InfoType.INFO, lectureWrapperDTO); } else if (messageAction.equals(ISchedulerListener.InfoType.DENIED.toString())) { schedulerListener.notify(ISchedulerListener.InfoType.DENIED, lectureWrapperDTO); } else if (messageAction.equals(ISchedulerListener.InfoType.STREAMED.toString())) { schedulerListener.notify(ISchedulerListener.InfoType.STREAMED, lectureWrapperDTO); } } catch (JMSException e) { e.printStackTrace(); } }
private void publishCIPendingEvents() { // logger.info("start reading" + eventType); isRunning = true; lastRun = System.currentTimeMillis(); List<CMSEvent> events = ciEventReader.getEvents(); while (events.size() > 0) { logger.info("Got " + events.size() + " ci events; Using CIEventPublisher"); for (CMSEvent event : events) { String action = event.getHeaders().get("action"); try { if (event.getPayload() != null || "delete".equals(action)) { eventPublisher.publishCIEvents(event); } else { logger.info("Event payload found null for " + event.getHeaders()); } ciEventReader.removeEvent(event.getEventId()); } catch (JMSException e) { e.printStackTrace(); logger.error(e.getMessage(), e); // stopPublishing(); return; } } events = ciEventReader.getEvents(); } // System.out.println("Done;"); }
private void publishControllerPendingEvents() { isRunning = true; lastRun = System.currentTimeMillis(); List<CMSEvent> events = controllerEventReader.getEvents(); while (events.size() > 0) { logger.info("Got " + events.size() + " controller events; Using ControllerEventPublisher"); for (CMSEvent event : events) { try { if (event.getPayload() != null) { eventPublisher.publishControllerEvents(event); } else { logger.info("Event payload found null for " + event.getHeaders()); } controllerEventReader.removeEvent(event.getEventId()); } catch (JMSException e) { e.printStackTrace(); logger.error(e.getMessage(), e); // stopPublishing(); return; } } events = controllerEventReader.getEvents(); } // System.out.println("Done;"); }
/** * @see MessageListener#onMessage(Message) * <p>This method expects a MapMessage containing information about a flight that has been * added to the database. This method will print out the information about the flight. */ public void onMessage(Message message) { try { if (message instanceof MapMessage) { MapMessage msg = (MapMessage) message; StringBuffer sb = new StringBuffer(); sb.append("Flight #: " + msg.getString("flightId") + "\n"); sb.append("Flight Date: " + msg.getString("flightDate") + "\n"); sb.append("Departure Airport: " + msg.getString("departureAirport") + "\n"); sb.append("Destination Airport: " + msg.getString("destinationAirport") + "\n"); sb.append("Number of Seats: " + msg.getInt("numSeats") + "\n"); sb.append("Seat Cost: $" + msg.getDouble("cost") + "\n"); sb.append("Airplane #: " + msg.getString("airplaneId") + "\n"); sb.append("*************************************************** \n\n"); System.out.println( "\n**" + getClass().getSimpleName() + ": Flight Added!\n" + sb.toString()); } else { System.out.println( getClass().getSimpleName() + " - Error: The message provided was not of type MapMessage!"); } } catch (JMSException e) { System.out.println( getClass().getSimpleName() + ": Error occuredwhen attempting to read the MapMessage"); e.printStackTrace(); } }
@Override public void onMessage(Message message) { try { System.out.println("QueueReceiver1接收到消息:" + ((TextMessage) message).getText()); } catch (JMSException e) { e.printStackTrace(); } }
public Topic getTopic(Session session) { try { return session.createTopic(JMS_TOPIC); } catch (JMSException e) { e.printStackTrace(); } return null; }
public Queue getQueue(Session session) { try { return session.createQueue(JMS_QUEUE); } catch (JMSException e) { e.printStackTrace(); } return null; }
public void stop() { try { jmsService.removeMessageListener(this); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } }