summaryrefslogtreecommitdiff
path: root/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/basic/PropertyValueTest.java
blob: 3b8b4946da3d093ebefd1433a5e8094643b76bf8 (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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/*
 *
 * 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.basic;

import junit.framework.Assert;

import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQQueue;
import org.apache.qpid.client.AMQSession;
import org.apache.qpid.client.AMQDestination;
import org.apache.qpid.client.message.JMSTextMessage;
import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.test.utils.QpidBrokerTestCase;
import org.apache.qpid.url.BindingURL;
import org.apache.qpid.url.AMQBindingURL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageFormatException;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.net.URISyntaxException;

import java.lang.reflect.*;

public class PropertyValueTest extends QpidBrokerTestCase implements MessageListener
{
    private static final Logger _logger = LoggerFactory.getLogger(PropertyValueTest.class);

    private int count = 0;
    private AMQConnection _connection;
    private Destination _destination;
    private AMQSession _session;
    private final List<JMSTextMessage> received = new ArrayList<JMSTextMessage>();
    private final List<String> messages = new ArrayList<String>();
    private int _count = 1;
    public String _connectionString = "vm://:1";
    private static final String USERNAME = "guest";

    protected void setUp() throws Exception
    {
        super.setUp();
    }

    protected void tearDown() throws Exception
    {
        super.tearDown();
    }

    private void init(AMQConnection connection) throws Exception
    {
        Destination destination = new AMQQueue(connection, randomize("PropertyValueTest"), true);
        init(connection, destination);
    }

    private void init(AMQConnection connection, Destination destination) throws Exception
    {
        _connection = connection;
        _destination = destination;
        _session = (AMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // set up a slow consumer
        _session.createConsumer(destination).setMessageListener(this);
        connection.start();
    }

    private Message getTestMessage() throws Exception
    {
        Connection conn = getConnection();
        Session ssn = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        return ssn.createTextMessage();
    }

    public void testGetNonexistent() throws Exception
    {
        Message m = getTestMessage();
        String s = m.getStringProperty("nonexistent");
        assertNull(s);
    }

    private static final String[] NAMES = {
        "setBooleanProperty", "setByteProperty", "setShortProperty",
        "setIntProperty", "setLongProperty", "setFloatProperty",
        "setDoubleProperty", "setObjectProperty"
    };

    private static final Class[] TYPES = {
        boolean.class, byte.class, short.class, int.class, long.class,
        float.class, double.class, Object.class
    };

    private static final Object[] VALUES = {
        true, (byte) 0, (short) 0, 0, (long) 0, (float) 0, (double) 0,
        new Object()
    };

    public void testSetEmptyPropertyName() throws Exception
    {
        Message m = getTestMessage();

        for (int i = 0; i < NAMES.length; i++)
        {
            Method meth = m.getClass().getMethod(NAMES[i], String.class, TYPES[i]);
            try
            {
                meth.invoke(m, "", VALUES[i]);
                fail("expected illegal argument exception");
            }
            catch (InvocationTargetException e)
            {
                assertEquals(e.getCause().getClass(), IllegalArgumentException.class);
            }
        }
    }

    public void testSetDisallowedClass() throws Exception
    {
        Message m = getTestMessage();
        try
        {
            m.setObjectProperty("foo", new Object());
            fail("expected a MessageFormatException");
        }
        catch (MessageFormatException e)
        {
            // pass
        }
    }

    public void testOnce()
    {
        runBatch(1);
    }

    public void test50()
    {
        runBatch(50);
    }

    private void runBatch(int runSize)
    {
        try
        {
            int run = 0;
            while (run < runSize)
            {
                _logger.error("Run Number:" + run++);
                try
                {
                    init( (AMQConnection) getConnection("guest", "guest"));
                }
                catch (Exception e)
                {
                    _logger.error("exception:", e);
                    fail("Unable to initialilse connection: " + e);
                }

                int count = _count;
                send(count);
                waitFor(count);
                check();
                _logger.info("Completed without failure");

                Thread.sleep(10);
                _connection.close();

                _logger.error("End Run Number:" + (run - 1));
            }
        }
        catch (Exception e)
        {
            _logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
    }

    void send(int count) throws JMSException
    {
        // create a publisher
        MessageProducer producer = _session.createProducer(_destination);
        for (int i = 0; i < count; i++)
        {
            String text = "Message " + i;
            messages.add(text);
            Message m = _session.createTextMessage(text);

            m.setBooleanProperty("Bool", true);

            m.setByteProperty("Byte", (byte) Byte.MAX_VALUE);
            m.setDoubleProperty("Double", (double) Double.MAX_VALUE);
            m.setFloatProperty("Float", (float) Float.MAX_VALUE);
            m.setIntProperty("Int", (int) Integer.MAX_VALUE);

            m.setJMSCorrelationID("Correlation");
            // fixme the m.setJMSMessage has no effect
            producer.setPriority(8);
            m.setJMSPriority(3);

            // Queue
            Queue q;

            if ((i / 2) == 0)
            {
                q = _session.createTemporaryQueue();
            }
            else
            {
                q = new AMQQueue(_connection, "TestReply");
            }

            m.setJMSReplyTo(q);
            m.setStringProperty("TempQueue", q.toString());

            _logger.debug("Message:" + m);

            Assert.assertEquals("Check temp queue has been set correctly", m.getJMSReplyTo().toString(),
                m.getStringProperty("TempQueue"));

            m.setJMSType("Test");
            m.setLongProperty("UnsignedInt", (long) 4294967295L);
            m.setLongProperty("Long", (long) Long.MAX_VALUE);

            m.setShortProperty("Short", (short) Short.MAX_VALUE);
            m.setStringProperty("String", "Test");

            _logger.debug("Sending Msg:" + m);
            producer.send(m);
        }
    }

    void waitFor(int count) throws InterruptedException
    {
        synchronized (received)
        {
            while (received.size() < count)
            {
                received.wait();
            }
        }
    }

    void check() throws JMSException, URISyntaxException
    {
        List<String> actual = new ArrayList<String>();
        for (JMSTextMessage m : received)
        {
            actual.add(m.getText());

            // Check Properties

            Assert.assertEquals("Check Boolean properties are correctly transported", true, m.getBooleanProperty("Bool"));
            Assert.assertEquals("Check Byte properties are correctly transported", (byte) Byte.MAX_VALUE,
                m.getByteProperty("Byte"));
            Assert.assertEquals("Check Double properties are correctly transported", (double) Double.MAX_VALUE,
                m.getDoubleProperty("Double"));
            Assert.assertEquals("Check Float properties are correctly transported", (float) Float.MAX_VALUE,
                m.getFloatProperty("Float"));
            Assert.assertEquals("Check Int properties are correctly transported", (int) Integer.MAX_VALUE,
                m.getIntProperty("Int"));
            Assert.assertEquals("Check CorrelationID properties are correctly transported", "Correlation",
                m.getJMSCorrelationID());
            Assert.assertEquals("Check Priority properties are correctly transported", 8, m.getJMSPriority());

            // Queue
            Assert.assertEquals("Check ReplyTo properties are correctly transported", AMQDestination.createDestination(new AMQBindingURL(m.getStringProperty("TempQueue"))),
                m.getJMSReplyTo());

            Assert.assertEquals("Check Type properties are correctly transported", "Test", m.getJMSType());

            Assert.assertEquals("Check Short properties are correctly transported", (short) Short.MAX_VALUE,
                m.getShortProperty("Short"));
            Assert.assertEquals("Check UnsignedInt properties are correctly transported", (long) 4294967295L,
                m.getLongProperty("UnsignedInt"));
            Assert.assertEquals("Check Long properties are correctly transported", (long) Long.MAX_VALUE,
                m.getLongProperty("Long"));
            Assert.assertEquals("Check String properties are correctly transported", "Test", m.getStringProperty("String"));
/*
            // AMQP Tests Specific values

            Assert.assertEquals("Check Timestamp properties are correctly transported", m.getStringProperty("time-str"),
                ((AMQMessage) m).getTimestampProperty(new AMQShortString("time")).toString());

            // Decimal
            BigDecimal bd = new BigDecimal(Integer.MAX_VALUE);

            Assert.assertEquals("Check decimal properties are correctly transported", bd.setScale(Byte.MAX_VALUE),
                ((AMQMessage) m).getDecimalProperty(new AMQShortString("decimal")));

            // Void
            ((AMQMessage) m).setVoidProperty(new AMQShortString("void"));

            Assert.assertTrue("Check void properties are correctly transported",
                              ((AMQMessage) m).getPropertyHeaders().containsKey("void"));
*/
            //JMSXUserID
            if (m.getStringProperty("JMSXUserID") != null)
            {
                Assert.assertEquals("Check 'JMSXUserID' is supported ", USERNAME,
                                    m.getStringProperty("JMSXUserID"));
            }
        }

        received.clear();

        assertEqual(messages.iterator(), actual.iterator());

        messages.clear();
    }

    private static void assertEqual(Iterator expected, Iterator actual)
    {
        List<String> errors = new ArrayList<String>();
        while (expected.hasNext() && actual.hasNext())
        {
            try
            {
                assertEqual(expected.next(), actual.next());
            }
            catch (Exception e)
            {
                errors.add(e.getMessage());
            }
        }
        while (expected.hasNext())
        {
            errors.add("Expected " + expected.next() + " but no more actual values.");
        }
        while (actual.hasNext())
        {
            errors.add("Found " + actual.next() + " but no more expected values.");
        }

        if (!errors.isEmpty())
        {
            throw new RuntimeException(errors.toString());
        }
    }

    private static void assertEqual(Object expected, Object actual)
    {
        if (!expected.equals(actual))
        {
            throw new RuntimeException("Expected '" + expected + "' found '" + actual + "'");
        }
    }

    public void onMessage(Message message)
    {
        synchronized (received)
        {
            received.add((JMSTextMessage) message);
            received.notify();
        }
    }

    private static String randomize(String in)
    {
        return in + System.currentTimeMillis();
    }

    public static void main(String[] argv) throws Exception
    {
        PropertyValueTest test = new PropertyValueTest();
        test._connectionString = (argv.length == 0) ? "vm://:1" : argv[0];
        test.setUp();
        if (argv.length > 1)
        {
            test._count = Integer.parseInt(argv[1]);
        }

        test.testOnce();
    }

    public static junit.framework.Test suite()
    {
        return new junit.framework.TestSuite(PropertyValueTest.class);
    }
}