summaryrefslogtreecommitdiff
path: root/qpid/java/systests/src/main/java/org/apache/qpid/test/utils/QpidClientConnectionHelper.java
blob: 72003ed7d715ff3873f087ca4c5a4b13176912aa (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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/*
 *
 * 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.test.utils;

import org.apache.log4j.Logger;

import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQConnectionFactory;
import org.apache.qpid.client.AMQConnectionURL;
import org.apache.qpid.client.JMSAMQException;
import org.apache.qpid.url.URLSyntaxException;

import javax.jms.Connection;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

/**
 * @todo This was originally cut and paste from the client module leading to a duplicate class, then altered very
 *       slightly. To avoid the duplicate class the name was altered slightly to have 'Helper' on the end in order
 *       to distinguish it from the original. Delete this class and use the original instead, just upgrade it to
 *       provide the new features needed.
 */
public class QpidClientConnectionHelper implements ExceptionListener
{

    private static final Logger _logger = Logger.getLogger(QpidClientConnectionHelper.class);

    private boolean transacted = true;
    private int ackMode = Session.CLIENT_ACKNOWLEDGE;
    private Connection connection;

    private String virtualHost;
    private String brokerlist;
    private int prefetch;
    protected Session session;
    protected boolean connected;

    public QpidClientConnectionHelper(String broker)
    {
        super();
        setVirtualHost("/test");
        setBrokerList(broker);
        setPrefetch(5000);
    }

    public void connect() throws JMSException
    {
        if (!connected)
        {
            /*
             * amqp://[user:pass@][clientid]/virtualhost?
             * brokerlist='[transport://]host[:port][?option='value'[&option='value']];'
             * [&failover='method[?option='value'[&option='value']]']
             * [&option='value']"
             */
            String brokerUrl = "amqp://guest:guest@" + virtualHost + "?brokerlist='" + brokerlist + "'";
            try
            {
                AMQConnectionFactory factory = new AMQConnectionFactory(new AMQConnectionURL(brokerUrl));
                _logger.info("connecting to Qpid :" + brokerUrl);
                connection = factory.createConnection();

                // register exception listener
                connection.setExceptionListener(this);

                session = ((AMQConnection) connection).createSession(transacted, ackMode, prefetch);

                _logger.info("starting connection");
                connection.start();

                connected = true;
            }
            catch (URLSyntaxException e)
            {
                throw new JMSAMQException("URL syntax error in [" + brokerUrl + "]: " + e.getMessage(), e);
            }
        }
    }

    public void disconnect() throws JMSException
    {
        if (connected)
        {
            session.commit();
            session.close();
            connection.close();
            connected = false;
            _logger.info("disconnected");
        }
    }

    public void disconnectWithoutCommit() throws JMSException
    {
        if (connected)
        {
            session.close();
            connection.close();
            connected = false;
            _logger.info("disconnected without commit");
        }
    }

    public String getBrokerList()
    {
        return brokerlist;
    }

    public void setBrokerList(String brokerlist)
    {
        this.brokerlist = brokerlist;
    }

    public String getVirtualHost()
    {
        return virtualHost;
    }

    public void setVirtualHost(String virtualHost)
    {
        this.virtualHost = virtualHost;
    }

    public void setPrefetch(int prefetch)
    {
        this.prefetch = prefetch;
    }

    /** override as necessary */
    public void onException(JMSException exception)
    {
        _logger.info("ExceptionListener event: error " + exception.getErrorCode() + ", message: " + exception.getMessage());
    }

    public boolean isConnected()
    {
        return connected;
    }

    public Session getSession()
    {
        return session;
    }

    /**
     * Put a String as a text messages, repeat n times. A null payload will result in a null message.
     *
     * @param queueName The queue name to put to
     * @param payload   the content of the payload
     * @param copies    the number of messages to put
     *
     * @throws javax.jms.JMSException any exception that occurs
     */
    public void put(String queueName, String payload, int copies, int deliveryMode) throws JMSException
    {
        if (!connected)
        {
            connect();
        }

        _logger.info("putting to queue " + queueName);
        Queue queue = session.createQueue(queueName);

        final MessageProducer sender = session.createProducer(queue);

        sender.setDeliveryMode(deliveryMode);

        for (int i = 0; i < copies; i++)
        {
            Message m = session.createTextMessage(payload + i);
            m.setIntProperty("index", i + 1);
            sender.send(m);
        }

        session.commit();
        sender.close();
        _logger.info("put " + copies + " copies");
    }

    /**
     * GET the top message on a queue. Consumes the message. Accepts timeout value.
     *
     * @param queueName   The quename to get from
     * @param readTimeout The timeout to use
     *
     * @return the content of the text message if any
     *
     * @throws javax.jms.JMSException any exception that occured
     */
    public Message getNextMessage(String queueName, long readTimeout) throws JMSException
    {
        if (!connected)
        {
            connect();
        }

        Queue queue = session.createQueue(queueName);

        final MessageConsumer consumer = session.createConsumer(queue);

        Message message = consumer.receive(readTimeout);
        session.commit();
        consumer.close();

        Message result;

        // all messages we consume should be TextMessages
        if (message instanceof TextMessage)
        {
            result = ((TextMessage) message);
        }
        else if (null == message)
        {
            result = null;
        }
        else
        {
            _logger.info("warning: received non-text message");
            result = message;
        }

        return result;
    }

    /**
     * GET the top message on a queue. Consumes the message.
     *
     * @param queueName The Queuename to get from
     *
     * @return The string content of the text message, if any received
     *
     * @throws javax.jms.JMSException any exception that occurs
     */
    public Message getNextMessage(String queueName) throws JMSException
    {
        return getNextMessage(queueName, 0);
    }

    /**
     * Completely clears a queue. For readTimeout behaviour see Javadocs for javax.jms.MessageConsumer.
     *
     * @param queueName   The Queue name to consume from
     * @param readTimeout The timeout for each consume
     *
     * @throws javax.jms.JMSException Any exception that occurs during the consume
     * @throws InterruptedException   If the consume thread was interrupted during a consume.
     */
    public void consume(String queueName, int readTimeout) throws JMSException, InterruptedException
    {
        if (!connected)
        {
            connect();
        }

        _logger.info("consuming queue " + queueName);
        Queue queue = session.createQueue(queueName);

        final MessageConsumer consumer = session.createConsumer(queue);
        int messagesReceived = 0;

        _logger.info("consuming...");
        while ((consumer.receive(readTimeout)) != null)
        {
            messagesReceived++;
        }

        session.commit();
        consumer.close();
        _logger.info("consumed: " + messagesReceived);
    }
}