diff options
Diffstat (limited to 'qpid/java/client/src/test/java')
28 files changed, 5536 insertions, 0 deletions
diff --git a/qpid/java/client/src/test/java/org/apache/mina/transport/vmpipe/support/VmPipeIdleStatusChecker.java b/qpid/java/client/src/test/java/org/apache/mina/transport/vmpipe/support/VmPipeIdleStatusChecker.java new file mode 100644 index 0000000000..5323ad28bf --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/mina/transport/vmpipe/support/VmPipeIdleStatusChecker.java @@ -0,0 +1,125 @@ +/* + * + * 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.mina.transport.vmpipe.support; + +import org.apache.mina.common.IdleStatus; + +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.Iterator; +import java.util.Map; + +/** + * This file is a patch to override MINA, because of the IdentityHashMap bug. Workaround to be supplied in MINA 1.0.7. + * This patched file will be removed once upgraded onto a newer MINA. + * + * Dectects idle sessions and fires <tt>sessionIdle</tt> events to them. + * + * @author The Apache Directory Project (mina-dev@directory.apache.org) + */ +public class VmPipeIdleStatusChecker +{ + private static final VmPipeIdleStatusChecker INSTANCE = new VmPipeIdleStatusChecker(); + + public static VmPipeIdleStatusChecker getInstance() + { + return INSTANCE; + } + + private final Map sessions = new HashMap(); // will use as a set + + private final Worker worker = new Worker(); + + private VmPipeIdleStatusChecker() + { + worker.start(); + } + + public void addSession(VmPipeSessionImpl session) + { + synchronized (sessions) + { + sessions.put(session, session); + } + } + + private class Worker extends Thread + { + private Worker() + { + super("VmPipeIdleStatusChecker"); + setDaemon(true); + } + + public void run() + { + for (;;) + { + try + { + Thread.sleep(1000); + } + catch (InterruptedException e) + { } + + long currentTime = System.currentTimeMillis(); + + synchronized (sessions) + { + Iterator it = sessions.keySet().iterator(); + while (it.hasNext()) + { + VmPipeSessionImpl session = (VmPipeSessionImpl) it.next(); + if (!session.isConnected()) + { + it.remove(); + } + else + { + notifyIdleSession(session, currentTime); + } + } + } + } + } + } + + private void notifyIdleSession(VmPipeSessionImpl session, long currentTime) + { + notifyIdleSession0(session, currentTime, session.getIdleTimeInMillis(IdleStatus.BOTH_IDLE), IdleStatus.BOTH_IDLE, + Math.max(session.getLastIoTime(), session.getLastIdleTime(IdleStatus.BOTH_IDLE))); + notifyIdleSession0(session, currentTime, session.getIdleTimeInMillis(IdleStatus.READER_IDLE), IdleStatus.READER_IDLE, + Math.max(session.getLastReadTime(), session.getLastIdleTime(IdleStatus.READER_IDLE))); + notifyIdleSession0(session, currentTime, session.getIdleTimeInMillis(IdleStatus.WRITER_IDLE), IdleStatus.WRITER_IDLE, + Math.max(session.getLastWriteTime(), session.getLastIdleTime(IdleStatus.WRITER_IDLE))); + } + + private void notifyIdleSession0(VmPipeSessionImpl session, long currentTime, long idleTime, IdleStatus status, + long lastIoTime) + { + if ((idleTime > 0) && (lastIoTime != 0) && ((currentTime - lastIoTime) >= idleTime)) + { + session.increaseIdleCount(status); + session.getFilterChain().fireSessionIdle(session, status); + } + } + +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/AMQQueueTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/AMQQueueTest.java new file mode 100644 index 0000000000..7789f87ace --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/client/AMQQueueTest.java @@ -0,0 +1,42 @@ +/* + * + * 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.client; + +import org.apache.qpid.framing.AMQShortString; + +import junit.framework.TestCase; + +public class AMQQueueTest extends TestCase +{ + AMQShortString exchange = new AMQShortString("test.exchange"); + AMQShortString routingkey = new AMQShortString("test-route"); + AMQShortString qname = new AMQShortString("test-queue"); + AMQShortString[] oneBinding = new AMQShortString[]{new AMQShortString("bindingA")}; + AMQShortString[] bindings = new AMQShortString[]{new AMQShortString("bindingB"), + new AMQShortString("bindingC")}; + + public void testToURLNoBindings() + { + AMQQueue dest = new AMQQueue(exchange, routingkey, qname); + String url = dest.toURL(); + assertEquals("direct://test.exchange/test-route/test-queue?routingkey='test-route'", url); + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/MockAMQConnection.java b/qpid/java/client/src/test/java/org/apache/qpid/client/MockAMQConnection.java new file mode 100644 index 0000000000..5972bf3fae --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/client/MockAMQConnection.java @@ -0,0 +1,89 @@ +/* + * + * 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.client; + +import org.apache.qpid.AMQException; +import org.apache.qpid.client.state.AMQState; +import org.apache.qpid.framing.ProtocolVersion; +import org.apache.qpid.jms.ConnectionURL; +import org.apache.qpid.jms.BrokerDetails; +import org.apache.qpid.url.URLSyntaxException; + +import java.io.IOException; + +public class MockAMQConnection extends AMQConnection +{ + public MockAMQConnection(String broker, String username, String password, String clientName, String virtualHost) + throws AMQException, URLSyntaxException + { + super(broker, username, password, clientName, virtualHost); + } + + public MockAMQConnection(String broker, String username, String password, String clientName, String virtualHost, SSLConfiguration sslConfig) + throws AMQException, URLSyntaxException + { + super(broker, username, password, clientName, virtualHost, sslConfig); + } + + public MockAMQConnection(String host, int port, String username, String password, String clientName, String virtualHost) + throws AMQException, URLSyntaxException + { + super(host, port, username, password, clientName, virtualHost); + } + + public MockAMQConnection(String host, int port, String username, String password, String clientName, String virtualHost, SSLConfiguration sslConfig) + throws AMQException, URLSyntaxException + { + super(host, port, username, password, clientName, virtualHost, sslConfig); + } + + public MockAMQConnection(String host, int port, boolean useSSL, String username, String password, String clientName, String virtualHost, SSLConfiguration sslConfig) + throws AMQException, URLSyntaxException + { + super(host, port, useSSL, username, password, clientName, virtualHost, sslConfig); + } + + public MockAMQConnection(String connection) + throws AMQException, URLSyntaxException + { + super(connection); + } + + public MockAMQConnection(String connection, SSLConfiguration sslConfig) + throws AMQException, URLSyntaxException + { + super(connection, sslConfig); + } + + public MockAMQConnection(ConnectionURL connectionURL, SSLConfiguration sslConfig) + throws AMQException + { + super(connectionURL, sslConfig); + } + + @Override + public ProtocolVersion makeBrokerConnection(BrokerDetails brokerDetail) throws IOException + { + _connected = true; + _protocolHandler.getStateManager().changeState(AMQState.CONNECTION_OPEN); + return null; + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/message/AbstractJMSMessageTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/message/AbstractJMSMessageTest.java new file mode 100644 index 0000000000..f81f482c6a --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/client/message/AbstractJMSMessageTest.java @@ -0,0 +1,57 @@ +package org.apache.qpid.client.message; +/* + * + * 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. + * + */ + + +import javax.jms.JMSException; + +import junit.framework.TestCase; + +public class AbstractJMSMessageTest extends TestCase +{ + + public void testSetNullJMSReplyTo08() throws JMSException + { + JMSTextMessage message = new JMSTextMessage(AMQMessageDelegateFactory.FACTORY_0_8); + try + { + message.setJMSReplyTo(null); + } + catch (IllegalArgumentException e) + { + fail("Null destination should be allowed"); + } + } + + public void testSetNullJMSReplyTo10() throws JMSException + { + JMSTextMessage message = new JMSTextMessage(AMQMessageDelegateFactory.FACTORY_0_10); + try + { + message.setJMSReplyTo(null); + } + catch (IllegalArgumentException e) + { + fail("Null destination should be allowed"); + } + } + +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/message/TestMessageHelper.java b/qpid/java/client/src/test/java/org/apache/qpid/client/message/TestMessageHelper.java new file mode 100644 index 0000000000..7ee991b63c --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/client/message/TestMessageHelper.java @@ -0,0 +1,46 @@ +/* + * + * 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.client.message; + +import javax.jms.JMSException; + +public class TestMessageHelper +{ + public static JMSTextMessage newJMSTextMessage() throws JMSException + { + return new JMSTextMessage(AMQMessageDelegateFactory.FACTORY_0_8); + } + + public static JMSBytesMessage newJMSBytesMessage() throws JMSException + { + return new JMSBytesMessage(AMQMessageDelegateFactory.FACTORY_0_8); + } + + public static JMSMapMessage newJMSMapMessage() throws JMSException + { + return new JMSMapMessage(AMQMessageDelegateFactory.FACTORY_0_8); + } + + public static JMSStreamMessage newJMSStreamMessage() + { + return new JMSStreamMessage(AMQMessageDelegateFactory.FACTORY_0_8); + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/protocol/AMQProtocolHandlerTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/protocol/AMQProtocolHandlerTest.java new file mode 100644 index 0000000000..f520a21ba0 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/client/protocol/AMQProtocolHandlerTest.java @@ -0,0 +1,289 @@ +/* + * + * 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.client.protocol; + +import junit.framework.TestCase; +import org.apache.qpid.framing.AMQFrame; +import org.apache.qpid.framing.AMQBody; +import org.apache.qpid.framing.AMQMethodBody; +import org.apache.qpid.framing.amqp_8_0.BasicRecoverOkBodyImpl; +import org.apache.qpid.AMQException; +import org.apache.qpid.protocol.AMQConstant; +import org.apache.qpid.transport.TestNetworkDriver; +import org.apache.qpid.client.MockAMQConnection; +import org.apache.qpid.client.AMQAuthenticationException; +import org.apache.qpid.client.state.AMQState; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * This is a test address QPID-1431 where frame listeners would fail to be notified of an incomming exception. + * + * Currently we do checks at the Session level to ensure that the connection/session are open. However, it is possible + * for the connection to close AFTER this check has been performed. + * + * Performing a similar check at the frameListener level in AMQProtocolHandler makes most sence as this will prevent + * listening when there can be no returning frames. + * + * With the correction in place it also means that the new listener will either make it on to the list for notification + * or it will be notified of any existing exception due to the connection being closed. + * + * There may still be an issue in this space if the client utilises a second thread to close the session as there will + * be no exception set to throw and so the wait will occur. That said when the session is closed the framelisteners + * should be notified. Not sure this is tested. + */ +public class AMQProtocolHandlerTest extends TestCase +{ + private static final Logger _logger = LoggerFactory.getLogger(AMQProtocolHandlerTest.class); + + // The handler to test + AMQProtocolHandler _handler; + + // A frame to block upon whilst waiting the exception + AMQFrame _blockFrame; + + // Latch to know when the listener receives an exception + private CountDownLatch _handleCountDown; + // The listener that will receive an exception + BlockToAccessFrameListener _listener; + + @Override + public void setUp() throws Exception + { + //Create a new ProtocolHandler with a fake connection. + _handler = new AMQProtocolHandler(new MockAMQConnection("amqp://guest:guest@client/test?brokerlist='vm://:1'")); + _handler.setNetworkDriver(new TestNetworkDriver()); + AMQBody body = BasicRecoverOkBodyImpl.getFactory().newInstance(null, 1); + _blockFrame = new AMQFrame(0, body); + + _handleCountDown = new CountDownLatch(1); + + _logger.info("Creating _Listener that should also receive the thrown exception."); + _listener = new BlockToAccessFrameListener(1); + } + + /** + * There are two paths based on the type of exception thrown. + * + * This tests that when an AMQException is thrown we get the same type of AMQException back with the real exception + * wrapped as the cause. + * + * @throws InterruptedException - if we are unable to wait for the test signals + */ + public void testFrameListenerUpdateWithAMQException() throws InterruptedException + { + AMQException trigger = new AMQAuthenticationException(AMQConstant.ACCESS_REFUSED, + "AMQPHTest", new RuntimeException()); + + performWithException(trigger); + + + AMQException receivedException = (AMQException) _listener.getReceivedException(); + + assertEquals("Return exception was not the expected type", + AMQAuthenticationException.class, receivedException.getClass()); + + assertEquals("The _Listener did not receive the correct error code", + trigger.getErrorCode(), receivedException.getErrorCode()); + } + + /** + * There are two paths based on the type of exception thrown. + * + * This tests that when a generic Exception is thrown we get the exception back wrapped in a AMQException + * as the cause. + * @throws InterruptedException - if we are unable to wait for the test signals + */ + public void testFrameListenerUpdateWithException() throws InterruptedException + { + + Exception trigger = new Exception(new RuntimeException()); + + performWithException(trigger); + + assertEquals("The _Listener did not receive the correct error code", + AMQConstant.INTERNAL_ERROR, ((AMQException)_listener.getReceivedException()).getErrorCode()); + } + + /** + * This is the main test method for both test cases. + * + * What occurs is that we create a new thread that will block (<30s[DEFAULT]) for a frame or exception to occur . + * + * We use a CountDownLatch to ensure that the new thread is running before we then yield and sleep to help ensure + * the new thread has entered the synchronized block in the writeCommandFrameAndWaitForReply. + * + * We can then ack like an the incomming exception handler in (ConnectionCloseMethodHandler). + * + * We fire the error to the stateManager, which in this case will recored the error as there are no state listeners. + * + * We then set the connection to be closed, as we would normally close the socket at this point. + * + * Then fire the exception in to any frameListeners. + * + * The blocked listener (created above) when receiving the error simulates the user by creating a new request to + * block for a frame. + * + * This request should fail. Prior to the fix this will fail with a NPE as we are attempting to use a null listener + * in the writeCommand.... call L:268. + * + * This highlights that the listener would be added dispite there being a pending error state that the listener will + * miss as it is not currently part of the _frameListeners set that is being notified by the iterator. + * + * The method waits to ensure that an exception is received before returning. + * + * The calling methods validate that exception that was received based on the one they sent in. + * + * @param trigger The exception to throw through the handler + */ + private void performWithException(Exception trigger) throws InterruptedException + { + + final CountDownLatch callingWriteCommand = new CountDownLatch(1); + + //Set an initial listener that will allow us to create a new blocking method + new Thread(new Runnable() + { + public void run() + { + + try + { + + _logger.info("At initial block, signalling to fire new exception"); + callingWriteCommand.countDown(); + + _handler.writeCommandFrameAndWaitForReply(_blockFrame, _listener); + } + catch (Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + } + } + }).start(); + + _logger.info("Waiting for 'initial block' to start "); + if (!callingWriteCommand.await(1000, TimeUnit.MILLISECONDS)) + { + fail("Failed to start new thread to block for frame"); + } + + // Do what we can to ensure that this thread does not continue before the above thread has hit the synchronized + // block in the writeCommandFrameAndWaitForReply + Thread.yield(); + Thread.sleep(1000); + + _logger.info("Firing Erorr through state manager. There should be not state waiters here."); + _handler.getStateManager().error(trigger); + + _logger.info("Setting state to be CONNECTION_CLOSED."); + + _handler.getStateManager().changeState(AMQState.CONNECTION_CLOSED); + + _logger.info("Firing exception"); + _handler.propagateExceptionToFrameListeners(trigger); + + _logger.info("Awaiting notifcation from handler that exception arrived."); + + if (!_handleCountDown.await(2000, TimeUnit.MILLISECONDS)) + { + fail("Failed to handle exception and timeout has not occured"); + } + + + assertNotNull("The _Listener did not receive the exception", _listener.getReceivedException()); + + assertTrue("Received exception not an AMQException", + _listener.getReceivedException() instanceof AMQException); + + AMQException receivedException = (AMQException) _listener.getReceivedException(); + + assertTrue("The _Listener did not receive the correct message", + receivedException.getMessage().startsWith(trigger.getMessage())); + + + assertEquals("The _Listener did not receive the correct cause", + trigger, receivedException.getCause()); + + assertEquals("The _Listener did not receive the correct sub cause", + trigger.getCause(), receivedException.getCause().getCause()); + + } + + class BlockToAccessFrameListener extends BlockingMethodFrameListener + { + private Exception _receivedException = null; + + /** + * Creates a new method listener, that filters incoming method to just those that match the specified channel id. + * + * @param channelId The channel id to filter incoming methods with. + */ + public BlockToAccessFrameListener(int channelId) + { + super(channelId); + _logger.info("Creating a listener:" + this); + } + + public boolean processMethod(int channelId, AMQMethodBody frame) + { + return true; + } + + @Override + public void error(Exception e) + { + _logger.info("Exception(" + e + ") Received by:" + this); + // Create a new Thread to start the blocking registration. + new Thread(new Runnable() + { + + public void run() + { + //Set an initial listener that will allow us to create a new blocking method + try + { + _handler.writeCommandFrameAndWaitForReply(_blockFrame, null, 2000L); + _logger.info("listener(" + this + ") Wait completed"); + } + catch (Exception e) + { + _logger.info("listener(" + this + ") threw exception:" + e.getMessage()); + _receivedException = e; + } + + _logger.info("listener(" + this + ") completed"); + _handleCountDown.countDown(); + } + }).start(); + } + + public Exception getReceivedException() + { + return _receivedException; + } + } + +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/protocol/MockIoSession.java b/qpid/java/client/src/test/java/org/apache/qpid/client/protocol/MockIoSession.java new file mode 100644 index 0000000000..f0938a4bc0 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/client/protocol/MockIoSession.java @@ -0,0 +1,312 @@ +/* + * + * 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.client.protocol; + +import org.apache.mina.common.*; +import org.apache.mina.common.support.DefaultCloseFuture; +import org.apache.mina.common.support.DefaultWriteFuture; +import org.apache.mina.common.support.AbstractIoFilterChain; +import org.apache.qpid.client.protocol.AMQProtocolSession; + +import java.net.SocketAddress; +import java.net.InetSocketAddress; +import java.util.Set; + +public class MockIoSession implements IoSession +{ + private AMQProtocolSession _protocolSession; + + /** + * Stores the last response written + */ + private Object _lastWrittenObject; + + private boolean _closing; + private IoFilterChain _filterChain; + + public MockIoSession() + { + _filterChain = new AbstractIoFilterChain(this) + { + protected void doWrite(IoSession ioSession, IoFilter.WriteRequest writeRequest) throws Exception + { + + } + + protected void doClose(IoSession ioSession) throws Exception + { + + } + }; + } + + public Object getLastWrittenObject() + { + return _lastWrittenObject; + } + + public IoService getService() + { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + public IoServiceConfig getServiceConfig() + { + return null; + } + + public IoHandler getHandler() + { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + public IoSessionConfig getConfig() + { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + public IoFilterChain getFilterChain() + { + return _filterChain; + } + + public WriteFuture write(Object message) + { + WriteFuture wf = new DefaultWriteFuture(null); + _lastWrittenObject = message; + return wf; + } + + public CloseFuture close() + { + _closing = true; + CloseFuture cf = new DefaultCloseFuture(null); + cf.setClosed(); + return cf; + } + + public Object getAttachment() + { + return _protocolSession; + } + + public Object setAttachment(Object attachment) + { + Object current = _protocolSession; + _protocolSession = (AMQProtocolSession) attachment; + return current; + } + + public Object getAttribute(String key) + { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + public Object setAttribute(String key, Object value) + { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + public Object setAttribute(String key) + { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + public Object removeAttribute(String key) + { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + public boolean containsAttribute(String key) + { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + public Set getAttributeKeys() + { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + public TransportType getTransportType() + { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + public boolean isConnected() + { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + public boolean isClosing() + { + return _closing; + } + + public CloseFuture getCloseFuture() + { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + public SocketAddress getRemoteAddress() + { + return new InetSocketAddress("127.0.0.1", 1234); //To change body of implemented methods use File | Settings | File Templates. + } + + public SocketAddress getLocalAddress() + { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + public SocketAddress getServiceAddress() + { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + public int getIdleTime(IdleStatus status) + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + public long getIdleTimeInMillis(IdleStatus status) + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + public void setIdleTime(IdleStatus status, int idleTime) + { + //To change body of implemented methods use File | Settings | File Templates. + } + + public int getWriteTimeout() + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + public long getWriteTimeoutInMillis() + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + public void setWriteTimeout(int writeTimeout) + { + //To change body of implemented methods use File | Settings | File Templates. + } + + public TrafficMask getTrafficMask() + { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + public void setTrafficMask(TrafficMask trafficMask) + { + //To change body of implemented methods use File | Settings | File Templates. + } + + public void suspendRead() + { + //To change body of implemented methods use File | Settings | File Templates. + } + + public void suspendWrite() + { + //To change body of implemented methods use File | Settings | File Templates. + } + + public void resumeRead() + { + //To change body of implemented methods use File | Settings | File Templates. + } + + public void resumeWrite() + { + //To change body of implemented methods use File | Settings | File Templates. + } + + public long getReadBytes() + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + public long getWrittenBytes() + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + public long getReadMessages() + { + return 0L; + } + + public long getWrittenMessages() + { + return 0L; + } + + public long getWrittenWriteRequests() + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + public int getScheduledWriteRequests() + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + public int getScheduledWriteBytes() + { + return 0; //TODO + } + + public long getCreationTime() + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + public long getLastIoTime() + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + public long getLastReadTime() + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + public long getLastWriteTime() + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + public boolean isIdle(IdleStatus status) + { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + public int getIdleCount(IdleStatus status) + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + public long getLastIdleTime(IdleStatus status) + { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/security/UsernameHashedPasswordCallbackHandlerTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/security/UsernameHashedPasswordCallbackHandlerTest.java new file mode 100644 index 0000000000..98fc09c25b --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/client/security/UsernameHashedPasswordCallbackHandlerTest.java @@ -0,0 +1,99 @@ +/* + * + * 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.client.security; + +import java.security.MessageDigest; +import java.util.Arrays; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; + +import junit.framework.TestCase; + +import org.apache.qpid.client.AMQConnection; +import org.apache.qpid.client.AMQConnectionURL; +import org.apache.qpid.client.MockAMQConnection; +import org.apache.qpid.client.protocol.AMQProtocolHandler; +import org.apache.qpid.client.protocol.AMQProtocolSession; + +/** + * Unit tests for the UsernameHashPasswordCallbackHandler. This callback handler is + * used by the CRAM-MD5-HASHED SASL mechanism. + * + */ +public class UsernameHashedPasswordCallbackHandlerTest extends TestCase +{ + private AMQCallbackHandler _callbackHandler = new UsernameHashedPasswordCallbackHandler(); // Class under test + private static final String PROMPT_UNUSED = "unused"; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + + final String url = "amqp://username:password@client/test?brokerlist='vm://:1'"; + _callbackHandler.initialise(new AMQConnectionURL(url)); + } + + /** + * Tests that the callback handler can correctly retrieve the username from the connection url. + */ + public void testNameCallback() throws Exception + { + final String expectedName = "username"; + NameCallback nameCallback = new NameCallback(PROMPT_UNUSED); + + assertNull("Unexpected name before test", nameCallback.getName()); + _callbackHandler.handle(new Callback[] {nameCallback}); + assertEquals("Unexpected name", expectedName, nameCallback.getName()); + } + + /** + * Tests that the callback handler can correctly retrieve the password from the connection url + * and calculate a MD5. + */ + public void testDigestedPasswordCallback() throws Exception + { + final char[] expectedPasswordDigested = getHashPassword("password"); + + PasswordCallback passwordCallback = new PasswordCallback(PROMPT_UNUSED, false); + assertNull("Unexpected password before test", passwordCallback.getPassword()); + _callbackHandler.handle(new Callback[] {passwordCallback}); + assertTrue("Unexpected password", Arrays.equals(expectedPasswordDigested, passwordCallback.getPassword())); + } + + private char[] getHashPassword(final String password) throws Exception + { + MessageDigest md5Digester = MessageDigest.getInstance("MD5"); + final byte[] digest = md5Digester.digest(password.getBytes("UTF-8")); + + char[] hash = new char[digest.length]; + + int index = 0; + for (byte b : digest) + { + hash[index++] = (char) b; + } + + return hash; + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/client/security/UsernamePasswordCallbackHandlerTest.java b/qpid/java/client/src/test/java/org/apache/qpid/client/security/UsernamePasswordCallbackHandlerTest.java new file mode 100644 index 0000000000..05a60fbef7 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/client/security/UsernamePasswordCallbackHandlerTest.java @@ -0,0 +1,78 @@ +/* + * + * 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.client.security; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; + +import junit.framework.TestCase; + +import org.apache.qpid.client.AMQConnection; +import org.apache.qpid.client.AMQConnectionURL; +import org.apache.qpid.client.MockAMQConnection; +import org.apache.qpid.client.protocol.AMQProtocolHandler; +import org.apache.qpid.client.protocol.AMQProtocolSession; + +/** + * Unit tests for the UsernamePasswordCallbackHandler. + * + */ +public class UsernamePasswordCallbackHandlerTest extends TestCase +{ + private AMQCallbackHandler _callbackHandler = new UsernamePasswordCallbackHandler(); // Class under test + private static final String PROMPT_UNUSED = "unused"; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + + final String url = "amqp://username:password@client/test?brokerlist='vm://:1'"; + + _callbackHandler.initialise(new AMQConnectionURL(url)); + } + + /** + * Tests that the callback handler can correctly retrieve the username from the connection url. + */ + public void testNameCallback() throws Exception + { + final String expectedName = "username"; + NameCallback nameCallback = new NameCallback(PROMPT_UNUSED); + + assertNull("Unexpected name before test", nameCallback.getName()); + _callbackHandler.handle(new Callback[] {nameCallback}); + assertEquals("Unexpected name", expectedName, nameCallback.getName()); + } + + /** + * Tests that the callback handler can correctly retrieve the password from the connection url. + */ + public void testPasswordCallback() throws Exception + { + final String expectedPassword = "password"; + PasswordCallback passwordCallback = new PasswordCallback(PROMPT_UNUSED, false); + assertNull("Unexpected password before test", passwordCallback.getPassword()); + _callbackHandler.handle(new Callback[] {passwordCallback}); + assertEquals("Unexpected password", expectedPassword, new String(passwordCallback.getPassword())); + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/jms/FailoverPolicyTest.java b/qpid/java/client/src/test/java/org/apache/qpid/jms/FailoverPolicyTest.java new file mode 100644 index 0000000000..438995aedc --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/jms/FailoverPolicyTest.java @@ -0,0 +1,338 @@ +/* + * + * 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.jms; + +import javax.jms.ConnectionConsumer; +import javax.jms.ConnectionMetaData; +import javax.jms.Destination; +import javax.jms.ExceptionListener; +import javax.jms.JMSException; +import javax.jms.ServerSessionPool; +import javax.jms.Topic; + +import org.apache.qpid.client.AMQConnectionURL; +import org.apache.qpid.jms.failover.FailoverExchangeMethod; +import org.apache.qpid.jms.failover.FailoverMethod; +import org.apache.qpid.jms.failover.FailoverRoundRobinServers; +import org.apache.qpid.jms.failover.FailoverSingleServer; +import org.apache.qpid.jms.failover.NoFailover; + +import junit.framework.TestCase; + +/** + * Tests the ability of FailoverPolicy to instantiate the correct FailoverMethod. + * + * This test presently does <i>not</i> test {@link FailoverPolicy#FailoverPolicy(FailoverMethod) or + * {@link FailoverPolicy#addMethod(FailoverMethod)} as it appears that this functionality + * is no longer in use. + * + */ +public class FailoverPolicyTest extends TestCase +{ + private FailoverPolicy _failoverPolicy = null; // class under test + private String _url; + private Connection _connection = null; + private ConnectionURL _connectionUrl = null; + + /** + * Tests single server method is selected for a brokerlist with one broker when + * the failover option is not specified. + */ + public void testBrokerListWithOneBrokerDefaultsToSingleServerPolicy() throws Exception + { + _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'"; + _connectionUrl = new AMQConnectionURL(_url); + _connection = createStubConnection(); + + _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); + + assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverSingleServer); + } + + /** + * Tests round robin method is selected for a brokerlist with two brokers when + * the failover option is not specified. + */ + public void testBrokerListWithTwoBrokersDefaultsToRoundRobinPolicy() throws Exception + { + _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'"; + _connectionUrl = new AMQConnectionURL(_url); + _connection = createStubConnection(); + + _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); + + assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverRoundRobinServers); + } + + /** + * Tests single server method is selected for a brokerlist with one broker when + * the failover option passed as 'singlebroker'. + */ + public void testExplictFailoverOptionSingleBroker() throws Exception + { + _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='singlebroker'"; + _connectionUrl = new AMQConnectionURL(_url); + _connection = createStubConnection(); + + _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); + + assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverSingleServer); + } + + /** + * Tests round robin method is selected for a brokerlist with two brokers when + * the failover option passed as 'roundrobin'. + */ + public void testExplictFailoverOptionRoundrobin() throws Exception + { + _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'&failover='roundrobin'"; + _connectionUrl = new AMQConnectionURL(_url); + _connection = createStubConnection(); + + _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); + + assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverRoundRobinServers); + } + + /** + * Tests no failover method is selected for a brokerlist with one broker when + * the failover option passed as 'nofailover'. + */ + public void testExplictFailoverOptionNofailover() throws Exception + { + _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='nofailover'"; + _connectionUrl = new AMQConnectionURL(_url); + _connection = createStubConnection(); + + _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); + + assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof NoFailover); + } + + /** + * Tests failover exchange method is selected for a brokerlist with one broker when + * the failover option passed as 'failover_exchange'. + */ + public void testExplictFailoverOptionFailoverExchange() throws Exception + { + _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='failover_exchange'"; + _connectionUrl = new AMQConnectionURL(_url); + _connection = createStubConnection(); + + _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); + + assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof FailoverExchangeMethod); + } + + /** + * Tests that a custom method can be selected for a brokerlist with one brokers when + * the failover option passed as a qualified class-name. + */ + public void testExplictFailoverOptionDynamicallyLoadedFailoverMethod() throws Exception + { + _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='org.apache.qpid.jms.FailoverPolicyTest$MyFailoverMethod'"; + _connectionUrl = new AMQConnectionURL(_url); + _connection = createStubConnection(); + + _failoverPolicy = new FailoverPolicy(_connectionUrl, _connection); + + assertTrue("Unexpected failover method", _failoverPolicy.getCurrentMethod() instanceof MyFailoverMethod); + } + + /** + * Tests that an unknown method caused an exception. + */ + public void testUnknownFailoverMethod() throws Exception + { + _url = "amqp://user:pass@clientid/test?brokerlist='tcp://localhost:5672'&failover='unknown'"; + _connectionUrl = new AMQConnectionURL(_url); + _connection = createStubConnection(); + + try + { + new FailoverPolicy(_connectionUrl, _connection); + fail("Exception not thrown"); + } + catch(IllegalArgumentException iae) + { + // PASS + } + } + + private Connection createStubConnection() + { + return new Connection() + { + + @Override + public Session createSession(boolean transacted, + int acknowledgeMode, int prefetch) throws JMSException + { + return null; + } + + @Override + public Session createSession(boolean transacted, + int acknowledgeMode, int prefetchHigh, int prefetchLow) + throws JMSException + { + return null; + } + + @Override + public ConnectionListener getConnectionListener() + { + return null; + } + + @Override + public long getMaximumChannelCount() throws JMSException + { + return 0; + } + + @Override + public void setConnectionListener(ConnectionListener listener) + { + } + + @Override + public void close() throws JMSException + { + } + + @Override + public ConnectionConsumer createConnectionConsumer( + Destination arg0, String arg1, ServerSessionPool arg2, + int arg3) throws JMSException + { + return null; + } + + @Override + public ConnectionConsumer createDurableConnectionConsumer( + Topic arg0, String arg1, String arg2, + ServerSessionPool arg3, int arg4) throws JMSException + { + return null; + } + + @Override + public javax.jms.Session createSession(boolean arg0, int arg1) + throws JMSException + { + return null; + } + + @Override + public String getClientID() throws JMSException + { + return null; + } + + @Override + public ExceptionListener getExceptionListener() throws JMSException + { + return null; + } + + @Override + public ConnectionMetaData getMetaData() throws JMSException + { + return null; + } + + @Override + public void setClientID(String arg0) throws JMSException + { + } + + @Override + public void setExceptionListener(ExceptionListener arg0) + throws JMSException + { + } + + @Override + public void start() throws JMSException + { + } + + @Override + public void stop() throws JMSException + { + } + }; + } + + // Class used to test the ability of FailoverPolicy to load an implementation. + static class MyFailoverMethod implements FailoverMethod + { + public MyFailoverMethod(ConnectionURL connectionDetails) + { + } + + @Override + public void attainedConnection() + { + } + + @Override + public boolean failoverAllowed() + { + return false; + } + + @Override + public BrokerDetails getCurrentBrokerDetails() + { + return null; + } + + @Override + public BrokerDetails getNextBrokerDetails() + { + return null; + } + + @Override + public String methodName() + { + return null; + } + + @Override + public void reset() + { + } + + @Override + public void setBroker(BrokerDetails broker) + { + } + + @Override + public void setRetries(int maxRetries) + { + } + } + +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java new file mode 100644 index 0000000000..ddbc69826d --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java @@ -0,0 +1,96 @@ +/* + * + * 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 java.util.Enumeration; +import java.util.Iterator; +import java.util.NoSuchElementException; + +import javax.jms.JMSException; + +import junit.framework.TestCase; + +import org.apache.qpid.client.message.JMSTextMessage; +import org.apache.qpid.client.message.TestMessageHelper; +import org.apache.qpid.framing.FieldTable; +import org.apache.qpid.framing.FieldTableFactory; + +public class FieldTableKeyEnumeratorTest extends TestCase +{ + public void testTrue() + { + + } + public void testKeyEnumeration() + { + FieldTable result = FieldTableFactory.newFieldTable(); + result.setObject("one", 1L); + result.setObject("two", 2L); + result.setObject("three", 3L); + result.setObject("four", 4L); + result.setObject("five", 5L); + + Iterator iterator = result.keys().iterator(); + + try + { + assertTrue("one".equals(iterator.next())); + assertTrue("two".equals(iterator.next())); + assertTrue("three".equals(iterator.next())); + assertTrue("four".equals(iterator.next())); + assertTrue("five".equals(iterator.next())); + } + catch (NoSuchElementException e) + { + fail("All elements should be found."); + } + + } + + public void testPropertEnu() + { + try + { + JMSTextMessage text = TestMessageHelper.newJMSTextMessage(); + + text.setBooleanProperty("Boolean1", true); + text.setBooleanProperty("Boolean2", true); + text.setIntProperty("Int", 2); + text.setLongProperty("Long", 2); + + Enumeration e = text.getPropertyNames(); + + assertTrue("Boolean1".equals(e.nextElement())); + assertTrue("Boolean2".equals(e.nextElement())); + assertTrue("Int".equals(e.nextElement())); + assertTrue("Long".equals(e.nextElement())); + } + catch (JMSException e) + { + + } + } + + public static junit.framework.Test suite() + { + return new junit.framework.TestSuite(FieldTableKeyEnumeratorTest.class); + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTablePropertyTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTablePropertyTest.java new file mode 100644 index 0000000000..60ed688897 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTablePropertyTest.java @@ -0,0 +1,62 @@ +/* + * + * 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 java.util.Enumeration; + +import javax.jms.JMSException; + +import junit.framework.TestCase; + +import org.apache.qpid.client.message.JMSTextMessage; +import org.apache.qpid.client.message.TestMessageHelper; + +public class FieldTablePropertyTest extends TestCase +{ + public void testPropertyNames() + { + try + { + JMSTextMessage text = TestMessageHelper.newJMSTextMessage(); + + text.setBooleanProperty("Boolean1", true); + text.setBooleanProperty("Boolean2", true); + text.setIntProperty("Int", 2); + text.setLongProperty("Long", 2); + + Enumeration e = text.getPropertyNames(); + + assertEquals("Boolean1", e.nextElement()); + assertTrue("Boolean2".equals(e.nextElement())); + assertTrue("Int".equals(e.nextElement())); + assertTrue("Long".equals(e.nextElement())); + } + catch (JMSException e) + { + + } + } + + public static junit.framework.Test suite() + { + return new junit.framework.TestSuite(FieldTablePropertyTest.class); + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/BrokerDetails/BrokerDetailsTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/BrokerDetails/BrokerDetailsTest.java new file mode 100644 index 0000000000..1b27ff6300 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/BrokerDetails/BrokerDetailsTest.java @@ -0,0 +1,99 @@ +/* + * 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.client.BrokerDetails; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.apache.qpid.client.AMQBrokerDetails; +import org.apache.qpid.client.AMQConnectionURL; +import org.apache.qpid.jms.ConnectionURL; +import org.apache.qpid.jms.BrokerDetails; +import org.apache.qpid.url.URLSyntaxException; + +public class BrokerDetailsTest extends TestCase +{ + public void testMultiParameters() throws URLSyntaxException + { + String url = "tcp://localhost:5672?timeout='200',immediatedelivery='true'"; + + AMQBrokerDetails broker = new AMQBrokerDetails(url); + + assertTrue(broker.getProperty("timeout").equals("200")); + assertTrue(broker.getProperty("immediatedelivery").equals("true")); + } + + public void testVMBroker() throws URLSyntaxException + { + String url = "vm://:2"; + + AMQBrokerDetails broker = new AMQBrokerDetails(url); + assertTrue(broker.getTransport().equals("vm")); + assertEquals(broker.getPort(), 2); + } + + public void testTransportsDefaultToTCP() throws URLSyntaxException + { + String url = "localhost:5672"; + + AMQBrokerDetails broker = new AMQBrokerDetails(url); + assertTrue(broker.getTransport().equals("tcp")); + } + + public void testCheckDefaultPort() throws URLSyntaxException + { + String url = "tcp://localhost"; + + AMQBrokerDetails broker = new AMQBrokerDetails(url); + assertTrue(broker.getPort() == AMQBrokerDetails.DEFAULT_PORT); + } + + public void testBothDefaults() throws URLSyntaxException + { + String url = "localhost"; + + AMQBrokerDetails broker = new AMQBrokerDetails(url); + + assertTrue(broker.getTransport().equals("tcp")); + assertTrue(broker.getPort() == AMQBrokerDetails.DEFAULT_PORT); + } + + public void testWrongOptionSeparatorInBroker() + { + String url = "tcp://localhost:5672+option='value'"; + try + { + new AMQBrokerDetails(url); + } + catch (URLSyntaxException urise) + { + assertTrue(urise.getReason().equals("Illegal character in port number")); + } + + } + + public static junit.framework.Test suite() + { + return new junit.framework.TestSuite(BrokerDetailsTest.class); + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseMethodHandlerNoCloseOk.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseMethodHandlerNoCloseOk.java new file mode 100644 index 0000000000..66f220643c --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseMethodHandlerNoCloseOk.java @@ -0,0 +1,97 @@ +/* + * 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.client.channelclose; + +import org.apache.qpid.AMQChannelClosedException; +import org.apache.qpid.AMQException; +import org.apache.qpid.AMQInvalidArgumentException; +import org.apache.qpid.AMQInvalidRoutingKeyException; +import org.apache.qpid.client.AMQNoConsumersException; +import org.apache.qpid.client.AMQNoRouteException; +import org.apache.qpid.client.protocol.AMQProtocolSession; +import org.apache.qpid.client.state.StateAwareMethodListener; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.ChannelCloseBody; +import org.apache.qpid.protocol.AMQConstant; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ChannelCloseMethodHandlerNoCloseOk implements StateAwareMethodListener<ChannelCloseBody> +{ + private static final Logger _logger = LoggerFactory.getLogger(ChannelCloseMethodHandlerNoCloseOk.class); + + private static ChannelCloseMethodHandlerNoCloseOk _handler = new ChannelCloseMethodHandlerNoCloseOk(); + + public static ChannelCloseMethodHandlerNoCloseOk getInstance() + { + return _handler; + } + + public void methodReceived(AMQProtocolSession session, ChannelCloseBody method, int channelId) + throws AMQException + { + _logger.debug("ChannelClose method received"); + + AMQConstant errorCode = AMQConstant.getConstant(method.getReplyCode()); + AMQShortString reason = method.getReplyText(); + if (_logger.isDebugEnabled()) + { + _logger.debug("Channel close reply code: " + errorCode + ", reason: " + reason); + } + + // For this test Method Handler .. don't send Close-OK + // // TODO: Be aware of possible changes to parameter order as versions change. + // AMQFrame frame = ChannelCloseOkBody.createAMQFrame(evt.getChannelId(), method.getMajor(), method.getMinor()); + // protocolSession.writeFrame(frame); + if (errorCode != AMQConstant.REPLY_SUCCESS) + { + _logger.error("Channel close received with errorCode " + errorCode + ", and reason " + reason); + if (errorCode == AMQConstant.NO_CONSUMERS) + { + throw new AMQNoConsumersException("Error: " + reason, null, null); + } + else if (errorCode == AMQConstant.NO_ROUTE) + { + throw new AMQNoRouteException("Error: " + reason, null, null); + } + else if (errorCode == AMQConstant.INVALID_ARGUMENT) + { + _logger.debug("Broker responded with Invalid Argument."); + + throw new AMQInvalidArgumentException(String.valueOf(reason), null); + } + else if (errorCode == AMQConstant.INVALID_ROUTING_KEY) + { + _logger.debug("Broker responded with Invalid Routing Key."); + + throw new AMQInvalidRoutingKeyException(String.valueOf(reason), null); + } + else + { + throw new AMQChannelClosedException(errorCode, "Error: " + reason, null); + } + + } + + session.channelClosed(channelId, errorCode, String.valueOf(reason)); + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/NoCloseOKStateManager.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/NoCloseOKStateManager.java new file mode 100644 index 0000000000..c7eb745566 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/NoCloseOKStateManager.java @@ -0,0 +1,65 @@ +/* + * 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.client.channelclose; + +import org.apache.qpid.client.state.AMQStateManager; +import org.apache.qpid.client.state.AMQState; +import org.apache.qpid.client.handler.ConnectionStartMethodHandler; +import org.apache.qpid.client.handler.ConnectionCloseMethodHandler; +import org.apache.qpid.client.handler.ConnectionTuneMethodHandler; +import org.apache.qpid.client.handler.ConnectionSecureMethodHandler; +import org.apache.qpid.client.handler.ConnectionOpenOkMethodHandler; +import org.apache.qpid.client.handler.ChannelCloseOkMethodHandler; +import org.apache.qpid.client.handler.BasicDeliverMethodHandler; +import org.apache.qpid.client.handler.BasicReturnMethodHandler; +import org.apache.qpid.client.handler.BasicCancelOkMethodHandler; +import org.apache.qpid.client.handler.ChannelFlowOkMethodHandler; +import org.apache.qpid.client.handler.QueueDeleteOkMethodHandler; +import org.apache.qpid.client.handler.ExchangeBoundOkMethodHandler; +import org.apache.qpid.client.protocol.AMQProtocolSession; +import org.apache.qpid.framing.ConnectionStartBody; +import org.apache.qpid.framing.ConnectionCloseBody; +import org.apache.qpid.framing.ConnectionTuneBody; +import org.apache.qpid.framing.ConnectionSecureBody; +import org.apache.qpid.framing.ConnectionOpenOkBody; +import org.apache.qpid.framing.ChannelCloseBody; +import org.apache.qpid.framing.ChannelCloseOkBody; +import org.apache.qpid.framing.BasicDeliverBody; +import org.apache.qpid.framing.BasicReturnBody; +import org.apache.qpid.framing.BasicCancelOkBody; +import org.apache.qpid.framing.ChannelFlowOkBody; +import org.apache.qpid.framing.QueueDeleteOkBody; +import org.apache.qpid.framing.ExchangeBoundOkBody; + +import java.util.Map; +import java.util.HashMap; + +public class NoCloseOKStateManager extends AMQStateManager +{ + public NoCloseOKStateManager(AMQProtocolSession protocolSession) + { + super(protocolSession); + } + + + + +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java new file mode 100644 index 0000000000..2c5fa0112e --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java @@ -0,0 +1,588 @@ +/* + * + * 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.client.connectionurl; + +import junit.framework.TestCase; + +import org.apache.qpid.client.AMQBrokerDetails; +import org.apache.qpid.client.AMQConnectionURL; +import org.apache.qpid.jms.BrokerDetails; +import org.apache.qpid.jms.ConnectionURL; +import org.apache.qpid.url.URLSyntaxException; + +public class ConnectionURLTest extends TestCase +{ + + public void testFailoverURL() throws URLSyntaxException + { + String url = "amqp://ritchiem:bob@/test?brokerlist='tcp://localhost:5672;tcp://fancyserver:3000/',failover='roundrobin?cyclecount='100''"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getFailoverMethod().equals("roundrobin")); + assertEquals("100", connectionurl.getFailoverOption(ConnectionURL.OPTIONS_FAILOVER_CYCLE)); + assertTrue(connectionurl.getUsername().equals("ritchiem")); + assertTrue(connectionurl.getPassword().equals("bob")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + assertTrue(connectionurl.getBrokerCount() == 2); + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertTrue(service.getTransport().equals("tcp")); + assertTrue(service.getHost().equals("localhost")); + assertTrue(service.getPort() == 5672); + + service = connectionurl.getBrokerDetails(1); + + assertTrue(service.getTransport().equals("tcp")); + assertTrue(service.getHost().equals("fancyserver")); + assertTrue(service.getPort() == 3000); + + } + + public void testSingleTransportUsernamePasswordURL() throws URLSyntaxException + { + String url = "amqp://ritchiem:bob@/test?brokerlist='tcp://localhost:5672'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getFailoverMethod() == null); + assertTrue(connectionurl.getUsername().equals("ritchiem")); + assertTrue(connectionurl.getPassword().equals("bob")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + assertTrue(connectionurl.getBrokerCount() == 1); + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertTrue(service.getTransport().equals("tcp")); + assertTrue(service.getHost().equals("localhost")); + assertTrue(service.getPort() == 5672); + } + + public void testSingleTransportUsernameBlankPasswordURL() throws URLSyntaxException + { + String url = "amqp://ritchiem:@/test?brokerlist='tcp://localhost:5672'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getFailoverMethod() == null); + assertTrue(connectionurl.getUsername().equals("ritchiem")); + assertTrue(connectionurl.getPassword().equals("")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + assertTrue(connectionurl.getBrokerCount() == 1); + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertTrue(service.getTransport().equals("tcp")); + assertTrue(service.getHost().equals("localhost")); + assertTrue(service.getPort() == 5672); + } + + public void testFailedURLNullPassword() + { + String url = "amqp://ritchiem@/test?brokerlist='tcp://localhost:5672'"; + + try + { + new AMQConnectionURL(url); + fail("URL has null password"); + } + catch (URLSyntaxException e) + { + assertTrue(e.getReason().equals("Null password in user information not allowed.")); + assertTrue(e.getIndex() == 7); + } + } + + + public void testSingleTransportURL() throws URLSyntaxException + { + String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + + assertTrue(connectionurl.getFailoverMethod() == null); + assertTrue(connectionurl.getUsername().equals("guest")); + assertTrue(connectionurl.getPassword().equals("guest")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + + assertTrue(connectionurl.getBrokerCount() == 1); + + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertTrue(service.getTransport().equals("tcp")); + assertTrue(service.getHost().equals("localhost")); + assertTrue(service.getPort() == 5672); + } + + public void testSingleTransportWithClientURLURL() throws URLSyntaxException + { + String url = "amqp://guest:guest@clientname/test?brokerlist='tcp://localhost:5672'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + + assertTrue(connectionurl.getFailoverMethod() == null); + assertTrue(connectionurl.getUsername().equals("guest")); + assertTrue(connectionurl.getPassword().equals("guest")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + assertTrue(connectionurl.getClientName().equals("clientname")); + + + assertTrue(connectionurl.getBrokerCount() == 1); + + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertTrue(service.getTransport().equals("tcp")); + assertTrue(service.getHost().equals("localhost")); + assertTrue(service.getPort() == 5672); + } + + public void testSingleTransport1OptionURL() throws URLSyntaxException + { + String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672',routingkey='jim'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getFailoverMethod() == null); + assertTrue(connectionurl.getUsername().equals("guest")); + assertTrue(connectionurl.getPassword().equals("guest")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + + assertTrue(connectionurl.getBrokerCount() == 1); + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertTrue(service.getTransport().equals("tcp")); + + assertTrue(service.getHost().equals("localhost")); + assertTrue(service.getPort() == 5672); + assertTrue(connectionurl.getOption("routingkey").equals("jim")); + } + + public void testSingleTransportDefaultedBroker() throws URLSyntaxException + { + String url = "amqp://guest:guest@/test?brokerlist='localhost'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getFailoverMethod() == null); + assertTrue(connectionurl.getUsername().equals("guest")); + assertTrue(connectionurl.getPassword().equals("guest")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + + assertTrue(connectionurl.getBrokerCount() == 1); + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertTrue(service.getTransport().equals("tcp")); + + assertTrue(service.getHost().equals("localhost")); + assertTrue(service.getPort() == 5672); + } + + public void testSingleTransportDefaultedBrokerWithPort() throws URLSyntaxException + { + String url = "amqp://guest:guest@/test?brokerlist='localhost:1234'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getFailoverMethod() == null); + assertTrue(connectionurl.getUsername().equals("guest")); + assertTrue(connectionurl.getPassword().equals("guest")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + + assertTrue(connectionurl.getBrokerCount() == 1); + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertTrue(service.getTransport().equals("tcp")); + + assertTrue(service.getHost().equals("localhost")); + assertTrue(service.getPort() == 1234); + } + + public void testSingleTransportDefaultedBrokerWithIP() throws URLSyntaxException + { + String url = "amqp://guest:guest@/test?brokerlist='127.0.0.1'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getFailoverMethod() == null); + assertTrue(connectionurl.getUsername().equals("guest")); + assertTrue(connectionurl.getPassword().equals("guest")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + + assertTrue(connectionurl.getBrokerCount() == 1); + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertTrue(service.getTransport().equals("tcp")); + + assertTrue(service.getHost().equals("127.0.0.1")); + assertTrue(service.getPort() == 5672); + } + + public void testSingleTransportDefaultedBrokerWithIPandPort() throws URLSyntaxException + { + String url = "amqp://guest:guest@/test?brokerlist='127.0.0.1:1234'"; + +// ConnectionURL connectionurl = new AMQConnectionURL(url); +// +// assertTrue(connectionurl.getFailoverMethod() == null); +// assertTrue(connectionurl.getUsername().equals("guest")); +// assertTrue(connectionurl.getPassword().equals("guest")); +// assertTrue(connectionurl.getVirtualHost().equals("/temp")); +// +// +// assertTrue(connectionurl.getBrokerCount() == 1); +// +// BrokerDetails service = connectionurl.getBrokerDetails(0); +// +// assertTrue(service.getTransport().equals("tcp")); +// +// assertTrue(service.getHost().equals("127.0.0.1")); +// assertTrue(service.getPort() == 1234); + } + + + public void testSingleTransportMultiOptionURL() throws URLSyntaxException + { + String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672?foo='jim'&bar='bob'&fred='jimmy'',routingkey='jim',timeout='200',immediatedelivery='true'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getFailoverMethod() == null); + assertTrue(connectionurl.getUsername().equals("guest")); + assertTrue(connectionurl.getPassword().equals("guest")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + assertTrue(connectionurl.getBrokerCount() == 1); + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertTrue(service.getTransport().equals("tcp")); + + assertTrue(service.getHost().equals("localhost")); + assertTrue(service.getPort() == 5672); + + assertTrue(connectionurl.getOption("routingkey").equals("jim")); + assertTrue(connectionurl.getOption("timeout").equals("200")); + assertTrue(connectionurl.getOption("immediatedelivery").equals("true")); + } + + public void testSinglevmURL() throws URLSyntaxException + { + String url = "amqp://guest:guest@/test?brokerlist='vm://:2'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getFailoverMethod() == null); + assertTrue(connectionurl.getUsername().equals("guest")); + assertTrue(connectionurl.getPassword().equals("guest")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + assertTrue(connectionurl.getBrokerCount() == 1); + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertTrue(service.getTransport().equals("vm")); + assertTrue(service.getHost().equals("")); + assertTrue(service.getPort() == 2); + + } + + public void testFailoverVMURL() throws URLSyntaxException + { + String url = "amqp://ritchiem:bob@/test?brokerlist='vm://:2;vm://:3',failover='roundrobin'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getFailoverMethod().equals("roundrobin")); + assertTrue(connectionurl.getUsername().equals("ritchiem")); + assertTrue(connectionurl.getPassword().equals("bob")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + assertTrue(connectionurl.getBrokerCount() == 2); + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertTrue(service.getTransport().equals("vm")); + assertTrue(service.getHost().equals("")); + assertTrue(service.getPort() == 2); + + service = connectionurl.getBrokerDetails(1); + assertTrue(service.getTransport().equals("vm")); + assertTrue(service.getHost().equals("")); + assertTrue(service.getPort() == 3); + } + + + public void testNoVirtualHostURL() + { + String url = "amqp://user@?brokerlist='tcp://localhost:5672'"; + + try + { + new AMQConnectionURL(url); + fail("URL has no virtual host should not parse"); + } + catch (URLSyntaxException e) + { + // This should occur. + } + } + + public void testNoClientID() throws URLSyntaxException + { + String url = "amqp://user:@/test?brokerlist='tcp://localhost:5672'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getUsername().equals("user")); + assertTrue(connectionurl.getPassword().equals("")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + assertTrue(connectionurl.getBrokerCount() == 1); + } + + public void testClientIDWithUnderscore() throws URLSyntaxException + { + String url = "amqp://user:pass@client_id/test?brokerlist='tcp://localhost:5672'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getUsername().equals("user")); + assertTrue(connectionurl.getPassword().equals("pass")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + assertTrue(connectionurl.getClientName().equals("client_id")); + + assertTrue(connectionurl.getBrokerCount() == 1); + } + + public void testWrongOptionSeparatorInOptions() + { + String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'+failover='roundrobin'"; + try + { + new AMQConnectionURL(url); + fail("URL Should not parse"); + } + catch (URLSyntaxException urise) + { + assertTrue(urise.getReason().equals("Unterminated option. Possible illegal option separator:'+'")); + } + + } + + + public void testNoUserDetailsProvidedWithClientID() + + { + String url = "amqp://clientID/test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'"; + try + { + new AMQConnectionURL(url); + fail("URL Should not parse"); + } + catch (URLSyntaxException urise) + { + assertTrue(urise.getMessage().startsWith("User information not found on url")); + } + + } + + public void testNoUserDetailsProvidedNOClientID() + + { + String url = "amqp:///test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'"; + try + { + new AMQConnectionURL(url); + fail("URL Should not parse"); + } + catch (URLSyntaxException urise) + { + assertTrue(urise.getMessage().startsWith("User information not found on url")); + } + + } + + public void testCheckVirtualhostFormat() throws URLSyntaxException + { + String url = "amqp://guest:guest@/t.-_+!=:?brokerlist='tcp://localhost:5672'"; + + AMQConnectionURL connection = new AMQConnectionURL(url); + assertTrue(connection.getVirtualHost().equals("/t.-_+!=:")); + } + + public void testCheckDefaultPort() throws URLSyntaxException + { + String url = "amqp://guest:guest@/test=:?brokerlist='tcp://localhost'"; + + AMQConnectionURL connection = new AMQConnectionURL(url); + + BrokerDetails broker = connection.getBrokerDetails(0); + assertTrue(broker.getPort() == AMQBrokerDetails.DEFAULT_PORT); + + } + + public void testCheckMissingFinalQuote() throws URLSyntaxException + { + String url = "amqp://guest:guest@id/test" + "?brokerlist='tcp://localhost:5672"; + + try + { + new AMQConnectionURL(url); + } + catch (URLSyntaxException e) + { + assertEquals(e.getMessage(), "Unterminated option at index 32: brokerlist='tcp://localhost:5672"); + } + } + + + public void testDefaultExchanges() throws URLSyntaxException + { + String url = "amqp://guest:guest@id/test" + "?defaultQueueExchange='test.direct'&defaultTopicExchange='test.topic'&temporaryQueueExchange='tmp.direct'&temporaryTopicExchange='tmp.topic'"; + + AMQConnectionURL conn = new AMQConnectionURL(url); + + assertEquals(conn.getDefaultQueueExchangeName(),"test.direct"); + + assertEquals(conn.getDefaultTopicExchangeName(),"test.topic"); + + assertEquals(conn.getTemporaryQueueExchangeName(),"tmp.direct"); + + assertEquals(conn.getTemporaryTopicExchangeName(),"tmp.topic"); + + } + + public void testSocketProtocol() throws URLSyntaxException + { + String url = "amqp://guest:guest@id/test" + "?brokerlist='socket://VM-Unique-socketID'"; + + try + { + AMQConnectionURL curl = new AMQConnectionURL(url); + assertNotNull(curl); + assertEquals(1, curl.getBrokerCount()); + assertNotNull(curl.getBrokerDetails(0)); + assertEquals(BrokerDetails.SOCKET, curl.getBrokerDetails(0).getTransport()); + assertEquals("VM-Unique-socketID", curl.getBrokerDetails(0).getHost()); + assertEquals("URL does not toString as expected", + url.replace(":guest", ":********"), curl.toString()); + } + catch (URLSyntaxException e) + { + fail(e.getMessage()); + } + } + + public void testSingleTransportMultiOptionOnBrokerURL() throws URLSyntaxException + { + String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672?foo='jim'&bar='bob'&fred='jimmy'',routingkey='jim',timeout='200',immediatedelivery='true'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getFailoverMethod() == null); + assertTrue(connectionurl.getUsername().equals("guest")); + assertTrue(connectionurl.getPassword().equals("guest")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + assertTrue(connectionurl.getBrokerCount() == 1); + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertTrue(service.getTransport().equals("tcp")); + + + assertTrue(service.getHost().equals("localhost")); + assertTrue(service.getPort() == 5672); + assertEquals("jim",service.getProperty("foo")); + assertEquals("bob",service.getProperty("bar")); + assertEquals("jimmy",service.getProperty("fred")); + + assertTrue(connectionurl.getOption("routingkey").equals("jim")); + assertTrue(connectionurl.getOption("timeout").equals("200")); + assertTrue(connectionurl.getOption("immediatedelivery").equals("true")); + } + + /** + * Test that options other than failover and brokerlist are returned in the string representation. + * <p> + * QPID-2697 + */ + public void testOptionToString() throws Exception + { + ConnectionURL url = new AMQConnectionURL("amqp://user:pass@temp/test?maxprefetch='12345'&brokerlist='tcp://localhost:5672'"); + + assertTrue("String representation should contain options and values", url.toString().contains("maxprefetch='12345'")); + } + + public void testHostNamesWithUnderScore() throws URLSyntaxException + { + String url = "amqp://guest:guest@clientid/test?brokerlist='tcp://under_score:6672'"; + + ConnectionURL connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getUsername().equals("guest")); + assertTrue(connectionurl.getPassword().equals("guest")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + assertTrue(connectionurl.getBrokerCount() == 1); + BrokerDetails service = connectionurl.getBrokerDetails(0); + assertTrue(service.getTransport().equals("tcp")); + assertTrue(service.getHost().equals("under_score")); + assertTrue(service.getPort() == 6672); + + url = "amqp://guest:guest@clientid/test?brokerlist='tcp://under_score'"; + + connectionurl = new AMQConnectionURL(url); + + assertTrue(connectionurl.getUsername().equals("guest")); + assertTrue(connectionurl.getPassword().equals("guest")); + assertTrue(connectionurl.getVirtualHost().equals("/test")); + + assertTrue(connectionurl.getBrokerCount() == 1); + service = connectionurl.getBrokerDetails(0); + assertTrue(service.getTransport().equals("tcp")); + assertTrue(service.getHost().equals("under_score")); + assertTrue(service.getPort() == 5672); + } + + public static junit.framework.Test suite() + { + return new junit.framework.TestSuite(ConnectionURLTest.class); + } +} + diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/destinationurl/DestinationURLTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/destinationurl/DestinationURLTest.java new file mode 100644 index 0000000000..7de09cff45 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/destinationurl/DestinationURLTest.java @@ -0,0 +1,197 @@ +/* + * + * 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.client.destinationurl; + +import junit.framework.TestCase; + +import org.apache.qpid.exchange.ExchangeDefaults; +import org.apache.qpid.url.AMQBindingURL; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.net.URISyntaxException; + +public class DestinationURLTest extends TestCase +{ + private static final Logger _logger = LoggerFactory.getLogger(DestinationURLTest.class); + + public void testFullURL() throws URISyntaxException + { + + String url = "exchange.Class://exchangeName/Destination/Queue"; + + AMQBindingURL dest = new AMQBindingURL(url); + + assertTrue(url.equals(dest.toString())); + + assertTrue(dest.getExchangeClass().equals("exchange.Class")); + assertTrue(dest.getExchangeName().equals("exchangeName")); + assertTrue(dest.getDestinationName().equals("Destination")); + assertTrue(dest.getQueueName().equals("Queue")); + } + + public void testQueue() throws URISyntaxException + { + + String url = "exchangeClass://exchangeName//Queue"; + + AMQBindingURL dest = new AMQBindingURL(url); + + assertTrue(url.equals(dest.toString())); + + assertTrue(dest.getExchangeClass().equals("exchangeClass")); + assertTrue(dest.getExchangeName().equals("exchangeName")); + assertTrue(dest.getDestinationName().equals("")); + assertTrue(dest.getQueueName().equals("Queue")); + } + + public void testQueueWithOption() throws URISyntaxException + { + + String url = "exchangeClass://exchangeName//Queue?option='value'"; + + AMQBindingURL dest = new AMQBindingURL(url); + + assertTrue(url.equals(dest.toString())); + + assertTrue(dest.getExchangeClass().equals("exchangeClass")); + assertTrue(dest.getExchangeName().equals("exchangeName")); + assertTrue(dest.getDestinationName().equals("")); + assertTrue(dest.getQueueName().equals("Queue")); + assertTrue(dest.getOption("option").equals("value")); + } + + + public void testDestination() throws URISyntaxException + { + + String url = "exchangeClass://exchangeName/Destination/"; + + AMQBindingURL dest = new AMQBindingURL(url); + + assertTrue(url.equals(dest.toString())); + + assertTrue(dest.getExchangeClass().equals("exchangeClass")); + assertTrue(dest.getExchangeName().equals("exchangeName")); + assertTrue(dest.getDestinationName().equals("Destination")); + assertTrue(dest.getQueueName().equals("")); + } + + public void testDestinationWithOption() throws URISyntaxException + { + + String url = "exchangeClass://exchangeName/Destination/?option='value'"; + + AMQBindingURL dest = new AMQBindingURL(url); + + assertTrue(url.equals(dest.toString())); + + assertTrue(dest.getExchangeClass().equals("exchangeClass")); + assertTrue(dest.getExchangeName().equals("exchangeName")); + assertTrue(dest.getDestinationName().equals("Destination")); + assertTrue(dest.getQueueName().equals("")); + + assertTrue(dest.getOption("option").equals("value")); + } + + public void testDestinationWithMultiOption() throws URISyntaxException + { + + String url = "exchangeClass://exchangeName/Destination/?option='value',option2='value2'"; + + AMQBindingURL dest = new AMQBindingURL(url); + + assertTrue(dest.getExchangeClass().equals("exchangeClass")); + assertTrue(dest.getExchangeName().equals("exchangeName")); + assertTrue(dest.getDestinationName().equals("Destination")); + assertTrue(dest.getQueueName().equals("")); + + assertTrue(dest.getOption("option").equals("value")); + assertTrue(dest.getOption("option2").equals("value2")); + } + + public void testDestinationWithNoExchangeDefaultsToDirect() throws URISyntaxException + { + + String url = "IBMPerfQueue1?durable='true'"; + + AMQBindingURL dest = new AMQBindingURL(url); + + assertTrue(dest.getExchangeClass().equals(ExchangeDefaults.DIRECT_EXCHANGE_CLASS)); + assertTrue(dest.getExchangeName().equals("")); + assertTrue(dest.getDestinationName().equals("")); + assertTrue(dest.getQueueName().equals("IBMPerfQueue1")); + + assertTrue(dest.getOption("durable").equals("true")); + } + + public void testDestinationWithMultiBindingKeys() throws URISyntaxException + { + + String url = "exchangeClass://exchangeName/Destination/?bindingkey='key1',bindingkey='key2'"; + + AMQBindingURL dest = new AMQBindingURL(url); + + assertTrue(dest.getExchangeClass().equals("exchangeClass")); + assertTrue(dest.getExchangeName().equals("exchangeName")); + assertTrue(dest.getDestinationName().equals("Destination")); + assertTrue(dest.getQueueName().equals("")); + + assertTrue(dest.getBindingKeys().length == 2); + } + + // You can only specify only a routing key or binding key, but not both. + public void testDestinationIfOnlyRoutingKeyOrBindingKeyIsSpecified() throws URISyntaxException + { + + String url = "exchangeClass://exchangeName/Destination/?bindingkey='key1',routingkey='key2'"; + boolean exceptionThrown = false; + try + { + + new AMQBindingURL(url); + } + catch(URISyntaxException e) + { + exceptionThrown = true; + _logger.info("Exception thrown",e); + } + + assertTrue("Failed to throw an URISyntaxException when both the bindingkey and routingkey is specified",exceptionThrown); + } + + public void testDestinationWithDurableTopic() throws URISyntaxException + { + + String url = "topic://amq.topic//testTopicD?durable='true'&autodelete='true'&clientid='test'&subscription='testQueueD'"; + + AMQBindingURL dest = new AMQBindingURL(url); + + assertTrue(dest.getExchangeClass().equals("topic")); + assertTrue(dest.getExchangeName().equals("amq.topic")); + assertTrue(dest.getQueueName().equals("test:testQueueD")); + } + + public static junit.framework.Test suite() + { + return new junit.framework.TestSuite(DestinationURLTest.class); + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/BytesMessageTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/BytesMessageTest.java new file mode 100644 index 0000000000..65013e7e6d --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/BytesMessageTest.java @@ -0,0 +1,569 @@ +/* + * + * 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.client.message; + +import java.util.HashMap; + +import javax.jms.MessageEOFException; +import javax.jms.MessageFormatException; +import javax.jms.MessageNotReadableException; +import javax.jms.MessageNotWriteableException; + +import junit.framework.TestCase; + +import org.apache.qpid.client.message.JMSBytesMessage; +import org.apache.qpid.client.message.TestMessageHelper; + +public class BytesMessageTest extends TestCase +{ + /** + * Tests that on creation a call to getBodyLength() throws an exception + * if null was passed in during creation + */ + public void testNotReadableOnCreationWithNull() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.getBodyLength(); + fail("expected exception did not occur"); + } + catch (MessageNotReadableException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageNotReadableException, got " + e); + } + } + + public void testResetMakesReadble() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeInt(10); + bm.reset(); + bm.writeInt(12); + fail("expected exception did not occur"); + } + catch (MessageNotWriteableException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageNotWriteableException, got " + e); + } + } + + public void testClearBodyMakesWritable() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeInt(10); + bm.reset(); + bm.clearBody(); + bm.writeInt(10); + } + + public void testWriteBoolean() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeBoolean(true); + bm.writeBoolean(false); + bm.reset(); + boolean val = bm.readBoolean(); + assertEquals(true, val); + val = bm.readBoolean(); + assertEquals(false, val); + } + + public void testWriteInt() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeInt(10); + bm.reset(); + long len = bm.getBodyLength(); + assertTrue(len == 4); + int val = bm.readInt(); + assertTrue(val == 10); + } + + public void testWriteString() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeUTF("Bananas"); + bm.reset(); + String res = bm.readUTF(); + assertEquals("Bananas", res); + } + + public void testWriteBytes() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + byte[] bytes = {1,2,3,4}; + bm.writeBytes(bytes, 1, 2); + bm.reset(); + bytes = new byte[2]; + bm.readBytes(bytes); + assertEquals(2, bytes[0]); + assertEquals(3, bytes[1]); + } + + public void testWriteObject() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeObject(new Boolean(true)); + bm.writeObject(new Boolean(false)); + bm.writeObject(new Byte((byte)2)); + bm.writeObject(new byte[]{1,2,3,4}); + bm.writeObject(new Character('g')); + bm.writeObject(new Short((short) 29)); + bm.writeObject(new Integer(101)); + bm.writeObject(new Long(50003222L)); + bm.writeObject("Foobar"); + bm.writeObject(new Float(1.7f)); + bm.writeObject(new Double(8.7d)); + bm.reset(); + assertTrue(bm.readBoolean()); + assertTrue(!bm.readBoolean()); + assertEquals((byte)2, bm.readByte()); + byte[] bytes = new byte[4]; + bm.readBytes(bytes); + assertEquals('g', bm.readChar()); + assertEquals((short) 29, bm.readShort()); + assertEquals(101, bm.readInt()); + assertEquals(50003222L, bm.readLong()); + assertEquals("Foobar", bm.readUTF()); + assertEquals(1.7f, bm.readFloat()); + assertEquals(8.7d, bm.readDouble()); + } + + public void testWriteObjectRejectsNonPrimitives() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeObject(new HashMap()); + fail("expected MessageFormatException was not thrown"); + } + catch (MessageFormatException e) + { + // pass + } + } + + public void testWriteObjectThrowsNPE() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeObject(null); + fail("expected exception did not occur"); + } + catch (NullPointerException n) + { + // ok + } + catch (Exception e) + { + fail("expected NullPointerException, got " + e); + } + } + + public void testReadBoolean() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeBoolean(true); + bm.reset(); + boolean result = bm.readBoolean(); + assertTrue(result); + } + + public void testReadUnsignedByte() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeByte((byte) 9); + bm.reset(); + int result = bm.readUnsignedByte(); + assertEquals(9, result); + } + + public void testReadUnsignedShort() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeShort((byte) 9); + bm.reset(); + int result = bm.readUnsignedShort(); + assertEquals(9, result); + } + + public void testReadBytesChecksNull() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.readBytes(null); + } + catch (IllegalArgumentException e) + { + // pass + } + + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.readBytes(null, 1); + } + catch (IllegalArgumentException e) + { + // pass + } + } + + public void testReadBytesChecksMaxSize() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + byte[] bytes = new byte[100]; + bm.readBytes(bytes, 120); + } + catch (IllegalArgumentException e) + { + // pass + } + } + + public void testReadBytesReturnsCorrectLengths() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + byte[] bytes = {2, 3}; + bm.writeBytes(bytes); + bm.reset(); + int len = bm.readBytes(bytes); + assertEquals(2, len); + len = bm.readBytes(bytes); + assertEquals(-1, len); + len = bm.readBytes(bytes, 2); + assertEquals(-1, len); + bm.reset(); + len = bm.readBytes(bytes, 2); + assertEquals(2, len); + bm.reset(); + len = bm.readBytes(bytes, 1); + assertEquals(1, len); + + } + + public void testEOFByte() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeByte((byte)1); + bm.reset(); + bm.readByte(); + // should throw + bm.readByte(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFUnsignedByte() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeByte((byte)1); + bm.reset(); + bm.readByte(); + // should throw + bm.readUnsignedByte(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFBoolean() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeBoolean(true); + bm.reset(); + bm.readBoolean(); + // should throw + bm.readBoolean(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFChar() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeChar('A'); + bm.reset(); + bm.readChar(); + // should throw + bm.readChar(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFDouble() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeDouble(1.3d); + bm.reset(); + bm.readDouble(); + // should throw + bm.readDouble(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFFloat() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeFloat(1.3f); + bm.reset(); + bm.readFloat(); + // should throw + bm.readFloat(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFInt() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeInt(99); + bm.reset(); + bm.readInt(); + // should throw + bm.readInt(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFLong() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeLong(4L); + bm.reset(); + bm.readLong(); + // should throw + bm.readLong(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFShort() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeShort((short)4); + bm.reset(); + bm.readShort(); + // should throw + bm.readShort(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFUnsignedShort() throws Exception + { + try + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeShort((short)4); + bm.reset(); + bm.readUnsignedShort(); + // should throw + bm.readUnsignedShort(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + /** + * Tests that the readBytes() method populates the passed in array + * correctly + * @throws Exception + */ + public void testReadBytes() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeByte((byte)3); + bm.writeByte((byte)4); + bm.reset(); + byte[] result = new byte[2]; + int count = bm.readBytes(result); + assertEquals((byte)3, result[0]); + assertEquals((byte)4, result[1]); + assertEquals(2, count); + } + + public void testReadBytesEOF() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeByte((byte)3); + bm.writeByte((byte)4); + bm.reset(); + byte[] result = new byte[2]; + bm.readBytes(result); + int count = bm.readBytes(result); + assertEquals(-1, count); + } + + public void testReadBytesWithLargerArray() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeByte((byte)3); + bm.writeByte((byte)4); + bm.reset(); + byte[] result = new byte[3]; + int count = bm.readBytes(result); + assertEquals(2, count); + assertEquals((byte)3, result[0]); + assertEquals((byte)4, result[1]); + assertEquals((byte)0, result[2]); + } + + public void testReadBytesWithCount() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.writeByte((byte)3); + bm.writeByte((byte)4); + bm.writeByte((byte)5); + bm.reset(); + byte[] result = new byte[3]; + int count = bm.readBytes(result, 2); + assertEquals(2, count); + assertEquals((byte)3, result[0]); + assertEquals((byte)4, result[1]); + assertEquals((byte)0, result[2]); + } + + public void testToBodyStringWithNull() throws Exception + { + JMSBytesMessage bm = TestMessageHelper.newJMSBytesMessage(); + bm.reset(); + String result = bm.toBodyString(); + assertEquals("\"\"", result); + } + + public static junit.framework.Test suite() + { + return new junit.framework.TestSuite(BytesMessageTest.class); + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/MapMessageTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/MapMessageTest.java new file mode 100644 index 0000000000..3e04c36b38 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/MapMessageTest.java @@ -0,0 +1,383 @@ +/* + * 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.client.message; + +import javax.jms.JMSException; +import javax.jms.MessageFormatException; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.qpid.client.message.JMSMapMessage; +import org.apache.qpid.client.message.TestMessageHelper; + + +public class MapMessageTest extends TestCase +{ + + //Test Lookups + + public void testBooleanLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + + mm.setBoolean("value", true); + Assert.assertEquals(true, mm.getBoolean("value")); + Assert.assertEquals("true", mm.getString("value")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testByteLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.setByte("value", Byte.MAX_VALUE); + + Assert.assertEquals(Byte.MAX_VALUE, mm.getByte("value")); + Assert.assertEquals((short) Byte.MAX_VALUE, mm.getShort("value")); + Assert.assertEquals(Byte.MAX_VALUE, mm.getInt("value")); + Assert.assertEquals((long) Byte.MAX_VALUE, mm.getLong("value")); + Assert.assertEquals("" + Byte.MAX_VALUE, mm.getString("value")); + + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testShortLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.setShort("value", Short.MAX_VALUE); + Assert.assertEquals(Short.MAX_VALUE, mm.getShort("value")); + Assert.assertEquals((int) Short.MAX_VALUE, mm.getInt("value")); + Assert.assertEquals((long) Short.MAX_VALUE, mm.getLong("value")); + Assert.assertEquals("" + Short.MAX_VALUE, mm.getString("value")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + + public void testCharLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + + mm.setChar("value", 'c'); + Assert.assertEquals('c', mm.getChar("value")); + Assert.assertEquals("c", mm.getString("value")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + + mm.setString("value", null); + mm.getChar("value"); + fail("Expected NullPointerException"); + + } + catch (NullPointerException e) + { + ; // pass + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + + + + } + + public void testDoubleLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.setDouble("value", Double.MAX_VALUE); + Assert.assertEquals(Double.MAX_VALUE, mm.getDouble("value")); + Assert.assertEquals("" + Double.MAX_VALUE, mm.getString("value")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testFloatLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.setFloat("value", Float.MAX_VALUE); + Assert.assertEquals(Float.MAX_VALUE, mm.getFloat("value")); + Assert.assertEquals((double) Float.MAX_VALUE, mm.getDouble("value")); + Assert.assertEquals("" + Float.MAX_VALUE, mm.getString("value")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testIntLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.setInt("value", Integer.MAX_VALUE); + Assert.assertEquals(Integer.MAX_VALUE, mm.getInt("value")); + Assert.assertEquals((long) Integer.MAX_VALUE, mm.getLong("value")); + Assert.assertEquals("" + Integer.MAX_VALUE, mm.getString("value")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testLongLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.setLong("value", Long.MAX_VALUE); + Assert.assertEquals(Long.MAX_VALUE, mm.getLong("value")); + Assert.assertEquals("" + Long.MAX_VALUE, mm.getString("value")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testBytesLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + byte[] bytes = {99, 98, 97, 96, 95}; + mm.setBytes("bytes", bytes); + assertBytesEqual(bytes, mm.getBytes("bytes")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + // Failed Lookups + + public void testFailedBooleanLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + Assert.assertEquals(false, mm.getBoolean("int")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testFailedByteLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getByte("random"); + Assert.fail("NumberFormatException expected"); + } + catch (NumberFormatException e) + { + //normal execution + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + + } + + public void testFailedBytesLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getBytes("random"); + Assert.fail("MessageFormatException expected"); + } + catch (MessageFormatException mfe) + { + //normal path + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + } + + public void testFailedCharLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getChar("random"); + Assert.fail("MessageFormatException expected"); + } + catch (MessageFormatException e) + { + //normal execution + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + } + + public void testFailedDoubleLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getDouble("random"); + Assert.fail("NullPointerException should be received."); + } + catch (NullPointerException e) + { + //normal execution + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + } + + public void testFailedFloatLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getFloat("random"); + Assert.fail("NullPointerException should be received."); + } + catch (NullPointerException e) + { + //normal execution + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + } + + public void testFailedIntLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getInt("random"); + Assert.fail("NumberFormatException should be received."); + } + catch (NumberFormatException e) + { + //normal execution + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + } + + public void testFailedLongLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getLong("random"); + Assert.fail("NumberFormatException should be received."); + } + catch (NumberFormatException e) + { + //normal execution + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + } + + public void testFailedShortLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getShort("random"); + Assert.fail("NumberFormatException should be received."); + } + catch (NumberFormatException e) + { + //normal execution + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + } + + + private void assertBytesEqual(byte[] expected, byte[] actual) + { + Assert.assertEquals(expected.length, actual.length); + + for (int index = 0; index < expected.length; index++) + { + Assert.assertEquals(expected[index], actual[index]); + } + } + + public static junit.framework.Test suite() + { + return new junit.framework.TestSuite(MapMessageTest.class); + } + + +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/StreamMessageTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/StreamMessageTest.java new file mode 100644 index 0000000000..085dd81079 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/StreamMessageTest.java @@ -0,0 +1,623 @@ +/* + * + * 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.client.message; + +import java.util.HashMap; + +import javax.jms.JMSException; +import javax.jms.MessageEOFException; +import javax.jms.MessageFormatException; +import javax.jms.MessageNotReadableException; +import javax.jms.MessageNotWriteableException; +import javax.jms.StreamMessage; + +import junit.framework.TestCase; + +import org.apache.qpid.client.message.JMSStreamMessage; +import org.apache.qpid.client.message.TestMessageHelper; + +/** + * @author Apache Software Foundation + */ +public class StreamMessageTest extends TestCase +{ + /** + * Tests that on creation a call to getBodyLength() throws an exception + * if null was passed in during creation + */ + public void testNotReadableOnCreationWithNull() throws Exception + { + try + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.readByte(); + fail("expected exception did not occur"); + } + catch (MessageNotReadableException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageNotReadableException, got " + e); + } + } + + public void testResetMakesReadble() throws Exception + { + try + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeInt(10); + bm.reset(); + bm.writeInt(12); + fail("expected exception did not occur"); + } + catch (MessageNotWriteableException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageNotWriteableException, got " + e); + } + } + + public void testClearBodyMakesWritable() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeInt(10); + bm.reset(); + bm.clearBody(); + bm.writeInt(10); + } + + public void testWriteBoolean() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeBoolean(true); + bm.writeBoolean(false); + bm.reset(); + boolean val = bm.readBoolean(); + assertEquals(true, val); + val = bm.readBoolean(); + assertEquals(false, val); + } + + public void testWriteInt() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeInt(10); + bm.reset(); + int val = bm.readInt(); + assertTrue(val == 10); + } + + public void testWriteString() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeString("Bananas"); + bm.reset(); + String res = bm.readString(); + assertEquals("Bananas", res); + } + + public void testWriteBytes() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + byte[] bytes = {1,2,3,4}; + bm.writeBytes(bytes, 1, 2); + bm.reset(); + bytes = new byte[2]; + bm.readBytes(bytes); + assertEquals(2, bytes[0]); + assertEquals(3, bytes[1]); + } + + public void testWriteObject() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeObject(new Boolean(true)); + bm.writeObject(new Boolean(false)); + bm.writeObject(new Byte((byte)2)); + bm.writeObject(new byte[]{1,2,3,4}); + bm.writeObject(new Character('g')); + bm.writeObject(new Short((short) 29)); + bm.writeObject(new Integer(101)); + bm.writeObject(new Long(50003222L)); + bm.writeObject("Foobar"); + bm.writeObject(new Float(1.7f)); + bm.writeObject(new Double(8.7d)); + bm.reset(); + assertTrue(bm.readBoolean()); + assertTrue(!bm.readBoolean()); + assertEquals((byte)2, bm.readByte()); + byte[] bytes = new byte[4]; + bm.readBytes(bytes); + assertEquals('g', bm.readChar()); + assertEquals((short) 29, bm.readShort()); + assertEquals(101, bm.readInt()); + assertEquals(50003222L, bm.readLong()); + assertEquals("Foobar", bm.readString()); + assertEquals(1.7f, bm.readFloat()); + assertEquals(8.7d, bm.readDouble()); + } + + public void testWriteObjectRejectsNonPrimitives() throws Exception + { + try + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeObject(new HashMap()); + fail("expected MessageFormatException was not thrown"); + } + catch (MessageFormatException e) + { + // pass + } + } + + public void testReadBoolean() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeBoolean(true); + bm.reset(); + boolean result = bm.readBoolean(); + assertTrue(result); + } + + public void testReadBytesChecksNull() throws Exception + { + try + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.readBytes(null); + } + catch (IllegalArgumentException e) + { + // pass + } + } + + public void testReadBytesReturnsCorrectLengths() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + byte[] bytes = {2, 3}; + bm.writeBytes(bytes); + bm.writeBytes(null); + bm.writeBytes(new byte[]{}); + bm.reset(); + int len = bm.readBytes(bytes); + assertEquals(2, len); + len = bm.readBytes(bytes); + assertEquals(-1, len); + len = bm.readBytes(bytes); + assertEquals(-1, len); + len = bm.readBytes(bytes); + assertEquals(0, len); + } + + public void testReadBytesFollowedByPrimitive() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeBytes(new byte[]{2, 3, 4, 5, 6, 7, 8}); + bm.writeBytes(new byte[]{2, 3, 4, 5, 6, 7}); + bm.writeString("Foo"); + bm.reset(); + int len; + do + { + len = bm.readBytes(new byte[2]); + } + while (len == 2); + + do + { + len = bm.readBytes(new byte[2]); + } + while (len == 2); + + assertEquals("Foo", bm.readString()); + } + + public void testReadMultipleByteArrays() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + byte[] bytes = {2, 3, 4}; + bm.writeBytes(bytes); + bm.writeBytes(bytes); + bm.reset(); + byte[] result = new byte[2]; + int len = bm.readBytes(result); + assertEquals(2, len); + len = bm.readBytes(result); + assertEquals(1, len); + len = bm.readBytes(result); + assertEquals(2, len); + } + + public void testEOFByte() throws Exception + { + try + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeByte((byte)1); + bm.reset(); + bm.readByte(); + // should throw + bm.readByte(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFBoolean() throws Exception + { + try + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeBoolean(true); + bm.reset(); + bm.readBoolean(); + // should throw + bm.readBoolean(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFChar() throws Exception + { + try + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeChar('A'); + bm.reset(); + bm.readChar(); + // should throw + bm.readChar(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFDouble() throws Exception + { + try + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeDouble(1.3d); + bm.reset(); + bm.readDouble(); + // should throw + bm.readDouble(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFFloat() throws Exception + { + try + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeFloat(1.3f); + bm.reset(); + bm.readFloat(); + // should throw + bm.readFloat(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFInt() throws Exception + { + try + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeInt(99); + bm.reset(); + bm.readInt(); + // should throw + bm.readInt(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFLong() throws Exception + { + try + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeLong(4L); + bm.reset(); + bm.readLong(); + // should throw + bm.readLong(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testEOFShort() throws Exception + { + try + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeShort((short)4); + bm.reset(); + bm.readShort(); + // should throw + bm.readShort(); + fail("expected exception did not occur"); + } + catch (MessageEOFException m) + { + // ok + } + catch (Exception e) + { + fail("expected MessageEOFException, got " + e); + } + } + + public void testToBodyStringWithNull() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.reset(); + String result = bm.toBodyString(); + assertEquals("\"\"", result); + } + + private void checkConversionsFail(StreamMessage sm, int[] conversions) throws JMSException + { + for (int conversion : conversions) + { + try + { + switch (conversion) + { + case 0: + sm.readBoolean(); + break; + case 1: + sm.readByte(); + break; + case 2: + sm.readShort(); + break; + case 3: + sm.readChar(); + break; + case 4: + sm.readInt(); + break; + case 5: + sm.readLong(); + break; + case 6: + sm.readFloat(); + break; + case 7: + sm.readDouble(); + break; + case 8: + sm.readString(); + break; + case 9: + sm.readBytes(new byte[3]); + break; + } + fail("MessageFormatException was not thrown"); + } + catch (MessageFormatException e) + { + // PASS + } + sm.reset(); + } + } + public void testBooleanConversions() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeBoolean(true); + bm.reset(); + String result = bm.readString(); + assertEquals("true", result); + bm.reset(); + checkConversionsFail(bm, new int[]{1,2,3,4,5,6,7,9}); + } + + public void testByteConversions() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeByte((byte) 43); + bm.reset(); + assertEquals(43, bm.readShort()); + bm.reset(); + assertEquals(43, bm.readInt()); + bm.reset(); + assertEquals(43, bm.readLong()); + bm.reset(); + String result = bm.readString(); + assertEquals("43", result); + bm.reset(); + checkConversionsFail(bm, new int[]{0, 3, 6, 7, 9}); + } + + public void testShortConversions() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeShort((short) 87); + bm.reset(); + assertEquals(87, bm.readInt()); + bm.reset(); + assertEquals(87, bm.readLong()); + bm.reset(); + assertEquals("87", bm.readString()); + bm.reset(); + checkConversionsFail(bm, new int[]{0, 1, 3, 6, 7, }); + } + + public void testCharConversions() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeChar('d'); + bm.reset(); + assertEquals("d", bm.readString()); + bm.reset(); + checkConversionsFail(bm, new int[]{0, 1, 2, 4, 5, 6, 7, 9}); + } + + public void testIntConversions() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeInt(167); + bm.reset(); + assertEquals(167, bm.readLong()); + bm.reset(); + assertEquals("167", bm.readString()); + bm.reset(); + checkConversionsFail(bm, new int[]{0, 1, 2, 3, 6, 7, 9}); + } + + public void testLongConversions() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeLong(1678); + bm.reset(); + assertEquals("1678", bm.readString()); + bm.reset(); + checkConversionsFail(bm, new int[]{0, 1, 2, 3, 4, 6, 7, 9}); + } + + public void testFloatConversions() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeFloat(6.2f); + bm.reset(); + assertEquals(6.2d, bm.readDouble(), 0.01); + bm.reset(); + assertEquals("6.2", bm.readString()); + bm.reset(); + checkConversionsFail(bm, new int[]{0, 1, 2, 3, 4, 5, 9}); + } + + public void testDoubleConversions() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeDouble(88.35d); + bm.reset(); + assertEquals("88.35", bm.readString()); + bm.reset(); + checkConversionsFail(bm, new int[]{0, 1, 2, 3, 4, 5, 6, 9}); + } + + public void testStringConversions() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeString("true"); + bm.reset(); + assertEquals(true, bm.readBoolean()); + bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeString("2"); + bm.reset(); + assertEquals((byte)2, bm.readByte()); + bm.reset(); + assertEquals((short)2, bm.readShort()); + bm.reset(); + assertEquals(2, bm.readInt()); + bm.reset(); + assertEquals((long)2, bm.readLong()); + bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeString("5.7"); + bm.reset(); + assertEquals(5.7f, bm.readFloat()); + bm.reset(); + assertEquals(5.7d, bm.readDouble()); + } + + public void testNulls() throws Exception + { + JMSStreamMessage bm = TestMessageHelper.newJMSStreamMessage(); + bm.writeString(null); + bm.writeObject(null); + bm.reset(); + assertNull(bm.readObject()); + assertNull(bm.readObject()); + } + + public static junit.framework.Test suite() + { + return new junit.framework.TestSuite(StreamMessageTest.class); + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/TextMessageTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/TextMessageTest.java new file mode 100644 index 0000000000..30f3b0b4eb --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/client/message/TextMessageTest.java @@ -0,0 +1,300 @@ +/* + * + * 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.client.message; + +import javax.jms.JMSException; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.qpid.client.message.JMSMapMessage; +import org.apache.qpid.client.message.JMSTextMessage; +import org.apache.qpid.client.message.TestMessageHelper; + +public class TextMessageTest extends TestCase +{ + public void testTextOnConstruction() throws Exception + { + JMSTextMessage tm = TestMessageHelper.newJMSTextMessage(); + tm.setText("pies"); + String val = tm.getText(); + assertEquals(val, "pies"); + } + + public void testClearBody() throws Exception + { + JMSTextMessage tm = TestMessageHelper.newJMSTextMessage(); + tm.setText("pies"); + tm.clearBody(); + String val = tm.getText(); + assertNull(val); + tm.setText("Banana"); + val = tm.getText(); + assertEquals(val, "Banana"); + } + + + public void testBooleanPropertyLookup() + { + try + { + JMSTextMessage tm = TestMessageHelper.newJMSTextMessage(); + + tm.setBooleanProperty("value", true); + Assert.assertEquals(true, tm.getBooleanProperty("value")); + Assert.assertEquals("true", tm.getStringProperty("value")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testBytePropertyLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.setByteProperty("value", Byte.MAX_VALUE); + + Assert.assertEquals(Byte.MAX_VALUE, mm.getByteProperty("value")); + Assert.assertEquals((short) Byte.MAX_VALUE, mm.getShortProperty("value")); + Assert.assertEquals(Byte.MAX_VALUE, mm.getIntProperty("value")); + Assert.assertEquals((long) Byte.MAX_VALUE, mm.getLongProperty("value")); + Assert.assertEquals("" + Byte.MAX_VALUE, mm.getStringProperty("value")); + + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testShortPropertyLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.setShortProperty("value", Short.MAX_VALUE); + Assert.assertEquals(Short.MAX_VALUE, mm.getShortProperty("value")); + Assert.assertEquals((int) Short.MAX_VALUE, mm.getIntProperty("value")); + Assert.assertEquals((long) Short.MAX_VALUE, mm.getLongProperty("value")); + Assert.assertEquals("" + Short.MAX_VALUE, mm.getStringProperty("value")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testDoublePropertyLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.setDoubleProperty("value", Double.MAX_VALUE); + Assert.assertEquals(Double.MAX_VALUE, mm.getDoubleProperty("value")); + Assert.assertEquals("" + Double.MAX_VALUE, mm.getStringProperty("value")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testFloatPropertyLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.setFloatProperty("value", Float.MAX_VALUE); + Assert.assertEquals(Float.MAX_VALUE, mm.getFloatProperty("value")); + Assert.assertEquals((double) Float.MAX_VALUE, mm.getDoubleProperty("value")); + Assert.assertEquals("" + Float.MAX_VALUE, mm.getStringProperty("value")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testIntPropertyLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.setIntProperty("value", Integer.MAX_VALUE); + Assert.assertEquals(Integer.MAX_VALUE, mm.getIntProperty("value")); + Assert.assertEquals((long) Integer.MAX_VALUE, mm.getLongProperty("value")); + Assert.assertEquals("" + Integer.MAX_VALUE, mm.getStringProperty("value")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testLongPropertyLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.setLongProperty("value", Long.MAX_VALUE); + Assert.assertEquals(Long.MAX_VALUE, mm.getLongProperty("value")); + Assert.assertEquals("" + Long.MAX_VALUE, mm.getStringProperty("value")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + + // Failed Lookups + + public void testFailedBooleanPropertyLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + Assert.assertEquals(false, mm.getBooleanProperty("int")); + } + catch (JMSException e) + { + Assert.fail("JMSException received." + e); + } + } + + public void testFailedBytePropertyLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getByteProperty("random"); + Assert.fail("NumberFormatException expected"); + } + catch (NumberFormatException e) + { + //normal execution + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + + } + + public void testFailedDoublePropertyLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getDoubleProperty("random"); + Assert.fail("NullPointerException should be received."); + } + catch (NullPointerException e) + { + //normal execution + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + } + + public void testFailedFloatPropertyLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getFloatProperty("random"); + Assert.fail("NullPointerException should be received."); + } + catch (NullPointerException e) + { + //normal execution + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + } + + public void testFailedIntPropertyLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getIntProperty("random"); + Assert.fail("NumberFormatException should be received."); + } + catch (NumberFormatException e) + { + //normal execution + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + } + + public void testFailedLongPropertyLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getLongProperty("random"); + Assert.fail("NumberFormatException should be received."); + } + catch (NumberFormatException e) + { + //normal execution + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + } + + public void testFailedShortPropertyLookup() + { + try + { + JMSMapMessage mm = TestMessageHelper.newJMSMapMessage(); + mm.getShortProperty("random"); + Assert.fail("NumberFormatException should be received."); + } + catch (NumberFormatException e) + { + //normal execution + } + catch (JMSException e) + { + Assert.fail("JMSException received:" + e); + } + } + + + public static junit.framework.Test suite() + { + return new junit.framework.TestSuite(TextMessageTest.class); + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/jndi/ConnectionFactoryTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/jndi/ConnectionFactoryTest.java new file mode 100644 index 0000000000..9e76b0d468 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/jndi/ConnectionFactoryTest.java @@ -0,0 +1,75 @@ +/* + * + * 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.jndi; + +import junit.framework.TestCase; +import org.apache.qpid.client.AMQConnectionFactory; +import org.apache.qpid.jms.BrokerDetails; +import org.apache.qpid.jms.ConnectionURL; +import org.apache.qpid.url.URLSyntaxException; + +public class ConnectionFactoryTest extends TestCase +{ + + //URL will be returned with the password field swapped for '********' + // so ensure that these two strings are kept in sync. + public static final String URL = "amqp://guest:guest@clientID/test?brokerlist='tcp://localhost:5672'"; + public static final String URL_STAR_PWD = "amqp://guest:********@clientID/test?brokerlist='tcp://localhost:5672'"; + + public void testConnectionURLString() + { + AMQConnectionFactory factory = new AMQConnectionFactory(); + + assertNull("ConnectionURL should have no value at start", + factory.getConnectionURL()); + + try + { + factory.setConnectionURLString(URL); + } + catch (URLSyntaxException e) + { + fail(e.getMessage()); + } + + //URL will be returned with the password field swapped for '********' + assertEquals("Connection URL not correctly set", URL_STAR_PWD, factory.getConnectionURLString()); + + // Further test that the processed ConnectionURL is as expected after + // the set call + ConnectionURL connectionurl = factory.getConnectionURL(); + + assertNull("Failover is set.", connectionurl.getFailoverMethod()); + assertEquals("guest", connectionurl.getUsername()); + assertEquals("guest", connectionurl.getPassword()); + assertEquals("clientID", connectionurl.getClientName()); + assertEquals("/test", connectionurl.getVirtualHost()); + + assertEquals(1, connectionurl.getBrokerCount()); + + BrokerDetails service = connectionurl.getBrokerDetails(0); + + assertEquals("tcp", service.getTransport()); + assertEquals("localhost", service.getHost()); + assertEquals(5672, service.getPort()); + + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDIPropertyFileTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDIPropertyFileTest.java new file mode 100644 index 0000000000..a1b14d5723 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDIPropertyFileTest.java @@ -0,0 +1,70 @@ +/* + * 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.jndi; + +import java.util.Properties; + +import javax.jms.Queue; +import javax.jms.Topic; +import javax.naming.Context; +import javax.naming.InitialContext; + +import org.apache.qpid.client.AMQDestination; +import org.apache.qpid.framing.AMQShortString; + +import junit.framework.TestCase; + +public class JNDIPropertyFileTest extends TestCase +{ + Context ctx; + + public JNDIPropertyFileTest() throws Exception + { + Properties properties = new Properties(); + properties.load(this.getClass().getResourceAsStream("JNDITest.properties")); + + //Create the initial context + ctx = new InitialContext(properties); + } + + public void testQueueNamesWithTrailingSpaces() throws Exception + { + Queue queue = (Queue)ctx.lookup("QueueNameWithSpace"); + assertEquals("QueueNameWithSpace",queue.getQueueName()); + } + + public void testTopicNamesWithTrailingSpaces() throws Exception + { + Topic topic = (Topic)ctx.lookup("TopicNameWithSpace"); + assertEquals("TopicNameWithSpace",topic.getTopicName()); + } + + public void testMultipleTopicNamesWithTrailingSpaces() throws Exception + { + Topic topic = (Topic)ctx.lookup("MultipleTopicNamesWithSpace"); + int i = 0; + for (AMQShortString bindingKey: ((AMQDestination)topic).getBindingKeys()) + { + i++; + assertEquals("Topic" + i + "WithSpace",bindingKey.asString()); + } + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDITest.properties b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDITest.properties new file mode 100644 index 0000000000..07017a05a6 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDITest.properties @@ -0,0 +1,28 @@ +# +# 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. +# +java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory + +# Queue name with spaces +queue.QueueNameWithSpace = QueueNameWithSpace + +# Topic name with spaces +topic.TopicNameWithSpace = TopicNameWithSpace + +# Multiple topic names with spaces +topic.MultipleTopicNamesWithSpace = Topic1WithSpace , Topic2WithSpace , Topic3WithSpace diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java new file mode 100644 index 0000000000..b5e7ae82b5 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java @@ -0,0 +1,140 @@ +/* + * + * 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.message; + +import javax.jms.*; + +import junit.framework.TestCase; + +import org.apache.qpid.client.*; +import org.apache.qpid.client.protocol.AMQProtocolHandler; +import org.apache.qpid.client.failover.FailoverException; +import org.apache.qpid.client.message.*; +import org.apache.qpid.exchange.ExchangeDefaults; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.FieldTable; +import org.apache.qpid.AMQException; + +import java.util.Map; + + +public class MessageConverterTest extends TestCase +{ + + public static final String JMS_CORR_ID = "QPIDID_01"; + public static final int JMS_DELIV_MODE = 1; + public static final String JMS_TYPE = "test.jms.type"; + public static final Destination JMS_REPLY_TO = new AMQQueue(ExchangeDefaults.DIRECT_EXCHANGE_NAME,"my.replyto"); + + protected JMSTextMessage testTextMessage; + + protected JMSMapMessage testMapMessage; + private AMQSession _session = new TestAMQSession(); + + + protected void setUp() throws Exception + { + super.setUp(); + testTextMessage = new JMSTextMessage(AMQMessageDelegateFactory.FACTORY_0_8); + + //Set Message Text + testTextMessage.setText("testTextMessage text"); + setMessageProperties(testTextMessage); + + testMapMessage = new JMSMapMessage(AMQMessageDelegateFactory.FACTORY_0_8); + testMapMessage.setString("testMapString", "testMapStringValue"); + testMapMessage.setDouble("testMapDouble", Double.MAX_VALUE); + } + + public void testSetProperties() throws Exception + { + AbstractJMSMessage newMessage = new MessageConverter(_session, (TextMessage) testTextMessage).getConvertedMessage(); + mesagePropertiesTest(testTextMessage, newMessage); + } + + public void testJMSTextMessageConversion() throws Exception + { + AbstractJMSMessage newMessage = new MessageConverter(_session, (TextMessage) testTextMessage).getConvertedMessage(); + assertEquals("Converted message text mismatch", ((JMSTextMessage) newMessage).getText(), testTextMessage.getText()); + } + + public void testJMSMapMessageConversion() throws Exception + { + AbstractJMSMessage newMessage = new MessageConverter(_session, (MapMessage) testMapMessage).getConvertedMessage(); + assertEquals("Converted map message String mismatch", ((JMSMapMessage) newMessage).getString("testMapString"), + testMapMessage.getString("testMapString")); + assertEquals("Converted map message Double mismatch", ((JMSMapMessage) newMessage).getDouble("testMapDouble"), + testMapMessage.getDouble("testMapDouble")); + + } + + public void testMessageConversion() throws Exception + { + Message newMessage = new NonQpidMessage(); + setMessageProperties(newMessage); + mesagePropertiesTest(testTextMessage, newMessage); + } + + private void setMessageProperties(Message message) throws JMSException + { + message.setJMSCorrelationID(JMS_CORR_ID); + message.setJMSDeliveryMode(JMS_DELIV_MODE); + message.setJMSType(JMS_TYPE); + message.setJMSReplyTo(JMS_REPLY_TO); + + //Add non-JMS properties + message.setStringProperty("testProp1", "testValue1"); + message.setDoubleProperty("testProp2", Double.MIN_VALUE); + } + + + private void mesagePropertiesTest(Message expectedMessage, Message actualMessage) + { + try + { + //check JMS prop values on newMessage match + assertEquals("JMS Correlation ID mismatch", expectedMessage.getJMSCorrelationID(), actualMessage.getJMSCorrelationID()); + assertEquals("JMS Delivery mode mismatch", expectedMessage.getJMSDeliveryMode(), actualMessage.getJMSDeliveryMode()); + assertEquals("JMS Type mismatch", expectedMessage.getJMSType(), actualMessage.getJMSType()); + assertEquals("JMS Reply To mismatch", expectedMessage.getJMSReplyTo(), actualMessage.getJMSReplyTo()); + + //check non-JMS standard props ok too + assertEquals("Test String prop value mismatch", expectedMessage.getStringProperty("testProp1"), + actualMessage.getStringProperty("testProp1")); + + assertEquals("Test Double prop value mismatch", expectedMessage.getDoubleProperty("testProp2"), + actualMessage.getDoubleProperty("testProp2")); + } + catch (JMSException e) + { + fail("An error occured testing the property values" + e.getCause()); + e.printStackTrace(); + } + } + + protected void tearDown() throws Exception + { + super.tearDown(); + testTextMessage = null; + } + + +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/NonQpidMessage.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/NonQpidMessage.java new file mode 100644 index 0000000000..b1cf23bb9e --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/NonQpidMessage.java @@ -0,0 +1,420 @@ +/* + * 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.message; + +import java.util.Enumeration; +import java.util.Hashtable; + +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageFormatException; + +public class NonQpidMessage implements Message +{ + private String _JMSMessageID; + private long _JMSTimestamp; + private byte[] _JMSCorrelationIDAsBytes; + private String _JMSCorrelationID; + private Destination _JMSReplyTo; + private Destination _JMSDestination; + private int _JMSDeliveryMode; + private boolean _JMSRedelivered; + private String _JMSType; + private long _JMSExpiration; + private int _JMSPriority; + private Hashtable _properties; + + public NonQpidMessage() + { + _properties = new Hashtable(); + _JMSPriority = javax.jms.Message.DEFAULT_PRIORITY; + _JMSDeliveryMode = javax.jms.Message.DEFAULT_DELIVERY_MODE; + } + + public String getJMSMessageID() throws JMSException + { + return _JMSMessageID; + } + + public void setJMSMessageID(String string) throws JMSException + { + _JMSMessageID = string; + } + + public long getJMSTimestamp() throws JMSException + { + return _JMSTimestamp; + } + + public void setJMSTimestamp(long l) throws JMSException + { + _JMSTimestamp = l; + } + + public byte[] getJMSCorrelationIDAsBytes() throws JMSException + { + return _JMSCorrelationIDAsBytes; + } + + public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException + { + _JMSCorrelationIDAsBytes = bytes; + } + + public void setJMSCorrelationID(String string) throws JMSException + { + _JMSCorrelationID = string; + } + + public String getJMSCorrelationID() throws JMSException + { + return _JMSCorrelationID; + } + + public Destination getJMSReplyTo() throws JMSException + { + return _JMSReplyTo; + } + + public void setJMSReplyTo(Destination destination) throws JMSException + { + _JMSReplyTo = destination; + } + + public Destination getJMSDestination() throws JMSException + { + return _JMSDestination; + } + + public void setJMSDestination(Destination destination) throws JMSException + { + _JMSDestination = destination; + } + + public int getJMSDeliveryMode() throws JMSException + { + return _JMSDeliveryMode; + } + + public void setJMSDeliveryMode(int i) throws JMSException + { + _JMSDeliveryMode = i; + } + + public boolean getJMSRedelivered() throws JMSException + { + return _JMSRedelivered; + } + + public void setJMSRedelivered(boolean b) throws JMSException + { + _JMSRedelivered = b; + } + + public String getJMSType() throws JMSException + { + return _JMSType; + } + + public void setJMSType(String string) throws JMSException + { + _JMSType = string; + } + + public long getJMSExpiration() throws JMSException + { + return _JMSExpiration; + } + + public void setJMSExpiration(long l) throws JMSException + { + _JMSExpiration = l; + } + + public int getJMSPriority() throws JMSException + { + return _JMSPriority; + } + + public void setJMSPriority(int i) throws JMSException + { + _JMSPriority = i; + } + + public void clearProperties() throws JMSException + { + _properties.clear(); + } + + public boolean propertyExists(String string) throws JMSException + { + return _properties.containsKey(string); + } + + public boolean getBooleanProperty(String string) throws JMSException + { + if (propertyExists(string)) + { + Object o = _properties.get(string); + if (o instanceof Boolean) + { + return (Boolean) o; + } + else + { + return Boolean.valueOf(null); + } + } + else + { + throw new JMSException("property does not exist: " + string); + } + } + + public byte getByteProperty(String string) throws JMSException + { + if (propertyExists(string)) + { + Object o = _properties.get(string); + if (o instanceof Byte) + { + return (Byte) o; + } + else + { + return Byte.valueOf(null); + } + } + else + { + throw new JMSException("property does not exist: " + string); + } + } + + public short getShortProperty(String string) throws JMSException + { + if (propertyExists(string)) + { + Object o = _properties.get(string); + if (o instanceof Short) + { + return (Short) o; + } + else + { + return Short.valueOf(null); + } + } + else + { + throw new JMSException("property does not exist: " + string); + } + } + + public int getIntProperty(String string) throws JMSException + { + if (propertyExists(string)) + { + Object o = _properties.get(string); + if (o instanceof Integer) + { + return (Integer) o; + } + else + { + return Integer.valueOf(null); + } + } + else + { + throw new JMSException("property does not exist: " + string); + } + } + + public long getLongProperty(String string) throws JMSException + { + if (propertyExists(string)) + { + Object o = _properties.get(string); + if (o instanceof Long) + { + return (Long) o; + } + else + { + return Long.valueOf(null); + } + } + else + { + throw new JMSException("property does not exist: " + string); + } + } + + public float getFloatProperty(String string) throws JMSException + { + if (propertyExists(string)) + { + Object o = _properties.get(string); + if (o instanceof Float) + { + return (Float) o; + } + else if(o instanceof String) + { + return Float.valueOf((String)o); + } + else if(o == null) + { + throw new NullPointerException("No such property: " + string); + } + else + { + throw new MessageFormatException("getFloatProperty(\""+string+"\") failed as value is not a float: " + o); + } + } + else + { + throw new JMSException("property does not exist: " + string); + } + } + + public double getDoubleProperty(String string) throws JMSException + { + if (propertyExists(string)) + { + Object o = _properties.get(string); + if (o instanceof Double) + { + return (Double) o; + } + else + { + return getFloatProperty(string); + } + } + else + { + throw new JMSException("property does not exist: " + string); + } + } + + public String getStringProperty(String string) throws JMSException + { + if (propertyExists(string)) + { + Object o = _properties.get(string); + if (o instanceof String) + { + return (String) o; + } + else + { + return null; + } + } + else + { + throw new JMSException("property does not exist: " + string); + } + } + + public Object getObjectProperty(String string) throws JMSException + { + if (propertyExists(string)) + { + Object o = _properties.get(string); + if (o instanceof Boolean) + { + return (Boolean) o; + } + else + { + return Boolean.valueOf(null); + } + } + else + { + throw new JMSException("property does not exist: " + string); + } + } + + public Enumeration getPropertyNames() throws JMSException + { + return _properties.keys(); + } + + public void setBooleanProperty(String string, boolean b) throws JMSException + { + _properties.put(string, b); + } + + public void setByteProperty(String string, byte b) throws JMSException + { + _properties.put(string, b); + } + + public void setShortProperty(String string, short i) throws JMSException + { + _properties.put(string, i); + } + + public void setIntProperty(String string, int i) throws JMSException + { + _properties.put(string, i); + } + + public void setLongProperty(String string, long l) throws JMSException + { + _properties.put(string, l); + } + + public void setFloatProperty(String string, float v) throws JMSException + { + _properties.put(string, v); + } + + public void setDoubleProperty(String string, double v) throws JMSException + { + _properties.put(string, v); + } + + public void setStringProperty(String string, String string1) throws JMSException + { + _properties.put(string, string1); + } + + public void setObjectProperty(String string, Object object) throws JMSException + { + _properties.put(string, object); + } + + public void acknowledge() throws JMSException + { + + } + + public void clearBody() throws JMSException + { + + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/TestAMQSession.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/TestAMQSession.java new file mode 100644 index 0000000000..4637c6e505 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/message/TestAMQSession.java @@ -0,0 +1,204 @@ +/* + * + * 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.message; + +import org.apache.qpid.client.*; +import org.apache.qpid.client.message.AMQMessageDelegateFactory; +import org.apache.qpid.client.protocol.AMQProtocolHandler; +import org.apache.qpid.client.failover.FailoverException; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.FieldTable; +import org.apache.qpid.AMQException; + +import javax.jms.*; + +import java.util.Map; + +public class TestAMQSession extends AMQSession<BasicMessageConsumer_0_8, BasicMessageProducer_0_8> +{ + + public TestAMQSession() + { + super(null, 0, false, AUTO_ACKNOWLEDGE, null, 0, 0); + } + + public void acknowledgeMessage(long deliveryTag, boolean multiple) + { + + } + + public void sendQueueBind(AMQShortString queueName, AMQShortString routingKey, FieldTable arguments, + AMQShortString exchangeName, AMQDestination destination, + boolean nowait) throws AMQException, FailoverException + { + + } + + public void sendClose(long timeout) throws AMQException, FailoverException + { + + } + + public void sendCommit() throws AMQException, FailoverException + { + + } + + public TopicSubscriber createDurableSubscriber(Topic topic, String name) throws JMSException + { + return null; + } + + public void sendCreateQueue(AMQShortString name, boolean autoDelete, boolean durable, boolean exclusive, Map<String, Object> arguments) throws AMQException, FailoverException + { + + } + + public TemporaryQueue createTemporaryQueue() throws JMSException + { + return null; + } + + protected void sendRecover() throws AMQException, FailoverException + { + + } + + public void rejectMessage(long deliveryTag, boolean requeue) + { + + } + + public void releaseForRollback() + { + + } + + public void sendRollback() throws AMQException, FailoverException + { + + } + + public BasicMessageConsumer_0_8 createMessageConsumer(AMQDestination destination, int prefetchHigh, int prefetchLow, boolean noLocal, boolean exclusive, String selector, FieldTable arguments, boolean noConsume, boolean autoClose) throws JMSException + { + return null; + } + + public boolean isQueueBound(AMQShortString exchangeName, AMQShortString queueName, AMQShortString routingKey) throws JMSException + { + return false; + } + + public boolean isQueueBound(AMQDestination destination) throws JMSException + { + return false; + } + + public void sendConsume(BasicMessageConsumer_0_8 consumer, AMQShortString queueName, AMQProtocolHandler protocolHandler, boolean nowait, String messageSelector, int tag) throws AMQException, FailoverException + { + + } + + public BasicMessageProducer_0_8 createMessageProducer(Destination destination, boolean mandatory, boolean immediate, boolean waitUntilSent, long producerId) + { + return null; + } + + protected Long requestQueueDepth(AMQDestination amqd) throws AMQException, FailoverException + { + return null; + } + + public void sendExchangeDeclare(AMQShortString name, AMQShortString type, AMQProtocolHandler protocolHandler, boolean nowait) throws AMQException, FailoverException + { + + } + + public void sendQueueDeclare(AMQDestination amqd, AMQProtocolHandler protocolHandler, + boolean nowait) throws AMQException, FailoverException + { + + } + + public void sendQueueDelete(AMQShortString queueName) throws AMQException, FailoverException + { + + } + + public void sendSuspendChannel(boolean suspend) throws AMQException, FailoverException + { + + } + + protected boolean tagLE(long tag1, long tag2) + { + return false; + } + + protected boolean updateRollbackMark(long current, long deliveryTag) + { + return false; + } + + public AMQMessageDelegateFactory getMessageDelegateFactory() + { + return AMQMessageDelegateFactory.FACTORY_0_8; + } + + protected Object getFailoverMutex() + { + return this; + } + + public void checkNotClosed() + { + + } + + public void sync() + { + } + + public void handleAddressBasedDestination(AMQDestination dest, + boolean isConsumer, + boolean noWait) throws AMQException + { + throw new UnsupportedOperationException("The new addressing based sytanx is " + + "not supported for AMQP 0-8/0-9 versions"); + } + + @Override + protected void flushAcknowledgments() + { + } + + public boolean isQueueBound(String exchangeName, String queueName, + String bindingKey, Map<String, Object> args) throws JMSException + { + return false; + } + + @Override + public AMQException getLastException() + { + return null; + } +} diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/tests.properties b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/tests.properties new file mode 100644 index 0000000000..2fd961a078 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/tests.properties @@ -0,0 +1,45 @@ +# 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. + + +java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory + +# use the following property to configure the default connector +#java.naming.provider.url - ignored. + +# register some connection factories +# connectionfactory.[jndiname] = [ConnectionURL] +connectionfactory.local = amqp://username:password@clientid/test?brokerlist='tcp://localhost:5672' +#qpid:password=guest;username=guest;client_id=clientid;virtualhost=test@tcp:127.0.0.1:5672 + + +# register some queues in JNDI using the form +# queue.[jndiName] = [physicalName] +queue.MyQueue = example.MyQueue +queue.queue = example.queue +queue.xaQueue = xaQueue + +# register some topics in JNDI using the form +# topic.[jndiName] = [physicalName] +#topic.ibmStocks = stocks.nyse.ibm +topic.xaTopic = xaTopic +topic.durableSubscriberTopic = durableSubscriberTopic + +# Register an AMQP destination in JNDI +# NOTE: Qpid currently only supports direct,topics and headers +# destination.[jniName] = [BindingURL] +#destination.direct = direct://amq.direct//directQueue |