summaryrefslogtreecommitdiff
path: root/trunk/qpid/java/client/example/src/main/java/org/apache/qpid/example/jmsexample/fanout/Listener.java
blob: fb750693b24254a628868c6f2dfd391be9eff1f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
package org.apache.qpid.example.jmsexample.fanout;

import java.util.Properties;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;

/**
 * The example creates a MessageConsumer on the specified
 * Queue and uses a MessageListener with this MessageConsumer
 * in order to enable asynchronous delivery.
 */
public class Listener implements MessageListener
{
    /* Used in log output. */
    private static final String CLASS = "Listener";

    /**
     * An object to synchronize on.
     */
    private final Object _lock = new Object();

    /**
     * A boolean to indicate a clean finish.
     */
    private boolean _finished = false;

    /**
     * A boolean to indicate an unsuccesful finish.
     */
    private boolean _failed = false;



    /**
     * Run the message consumer example.
     *
     * @param args Command line arguments.
     */
    public static void main(String[] args) throws Exception
    {
        if (args.length == 0)
        {
            throw new Exception("You need to specify the JNDI name for the queue");
        }
        Listener listener = new Listener();
        listener.runTest(args[0]);
    }

    /**
     * Start the example.
     */
    private void runTest(String queueName)
    {
        try
        {
            Properties properties = new Properties();
            properties.load(this.getClass().getResourceAsStream("fanout.properties"));

            //Create the initial context
            Context ctx = new InitialContext(properties);

            Destination destination = (Destination)ctx.lookup(queueName);

            // Declare the connection
            ConnectionFactory conFac = (ConnectionFactory)ctx.lookup("qpidConnectionfactory");
            Connection connection = conFac.createConnection();

            // As this application is using a MessageConsumer we need to set an ExceptionListener on the connection
            // so that errors raised within the JMS client library can be reported to the application
            System.out.println(
                    CLASS + ": Setting an ExceptionListener on the connection as sample uses a MessageConsumer");

            connection.setExceptionListener(new ExceptionListener()
            {
                public void onException(JMSException jmse)
                {
                    // The connection may have broken invoke reconnect code if available.
                    System.err.println(CLASS + ": The sample received an exception through the ExceptionListener");
                    System.exit(0);
                }
            });

            // Create a session on the connection
            // This session is a default choice of non-transacted and uses
            // the auto acknowledge feature of a session.
            System.out.println(CLASS + ": Creating a non-transacted, auto-acknowledged session");

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // Create a MessageConsumer
            System.out.println(CLASS + ": Creating a MessageConsumer");

            MessageConsumer messageConsumer = session.createConsumer(destination);

            // Set a message listener on the messageConsumer
            messageConsumer.setMessageListener(this);

            // Now the messageConsumer is set up we can start the connection
            System.out.println(CLASS + ": Starting connection so MessageConsumer can receive messages");
            connection.start();

            // Wait for the messageConsumer to have received all the messages it needs
            synchronized (_lock)
            {
                while (!_finished && !_failed)
                {
                    _lock.wait();
                }
            }

            // If the MessageListener abruptly failed (probably due to receiving a non-text message)
            if (_failed)
            {
                System.out.println(CLASS + ": This sample failed as it received unexpected messages");
            }

            // Close the connection to the server
            System.out.println(CLASS + ": Closing connection");
            connection.close();

            // Close the JNDI reference
            System.out.println(CLASS + ": Closing JNDI context");
            ctx.close();
        }
        catch (Exception exp)
        {
            System.err.println(CLASS + ": Caught an Exception: " + exp);
        }
    }

    /**
     * This method is required by the <CODE>MessageListener</CODE> interface. It
     * will be invoked  when messages are available.
     * After receiving the finish message (That's all, folks!) it releases a lock so that the
     * main program may continue.
     *
     * @param message The message.
     */
    public void onMessage(Message message)
    {
        try
        {
            String text;
            if (message instanceof TextMessage)
            {
                text = ((TextMessage) message).getText();
            }
            else
            {
                byte[] body = new byte[(int) ((BytesMessage) message).getBodyLength()];
                ((BytesMessage) message).readBytes(body);
                text = new String(body);
            }
            if (text.equals("That's all, folks!"))
            {
                System.out.println(CLASS + ": Received final message " + text);
                synchronized (_lock)
                {
                    _finished = true;
                    _lock.notifyAll();
                }
            }
            else
            {
                System.out.println(CLASS + ": Received  message:  " + text);
            }
        }
        catch (JMSException exp)
        {
            System.out.println(CLASS + ": Caught an exception handling a received message");
            exp.printStackTrace();
            synchronized (_lock)
            {
                _failed = true;
                _lock.notifyAll();
            }
        }
    }
}