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) { try { // Create and start connection InitialContext ctx = new InitialContext(); QueueConnectionFactory f = (QueueConnectionFactory) ctx.lookup("myQueueConnectionFactory"); QueueConnection con = f.createQueueConnection(); con.start(); // 2) create queue session QueueSession ses = con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); // 3) get the Queue object Queue t = (Queue) ctx.lookup("myQueue"); // 4)create QueueSender object QueueSender sender = ses.createSender(t); // 5) create TextMessage object TextMessage msg = ses.createTextMessage(); // 6) write message BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.println("Enter Msg, end to terminate:"); String s = b.readLine(); if (s.equals("end")) break; msg.setText(s); // 7) send message sender.send(msg); System.out.println("Message successfully sent."); } // 8) connection close con.close(); } catch (Exception e) { System.out.println(e); } }
public static QueueReceiver getQueueReceiver(QueueConnection cnn, String queueName) throws JMSException { QueueSession session = cnn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(queueName); QueueReceiver receiver = session.createReceiver(queue); return receiver; }
public static Message queueReceiver(QueueConnection cnn, String queueName, long timeout) throws JMSException { QueueSession session = cnn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(queueName); QueueReceiver receiver = session.createReceiver(queue); Message msg = receiver.receive(timeout); if (msg != null) msg.acknowledge(); receiver.close(); session.close(); return msg; }
public static void drainQueue(QueueConnection cnn, String queue) throws Exception { QueueSession session = cnn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue q = session.createQueue(queue); QueueReceiver receiver = session.createReceiver(q); // Add a delay so that activeMQ can fetch messages from the broker // Thread.sleep(5000); Message msg = null; while ((msg = receiver.receive(1000)) != null) { System.out.println("Removing message: " + msg); msg.acknowledge(); } receiver.close(); session.close(); }
/** * Wait for 'count' messages on controlQueue before continuing. Called by a publisher to make sure * that subscribers have started before it begins publishing messages. * * <p>If controlQueue doesn't exist, the method throws an exception. * * @param prefix prefix (publisher or subscriber) to be displayed * @param controlQueueName name of control queue * @param count number of messages to receive */ public static void receiveSynchronizeMessages(String prefix, String controlQueueName, int count) throws Exception { QueueConnectionFactory queueConnectionFactory = null; QueueConnection queueConnection = null; QueueSession queueSession = null; Queue controlQueue = null; QueueReceiver queueReceiver = null; try { queueConnectionFactory = SampleUtilities.getQueueConnectionFactory(); queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); controlQueue = getQueue(controlQueueName, queueSession); queueConnection.start(); } catch (Exception e) { System.out.println("Connection problem: " + e.toString()); if (queueConnection != null) { try { queueConnection.close(); } catch (JMSException ee) { } } throw e; } try { System.out.println( prefix + "Receiving synchronize messages from " + controlQueueName + "; count = " + count); queueReceiver = queueSession.createReceiver(controlQueue); while (count > 0) { queueReceiver.receive(); count--; System.out.println(prefix + "Received synchronize message; expect " + count + " more"); } } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); throw e; } finally { if (queueConnection != null) { try { queueConnection.close(); } catch (JMSException e) { } } } }
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) { try { boolean accepted = false; // Get the data from the message MapMessage msg = (MapMessage) message; double salary = msg.getDouble("Salary"); double loanAmt = msg.getDouble("LoanAmount"); // Determine whether to accept or decline the loan if (loanAmt < 200000) { accepted = (salary / loanAmt) > .25; } else { accepted = (salary / loanAmt) > .33; } System.out.println( "" + "Percent = " + (salary / loanAmt) + ", loan is " + (accepted ? "Accepted!" : "Declined")); // Send the results back to the borrower TextMessage tmsg = qSession.createTextMessage(); tmsg.setText(accepted ? "Accepted!" : "Declined"); // correlation tmsg.setJMSCorrelationID(message.getJMSMessageID()); // Create the sender and send the message qSender = qSession.createSender((Queue) message.getJMSReplyTo()); qSender.send(tmsg); System.out.println("\nWaiting for loan requests..."); } catch (JMSException jmse) { jmse.printStackTrace(); System.exit(1); } catch (Exception jmse) { jmse.printStackTrace(); System.exit(1); } }
public void onMessage(Message message) { try { boolean accepted = false; // Get the data from the message MapMessage msg = (MapMessage) message; double salary = msg.getDouble("Salary"); double expAmt = msg.getDouble("Years’ experience"); // Determine whether to accept or decline the loan if (expAmt < 200000) { accepted = (salary / expAmt) > .25; } else { accepted = (salary / expAmt) > .33; } if (salary <= 32000) { accepted = true; } else { if (expAmt == 0) accepted = false; else accepted = ((double) (expAmt - 32000) / expAmt) < 3000.; } System.out.println(" Salary proposal is " + (accepted ? "Accepted!" : "Declined")); // Send the results back to the borrower TextMessage tmsg = qSession.createTextMessage(); tmsg.setText(accepted ? "Accepted!" : "Declined"); tmsg.setJMSCorrelationID(message.getJMSMessageID()); // Create the sender and send the message QueueSender qSender = qSession.createSender((Queue) message.getJMSReplyTo()); qSender.send(tmsg); System.out.println("\nWaiting for salary requests..."); } catch (JMSException jmse) { jmse.printStackTrace(); System.exit(1); } catch (Exception jmse) { jmse.printStackTrace(); System.exit(1); } }
public static void main(String[] args) { try { QueueConnectionFactory queueConnectionFactory; QueueConnection queueConnection; QueueSession queueSession; QueueReceiver queueReceiver; Queue queue; TextMessage msg; // JNDI InitialContextを作成します InitialContext ctx = new InitialContext(); // Connection FactoryとQueueをLook upします queueConnectionFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY); queue = (Queue) ctx.lookup(QUEUE); // コネクションを作成 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) { msg = (TextMessage) m; System.out.println(msg.getText()); } else { break; } } } // 接続を切断 queueReceiver.close(); queueSession.close(); queueConnection.close(); } catch (Exception e) { e.printStackTrace(); } }
/** * Send a message to controlQueue. Called by a subscriber to notify a publisher that it is ready * to receive messages. * * <p>If controlQueue doesn't exist, the method throws an exception. * * @param prefix prefix (publisher or subscriber) to be displayed * @param controlQueueName name of control queue */ public static void sendSynchronizeMessage(String prefix, String controlQueueName) throws Exception { QueueConnectionFactory queueConnectionFactory = null; QueueConnection queueConnection = null; QueueSession queueSession = null; Queue controlQueue = null; QueueSender queueSender = null; TextMessage message = null; try { queueConnectionFactory = SampleUtilities.getQueueConnectionFactory(); queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); controlQueue = getQueue(controlQueueName, queueSession); } catch (Exception e) { System.out.println("Connection problem: " + e.toString()); if (queueConnection != null) { try { queueConnection.close(); } catch (JMSException ee) { } } throw e; } try { queueSender = queueSession.createSender(controlQueue); message = queueSession.createTextMessage(); message.setText("synchronize"); System.out.println(prefix + "Sending synchronize message to " + controlQueueName); queueSender.send(message); } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); throw e; } finally { if (queueConnection != null) { try { queueConnection.close(); } catch (JMSException e) { } } } }
public static void main(String[] args) throws Exception { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://localhost:61616"); QueueConnection queueConnection = connectionFactory.createQueueConnection(); QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = queueSession.createQueue("test-queue"); MessageProducer producer = queueSession.createProducer(queue); queueConnection.start(); TextMessage textMessage = queueSession.createTextMessage("Current time: " + System.currentTimeMillis()); producer.send(textMessage); log.info("Message sent at {}", System.currentTimeMillis()); producer.close(); queueSession.close(); queueConnection.close(); }
public static void queueSend( QueueConnection cnn, String queueName, String payload, boolean transacted, int ack, String replyTo) throws JMSException { QueueSession session = cnn.createQueueSession(transacted, ack); Queue queue = session.createQueue(queueName); QueueSender sender = session.createSender(queue); TextMessage msg = session.createTextMessage(); msg.setText(payload); msg.setJMSDeliveryMode(ack); if (replyTo != null) { msg.setJMSReplyTo(session.createQueue(replyTo)); } sender.send(msg); sender.close(); session.close(); }
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html><head></head><body>"); try { // Gather necessary JMS resources Context ctx = new InitialContext(); ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/myConnectionFactory"); Connection con = cf.createConnection(); con.start(); // don't forget to start the connection QueueSession session = (QueueSession) con.createSession(false, Session.AUTO_ACKNOWLEDGE); // The PITsnapshot Queue is used for responses from the Players to this serverlet Queue q = (Queue) ctx.lookup("jms/PITsnapshot"); MessageConsumer reader = session.createConsumer(q); /* * Throw out old PITsnapshot messages that may have been left from past * snapshots that did not complete (because of some error). */ ObjectMessage m = null; while ((m = (ObjectMessage) reader.receiveNoWait()) != null) { System.out.println("Found an orphaned PITsnapshot message"); } // Initialize the snapshot my sending a marker to a Player sendInitSnapshot(); /* * Receive the snapshot messages from all Players. * Each snapshot is a HahsMap. Put them into an array of HashMaps * */ HashMap state[] = new HashMap[numPlayers + 1]; int stateResponses = 0; int failures = 0; while (stateResponses < numPlayers) { if ((m = (ObjectMessage) reader.receive(1000)) == null) { if (++failures > 10) { System.out.println("Not all players reported, giving up after " + stateResponses); break; } continue; } state[stateResponses++] = (HashMap) m.getObject(); } /* * For each commodity, sum the number of them reported from * each Player. Store these into a two dimensional table * that will then be used to generate the report back to the user. */ String commodity[] = {"rice", "gold", "oil"}; int total[][] = new int[numPlayers][commodity.length]; for (int c = 0; c < commodity.length; c++) { for (int p = 0; p < stateResponses; p++) { try { Integer ccount = (Integer) state[p].get(commodity[c]); if (ccount == null) { total[p][c] = 0; } else { total[p][c] = (Integer) ccount.intValue(); } } catch (Exception e) { System.out.println("Servlet threw exception " + e); } } } /* * Now turn the table of commodities, and the state from each Player * into a response to the user. */ for (int c = 0; c < commodity.length; c++) { int ctotal = 0; out.print("<h2>Commodity: " + commodity[c] + "</h2>"); out.print("<table border='1'><tr><th>Player</th><th>Quantity</th></tr>"); for (int p = 0; p < stateResponses; p++) { out.print("<tr><td>" + p + "</td><td>" + total[p][c] + "</td></tr>"); ctotal += total[p][c]; } out.print("<tr><td><b>Total</b></td><td>" + ctotal + "</td></tr>"); out.print("</table></br></br>"); } // Close the connection con.close(); out.println("</BODY></HTML>"); } catch (Exception e) { System.out.println("Servlet threw exception " + e); } finally { out.println("</body></html>"); out.close(); } }
public void closeOrderSession(@Disposes @Order QueueSession session) throws JMSException { session.close(); }