Example usage for javax.jms Session AUTO_ACKNOWLEDGE

List of usage examples for javax.jms Session AUTO_ACKNOWLEDGE

Introduction

In this page you can find the example usage for javax.jms Session AUTO_ACKNOWLEDGE.

Prototype

int AUTO_ACKNOWLEDGE

To view the source code for javax.jms Session AUTO_ACKNOWLEDGE.

Click Source Link

Document

With this acknowledgment mode, the session automatically acknowledges a client's receipt of a message either when the session has successfully returned from a call to receive or when the message listener the session has called to process the message successfully returns.

Usage

From source file:example.tempdest.Consumer.java

public static void main(String[] args) {

    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();/* www  . j a v a 2s . c  o m*/
    }
    System.out.println("\nWaiting to receive messages... will timeout after " + TIMEOUT / 1000 + "s");
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {

        connection = connectionFactory.createConnection();
        connection.start();

        final Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("test-queue");
        MessageConsumer consumer = session.createConsumer(destination);

        int i = 0;
        while (true) {
            Message message = consumer.receive(TIMEOUT);

            if (message != null) {
                if (message instanceof TextMessage) {
                    String text = ((TextMessage) message).getText();
                    System.out.println("Got " + i++ + ". message: " + text);
                    Destination replyTo = message.getJMSReplyTo();
                    MessageProducer producer = session.createProducer(replyTo);
                    producer.send(
                            session.createTextMessage("You made it to the consumer, here is your response"));
                    producer.close();
                }
            } else {
                break;
            }
        }

        consumer.close();
        session.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("Could not close an open connection...");
            }
        }
    }
}

From source file:org.dawnsci.commandserver.mx.example.ActiveMQProducer.java

public static void main(String[] args) throws Exception {

    QueueConnectionFactory connectionFactory = ConnectionFactoryFacade
            .createConnectionFactory("tcp://ws097.diamond.ac.uk:61616");
    Connection send = connectionFactory.createConnection();

    Session session = send.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue("testQ");

    final MessageProducer producer = session.createProducer(queue);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    Message message = session.createTextMessage("Hello World");
    producer.send(message);/*from   w w  w .  jav a 2  s . co m*/

    message = session.createTextMessage("...and another message");
    producer.send(message);

    message = session.createObjectMessage(new TestObjectBean("this could be", "anything"));
    producer.send(message);

    // Test JSON
    SweepBean col = new SweepBean("fred", "d0000000001", 0, 100);

    ObjectMapper mapper = new ObjectMapper();
    String jsonString = mapper.writeValueAsString(col);

    message = session.createTextMessage(jsonString);
    producer.send(message);

    producer.close();
    session.close();
    send.close();

    // Now we peak at the queue
    // If the consumer is not going, the messages should still be there
    if (REQUIRE_PEAK) {
        QueueConnection qCon = connectionFactory.createQueueConnection();
        QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queue = qSes.createQueue("testQ");
        qCon.start();

        QueueBrowser qb = qSes.createBrowser(queue);
        Enumeration e = qb.getEnumeration();
        if (e.hasMoreElements())
            System.out.println("Peak at queue:");
        while (e.hasMoreElements()) {
            Message m = (Message) e.nextElement();
            if (m == null)
                continue;
            if (m instanceof TextMessage) {
                TextMessage t = (TextMessage) m;
                System.out.println(t.getText());
            } else if (m instanceof ObjectMessage) {
                ObjectMessage o = (ObjectMessage) m;
                System.out.println(o.getObject());
            }
        }

        qb.close();
        qSes.close();
        qCon.close();
    }

}

From source file:org.sdnmq.jms_demoapps.SimpleStaticFlowProgrammer.java

