@Override public void onMessage(Message message) { try { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText(); if ("SHUTDOWN".equals(text)) { LOG.info("Got the SHUTDOWN command -> exit"); producer.send(session.createTextMessage("SHUTDOWN is being performed")); } else if ("REPORT".equals(text)) { long time = System.currentTimeMillis() - start; producer.send(session.createTextMessage("Received " + count + " in " + time + "ms")); try { Thread.sleep(500); } catch (InterruptedException e) { LOG.info("Wait for the report message to be sent was interrupted"); } count = 0; } else { if (count == 0) { start = System.currentTimeMillis(); } count++; LOG.info("Received " + count + " messages."); } } } catch (JMSException e) { LOG.error("Got an JMS Exception handling message: " + message, e); } }
/** * Each message will be divided into groups and create the map message * * @param producer Used for sending messages to a destination * @param session Used to produce the messages to be sent * @param messagesList List of messages to be sent */ public static void publishTextMessage( MessageProducer producer, Session session, List<String> messagesList) throws JMSException { for (String message : messagesList) { TextMessage jmsMessage = session.createTextMessage(); jmsMessage.setText(message); producer.send(jmsMessage); } }
public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); ConnectionFactory cf; Destination dest; try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); cf = (ConnectionFactory) envCtx.lookup("jms/connectionFactory"); dest = (Destination) envCtx.lookup(QUEUE_NAME); } catch (NamingException e) { throw new RuntimeException(e); } Connection connection = null; try { connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(dest); TextMessage message = session.createTextMessage(); for (int i = 0; i < NUM_MSGS; i++) { message.setText("This is message " + (i + 1)); log.info("Sending message: " + message.getText()); producer.send(message); } producer.send(session.createTextMessage()); } catch (JMSException e) { throw new RuntimeException(e); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } out.write("<p>Wrote " + NUM_MSGS + " to queue " + QUEUE_NAME + " followed by a blank.</p>"); out.close(); }
private void sendTextMessage(String msg) throws Exception { try (Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer publisher = session.createProducer(queue); ) { connection.start(); TextMessage message = session.createTextMessage(msg); publisher.send(message); } }
public void sendReply(Message request, int sum) { try { MessageProducer MP = session.createProducer(null); Destination reply = request.getJMSReplyTo(); TextMessage TM = session.createTextMessage(); TM.setText("" + sum); MP.send(reply, TM); } catch (JMSException JMSE) { System.out.println("JMS Exception: " + JMSE); } }
public static void main(String[] args) throws JMSException { String user = env("ACTIVEMQ_USER", ""); String password = env("ACTIVEMQ_PASSWORD", ""); String host = env("ACTIVEMQ_HOST", "localhost"); int port = Integer.parseInt(env("ACTIVEMQ_PORT", "61616")); String destination = arg(args, 0, "foo.bar"); int messages = 10; int size = 256; String DATA = "abcdefghijklmnopqrstuvwxyz"; String body = ""; for (int i = 0; i < size; i++) { body += DATA.charAt(i % DATA.length()); } ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( "tcp://" + host + ":" + port + "?jms.useAsyncSend=false&jms.alwaysSyncSend=true"); Connection connection = factory.createConnection(user, password); logger.info("Connection created"); connection.start(); logger.info("Connection started"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination dest = new ActiveMQQueue(destination); MessageProducer producer = session.createProducer(dest); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); for (int i = 1; i <= messages; i++) { TextMessage msg = session.createTextMessage(body); msg.setIntProperty("id", i); producer.send(msg); logger.info("Message send" + i); } producer.send(session.createTextMessage("THE.END")); connection.close(); logger.info("Connection closed"); }
public boolean send(@NotNull Value value, @Optional JMSQueue replyTo) throws JMSException { Message message = null; if (value.isArray()) { message = _session.createMapMessage(); ArrayValue array = (ArrayValue) value; Set<Map.Entry<Value, Value>> entrySet = array.entrySet(); for (Map.Entry<Value, Value> entry : entrySet) { if (entry.getValue() instanceof BinaryValue) { byte[] bytes = ((BinaryValue) entry.getValue()).toBytes(); ((MapMessage) message).setBytes(entry.getKey().toString(), bytes); } else { // every primitive except for bytes can be translated from a string ((MapMessage) message).setString(entry.getKey().toString(), entry.getValue().toString()); } } } else if (value instanceof BinaryValue) { message = _session.createBytesMessage(); byte[] bytes = ((BinaryValue) value).toBytes(); ((BytesMessage) message).writeBytes(bytes); } else if (value.isLongConvertible()) { message = _session.createStreamMessage(); ((StreamMessage) message).writeLong(value.toLong()); } else if (value.isDoubleConvertible()) { message = _session.createStreamMessage(); ((StreamMessage) message).writeDouble(value.toDouble()); } else if (value.toJavaObject() instanceof String) { message = _session.createTextMessage(); ((TextMessage) message).setText(value.toString()); } else if (value.toJavaObject() instanceof Serializable) { message = _session.createObjectMessage(); ((ObjectMessage) message).setObject((Serializable) value.toJavaObject()); } else { return false; } if (replyTo != null) message.setJMSReplyTo(replyTo._destination); _producer.send(message); return true; }
public static void main(String[] args) throws JMSException { String user = env("ACTIVEMQ_USER", "admin"); String password = env("ACTIVEMQ_PASSWORD", "password"); String host = env("ACTIVEMQ_HOST", "localhost"); int port = Integer.parseInt(env("ACTIVEMQ_PORT", "61616")); String destination = arg(args, 0, "event"); int messages = 10000; int size = 256; String DATA = "abcdefghijklmnopqrstuvwxyz"; String body = ""; for (int i = 0; i < size; i++) { body += DATA.charAt(i % DATA.length()); } ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://" + host + ":" + port); Connection connection = factory.createConnection(user, password); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination dest = new ActiveMQTopic(destination); MessageProducer producer = session.createProducer(dest); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); for (int i = 1; i <= messages; i++) { TextMessage msg = session.createTextMessage(body); msg.setIntProperty("id", i); producer.send(msg); if ((i % 1000) == 0) { System.out.println(String.format("Sent %d messages", i)); } } producer.send(session.createTextMessage("SHUTDOWN")); connection.close(); }
public static void main(String[] args) throws JMSException { String uri = "failover://tcp://103.224.81.184:61616"; ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uri); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); Topic topic = session.createTopic("topic1"); MessageProducer producer = session.createProducer(topic); TextMessage textMessage = session.createTextMessage("HelloWorld4"); producer.send(textMessage); connection.start(); producer.close(); session.close(); connection.close(); }
// Sends a message using the exchange name over qpid private void sendMessage(String message, String exchangeName) { TextMessage textMessage; properties.setProperty("topic" + "." + "cow", exchangeName); try { context = new InitialContext(properties); Destination destination = (Destination) context.lookup("cow"); messageProducer = session.createProducer(destination); textMessage = session.createTextMessage(message); messageProducer.send(textMessage); } catch (Exception e) { log.debug(e.getMessage()); initialized = false; } }
/** * Send a text message given a queue or topic name and a text message. * * @param destinationName destinationName * @param messageContent messageContent */ public void sendTextMessageWithDestination( final String destinationName, final String messageContent) { if (!this.isConnected()) { throw new JmsNotConnectedException("JMS connection is down " + destinationName); } final Session session = getSession(); final MessageProducer producer = getProducer(destinationName); try { TextMessage message = session.createTextMessage(messageContent); producer.send(message); } catch (JMSException e) { throw new IllegalStateException("Unable to send message to " + destinationName, e); } }
private void sendJmsMessage() { String message = "Salutation generated for MDB"; try { Connection connection = queueConnectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = (MessageProducer) session.createProducer(queue); TextMessage textMessage = session.createTextMessage(); textMessage.setText(message); messageProducer.send(textMessage); Logger.getLogger("SalutationLog") .log(Level.WARNING, "Message sent successfully", "Message sent successfully2"); } catch (JMSException e) { e.printStackTrace(); } }
public void _sendOne(String topic, String msg) { Session session = null; try { session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(topic); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.PERSISTENT); TextMessage message = session.createTextMessage(JSON.toJSONString(msg)); producer.send(message); session.commit(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != session) session.close(); } catch (Throwable ignore) { } } }
@Override public boolean offer(T event) throws FalconException { Session session; try { session = getSession(); TextMessage msg = session.createTextMessage(event.toString()); msg.setLongProperty( ScheduledMessage.AMQ_SCHEDULED_DELAY, event.getDelay(TimeUnit.MILLISECONDS)); msg.setStringProperty("TYPE", event.getType().name()); producer.send(msg); LOG.debug( "Enqueued Message: {} with delay {} milli sec", event.toString(), event.getDelay(TimeUnit.MILLISECONDS)); return true; } catch (Exception e) { LOG.error("Unable to offer event: {} to ActiveMQ", event, e); throw new FalconException("Unable to offer event:" + event + " to ActiveMQ", e); } }
/** * Sends a command into a queue for processing * * @param queueName name of queue * @param command command to process * @param deliveryMode delivery mode: {@link javax.jms.DeliveryMode}. * @param priority priority of the message. Correct values are from 0 to 9, with higher number * denoting a higher priority. * @param timeToLive the message's lifetime (in milliseconds, where 0 is to never expire) */ public void send( String queueName, Command command, int deliveryMode, int priority, int timeToLive) { try { checkRange(deliveryMode, 1, 2, "delivery mode"); checkRange(priority, 0, 9, "priority"); if (timeToLive < 0) throw new HornetNestException("time to live cannot be negative"); Queue queue = (Queue) jmsServer.lookup("/queue/" + queueName); if (queue == null) throw new HornetNestException("Failed to find queue: " + queueName); Session session = producerConnection.createSession(); TextMessage msg = session.createTextMessage(command.toString()); msg.setStringProperty("command_class", command.getClass().getName()); MessageProducer p = session.createProducer(queue); p.send(msg, deliveryMode, priority, timeToLive); } catch (HornetNestException e) { throw e; } catch (Exception e) { throw new HornetNestException("Failed to send message", e); } }
public void sendOne(String topic, String msg) { long s = System.currentTimeMillis(); Session session = null; try { session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(topic); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.PERSISTENT); TextMessage message = session.createTextMessage(msg); producer.send(message); session.commit(); logger.info("cost: {}ms {}/{}", System.currentTimeMillis() - s, topic, msg); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != session) session.close(); } catch (Throwable ignore) { } } }
public void send(ExampleCommand command, String queueName, String filter) throws JMSException, IOException { try (Session session = connection.createSession()) { Message message; if (binaryMode) { message = session.createBytesMessage(); ((BytesMessage) message).writeBytes(command.toBytes()); } else { message = session.createTextMessage(command.toXml()); } if (filter != null && !blank(filter)) { String[] parts = filter.split("\\s*=\\s*"); message.setStringProperty(parts[0], parts[1]); } try (MessageProducer p = session.createProducer(ActiveMQJMSClient.createQueue(queueName))) { p.send(message, DeliveryMode.PERSISTENT, 4, 0); } } }
public void run() throws JMSException { ConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueName); MessageProducer producer = session.createProducer(destination); Message message = null; for (int i = 0; i < 10; i++) { System.out.println("Creating Message " + i); message = session.createTextMessage("Hello World! " + i); producer.send(message); } if (connection != null) { connection.close(); } }
// envoyer un messsage à l'ESB public void ecrireMessage(String messageXML) throws JMSException, NamingException { // BasicConfigurator.configure(); // Obtention de connexion JMS e partir du serveur ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); Connection connection = connectionFactory.createConnection(); connection.start(); try { // Creation de session (Messages JMS sont envoyes et recus en utilisant une session) Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Destination de la file Destination destination = session.createQueue(subject); // MessageProducer est utilise pour l'envoi de messages MessageProducer producer = session.createProducer(destination); // le message transferer TextMessage message = session.createTextMessage(messageXML); // Transfert de message vers la file ( L'ESB) producer.send(message); // System.out.println("message envoye : " + message.getText() + ""); } finally { connection.close(); } }
public static Message createMessage(Session session, Class messageClazz) throws JMSException { if (session == null) { throw new JMSException("session cannot be null"); } if (Message.class.isAssignableFrom(messageClazz)) { throw new JMSException("cannot create message of type: " + messageClazz.getName()); } if (TextMessage.class.equals(messageClazz)) { return session.createTextMessage(); } else if (StreamMessage.class.equals(messageClazz)) { return session.createStreamMessage(); } else if (MapMessage.class.equals(messageClazz)) { return session.createMapMessage(); } else if (ObjectMessage.class.equals(messageClazz)) { return session.createObjectMessage(); } else if (BytesMessage.class.equals(messageClazz)) { return session.createBytesMessage(); } else if (Message.class.equals(messageClazz)) { return session.createMessage(); } else { throw new JMSException("cannot create message of type: " + messageClazz.getName()); } }
public static void main(String... args) throws Exception { ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; MessageProducer producer = null; MessageConsumer consumer = null; Destination destination = null; TextMessage message = null; Context context = null; try { // Set up the context for the JNDI lookup final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY); env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL)); env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME)); env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD)); context = new InitialContext(env); // Perform the JNDI lookups String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY); log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\""); connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString); log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI"); String destinationString = System.getProperty("destination", DEFAULT_DESTINATION); log.info("Attempting to acquire destination \"" + destinationString + "\""); destination = (Destination) context.lookup(destinationString); log.info("Found destination \"" + destinationString + "\" in JNDI"); // Create the JMS connection, session, producer, and consumer connection = connectionFactory.createConnection( System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD)); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(destination); consumer = session.createConsumer(destination); connection.start(); int count = Integer.parseInt(System.getProperty("message.count", DEFAULT_MESSAGE_COUNT)); String content = System.getProperty("message.content", DEFAULT_MESSAGE); log.info("Sending " + count + " messages with content: " + content); // Send the specified number of messages for (int i = 0; i < count; i++) { message = session.createTextMessage(content); producer.send(message); } // Then receive the same number of messages that were sent for (int i = 0; i < count; i++) { message = (TextMessage) consumer.receive(5000); log.info("Received message with content " + message.getText()); } } catch (Exception exception) { log.severe(exception.getMessage()); throw exception; } finally { if (context != null) { context.close(); } // closing the connection takes care of the session, producer, and consumer if (connection != null) { connection.close(); } } }
// @Test public void testFetchGraphSimple() { try { String neId = "21100799"; String group = "bw"; // interesting for the BW String titleX = "Bandwidth"; String titleY = "bps"; int timespan = 0; // Daily /* String neId = "1005255"; String group = "cpu"; // interesting for the CPU String titleX = "CPU Utilization"; String titleY = "Utilization"; int timespan = 0; // Daily */ FetchGraphSimpleCommandMessage message = CommandMessageFactory.createRRDGraphSimpleCommandMessage( neId, group, timespan, titleX, titleY); MessageProducer producer = null; MessageConsumer consumer = null; try { // time to send the JMS request TextMessage reqMsg; Message replyMsg; producer = session.createProducer(new HornetQQueue(SERVICE_QUEUE)); // this will uniquelly identify the request String UIID = UUID.randomUUID().toString(); reqMsg = session.createTextMessage(); reqMsg.setStringProperty("ServiceRRD_msg_type", "fetchGraphSimple"); reqMsg.setStringProperty("ServiceRRD_correlation_id", UIID); String body = JsonUtil.getInstance().toJSON(message); reqMsg.setText(body); logger.info("SEND:\n" + body); producer.send(reqMsg); consumer = session.createConsumer( new HornetQQueue(SERVICE_REPLY_QUEUE), "ServiceRRD_correlation_id = '" + UIID + "'"); replyMsg = consumer.receive(30000); if (replyMsg == null) { logger.info("ServiceRRD timeout on receive()"); } else { if (replyMsg instanceof BytesMessage) { BytesMessage graphStream = (BytesMessage) replyMsg; byte[] graph = new byte[(int) graphStream.getBodyLength()]; graphStream.readBytes(graph); FileOutputStream image = new FileOutputStream( "/Users/cvasilak/Temp/svc-rrd-images/" + neId + "_" + group + "_" + timespan + ".png"); image.write(graph); image.close(); logger.info("image retrieved and saved!"); } else if (replyMsg instanceof TextMessage) { // the server responded with an error logger.info(((TextMessage) replyMsg).getText()); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (producer != null) producer.close(); if (consumer != null) consumer.close(); } catch (JMSException e) { } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Test public void testFetchLast() { try { String neId = "1005255"; // KLNNMS02(cpuusage=YES cpu1min=YES memutil=YES) KLNNMS05(cpuusage=YES // bususage=YES) // String neId = "1006119"; // KLNNMS02(cpuusage=YES cpu1min=YES memutil=YES // KLNNMS05(cpuusage=NO bususage=NO) Set<String> rras = new HashSet<String>(); // klnnms02 rras.add("cpu5sec"); rras.add("cpu1min"); rras.add("memutil"); // klnnms05 rras.add("cpuusage"); rras.add("bususage"); FetchLastCommandMessage message = CommandMessageFactory.createRRDLastCommandMessage(neId, "AVERAGE", 0, 0, null, rras); MessageProducer producer = null; MessageConsumer consumer = null; // time to send the JMS request try { TextMessage reqMsg, replyMsg; producer = session.createProducer(new HornetQQueue(SERVICE_QUEUE)); // this will uniquelly identify the request String UIID = UUID.randomUUID().toString(); reqMsg = session.createTextMessage(); reqMsg.setStringProperty("ServiceRRD_msg_type", "fetchLast"); reqMsg.setStringProperty("ServiceRRD_correlation_id", UIID); String body = JsonUtil.getInstance().toJSON(message); reqMsg.setText(body); logger.info("SEND:\n" + body); producer.send(reqMsg); consumer = session.createConsumer( new HornetQQueue(SERVICE_REPLY_QUEUE), "ServiceRRD_correlation_id = '" + UIID + "'"); replyMsg = (TextMessage) consumer.receive(30000); if (replyMsg == null) { logger.info("ServiceRRD timeout on receive()"); } else { logger.info("REPLY:\n" + replyMsg.getText()); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (producer != null) producer.close(); if (consumer != null) consumer.close(); } catch (JMSException e) { } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }