List of usage examples for javax.jms TextMessage setText
void setText(String string) throws JMSException;
From source file:io.datalayer.activemq.producer.SimpleProducer.java
/** * @param args the destination name to send to and optionally, the number of * messages to send/*from w ww . j av a 2 s.c o m*/ */ public static void main(String... args) { Context jndiContext = null; ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; Destination destination = null; MessageProducer producer = null; String destinationName = null; final int numMsgs; if ((args.length < 1) || (args.length > 2)) { LOG.info("Usage: java SimpleProducer <destination-name> [<number-of-messages>]"); System.exit(1); } destinationName = args[0]; LOG.info("Destination name is " + destinationName); if (args.length == 2) { numMsgs = (new Integer(args[1])).intValue(); } else { numMsgs = 1; } /* * Create a JNDI API InitialContext object */ 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 destination. */ try { connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory"); destination = (Destination) jndiContext.lookup(destinationName); } 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 { connection = connectionFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(destination); TextMessage message = session.createTextMessage(); for (int i = 0; i < numMsgs; i++) { message.setText("This is message " + (i + 1)); LOG.info("Sending message: " + message.getText()); producer.send(message); } /* * Send a non-text control message indicating end of messages. */ producer.send(session.createMessage()); } catch (JMSException e) { LOG.info("Exception occurred: " + e); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } }
From source file:org.sdnmq.jms_demoapps.SimplePacketSender.java
public static void main(String[] args) { // Standard JMS setup. try {/*from ww w .j a va 2s. c o m*/ // Uses settings from file jndi.properties if file is in CLASSPATH. ctx = new InitialContext(); } catch (NamingException e) { System.err.println(e.getMessage()); die(-1); } try { queueFactory = (QueueConnectionFactory) ctx.lookup("QueueConnectionFactory"); } catch (NamingException e) { System.err.println(e.getMessage()); die(-1); } try { connection = queueFactory.createQueueConnection(); } catch (JMSException e) { System.err.println(e.getMessage()); die(-1); } try { session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); } catch (JMSException e) { System.err.println(e.getMessage()); die(-1); } try { packetForwarderQueue = (Queue) ctx.lookup(PACKETFORWARDER_QUEUE_NAME); } catch (NameNotFoundException e) { System.err.println(e.getMessage()); die(-1); } catch (NamingException e) { System.err.println(e.getMessage()); die(-1); } try { sender = session.createSender(packetForwarderQueue); } catch (JMSException e) { System.err.println(e.getMessage()); die(-1); } try { connection.start(); } catch (JMSException e) { System.err.println(e.getMessage()); die(-1); } // Create packet using OpenDaylight packet classes (or any other packet parser/constructor you like most) // In most use cases, you will not create the complete packet yourself from scratch // but rather use a packet received from a packet-in event as basis. Let's assume that // the received packet-in event looks like this (in JSON representation as delivered by // the packet-in handler): // // {"node":{"id":"00:00:00:00:00:00:00:01","type":"OF"},"ingressPort":"1","protocol":1,"etherType":2048,"nwDst":"10.0.0.2","packet":"Io6q62g3mn66JKnjCABFAABUAABAAEABJqcKAAABCgAAAggAGFlGXgABELmmUwAAAAAVaA4AAAAAABAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc=","dlDst":"22:8E:AA:EB:68:37","nwSrc":"10.0.0.1","dlSrc":"9A:7E:BA:24:A9:E3"} // // Thus, we can use the "packet" field to re-construct the raw packet data from Base64-encoding: String packetInBase64 = "Io6q62g3mn66JKnjCABFAABUAABAAEABJqcKAAABCgAAAggAGFlGXgABELmmUwAAAAAVaA4AAAAAABAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc="; byte[] packetData = DatatypeConverter.parseBase64Binary(packetInBase64); // Now we can use the OpenDaylight classes to get Java objects for this packet: Ethernet ethPkt = new Ethernet(); try { ethPkt.deserialize(packetData, 0, packetData.length * 8); } catch (Exception e) { System.err.println("Failed to decode packet"); die(-1); } if (ethPkt.getEtherType() == 0x800) { IPv4 ipv4Pkt = (IPv4) ethPkt.getPayload(); // We could go on parsing layer by layer ... but you got the idea already I think. // So let's make some change to the packet to make it more interesting: InetAddress newDst = null; try { newDst = InetAddress.getByName("10.0.0.2"); } catch (UnknownHostException e) { die(-1); } assert (newDst != null); ipv4Pkt.setDestinationAddress(newDst); } // Now we can get the binary data of the new packet to be forwarded. byte[] pktBinary = null; try { pktBinary = ethPkt.serialize(); } catch (PacketException e1) { System.err.println("Failed to serialize packet"); die(-1); } assert (pktBinary != null); // Encode packet to Base64 textual representation to be sent in JSON. String pktBase64 = DatatypeConverter.printBase64Binary(pktBinary); // We need to tell the packet forwarder, which node should forward the packet. // In OpenDaylight, a node is identified by node id and node type (like "OF" for OpenFlow). // For a list of all node attributes, cf. class NodeAttributes. // For a list of possible node types, cf. class NodeAttributes.TypeValues. JSONObject nodeJson = new JSONObject(); String nodeId = "00:00:00:00:00:00:00:01"; nodeJson.put(NodeAttributes.Keys.ID.toJSON(), nodeId); nodeJson.put(NodeAttributes.Keys.TYPE.toJSON(), NodeAttributes.TypeValues.OF.toJSON()); // Create a packet forwarding request in JSON representation. // All attributes are described in class PacketForwarderRequestAttributes. JSONObject packetFwdRequestJson = new JSONObject(); packetFwdRequestJson.put(PacketForwarderRequestAttributes.Keys.NODE.toJSON(), nodeJson); packetFwdRequestJson.put(PacketForwarderRequestAttributes.Keys.EGRESS_PORT.toJSON(), 1); packetFwdRequestJson.put(PacketForwarderRequestAttributes.Keys.PACKET.toJSON(), pktBase64); // Send the request by posting it to the packet forwarder queue. System.out.println("Sending packet forwarding request: "); System.out.println(packetFwdRequestJson.toString()); try { TextMessage msg = session.createTextMessage(); msg.setText(packetFwdRequestJson.toString()); sender.send(msg); } catch (JMSException e) { System.err.println(e.getMessage()); die(-1); } die(0); }
From source file:org.sdnmq.jms_demoapps.SimpleStaticFlowProgrammer.java
public static void main(String[] args) { // Standard JMS setup. try {//from w ww .j a va 2s.co m // Uses settings from file jndi.properties if file is in CLASSPATH. ctx = new InitialContext(); } catch (NamingException e) { System.err.println(e.getMessage()); die(-1); } try { queueFactory = (QueueConnectionFactory) ctx.lookup("QueueConnectionFactory"); } catch (NamingException e) { System.err.println(e.getMessage()); die(-1); } try { connection = queueFactory.createQueueConnection(); } catch (JMSException e) { System.err.println(e.getMessage()); die(-1); } try { session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); } catch (JMSException e) { System.err.println(e.getMessage()); die(-1); } try { flowProgrammerQueue = (Queue) ctx.lookup(FLOWPROGRAMMER_QUEUE_NAME); } catch (NameNotFoundException e) { System.err.println(e.getMessage()); die(-1); } catch (NamingException e) { System.err.println(e.getMessage()); die(-1); } try { sender = session.createSender(flowProgrammerQueue); } catch (JMSException e) { System.err.println(e.getMessage()); die(-1); } try { connection.start(); } catch (JMSException e) { System.err.println(e.getMessage()); die(-1); } // First, create the flow specification as JSON object. // A flow consists of a match, set of actions, and priority. // The match: for a list of all possible match attributes, cf. class MatchAttributes. JSONObject matchJson = new JSONObject(); String inPort = "1"; matchJson.put(MatchAttributes.Keys.INGRESS_PORT.toJSON(), inPort); // The action: for a list of all possible action attributes, cf. class ActionAttributes. JSONObject actionJson = new JSONObject(); actionJson.put(ActionAttributes.Keys.ACTION.toJSON(), ActionAttributes.ActionTypeValues.DROP.toJSON()); // A flow can have a list of different actions. We specify a list of actions // as JSON array (here, the array only contains one action). JSONArray actionsJson = new JSONArray(); actionsJson.put(actionJson); // The flow consists of a match specification, action specification, and priority // (cf. class FlowAttributes) JSONObject flowJson = new JSONObject(); flowJson.put(FlowAttributes.Keys.MATCH.toJSON(), matchJson); flowJson.put(FlowAttributes.Keys.ACTIONS.toJSON(), actionsJson); flowJson.put(FlowAttributes.Keys.PRIORITY.toJSON(), 0); // We need to tell the flow programmer, which node to program. // In OpenDaylight, a node is identified by node id and node type (like "OF" for OpenFlow). // For a list of all node attributes, cf. class NodeAttributes. // For a list of possible node types, cf. class NodeAttributes.TypeValues. JSONObject nodeJson = new JSONObject(); String nodeId = "00:00:00:00:00:00:00:01"; nodeJson.put(NodeAttributes.Keys.ID.toJSON(), nodeId); nodeJson.put(NodeAttributes.Keys.TYPE.toJSON(), NodeAttributes.TypeValues.OF.toJSON()); // Create the FlowProgrammer request in JSON representation. // To add a flow, we need to specify the command, the flow, and the node to be programmed // (cf. class FlowProgrammerRequestAttributes). JSONObject addRequestJson = new JSONObject(); // All possible commands are specified in FlowProgrammerRequestAttributes.CommandValues addRequestJson.put(FlowProgrammerRequestAttributes.Keys.COMMAND.toJSON(), FlowProgrammerRequestAttributes.CommandValues.ADD.toJSON()); String flowName = "DemoFlow"; addRequestJson.put(FlowProgrammerRequestAttributes.Keys.FLOW_NAME.toJSON(), flowName); addRequestJson.put(FlowProgrammerRequestAttributes.Keys.FLOW.toJSON(), flowJson); addRequestJson.put(FlowProgrammerRequestAttributes.Keys.NODE.toJSON(), nodeJson); // Program the flow by sending the request to the flow programmer queue. System.out.println("Programming flow with following request: "); System.out.println(addRequestJson.toString()); try { TextMessage msg = session.createTextMessage(); msg.setText(addRequestJson.toString()); sender.send(msg); } catch (JMSException e) { System.err.println(e.getMessage()); die(-1); } // Delete the flow again after 10 s. System.out.println("Waiting 30 s ..."); try { Thread.sleep(30000); } catch (InterruptedException e) { } // A delete request just contains the flow name to be deleted together with the delete command. JSONObject deleteRequestJson = new JSONObject(); deleteRequestJson.put(FlowProgrammerRequestAttributes.Keys.COMMAND.toJSON(), FlowProgrammerRequestAttributes.CommandValues.DELETE.toJSON()); deleteRequestJson.put(FlowProgrammerRequestAttributes.Keys.FLOW_NAME.toJSON(), flowName); // Delete the flow by sending the delete request to the flow programmer queue. System.out.println("Deleting flow with the following request: "); System.out.println(deleteRequestJson.toString()); try { TextMessage msg = session.createTextMessage(); msg.setText(deleteRequestJson.toString()); sender.send(msg); } catch (JMSException e) { System.err.println(e.getMessage()); die(-1); } die(0); }
From source file:org.apache.uima.examples.as.GetMetaRequest.java
/** * retrieve meta information for a UIMA-AS Service attached to a broker * It uses the port 1099 as the JMX port on the broker, unless overridden * by defining the system property activemq.broker.jmx.port with a value of another port number * It uses the default JMX ActiveMQ Domain "org.apache.activemq", unless overridden * by defining the system property activemq.broker.jmx.domain with a value of the domain to use * This normally never needs to be done unless multiple brokers are run on the same node * as is sometimes done for unit tests. * @param args - brokerUri serviceName [-verbose] *//* w w w .j a v a2s . c o m*/ public static void main(String[] args) { if (args.length < 2) { System.err.println("Need arguments: brokerURI serviceName [-verbose]"); System.exit(1); } String brokerURI = args[0]; String queueName = args[1]; boolean printReply = false; if (args.length > 2) { if (args[2].equalsIgnoreCase("-verbose")) { printReply = true; } else { System.err.println("Unknown argument: " + args[2]); System.exit(1); } } final Connection connection; Session producerSession = null; Queue producerQueue = null; MessageProducer producer; MessageConsumer consumer; Session consumerSession = null; TemporaryQueue consumerDestination = null; long startTime = 0; // Check if JMX server port number was specified jmxPort = System.getProperty("activemq.broker.jmx.port"); if (jmxPort == null || jmxPort.trim().length() == 0) { jmxPort = "1099"; // default } try { // First create connection to a broker ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); connection = factory.createConnection(); connection.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { if (connection != null) { connection.close(); } if (jmxc != null) { jmxc.close(); } } catch (Exception ex) { } } })); URI target = new URI(brokerURI); String brokerHost = target.getHost(); attachToRemoteBrokerJMXServer(brokerURI); if (isQueueAvailable(queueName) == QueueState.exists) { System.out.println("Queue " + queueName + " found on " + brokerURI); System.out.println("Sending getMeta..."); } else if (isQueueAvailable(queueName) == QueueState.existsnot) { System.err.println("Queue " + queueName + " does not exist on " + brokerURI); System.exit(1); } else { System.out.println("Cannot see queues on JMX port " + brokerHost + ":" + jmxPort); System.out.println("Sending getMeta anyway..."); } producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producerQueue = producerSession.createQueue(queueName); producer = producerSession.createProducer(producerQueue); consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); consumerDestination = consumerSession.createTemporaryQueue(); // ----------------------------------------------------------------------------- // Create message consumer. The consumer uses a selector to filter out messages other // then GetMeta replies. Currently UIMA AS service returns two messages for each request: // ServiceInfo message and GetMeta message. The ServiceInfo message is returned by the // service immediately upon receiving a message from a client. This serves dual purpose, // 1) to make sure the client reply destination exists // 2) informs the client which service is processing its request // ----------------------------------------------------------------------------- consumer = consumerSession.createConsumer(consumerDestination, "Command=2001"); TextMessage msg = producerSession.createTextMessage(); msg.setStringProperty(AsynchAEMessage.MessageFrom, consumerDestination.getQueueName()); msg.setStringProperty(UIMAMessage.ServerURI, brokerURI); msg.setIntProperty(AsynchAEMessage.MessageType, AsynchAEMessage.Request); msg.setIntProperty(AsynchAEMessage.Command, AsynchAEMessage.GetMeta); msg.setJMSReplyTo(consumerDestination); msg.setText(""); producer.send(msg); startTime = System.nanoTime(); System.out.println("Sent getMeta request to " + queueName + " at " + brokerURI); System.out.println("Waiting for getMeta reply..."); ActiveMQTextMessage reply = (ActiveMQTextMessage) consumer.receive(); long waitTime = (System.nanoTime() - startTime) / 1000000; System.out.println( "Reply from " + reply.getStringProperty("ServerIP") + " received in " + waitTime + " ms"); if (printReply) { System.out.println("Reply MessageText: " + reply.getText()); } } catch (Exception e) { System.err.println(e.toString()); } System.exit(0); }
From source file:org.apache.activemq.demo.SimpleQueueSender.java
/** * Main method.// ww w. ja 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:io.datalayer.activemq.producer.SimpleQueueSender.java
/** * Main method./*from ww w .java2 s . co 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:example.transaction.Client.java
private static void acceptInputFromUser(Session senderSession, MessageProducer sender) throws JMSException { System.out.println("Type a message. Type COMMIT to send to receiver, type ROLLBACK to cancel"); Scanner inputReader = new Scanner(System.in); while (true) { String line = inputReader.nextLine(); if (line == null) { System.out.println("Done!"); break; } else if (line.length() > 0) { if (line.trim().equals("ROLLBACK")) { System.out.println("Rolling back..."); senderSession.rollback(); System.out.println("Messages have been rolledback"); } else if (line.trim().equals("COMMIT")) { System.out.println("Committing... "); senderSession.commit();//from w w w . j a va 2 s . c om System.out.println("Messages should have been sent"); } else { TextMessage message = senderSession.createTextMessage(); message.setText(line); System.out.println("Batching up:'" + message.getText() + "'"); sender.send(message); } } } }
From source file:org.easybatch.tutorials.advanced.jms.JMSUtil.java
public static void sendStringRecord(String jmsMessage) throws JMSException { TextMessage message = queueSession.createTextMessage(); message.setText(jmsMessage); queueSender.send(message);/*from w ww. j a v a 2 s.c o m*/ System.out.println("Message '" + jmsMessage + "' sent to JMS queue"); }
From source file:org.easybatch.tutorials.advanced.jms.JMSUtil.java
public static void sendStringRecord(StringRecord stringRecord) throws JMSException { TextMessage message = queueSession.createTextMessage(); message.setText(stringRecord.getPayload()); queueSender.send(message);// w w w .j a v a2 s .com System.out.println("Message '" + stringRecord.getPayload() + "' sent to JMS queue"); }
From source file:org.wso2.carbon.sample.jmsclient.JMSClientUtil.java
/** * 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 *//*from w ww . j a v a 2s . c o m*/ 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); } }