public static void main(String[] args) {
    // Standard JMS setup.
    try {// w w  w . j a va2 s .  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 {
        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.sdnmq.jms_demoapps.SimplePacketInSubscriber.java

public static void main(String[] args) {
    // Standard JMS setup.
    try {/*  w  ww.  jav a2  s.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 = (TopicConnectionFactory) ctx.lookup("TopicConnectionFactory");
    } catch (NamingException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        connection = queueFactory.createTopicConnection();
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        packetinTopic = (Topic) ctx.lookup(PACKETIN_TOPIC_NAME);
    } catch (NameNotFoundException e) {
        System.err.println(e.getMessage());
        die(-1);
    } catch (NamingException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        subscriber = session.createSubscriber(packetinTopic);
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        connection.start();
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    // Wait for packet-in events.

    while (true) {
        try {
            // Block until a packet-in event is received.
            // Another alternative is to define a callback function
            // (cf. example FilteringPacketInSubscriber).
            Message msg = subscriber.receive();
            if (msg instanceof TextMessage) {
                String messageStr = ((TextMessage) (msg)).getText();

                // Parse JSON message payload

                JSONObject json = null;
                try {
                    json = new JSONObject(messageStr);
                    // Print the JSON message to show how it looks like.
                    System.out.println(json.toString());
                    System.out.println();
                } catch (JSONException e) {
                    System.err.println(e.getMessage());
                    continue;
                }

                // Search for some packet attributes (for a list of all possible keys, see class PacketInAttributes).

                try {
                    int ethertype = json.getInt(PacketInAttributes.Keys.ETHERTYPE.toJSON());
                    System.out.println("Ethertype: " + ethertype);
                    String macSrcAddr = json.getString(PacketInAttributes.Keys.DL_SRC.toJSON());
                    System.out.println("Source MAC address: " + macSrcAddr);
                    if (json.has(PacketInAttributes.Keys.NW_SRC.toJSON())) {
                        InetAddress nwSrcAddr;
                        try {
                            nwSrcAddr = InetAddress.getByName(PacketInAttributes.Keys.NW_SRC.toJSON());
                            System.out.println(nwSrcAddr);
                        } catch (UnknownHostException e) {
                            System.err.println("Invalid source IP address: " + e.getMessage());
                        }
                    }
                    JSONObject nodeJson = json.getJSONObject(PacketInAttributes.Keys.NODE.toJSON());
                    String nodeId = nodeJson.getString(NodeAttributes.Keys.ID.toJSON());
                    System.out.println("Node (switch): " + nodeId);
                    String inport = json.getString(PacketInAttributes.Keys.INGRESS_PORT.toJSON());
                    System.out.println("Ingress port: " + inport);
                } catch (JSONException e) {
                    System.err.println(e.getMessage());
                }

                // If you want to use your own packet parser, you can also get
                // the raw packet data.

                String packetDataBase64 = json.getString(PacketInAttributes.Keys.PACKET.toJSON());
                byte[] packetData = DatatypeConverter.parseBase64Binary(packetDataBase64);
                // Add your own custom packet parsing here ... we just print the raw data here.
                for (int i = 0; i < packetData.length; i++) {
                    if (i % 16 == 0) {
                        System.out.println();
                    }
                    System.out.print(String.format("%02X ", packetData[i]) + " ");
                }
                System.out.println();
            }
        } catch (JMSException e) {
            System.err.println(e.getMessage());
        }
    }
}

From source file:org.jboss.activemq.clients.JMSConsumer.java

public static void main(String args[]) {
    Connection connection = null;

    try {// w  w  w  .  j ava2  s.c o  m

        Options options = new Options();
        options.addOption("h", "help", false, "help:");
        options.addOption("url", true, "url for the broker to connect to");
        options.addOption("u", "username", true, "User name for connection");
        options.addOption("p", "password", true, "password for connection");
        options.addOption("d", "destination", true, "destination to send to");
        options.addOption("n", "number", true, "number of messages to send");
        options.addOption("delay", true, "delay between each send");

        CommandLineParser parser = new BasicParser();
        CommandLine commandLine = parser.parse(options, args);

        if (commandLine.hasOption("h")) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("OptionsTip", options);
            System.exit(0);
        }

        String url = commandLine.hasOption("host") ? commandLine.getOptionValue("host") : URL;

        String userName = commandLine.hasOption("u") ? commandLine.getOptionValue("u") : "admin";
        String password = commandLine.hasOption("p") ? commandLine.getOptionValue("p") : "admin";
        String destinationName = commandLine.hasOption("d") ? commandLine.getOptionValue("d")
                : DESTINATION_NAME;
        int numberOfMessages = commandLine.hasOption("n") ? Integer.parseInt(commandLine.getOptionValue("n"))
                : NUM_MESSAGES_TO_RECEIVE;
        ;

        ConnectionFactory factory = new ActiveMQConnectionFactory(userName, password, url);

        connection = factory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(destinationName);

        MessageConsumer consumer = session.createConsumer(topic);

        LOG.info("Start consuming " + numberOfMessages + " messages from " + topic.toString());

        for (int i = 0; i < numberOfMessages; i++) {
            Message message = consumer.receive();
            if (message != null) {
                if (message instanceof BytesMessage) {
                    BytesMessage bytesMessage = (BytesMessage) message;
                    int len = (int) bytesMessage.getBodyLength();
                    byte[] data = new byte[len];
                    bytesMessage.readBytes(data);
                    String value = new String(data);

                    LOG.info("Got " + value);
                } else {
                    LOG.info("Got a message " + message);
                }
            }
        }

        consumer.close();
        session.close();
    } catch (Throwable t) {
        LOG.error("Error receiving message", t);
    } finally {

        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOG.error("Error closing connection", e);
            }
        }
    }
}

From source file:org.sdnmq.jms_demoapps.SimplePacketSender.java

public static void main(String[] args) {
    // Standard JMS setup.
    try {//from  w w w  . j  a  va2 s .c om
        // 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.apache.activemq.demo.SimpleConsumer.java

/**
 * @param args the queue used by the example
 *///from  www.  jav  a2s. c o m
public static void main(String[] args) {
    String destinationName = null;
    Context jndiContext = null;
    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    Session session = null;
    Destination destination = null;
    MessageConsumer consumer = null;

    /*
     * Read destination name from command line and display it.
     */
    if (args.length != 1) {
        LOG.info("Usage: java SimpleConsumer <destination-name>");
        System.exit(1);
    }
    destinationName = args[0];
    LOG.info("Destination name is " + destinationName);

    /*
     * 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.toString());
        System.exit(1);
    }

    /*
     * Create connection. Create session from connection; false means
     * session is not transacted. Create receiver, then start message
     * delivery. Receive all text messages from destination until a non-text
     * message is received indicating end of message stream. Close
     * connection.
     */
    try {
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        consumer = session.createConsumer(destination);
        connection.start();
        while (true) {
            Message m = consumer.receive(1);
            if (m != null) {
                if (m instanceof TextMessage) {
                    TextMessage message = (TextMessage) m;
                    LOG.info("Reading message: " + message.getText());
                } else {
                    break;
                }
            }
        }
    } 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.FilteringPacketInSubscriber.java

public static void main(String[] args) {
    // Standard JMS setup.

    try {/*from w  ww.j  a va 2 s  . 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 = (TopicConnectionFactory) ctx.lookup("TopicConnectionFactory");
    } catch (NamingException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        connection = queueFactory.createTopicConnection();
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        packetinTopic = (Topic) ctx.lookup(PACKETIN_TOPIC_NAME);
    } catch (NameNotFoundException e) {
        System.err.println(e.getMessage());
        die(-1);
    } catch (NamingException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        // This selector filters messages from the IPv4 source address 10.0.0.1.
        //
        // For a full list of filter attributes, cf. class MessageFilterAttributes.
        //
        // For a description of the JMS selector concept, the WebSphere MQ documentation below gives a good overview:
        // http://publib.boulder.ibm.com/infocenter/wmqv6/v6r0/index.jsp?topic=%2Fcom.ibm.mq.csqzaw.doc%2Fuj25420_.htm
        //
        // Hint: You can use the binary address attributes NW_SRC_BINARY and NW_DST_BINARY
        // together with the LIKE operator to match a subnet prefix as used by CIDR.
        String selector = MessageFilterAttributes.Keys.DL_TYPE.toFilterName() + "=" + IPV4_ETHERTYPE + " AND "
                + MessageFilterAttributes.Keys.NW_SRC.toFilterName() + "='10.0.0.1'";
        subscriber = session.createSubscriber(packetinTopic, selector, false);
        // The listener implements the callback function onMessage(),
        // which is called whenever a message is received.
        subscriber.setMessageListener(new FilteringPacketInSubscriber());
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        connection.start();
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    // Message handling is done asynchronously in the onMessage() callback.
    // The main thread can sleep meanwhile.

    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }
    }
}

From source file:org.apache.activemq.demo.SimpleQueueSender.java

/**
 * Main method.//from  www . ja  va2s.  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:io.datalayer.activemq.consumer.SimpleConsumer.java

/**
 * @param args the queue used by the example
 *///from   w ww .  j  av  a  2  s  .c  o  m
public static void main(String... args) {
    String destinationName = null;
    Context jndiContext = null;
    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    Session session = null;
    Destination destination = null;
    MessageConsumer consumer = null;

    /*
     * Read destination name from command line and display it.
     */
    if (args.length != 1) {
        LOG.info("Usage: java SimpleConsumer <destination-name>");
        System.exit(1);
    }
    destinationName = args[0];
    LOG.info("Destination name is " + destinationName);

    /*
     * 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.toString());
        System.exit(1);
    }

    /*
     * Create connection. Create session from connection; false means
     * session is not transacted. Create receiver, then start message
     * delivery. Receive all text messages from destination until a non-text
     * message is received indicating end of message stream. Close
     * connection.
     */
    try {
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        consumer = session.createConsumer(destination);
        connection.start();
        while (true) {
            Message m = consumer.receive(1);
            if (m != null) {
                if (m instanceof TextMessage) {
                    TextMessage message = (TextMessage) m;
                    LOG.info("Reading message: " + message.getText());
                } else {
                    break;
                }
            }
        }
    } catch (JMSException e) {
        LOG.info("Exception occurred: " + e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
}