summaryrefslogtreecommitdiff
path: root/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/transacted/TransactionTimeoutTestCase.java
blob: 637f43fb2c1ba432c05156155c7c829144e58244 (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
/*
 *
 * 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.unit.transacted;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import javax.jms.DeliveryMode;
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.TextMessage;

import junit.framework.TestCase;

import org.apache.qpid.AMQException;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQConnectionURL;
import org.apache.qpid.client.AMQQueue;
import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.jms.ConnectionURL;
import org.apache.qpid.jms.Session;
import org.apache.qpid.protocol.AMQConstant;
import org.apache.qpid.test.utils.QpidBrokerTestCase;
import org.apache.qpid.util.LogMonitor;

/**
 * The {@link TestCase} for transaction timeout testing.
 */
public class TransactionTimeoutTestCase extends QpidBrokerTestCase implements ExceptionListener
{
    public static final String VIRTUALHOST = "test";
    public static final String TEXT = "0123456789abcdefghiforgettherest";
    public static final String CHN_OPEN_TXN = "CHN-1007";
    public static final String CHN_IDLE_TXN = "CHN-1008";
    public static final String IDLE = "Idle";
    public static final String OPEN = "Open";
    
    protected LogMonitor _monitor;
    protected AMQConnection _con;
    protected Session _psession, _csession;
    protected Queue _queue;
    protected MessageConsumer _consumer;
    protected MessageProducer _producer;
    protected CountDownLatch _caught = new CountDownLatch(1);
    protected String _message;
    protected Exception _exception;
    protected AMQConstant _code;
    
    protected void configure() throws Exception
    {
        // Setup housekeeping every second
        setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".housekeeping.expiredMessageCheckPeriod", "100");
        
        /*
         * Set transaction timout properties. The XML in the virtualhosts configuration is as follows:
         * 
         *  <transactionTimeout>
         *      <openWarn>1000</openWarn>
         *      <openClose>2000</openClose>
         *      <idleWarn>500</idleWarn>
         *      <idleClose>1500</idleClose>
         *  </transactionTimeout>
         */
        setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".transactionTimeout.openWarn", "1000");
        setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".transactionTimeout.openClose", "2000");
        setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".transactionTimeout.idleWarn", "500");
        setConfigurationProperty("virtualhosts.virtualhost." + VIRTUALHOST + ".transactionTimeout.idleClose", "1000");
    }
        
    protected void setUp() throws Exception
    {
        // Configure timeouts
        configure();
        
        // Monitor log file
        _monitor = new LogMonitor(_outputFile);
        
        // Start broker
        super.setUp();
        
        // Connect to broker
        String broker = _broker.equals(VM) ? ("vm://:" + DEFAULT_VM_PORT) : ("tcp://localhost:" + DEFAULT_PORT);
        ConnectionURL url = new AMQConnectionURL("amqp://guest:guest@clientid/test?brokerlist='" + broker + "'&maxprefetch='1'");
        _con = (AMQConnection) getConnection(url);
        _con.setExceptionListener(this);
        _con.start();
        
        // Create queue
        Session qsession = _con.createSession(true, Session.SESSION_TRANSACTED);
        AMQShortString queueName = new AMQShortString("test");
        _queue = new AMQQueue(qsession.getDefaultQueueExchangeName(), queueName, queueName, false, true);
        qsession.close();
        
        // Create producer and consumer
        producer();
        consumer();
    }
    
    protected void tearDown() throws Exception
    {
        try
        {
            _con.close();
        }
        finally
        {
            super.tearDown();
        }
    }

    /**
     * Create a transacted persistent message producer session.
     */
    protected void producer() throws Exception
    {
        _psession = _con.createSession(true, Session.SESSION_TRANSACTED);
        _producer = _psession.createProducer(_queue);
        _producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    }

    /**
     * Create a transacted message consumer session.
     */
    protected void consumer() throws Exception
    {
        _csession = _con.createSession(true, Session.SESSION_TRANSACTED);
        _consumer = _csession.createConsumer(_queue);
    }

    /**
     * Send a number of messages to the queue, optionally pausing after each.
     */
    protected void send(int count, float delay) throws Exception
    {
        for (int i = 0; i < count; i++)
        {
	        sleep(delay);
            Message msg = _psession.createTextMessage(TEXT);
            msg.setIntProperty("i", i);
	        _producer.send(msg);
        }
    }
    
    /**
     * Sleep for a number of seconds.
     */
    protected void sleep(float seconds) throws Exception
    {
        try
        {
            Thread.sleep((long) (seconds * 1000.0f));
        }
        catch (InterruptedException ie)
        {
            throw new RuntimeException("Interrupted");
        }
    }
    
    /**
     * Check for idle and open messages.
     * 
     * Either exactly zero messages, or +-2 error accepted around the specified number.
     */
    protected void monitor(int idle, int open) throws Exception
    {
        List<String> idleMsgs = _monitor.findMatches(CHN_IDLE_TXN);
        List<String> openMsgs = _monitor.findMatches(CHN_OPEN_TXN);
        
        String idleErr = "Expected " + idle + " but found " + idleMsgs.size() + " txn idle messages";
        String openErr = "Expected " + open + " but found " + openMsgs.size() + " txn open messages";
        
        if (idle == 0)
        {
            assertTrue(idleErr, idleMsgs.isEmpty());
        }
        else
        {
	        assertTrue(idleErr, idleMsgs.size() >= idle - 2 && idleMsgs.size() <= idle + 2);
        }
        
        if (open == 0)
        {
            assertTrue(openErr, openMsgs.isEmpty());
        }
        else
        {
            assertTrue(openErr, openMsgs.size() >= open - 2 && openMsgs.size() <= open + 2);
        }
    }

    /**
     * Receive a number of messages, optionally pausing after each.
     */
    protected void expect(int count, float delay) throws Exception
    {
        for (int i = 0; i < count; i++)
        {
	        sleep(delay);
            Message msg = _consumer.receive(1000);
	        assertNotNull("Message should not be null", msg);
	        assertTrue("Message should be a text message", msg instanceof TextMessage);
	        assertEquals("Message content does not match expected", TEXT, ((TextMessage) msg).getText());
	        assertEquals("Message order is incorrect", i, msg.getIntProperty("i"));
        }
    }
    
    /**
     * Checks that the correct exception was thrown and was received
     * by the listener with a 506 error code.
     */
    protected void check(String reason)throws InterruptedException
    {
        assertTrue("Should have caught exception in listener", _caught.await(1, TimeUnit.SECONDS));
        assertNotNull("Should have thrown exception to client", _exception);
        assertTrue("Exception message should contain '" + reason + "': " + _message, _message.contains(reason + " transaction timed out"));
        assertNotNull("Exception should have an error code", _code);
        assertEquals("Error code should be 506", AMQConstant.RESOURCE_ERROR, _code);
    }

    /** @see javax.jms.ExceptionListener#onException(javax.jms.JMSException) */
    public void onException(JMSException jmse)
    {
        _caught.countDown();
        _message = jmse.getLinkedException().getMessage();
        if (jmse.getLinkedException() instanceof AMQException)
        {
            _code = ((AMQException) jmse.getLinkedException()).getErrorCode();
        }
    }
}