public void doSend() { QueueSession queueSession = null; QueueSender queueSender = null; TextMessage message = null; if (doSetup()) { try { queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queueSender = queueSession.createSender(queue); message = queueSession.createTextMessage(); for (int i = 0; i < NUM_MSGS; i++) { message.setText("This is message " + (i + 1)); System.out.println("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.error("JMS Send Exception occurred: " + e.toString()); } finally { doCleanup(); } } }
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); } }
@AroundInvoke public Object checkArguments(InvocationContext ctx) throws Exception { try { log = Logger.getLogger(LogoutInterceptor.class); Object[] args = ctx.getParameters(); String className = ctx.getTarget().getClass().getSimpleName(); log.trace("Class name: " + className); String methodName = ctx.getMethod().getName(); log.trace("Method: " + methodName); String sessionId = (String) args[0]; if ((sessionId == null) || (sessionId.length() == 0)) { throw new Exception("sessionId should not be null"); } cf = (QueueConnectionFactory) new InitialContext().lookup(QueueNames.CONNECTION_FACTORY); queue = (Queue) new InitialContext().lookup(QueueNames.LOGOUT_QUEUE); log.trace("Queue logout: " + queue.getQueueName()); QueueConnection connection = cf.createQueueConnection(); QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); QueueSender sender = session.createSender(queue); Message logoutMessage = session.createTextMessage(sessionId); Timestamp time = new Timestamp(new Date().getTime()); // Messages will not accept timestamp property- must change to string logoutMessage.setStringProperty(PropertyNames.TIME, time.toString()); sender.send(logoutMessage); session.close(); } catch (Exception e) { log.fatal("Error in LogoutInterceptor", e); } return ctx.proceed(); }
public void sendException(QueueSession session, Queue queue, Throwable exception) throws JMSException { QueueSender sender = session.createSender(queue); ObjectMessage message = session.createObjectMessage(exception); try { sender.send(message); } finally { sender.close(); } }
private void sendMessage(List<LuceneWork> queue) throws Exception { ObjectMessage message = getQueueSession().createObjectMessage(); final String indexName = org.hibernate.search.test.jms.master.TShirt.class.getName(); message.setStringProperty(Environment.INDEX_NAME_JMS_PROPERTY, indexName); IndexManager indexManager = getExtendedSearchIntegrator().getIndexManagerHolder().getIndexManager(indexName); byte[] data = indexManager.getSerializer().toSerializedModel(queue); message.setObject(data); QueueSender sender = getQueueSession().createSender(getMessageQueue()); sender.send(message); }
/** * Envia un mensaje a JMS. * * @param mensaje */ public void send(String mensaje) throws Exception { try { QueueSender queueSender = queueSession.createSender(cola); TextMessage textMessage = queueSession.createTextMessage(mensaje); queueSender.send(textMessage); queueSender.close(); } catch (JMSException e) { e.printStackTrace(); } finally { c.close(); } }
public void execute(JobExecutionContext context) throws JobExecutionException { QueueConnectionFactory qcf = null; QueueConnection conn = null; QueueSession session = null; Queue queue = null; QueueSender sender = null; InitialContext ctx = null; final JobDetail detail = context.getJobDetail(); final JobDataMap jobDataMap = detail.getJobDataMap(); try { qcf = (QueueConnectionFactory) ctx.lookup(jobDataMap.getString(JmsHelper.JMS_CONNECTION_FACTORY_JNDI)); ctx = JmsHelper.getInitialContext(jobDataMap); if (JmsHelper.isDestinationSecure(jobDataMap)) { String user = jobDataMap.getString(JmsHelper.JMS_USER); String pw = jobDataMap.getString(JmsHelper.JMS_PASSWORD); conn = qcf.createQueueConnection(user, pw); } else { conn = qcf.createQueueConnection(); } boolean useTransactions = JmsHelper.useTransaction(jobDataMap); int ackMode = jobDataMap.getInt(JmsHelper.JMS_ACK_MODE); session = conn.createQueueSession(useTransactions, ackMode); String queueName = jobDataMap.getString(JmsHelper.JMS_DESTINATION_JNDI); queue = (Queue) ctx.lookup(queueName); sender = session.createSender(queue); String factoryClass = jobDataMap.getString(JmsHelper.JMS_MSG_FACTORY_CLASS_NAME); JmsMessageFactory factory = JmsHelper.getMessageFactory(factoryClass); Message m = factory.createMessage(jobDataMap, session); sender.send(m); } catch (NamingException e) { throw new JobExecutionException(e.getMessage()); } catch (JMSException e) { throw new JobExecutionException(e.getMessage()); } catch (JmsJobException e) { throw new JobExecutionException(e.getMessage()); } finally { JmsHelper.closeResource(sender); JmsHelper.closeResource(session); JmsHelper.closeResource(conn); } }
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 void send( MessageProducer producer, Message message, Destination dest, boolean persistent, int priority, long ttl, boolean topic) throws JMSException { if (topic && producer instanceof TopicPublisher) { ((TopicPublisher) producer) .publish( (Topic) dest, message, (persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT), priority, ttl); } else if (producer instanceof QueueSender) { ((QueueSender) producer) .send( (Queue) dest, message, (persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT), priority, ttl); } else { throw new IllegalArgumentException("Producer and domain type do not match"); } }
private static void writeMessage( String message, QueueSession session, QueueSender sender, long seqNo) throws JMSException { System.out.println("Message is:" + message); Message reqMes = session.createTextMessage(message); reqMes.setLongProperty("SequenceNumber", seqNo); sender.send(reqMes); }
/** This implementation overrides the superclass method to use JMS 1.0.2 API. */ protected void doSend(MessageProducer producer, Message message) throws JMSException { if (isPubSubDomain()) { if (isExplicitQosEnabled()) { ((TopicPublisher) producer) .publish(message, getDeliveryMode(), getPriority(), getTimeToLive()); } else { ((TopicPublisher) producer).publish(message); } } else { if (isExplicitQosEnabled()) { ((QueueSender) producer).send(message, getDeliveryMode(), getPriority(), getTimeToLive()); } else { ((QueueSender) producer).send(message); } } }
protected void send(final Message message) { try { m_sender.send(message); } catch (final Exception e) { getErrorHandler().error("Error publishing message", e, null); } }
@AroundInvoke public Object log(InvocationContext context) throws Exception { System.out.println("---" + context.getMethod()); QueueConnection conn = qcf.createQueueConnection(); conn.start(); QueueSession session = conn.createQueueSession(true, Session.SESSION_TRANSACTED); TextMessage msg = session.createTextMessage(); msg.setText( context.getMethod().getDeclaringClass().getSimpleName() + ";" + context.getMethod().getName() + ";" + sessionContext.getCallerPrincipal().getName()); QueueSender queueSender = session.createSender(queue); queueSender.send(msg); return context.proceed(); }
private void close(QueueSender sender) { try { if (sender != null) { sender.close(); } } catch (Exception e) { } }
/** * Sends a message to a queue. * * @param queueName * @param key Optional. * @param obj Mandatory. */ public void sendMsgToQueue(final String queueName, final String key, final Serializable obj) { log.debug("sendMsgToQueue(queueName, key, obj)::started"); QueueConnection conn = null; QueueSession session = null; QueueSender sender = null; try { final String jndiName = "queue/" + queueName; final Context ctx = getInitialContext(null); final QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup(CONNECTION_FACTORY); conn = factory.createQueueConnection(); session = conn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); final Queue queue = (Queue) ctx.lookup(jndiName); sender = session.createSender(queue); ObjectMessage message = session.createObjectMessage(); if (key == null) { message.setObject((Serializable) obj); } else { message.setObjectProperty(key, obj); } sender.send(message); } catch (NamingException e) { throw new LocatorException( "A naming exception occured while trying to send message " + obj + " to queue " + queueName, e); } catch (JMSException e) { throw new LocatorException( "A JMS exception occured while trying to send message " + obj + " to queue " + queueName, e); } finally { log.debug("sendMsgToQueue(queueName, key, obj)::finished"); close(sender); close(session); close(conn); } }
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); } }
/** * 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 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"); // 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 loan requests..."); } catch (JMSException jmse) { jmse.printStackTrace(); System.exit(1); } catch (Exception jmse) { jmse.printStackTrace(); System.exit(1); } }
public boolean publishMessage(String textMessage) throws NamingException, JMSException { setInitialContext(); setConnectionFactory(); createQueueConnection(); createQueueSession(); lookupQueue(); createQueueSender(); qSender.send(createTextMessage(textMessage)); return true; }
/** @param failedMailId */ public void callBack(String failedMailId) { try { Properties props = new Properties(); props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); props.setProperty("java.naming.provider.url", SenderConfig.getProp("callbackUrl")); props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming"); InitialContext ctx = new InitialContext(props); QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory"); QueueConnection queueConnection = factory.createQueueConnection(); QueueSession queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); Queue queue = (Queue) ctx.lookup("queue/" + SenderConfig.getProp("callbackJNDI")); ObjectMessage objMsg = queueSession.createObjectMessage(); objMsg.setObject(failedMailId); QueueSender queueSender = queueSession.createSender(queue); queueSender.send(objMsg); queueSession.close(); queueConnection.close(); } catch (Exception e) { log.error("sendMail/SendMailListener/Exception: [" + failedMailId + "]", e); } }
protected synchronized void closeConnection() { try { if (null != m_sender) m_sender.close(); if (null != m_session) m_session.close(); if (null != m_connection) m_connection.close(); } catch (Exception e) { getErrorHandler().error("Error closing connection", e, null); } m_sender = null; m_session = null; m_connection = null; }
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(); }
public void publish(int nr) throws JMSException { if (producer == null) producer = ((QueueSession) session).createSender((Queue) destination); if (creator == null) throw new JMSException("Publish must have a MessageCreator set"); creator.setSession(session); log.debug("Publishing " + nr + " messages"); for (int i = 0; i < nr; i++) { if (qosConfig != null) { ((QueueSender) producer) .send( creator.createMessage(i), qosConfig.deliveryMode, qosConfig.priority, qosConfig.ttl); } else { ((QueueSender) producer).send(creator.createMessage(i)); } messageHandled.incrementAndGet(); } if (session.getTransacted()) session.commit(); log.debug("Finished publishing"); }
/** * Overrides the superclass method to use the JMS 1.0.2 API to send a response. * * <p>Uses the JMS pub-sub API if the given destination is a topic, else uses the JMS queue API. */ protected void sendResponse(Session session, Destination destination, Message response) throws JMSException { MessageProducer producer = null; try { if (destination instanceof Topic) { producer = ((TopicSession) session).createPublisher((Topic) destination); postProcessProducer(producer, response); ((TopicPublisher) producer).publish(response); } else { producer = ((QueueSession) session).createSender((Queue) destination); postProcessProducer(producer, response); ((QueueSender) producer).send(response); } } finally { JmsUtils.closeMessageProducer(producer); } }
@Test(timeout = 30000) public void testSenderCloseAgain() throws Exception { // Close it again (closing the session should have closed it already). sender.close(); }
@Test(timeout = 30000, expected = javax.jms.IllegalStateException.class) public void testSenderGetQueueFails() throws Exception { sender.getQueue(); }
public void send() throws JMSException { testSender.send(queueSession.createTextMessage("message for queue")); }
public static void main(String[] args) throws Exception { InputStream is = TibcoSender.class.getClassLoader().getResourceAsStream("messages.properties"); if (is == null) { System.out.println("message.properties must be in classpath"); return; } Properties messages = new Properties(); messages.load(is); is.close(); QueueConnection queueCon = null; QueueSession queueSession = null; QueueSender sender = null; long idStart = 100003000l; Scanner in = new Scanner(System.in); System.out.print( "Enter amount of message you wish to send (set 0 to read amount from init.properties): "); int count = 0; try { count = in.nextInt(); } catch (Exception e) { System.out.println("Error in reading input."); } Properties initial = new Properties(); is = TibcoSender.class.getClassLoader().getResourceAsStream("init.properties"); if (is != null) { initial.load(is); String value = initial.getProperty("start.id"); if (value != null) idStart = Long.valueOf(value).longValue(); value = initial.getProperty("count"); if (value != null && count <= 0) count = Integer.valueOf(value).intValue(); } if (args.length > 0) { try { idStart = Long.valueOf(args[0]); if (args.length > 1) count = Integer.valueOf(args[1]); } catch (Exception e) { } } initial.setProperty("count", "" + count); initial.setProperty("start.id", "" + (idStart + count)); OutputStream os = null; if (is != null) { os = new FileOutputStream( new File( TibcoSender.class.getClassLoader().getResource("init.properties").getPath())); is.close(); } else { os = new FileOutputStream(new File("init.properties")); } initial.store(os, ""); os.close(); Properties config = new Properties(); is = TibcoSender.class.getClassLoader().getResourceAsStream("config.properties"); if (is != null) { config.load(is); is.close(); } try { // messages // InitialContext properties Properties props = new Properties(); props.setProperty(Context.INITIAL_CONTEXT_FACTORY, config.getProperty("JNDI_ICF")); props.setProperty(Context.PROVIDER_URL, config.getProperty("JNDI_URL")); // Jndi initialization InitialContext jndiContext = new InitialContext(props); // get the connection factory QueueConnectionFactory qcf = (QueueConnectionFactory) jndiContext.lookup(config.getProperty("JMS_QCF")); // and open a connection String user = config.getProperty("JMS_USER"); String password = config.getProperty("JMS_PASSWORD"); if (user != null && !user.isEmpty() && password != null && !password.isEmpty()) queueCon = qcf.createQueueConnection(user, password); else queueCon = qcf.createQueueConnection(); // Create a queue session using the connection queueSession = queueCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); // get handle on queue, create a sender and send the message Queue topic = (Queue) jndiContext.lookup(config.getProperty("JMS_QUEUE")); sender = queueSession.createSender(topic); long i = 0; // new message index to be inserted into content of the message String[] cps = { "USD/HUF", "GBP/USD", "GBP/USD", "GBP/USD", "GBP/USD", "AUD/USD", "AUD/USD", "AUD/USD", "AUD/USD", "EUR/NOK", "USD/CZK", "EUR/USD", "EUR/JPY", "USD/HUF", "USD/SGD", "SGD/CHF" }; String[] valuedates = new String [0]; // {"20110803", "20110810", "20110817", "20110824", "20110831", "20110913", // "20110926"}; String[] tenors = {"SPOT", "TN", "1W", "1W", "SPOT", "2W", "1M", "1W", "SPOT", "SPOT", "1W"}; String[] clients = { "002-230", "003-0582", "004-0986", "Paypal1US", "003-0291" }; // FXB_OPERATINGCLIENT.APICLIENTID String tradeDate = date.format(new Date()); for (int j = 0; j < count; j++) { i = idStart + j; String message = createMessage( idStart, i, j, cps, valuedates, tenors, clients, tradeDate, config, messages); // send message to topic at server. writeMessage(message, queueSession, sender, i); } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { // close sender, topic session and topic connection if (sender != null) { sender.close(); sender = null; } if (queueSession != null) { queueSession.close(); queueSession = null; } if (queueCon != null) { queueCon.close(); queueCon = null; } } }